runtime.cc revision fa82427c68b09f4aedbee319dc71579afbfc66f5
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#include "runtime.h"
18
19// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
20#include <sys/mount.h>
21#include <linux/fs.h>
22
23#include <signal.h>
24#include <sys/syscall.h>
25
26#include <cstdio>
27#include <cstdlib>
28#include <limits>
29#include <vector>
30
31#include "arch/arm/registers_arm.h"
32#include "arch/mips/registers_mips.h"
33#include "arch/x86/registers_x86.h"
34#include "atomic.h"
35#include "class_linker.h"
36#include "debugger.h"
37#include "gc/accounting/card_table-inl.h"
38#include "gc/heap.h"
39#include "gc/space/space.h"
40#include "image.h"
41#include "instrumentation.h"
42#include "intern_table.h"
43#include "invoke_arg_array_builder.h"
44#include "jni_internal.h"
45#include "mirror/art_field-inl.h"
46#include "mirror/art_method-inl.h"
47#include "mirror/array.h"
48#include "mirror/class-inl.h"
49#include "mirror/class_loader.h"
50#include "mirror/throwable.h"
51#include "monitor.h"
52#include "oat_file.h"
53#include "ScopedLocalRef.h"
54#include "scoped_thread_state_change.h"
55#include "signal_catcher.h"
56#include "signal_set.h"
57#include "sirt_ref.h"
58#include "thread.h"
59#include "thread_list.h"
60#include "trace.h"
61#include "UniquePtr.h"
62#include "verifier/method_verifier.h"
63#include "well_known_classes.h"
64
65#include "JniConstants.h"  // Last to avoid LOG redefinition in ics-mr1-plus-art.
66
67namespace art {
68
69Runtime* Runtime::instance_ = NULL;
70
71Runtime::Runtime()
72    : is_compiler_(false),
73      is_zygote_(false),
74      is_concurrent_gc_enabled_(true),
75      is_explicit_gc_disabled_(false),
76      default_stack_size_(0),
77      heap_(NULL),
78      max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
79      monitor_list_(NULL),
80      thread_list_(NULL),
81      intern_table_(NULL),
82      class_linker_(NULL),
83      signal_catcher_(NULL),
84      java_vm_(NULL),
85      pre_allocated_OutOfMemoryError_(NULL),
86      resolution_method_(NULL),
87      imt_conflict_method_(NULL),
88      default_imt_(NULL),
89      threads_being_born_(0),
90      shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
91      shutting_down_(false),
92      shutting_down_started_(false),
93      started_(false),
94      finished_starting_(false),
95      vfprintf_(NULL),
96      exit_(NULL),
97      abort_(NULL),
98      stats_enabled_(false),
99      method_trace_(0),
100      method_trace_file_size_(0),
101      instrumentation_(),
102      use_compile_time_class_path_(false),
103      main_thread_group_(NULL),
104      system_thread_group_(NULL),
105      system_class_loader_(NULL) {
106  for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
107    callee_save_methods_[i] = NULL;
108  }
109}
110
111Runtime::~Runtime() {
112  Thread* self = Thread::Current();
113  {
114    MutexLock mu(self, *Locks::runtime_shutdown_lock_);
115    shutting_down_started_ = true;
116    while (threads_being_born_ > 0) {
117      shutdown_cond_->Wait(self);
118    }
119    shutting_down_ = true;
120  }
121  Trace::Shutdown();
122
123  // Make sure to let the GC complete if it is running.
124  heap_->WaitForConcurrentGcToComplete(self);
125  heap_->DeleteThreadPool();
126
127  // Make sure our internal threads are dead before we start tearing down things they're using.
128  Dbg::StopJdwp();
129  delete signal_catcher_;
130
131  // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
132  delete thread_list_;
133  delete monitor_list_;
134  delete class_linker_;
135  delete heap_;
136  delete intern_table_;
137  delete java_vm_;
138  Thread::Shutdown();
139  QuasiAtomic::Shutdown();
140  verifier::MethodVerifier::Shutdown();
141  // TODO: acquire a static mutex on Runtime to avoid racing.
142  CHECK(instance_ == NULL || instance_ == this);
143  instance_ = NULL;
144}
145
146struct AbortState {
147  void Dump(std::ostream& os) {
148    if (gAborting > 1) {
149      os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
150      return;
151    }
152    gAborting++;
153    os << "Runtime aborting...\n";
154    if (Runtime::Current() == NULL) {
155      os << "(Runtime does not yet exist!)\n";
156      return;
157    }
158    Thread* self = Thread::Current();
159    if (self == NULL) {
160      os << "(Aborting thread was not attached to runtime!)\n";
161    } else {
162      // TODO: we're aborting and the ScopedObjectAccess may attempt to acquire the mutator_lock_
163      //       which may block indefinitely if there's a misbehaving thread holding it exclusively.
164      //       The code below should be made robust to this.
165      ScopedObjectAccess soa(self);
166      os << "Aborting thread:\n";
167      self->Dump(os);
168      if (self->IsExceptionPending()) {
169        ThrowLocation throw_location;
170        mirror::Throwable* exception = self->GetException(&throw_location);
171        os << "Pending exception " << PrettyTypeOf(exception)
172            << " thrown by '" << throw_location.Dump() << "'\n"
173            << exception->Dump();
174      }
175    }
176    DumpAllThreads(os, self);
177  }
178
179  void DumpAllThreads(std::ostream& os, Thread* self) NO_THREAD_SAFETY_ANALYSIS {
180    bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
181    bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
182    if (!tll_already_held || !ml_already_held) {
183      os << "Dumping all threads without appropriate locks held:"
184          << (!tll_already_held ? " thread list lock" : "")
185          << (!ml_already_held ? " mutator lock" : "")
186          << "\n";
187    }
188    os << "All threads:\n";
189    Runtime::Current()->GetThreadList()->DumpLocked(os);
190  }
191};
192
193void Runtime::Abort() {
194  gAborting++;  // set before taking any locks
195
196  // Ensure that we don't have multiple threads trying to abort at once,
197  // which would result in significantly worse diagnostics.
198  MutexLock mu(Thread::Current(), *Locks::abort_lock_);
199
200  // Get any pending output out of the way.
201  fflush(NULL);
202
203  // Many people have difficulty distinguish aborts from crashes,
204  // so be explicit.
205  AbortState state;
206  LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state);
207
208  // Call the abort hook if we have one.
209  if (Runtime::Current() != NULL && Runtime::Current()->abort_ != NULL) {
210    LOG(INTERNAL_FATAL) << "Calling abort hook...";
211    Runtime::Current()->abort_();
212    // notreached
213    LOG(INTERNAL_FATAL) << "Unexpectedly returned from abort hook!";
214  }
215
216#if defined(__GLIBC__)
217  // TODO: we ought to be able to use pthread_kill(3) here (or abort(3),
218  // which POSIX defines in terms of raise(3), which POSIX defines in terms
219  // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through
220  // libpthread, which means the stacks we dump would be useless. Calling
221  // tgkill(2) directly avoids that.
222  syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT);
223  // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM?
224  // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3).
225  exit(1);
226#else
227  abort();
228#endif
229  // notreached
230}
231
232bool Runtime::PreZygoteFork() {
233  heap_->PreZygoteFork();
234  return true;
235}
236
237void Runtime::CallExitHook(jint status) {
238  if (exit_ != NULL) {
239    ScopedThreadStateChange tsc(Thread::Current(), kNative);
240    exit_(status);
241    LOG(WARNING) << "Exit hook returned instead of exiting!";
242  }
243}
244
245// Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
246// memory sizes.  [kK] indicates kilobytes, [mM] megabytes, and
247// [gG] gigabytes.
248//
249// "s" should point just past the "-Xm?" part of the string.
250// "div" specifies a divisor, e.g. 1024 if the value must be a multiple
251// of 1024.
252//
253// The spec says the -Xmx and -Xms options must be multiples of 1024.  It
254// doesn't say anything about -Xss.
255//
256// Returns 0 (a useless size) if "s" is malformed or specifies a low or
257// non-evenly-divisible value.
258//
259size_t ParseMemoryOption(const char* s, size_t div) {
260  // strtoul accepts a leading [+-], which we don't want,
261  // so make sure our string starts with a decimal digit.
262  if (isdigit(*s)) {
263    char* s2;
264    size_t val = strtoul(s, &s2, 10);
265    if (s2 != s) {
266      // s2 should be pointing just after the number.
267      // If this is the end of the string, the user
268      // has specified a number of bytes.  Otherwise,
269      // there should be exactly one more character
270      // that specifies a multiplier.
271      if (*s2 != '\0') {
272        // The remainder of the string is either a single multiplier
273        // character, or nothing to indicate that the value is in
274        // bytes.
275        char c = *s2++;
276        if (*s2 == '\0') {
277          size_t mul;
278          if (c == '\0') {
279            mul = 1;
280          } else if (c == 'k' || c == 'K') {
281            mul = KB;
282          } else if (c == 'm' || c == 'M') {
283            mul = MB;
284          } else if (c == 'g' || c == 'G') {
285            mul = GB;
286          } else {
287            // Unknown multiplier character.
288            return 0;
289          }
290
291          if (val <= std::numeric_limits<size_t>::max() / mul) {
292            val *= mul;
293          } else {
294            // Clamp to a multiple of 1024.
295            val = std::numeric_limits<size_t>::max() & ~(1024-1);
296          }
297        } else {
298          // There's more than one character after the numeric part.
299          return 0;
300        }
301      }
302      // The man page says that a -Xm value must be a multiple of 1024.
303      if (val % div == 0) {
304        return val;
305      }
306    }
307  }
308  return 0;
309}
310
311size_t ParseIntegerOrDie(const std::string& s) {
312  std::string::size_type colon = s.find(':');
313  if (colon == std::string::npos) {
314    LOG(FATAL) << "Missing integer: " << s;
315  }
316  const char* begin = &s[colon + 1];
317  char* end;
318  size_t result = strtoul(begin, &end, 10);
319  if (begin == end || *end != '\0') {
320    LOG(FATAL) << "Failed to parse integer in: " << s;
321  }
322  return result;
323}
324
325void Runtime::SweepSystemWeaks(RootVisitor* visitor, void* arg) {
326  GetInternTable()->SweepInternTableWeaks(visitor, arg);
327  GetMonitorList()->SweepMonitorList(visitor, arg);
328  GetJavaVM()->SweepJniWeakGlobals(visitor, arg);
329}
330
331Runtime::ParsedOptions* Runtime::ParsedOptions::Create(const Options& options, bool ignore_unrecognized) {
332  UniquePtr<ParsedOptions> parsed(new ParsedOptions());
333  const char* boot_class_path_string = getenv("BOOTCLASSPATH");
334  if (boot_class_path_string != NULL) {
335    parsed->boot_class_path_string_ = boot_class_path_string;
336  }
337  const char* class_path_string = getenv("CLASSPATH");
338  if (class_path_string != NULL) {
339    parsed->class_path_string_ = class_path_string;
340  }
341  // -Xcheck:jni is off by default for regular builds but on by default in debug builds.
342  parsed->check_jni_ = kIsDebugBuild;
343
344  parsed->heap_initial_size_ = gc::Heap::kDefaultInitialSize;
345  parsed->heap_maximum_size_ = gc::Heap::kDefaultMaximumSize;
346  parsed->heap_min_free_ = gc::Heap::kDefaultMinFree;
347  parsed->heap_max_free_ = gc::Heap::kDefaultMaxFree;
348  parsed->heap_target_utilization_ = gc::Heap::kDefaultTargetUtilization;
349  parsed->heap_growth_limit_ = 0;  // 0 means no growth limit.
350  // Default to number of processors minus one since the main GC thread also does work.
351  parsed->parallel_gc_threads_ = sysconf(_SC_NPROCESSORS_CONF) - 1;
352  // Only the main GC thread, no workers.
353  parsed->conc_gc_threads_ = 0;
354  parsed->stack_size_ = 0;  // 0 means default.
355  parsed->max_spins_before_thin_lock_inflation_ = Monitor::kDefaultMaxSpinsBeforeThinLockInflation;
356  parsed->low_memory_mode_ = false;
357
358  parsed->is_compiler_ = false;
359  parsed->is_zygote_ = false;
360  parsed->interpreter_only_ = false;
361  parsed->is_concurrent_gc_enabled_ = true;
362  parsed->is_explicit_gc_disabled_ = false;
363
364  parsed->long_pause_log_threshold_ = gc::Heap::kDefaultLongPauseLogThreshold;
365  parsed->long_gc_log_threshold_ = gc::Heap::kDefaultLongGCLogThreshold;
366  parsed->ignore_max_footprint_ = false;
367
368  parsed->lock_profiling_threshold_ = 0;
369  parsed->hook_is_sensitive_thread_ = NULL;
370
371  parsed->hook_vfprintf_ = vfprintf;
372  parsed->hook_exit_ = exit;
373  parsed->hook_abort_ = NULL;  // We don't call abort(3) by default; see Runtime::Abort.
374
375  parsed->compiler_filter_ = Runtime::kDefaultCompilerFilter;
376  parsed->huge_method_threshold_ = Runtime::kDefaultHugeMethodThreshold;
377  parsed->large_method_threshold_ = Runtime::kDefaultLargeMethodThreshold;
378  parsed->small_method_threshold_ = Runtime::kDefaultSmallMethodThreshold;
379  parsed->tiny_method_threshold_ = Runtime::kDefaultTinyMethodThreshold;
380  parsed->num_dex_methods_threshold_ = Runtime::kDefaultNumDexMethodsThreshold;
381
382  parsed->sea_ir_mode_ = false;
383//  gLogVerbosity.class_linker = true;  // TODO: don't check this in!
384//  gLogVerbosity.compiler = true;  // TODO: don't check this in!
385//  gLogVerbosity.verifier = true;  // TODO: don't check this in!
386//  gLogVerbosity.heap = true;  // TODO: don't check this in!
387//  gLogVerbosity.gc = true;  // TODO: don't check this in!
388//  gLogVerbosity.jdwp = true;  // TODO: don't check this in!
389//  gLogVerbosity.jni = true;  // TODO: don't check this in!
390//  gLogVerbosity.monitor = true;  // TODO: don't check this in!
391//  gLogVerbosity.startup = true;  // TODO: don't check this in!
392//  gLogVerbosity.third_party_jni = true;  // TODO: don't check this in!
393//  gLogVerbosity.threads = true;  // TODO: don't check this in!
394
395  parsed->method_trace_ = false;
396  parsed->method_trace_file_ = "/data/method-trace-file.bin";
397  parsed->method_trace_file_size_ = 10 * MB;
398
399  for (size_t i = 0; i < options.size(); ++i) {
400    const std::string option(options[i].first);
401    if (true && options[0].first == "-Xzygote") {
402      LOG(INFO) << "option[" << i << "]=" << option;
403    }
404    if (StartsWith(option, "-Xbootclasspath:")) {
405      parsed->boot_class_path_string_ = option.substr(strlen("-Xbootclasspath:")).data();
406    } else if (option == "-classpath" || option == "-cp") {
407      // TODO: support -Djava.class.path
408      i++;
409      if (i == options.size()) {
410        // TODO: usage
411        LOG(FATAL) << "Missing required class path value for " << option;
412        return NULL;
413      }
414      const StringPiece& value = options[i].first;
415      parsed->class_path_string_ = value.data();
416    } else if (option == "bootclasspath") {
417      parsed->boot_class_path_
418          = reinterpret_cast<const std::vector<const DexFile*>*>(options[i].second);
419    } else if (StartsWith(option, "-Ximage:")) {
420      parsed->image_ = option.substr(strlen("-Ximage:")).data();
421    } else if (StartsWith(option, "-Xcheck:jni")) {
422      parsed->check_jni_ = true;
423    } else if (StartsWith(option, "-Xrunjdwp:") || StartsWith(option, "-agentlib:jdwp=")) {
424      std::string tail(option.substr(option[1] == 'X' ? 10 : 15));
425      if (tail == "help" || !Dbg::ParseJdwpOptions(tail)) {
426        LOG(FATAL) << "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n"
427                   << "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n";
428        return NULL;
429      }
430    } else if (StartsWith(option, "-Xms")) {
431      size_t size = ParseMemoryOption(option.substr(strlen("-Xms")).c_str(), 1024);
432      if (size == 0) {
433        if (ignore_unrecognized) {
434          continue;
435        }
436        // TODO: usage
437        LOG(FATAL) << "Failed to parse " << option;
438        return NULL;
439      }
440      parsed->heap_initial_size_ = size;
441    } else if (StartsWith(option, "-Xmx")) {
442      size_t size = ParseMemoryOption(option.substr(strlen("-Xmx")).c_str(), 1024);
443      if (size == 0) {
444        if (ignore_unrecognized) {
445          continue;
446        }
447        // TODO: usage
448        LOG(FATAL) << "Failed to parse " << option;
449        return NULL;
450      }
451      parsed->heap_maximum_size_ = size;
452    } else if (StartsWith(option, "-XX:HeapGrowthLimit=")) {
453      size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapGrowthLimit=")).c_str(), 1024);
454      if (size == 0) {
455        if (ignore_unrecognized) {
456          continue;
457        }
458        // TODO: usage
459        LOG(FATAL) << "Failed to parse " << option;
460        return NULL;
461      }
462      parsed->heap_growth_limit_ = size;
463    } else if (StartsWith(option, "-XX:HeapMinFree=")) {
464      size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapMinFree=")).c_str(), 1024);
465      if (size == 0) {
466        if (ignore_unrecognized) {
467          continue;
468        }
469        // TODO: usage
470        LOG(FATAL) << "Failed to parse " << option;
471        return NULL;
472      }
473      parsed->heap_min_free_ = size;
474    } else if (StartsWith(option, "-XX:HeapMaxFree=")) {
475      size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapMaxFree=")).c_str(), 1024);
476      if (size == 0) {
477        if (ignore_unrecognized) {
478          continue;
479        }
480        // TODO: usage
481        LOG(FATAL) << "Failed to parse " << option;
482        return NULL;
483      }
484      parsed->heap_max_free_ = size;
485    } else if (StartsWith(option, "-XX:HeapTargetUtilization=")) {
486      std::istringstream iss(option.substr(strlen("-XX:HeapTargetUtilization=")));
487      double value;
488      iss >> value;
489      // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
490      const bool sane_val = iss.eof() && (value >= 0.1) && (value <= 0.9);
491      if (!sane_val) {
492        if (ignore_unrecognized) {
493          continue;
494        }
495        LOG(FATAL) << "Invalid option '" << option << "'";
496        return NULL;
497      }
498      parsed->heap_target_utilization_ = value;
499    } else if (StartsWith(option, "-XX:ParallelGCThreads=")) {
500      parsed->parallel_gc_threads_ =
501          ParseMemoryOption(option.substr(strlen("-XX:ParallelGCThreads=")).c_str(), 1024);
502    } else if (StartsWith(option, "-XX:ConcGCThreads=")) {
503      parsed->conc_gc_threads_ =
504          ParseMemoryOption(option.substr(strlen("-XX:ConcGCThreads=")).c_str(), 1024);
505    } else if (StartsWith(option, "-Xss")) {
506      size_t size = ParseMemoryOption(option.substr(strlen("-Xss")).c_str(), 1);
507      if (size == 0) {
508        if (ignore_unrecognized) {
509          continue;
510        }
511        // TODO: usage
512        LOG(FATAL) << "Failed to parse " << option;
513        return NULL;
514      }
515      parsed->stack_size_ = size;
516    } else if (StartsWith(option, "-XX:MaxSpinsBeforeThinLockInflation=")) {
517      parsed->max_spins_before_thin_lock_inflation_ =
518          strtoul(option.substr(strlen("-XX:MaxSpinsBeforeThinLockInflation=")).c_str(),
519                  nullptr, 10);
520    } else if (option == "-XX:LongPauseLogThreshold") {
521      parsed->long_pause_log_threshold_ =
522          ParseMemoryOption(option.substr(strlen("-XX:LongPauseLogThreshold=")).c_str(), 1024);
523    } else if (option == "-XX:LongGCLogThreshold") {
524          parsed->long_gc_log_threshold_ =
525              ParseMemoryOption(option.substr(strlen("-XX:LongGCLogThreshold")).c_str(), 1024);
526    } else if (option == "-XX:IgnoreMaxFootprint") {
527      parsed->ignore_max_footprint_ = true;
528    } else if (option == "-XX:LowMemoryMode") {
529      parsed->low_memory_mode_ = true;
530    } else if (StartsWith(option, "-D")) {
531      parsed->properties_.push_back(option.substr(strlen("-D")));
532    } else if (StartsWith(option, "-Xjnitrace:")) {
533      parsed->jni_trace_ = option.substr(strlen("-Xjnitrace:"));
534    } else if (option == "compiler") {
535      parsed->is_compiler_ = true;
536    } else if (option == "-Xzygote") {
537      parsed->is_zygote_ = true;
538    } else if (option == "-Xint") {
539      parsed->interpreter_only_ = true;
540    } else if (StartsWith(option, "-Xgc:")) {
541      std::vector<std::string> gc_options;
542      Split(option.substr(strlen("-Xgc:")), ',', gc_options);
543      for (size_t i = 0; i < gc_options.size(); ++i) {
544        if (gc_options[i] == "noconcurrent") {
545          parsed->is_concurrent_gc_enabled_ = false;
546        } else if (gc_options[i] == "concurrent") {
547          parsed->is_concurrent_gc_enabled_ = true;
548        } else {
549          LOG(WARNING) << "Ignoring unknown -Xgc option: " << gc_options[i];
550        }
551      }
552    } else if (option == "-XX:+DisableExplicitGC") {
553      parsed->is_explicit_gc_disabled_ = true;
554    } else if (StartsWith(option, "-verbose:")) {
555      std::vector<std::string> verbose_options;
556      Split(option.substr(strlen("-verbose:")), ',', verbose_options);
557      for (size_t i = 0; i < verbose_options.size(); ++i) {
558        if (verbose_options[i] == "class") {
559          gLogVerbosity.class_linker = true;
560        } else if (verbose_options[i] == "verifier") {
561          gLogVerbosity.verifier = true;
562        } else if (verbose_options[i] == "compiler") {
563          gLogVerbosity.compiler = true;
564        } else if (verbose_options[i] == "heap") {
565          gLogVerbosity.heap = true;
566        } else if (verbose_options[i] == "gc") {
567          gLogVerbosity.gc = true;
568        } else if (verbose_options[i] == "jdwp") {
569          gLogVerbosity.jdwp = true;
570        } else if (verbose_options[i] == "jni") {
571          gLogVerbosity.jni = true;
572        } else if (verbose_options[i] == "monitor") {
573          gLogVerbosity.monitor = true;
574        } else if (verbose_options[i] == "startup") {
575          gLogVerbosity.startup = true;
576        } else if (verbose_options[i] == "third-party-jni") {
577          gLogVerbosity.third_party_jni = true;
578        } else if (verbose_options[i] == "threads") {
579          gLogVerbosity.threads = true;
580        } else {
581          LOG(WARNING) << "Ignoring unknown -verbose option: " << verbose_options[i];
582        }
583      }
584    } else if (StartsWith(option, "-Xjnigreflimit:")) {
585      // Silently ignored for backwards compatibility.
586    } else if (StartsWith(option, "-Xlockprofthreshold:")) {
587      parsed->lock_profiling_threshold_ = ParseIntegerOrDie(option);
588    } else if (StartsWith(option, "-Xstacktracefile:")) {
589      parsed->stack_trace_file_ = option.substr(strlen("-Xstacktracefile:"));
590    } else if (option == "sensitiveThread") {
591      parsed->hook_is_sensitive_thread_ = reinterpret_cast<bool (*)()>(const_cast<void*>(options[i].second));
592    } else if (option == "vfprintf") {
593      parsed->hook_vfprintf_ =
594          reinterpret_cast<int (*)(FILE *, const char*, va_list)>(const_cast<void*>(options[i].second));
595    } else if (option == "exit") {
596      parsed->hook_exit_ = reinterpret_cast<void(*)(jint)>(const_cast<void*>(options[i].second));
597    } else if (option == "abort") {
598      parsed->hook_abort_ = reinterpret_cast<void(*)()>(const_cast<void*>(options[i].second));
599    } else if (option == "host-prefix") {
600      parsed->host_prefix_ = reinterpret_cast<const char*>(options[i].second);
601    } else if (option == "-Xgenregmap" || option == "-Xgc:precise") {
602      // We silently ignore these for backwards compatibility.
603    } else if (option == "-Xmethod-trace") {
604      parsed->method_trace_ = true;
605    } else if (StartsWith(option, "-Xmethod-trace-file:")) {
606      parsed->method_trace_file_ = option.substr(strlen("-Xmethod-trace-file:"));
607    } else if (StartsWith(option, "-Xmethod-trace-file-size:")) {
608      parsed->method_trace_file_size_ = ParseIntegerOrDie(option);
609    } else if (option == "-Xprofile:threadcpuclock") {
610      Trace::SetDefaultClockSource(kProfilerClockSourceThreadCpu);
611    } else if (option == "-Xprofile:wallclock") {
612      Trace::SetDefaultClockSource(kProfilerClockSourceWall);
613    } else if (option == "-Xprofile:dualclock") {
614      Trace::SetDefaultClockSource(kProfilerClockSourceDual);
615    } else if (option == "-compiler-filter:interpret-only") {
616      parsed->compiler_filter_ = kInterpretOnly;
617    } else if (option == "-compiler-filter:space") {
618      parsed->compiler_filter_ = kSpace;
619    } else if (option == "-compiler-filter:balanced") {
620      parsed->compiler_filter_ = kBalanced;
621    } else if (option == "-compiler-filter:speed") {
622      parsed->compiler_filter_ = kSpeed;
623    } else if (option == "-compiler-filter:everything") {
624      parsed->compiler_filter_ = kEverything;
625    } else if (option == "-sea_ir") {
626      parsed->sea_ir_mode_ = true;
627    } else if (StartsWith(option, "-huge-method-max:")) {
628      parsed->huge_method_threshold_ = ParseIntegerOrDie(option);
629    } else if (StartsWith(option, "-large-method-max:")) {
630      parsed->large_method_threshold_ = ParseIntegerOrDie(option);
631    } else if (StartsWith(option, "-small-method-max:")) {
632      parsed->small_method_threshold_ = ParseIntegerOrDie(option);
633    } else if (StartsWith(option, "-tiny-method-max:")) {
634      parsed->tiny_method_threshold_ = ParseIntegerOrDie(option);
635    } else if (StartsWith(option, "-num-dex-methods-max:")) {
636      parsed->num_dex_methods_threshold_ = ParseIntegerOrDie(option);
637    } else {
638      if (!ignore_unrecognized) {
639        // TODO: print usage via vfprintf
640        LOG(ERROR) << "Unrecognized option " << option;
641        // TODO: this should exit, but for now tolerate unknown options
642        // return NULL;
643      }
644    }
645  }
646
647  // If a reference to the dalvik core.jar snuck in, replace it with
648  // the art specific version. This can happen with on device
649  // boot.art/boot.oat generation by GenerateImage which relies on the
650  // value of BOOTCLASSPATH.
651  std::string core_jar("/core.jar");
652  size_t core_jar_pos = parsed->boot_class_path_string_.find(core_jar);
653  if (core_jar_pos != std::string::npos) {
654    parsed->boot_class_path_string_.replace(core_jar_pos, core_jar.size(), "/core-libart.jar");
655  }
656
657  if (!parsed->is_compiler_ && parsed->image_.empty()) {
658    parsed->image_ += GetAndroidRoot();
659    parsed->image_ += "/framework/boot.art";
660  }
661  if (parsed->heap_growth_limit_ == 0) {
662    parsed->heap_growth_limit_ = parsed->heap_maximum_size_;
663  }
664
665  return parsed.release();
666}
667
668bool Runtime::Create(const Options& options, bool ignore_unrecognized) {
669  // TODO: acquire a static mutex on Runtime to avoid racing.
670  if (Runtime::instance_ != NULL) {
671    return false;
672  }
673  InitLogging(NULL);  // Calls Locks::Init() as a side effect.
674  instance_ = new Runtime;
675  if (!instance_->Init(options, ignore_unrecognized)) {
676    delete instance_;
677    instance_ = NULL;
678    return false;
679  }
680  return true;
681}
682
683jobject CreateSystemClassLoader() {
684  if (Runtime::Current()->UseCompileTimeClassPath()) {
685    return NULL;
686  }
687
688  ScopedObjectAccess soa(Thread::Current());
689
690  mirror::Class* class_loader_class =
691      soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
692  CHECK(Runtime::Current()->GetClassLinker()->EnsureInitialized(class_loader_class, true, true));
693
694  mirror::ArtMethod* getSystemClassLoader =
695      class_loader_class->FindDirectMethod("getSystemClassLoader", "()Ljava/lang/ClassLoader;");
696  CHECK(getSystemClassLoader != NULL);
697
698  JValue result;
699  ArgArray arg_array(NULL, 0);
700  InvokeWithArgArray(soa, getSystemClassLoader, &arg_array, &result, 'L');
701  mirror::ClassLoader* class_loader = down_cast<mirror::ClassLoader*>(result.GetL());
702  CHECK(class_loader != NULL);
703
704  JNIEnv* env = soa.Self()->GetJniEnv();
705  ScopedLocalRef<jobject> system_class_loader(env, soa.AddLocalReference<jobject>(class_loader));
706  CHECK(system_class_loader.get() != NULL);
707
708  soa.Self()->SetClassLoaderOverride(class_loader);
709
710  mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
711  CHECK(Runtime::Current()->GetClassLinker()->EnsureInitialized(thread_class, true, true));
712
713  mirror::ArtField* contextClassLoader = thread_class->FindDeclaredInstanceField("contextClassLoader",
714                                                                                 "Ljava/lang/ClassLoader;");
715  CHECK(contextClassLoader != NULL);
716
717  contextClassLoader->SetObject(soa.Self()->GetPeer(), class_loader);
718
719  return env->NewGlobalRef(system_class_loader.get());
720}
721
722bool Runtime::Start() {
723  VLOG(startup) << "Runtime::Start entering";
724
725  CHECK(host_prefix_.empty()) << host_prefix_;
726
727  // Restore main thread state to kNative as expected by native code.
728  Thread* self = Thread::Current();
729  self->TransitionFromRunnableToSuspended(kNative);
730
731  started_ = true;
732
733  // InitNativeMethods needs to be after started_ so that the classes
734  // it touches will have methods linked to the oat file if necessary.
735  InitNativeMethods();
736
737  // Initialize well known thread group values that may be accessed threads while attaching.
738  InitThreadGroups(self);
739
740  Thread::FinishStartup();
741
742  if (is_zygote_) {
743    if (!InitZygote()) {
744      return false;
745    }
746  } else {
747    DidForkFromZygote();
748  }
749
750  StartDaemonThreads();
751
752  system_class_loader_ = CreateSystemClassLoader();
753
754  self->GetJniEnv()->locals.AssertEmpty();
755
756  VLOG(startup) << "Runtime::Start exiting";
757
758  finished_starting_ = true;
759
760  return true;
761}
762
763void Runtime::EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
764  DCHECK_GT(threads_being_born_, 0U);
765  threads_being_born_--;
766  if (shutting_down_started_ && threads_being_born_ == 0) {
767    shutdown_cond_->Broadcast(Thread::Current());
768  }
769}
770
771// Do zygote-mode-only initialization.
772bool Runtime::InitZygote() {
773  // zygote goes into its own process group
774  setpgid(0, 0);
775
776  // See storage config details at http://source.android.com/tech/storage/
777  // Create private mount namespace shared by all children
778  if (unshare(CLONE_NEWNS) == -1) {
779    PLOG(WARNING) << "Failed to unshare()";
780    return false;
781  }
782
783  // Mark rootfs as being a slave so that changes from default
784  // namespace only flow into our children.
785  if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) {
786    PLOG(WARNING) << "Failed to mount() rootfs as MS_SLAVE";
787    return false;
788  }
789
790  // Create a staging tmpfs that is shared by our children; they will
791  // bind mount storage into their respective private namespaces, which
792  // are isolated from each other.
793  const char* target_base = getenv("EMULATED_STORAGE_TARGET");
794  if (target_base != NULL) {
795    if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
796              "uid=0,gid=1028,mode=0751") == -1) {
797      LOG(WARNING) << "Failed to mount tmpfs to " << target_base;
798      return false;
799    }
800  }
801
802  return true;
803}
804
805void Runtime::DidForkFromZygote() {
806  is_zygote_ = false;
807
808  // Create the thread pool.
809  heap_->CreateThreadPool();
810
811  StartSignalCatcher();
812
813  // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
814  // this will pause the runtime, so we probably want this to come last.
815  Dbg::StartJdwp();
816}
817
818void Runtime::StartSignalCatcher() {
819  if (!is_zygote_) {
820    signal_catcher_ = new SignalCatcher(stack_trace_file_);
821  }
822}
823
824void Runtime::StartDaemonThreads() {
825  VLOG(startup) << "Runtime::StartDaemonThreads entering";
826
827  Thread* self = Thread::Current();
828
829  // Must be in the kNative state for calling native methods.
830  CHECK_EQ(self->GetState(), kNative);
831
832  JNIEnv* env = self->GetJniEnv();
833  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
834                            WellKnownClasses::java_lang_Daemons_start);
835  if (env->ExceptionCheck()) {
836    env->ExceptionDescribe();
837    LOG(FATAL) << "Error starting java.lang.Daemons";
838  }
839
840  VLOG(startup) << "Runtime::StartDaemonThreads exiting";
841}
842
843bool Runtime::Init(const Options& raw_options, bool ignore_unrecognized) {
844  CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
845
846  UniquePtr<ParsedOptions> options(ParsedOptions::Create(raw_options, ignore_unrecognized));
847  if (options.get() == NULL) {
848    LOG(ERROR) << "Failed to parse options";
849    return false;
850  }
851  VLOG(startup) << "Runtime::Init -verbose:startup enabled";
852
853  QuasiAtomic::Startup();
854
855  Monitor::Init(options->lock_profiling_threshold_, options->hook_is_sensitive_thread_);
856
857  host_prefix_ = options->host_prefix_;
858  boot_class_path_string_ = options->boot_class_path_string_;
859  class_path_string_ = options->class_path_string_;
860  properties_ = options->properties_;
861
862  is_compiler_ = options->is_compiler_;
863  is_zygote_ = options->is_zygote_;
864  is_concurrent_gc_enabled_ = options->is_concurrent_gc_enabled_;
865  is_explicit_gc_disabled_ = options->is_explicit_gc_disabled_;
866
867  compiler_filter_ = options->compiler_filter_;
868  huge_method_threshold_ = options->huge_method_threshold_;
869  large_method_threshold_ = options->large_method_threshold_;
870  small_method_threshold_ = options->small_method_threshold_;
871  tiny_method_threshold_ = options->tiny_method_threshold_;
872  num_dex_methods_threshold_ = options->num_dex_methods_threshold_;
873
874  sea_ir_mode_ = options->sea_ir_mode_;
875  vfprintf_ = options->hook_vfprintf_;
876  exit_ = options->hook_exit_;
877  abort_ = options->hook_abort_;
878
879  default_stack_size_ = options->stack_size_;
880  stack_trace_file_ = options->stack_trace_file_;
881
882  max_spins_before_thin_lock_inflation_ = options->max_spins_before_thin_lock_inflation_;
883
884  monitor_list_ = new MonitorList;
885  thread_list_ = new ThreadList;
886  intern_table_ = new InternTable;
887
888
889  if (options->interpreter_only_) {
890    GetInstrumentation()->ForceInterpretOnly();
891  }
892
893  heap_ = new gc::Heap(options->heap_initial_size_,
894                       options->heap_growth_limit_,
895                       options->heap_min_free_,
896                       options->heap_max_free_,
897                       options->heap_target_utilization_,
898                       options->heap_maximum_size_,
899                       options->image_,
900                       options->is_concurrent_gc_enabled_,
901                       options->parallel_gc_threads_,
902                       options->conc_gc_threads_,
903                       options->low_memory_mode_,
904                       options->long_pause_log_threshold_,
905                       options->long_gc_log_threshold_,
906                       options->ignore_max_footprint_);
907
908  BlockSignals();
909  InitPlatformSignalHandlers();
910
911  java_vm_ = new JavaVMExt(this, options.get());
912
913  Thread::Startup();
914
915  // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
916  // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
917  // thread, we do not get a java peer.
918  Thread* self = Thread::Attach("main", false, NULL, false);
919  CHECK_EQ(self->thin_lock_thread_id_, ThreadList::kMainThreadId);
920  CHECK(self != NULL);
921
922  // Set us to runnable so tools using a runtime can allocate and GC by default
923  self->TransitionFromSuspendedToRunnable();
924
925  // Now we're attached, we can take the heap locks and validate the heap.
926  GetHeap()->EnableObjectValidation();
927
928  CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
929  if (GetHeap()->GetContinuousSpaces()[0]->IsImageSpace()) {
930    class_linker_ = ClassLinker::CreateFromImage(intern_table_);
931  } else {
932    CHECK(options->boot_class_path_ != NULL);
933    CHECK_NE(options->boot_class_path_->size(), 0U);
934    class_linker_ = ClassLinker::CreateFromCompiler(*options->boot_class_path_, intern_table_);
935  }
936  CHECK(class_linker_ != NULL);
937  verifier::MethodVerifier::Init();
938
939  method_trace_ = options->method_trace_;
940  method_trace_file_ = options->method_trace_file_;
941  method_trace_file_size_ = options->method_trace_file_size_;
942
943  if (options->method_trace_) {
944    Trace::Start(options->method_trace_file_.c_str(), -1, options->method_trace_file_size_, 0,
945                 false, false, 0);
946  }
947
948  // Pre-allocate an OutOfMemoryError for the double-OOME case.
949  self->ThrowNewException(ThrowLocation(), "Ljava/lang/OutOfMemoryError;",
950                          "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
951  pre_allocated_OutOfMemoryError_ = self->GetException(NULL);
952  self->ClearException();
953
954  VLOG(startup) << "Runtime::Init exiting";
955  return true;
956}
957
958void Runtime::InitNativeMethods() {
959  VLOG(startup) << "Runtime::InitNativeMethods entering";
960  Thread* self = Thread::Current();
961  JNIEnv* env = self->GetJniEnv();
962
963  // Must be in the kNative state for calling native methods (JNI_OnLoad code).
964  CHECK_EQ(self->GetState(), kNative);
965
966  // First set up JniConstants, which is used by both the runtime's built-in native
967  // methods and libcore.
968  JniConstants::init(env);
969  WellKnownClasses::Init(env);
970
971  // Then set up the native methods provided by the runtime itself.
972  RegisterRuntimeNativeMethods(env);
973
974  // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
975  // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
976  // the library that implements System.loadLibrary!
977  {
978    std::string mapped_name(StringPrintf(OS_SHARED_LIB_FORMAT_STR, "javacore"));
979    std::string reason;
980    self->TransitionFromSuspendedToRunnable();
981    if (!instance_->java_vm_->LoadNativeLibrary(mapped_name, NULL, &reason)) {
982      LOG(FATAL) << "LoadNativeLibrary failed for \"" << mapped_name << "\": " << reason;
983    }
984    self->TransitionFromRunnableToSuspended(kNative);
985  }
986
987  // Initialize well known classes that may invoke runtime native methods.
988  WellKnownClasses::LateInit(env);
989
990  VLOG(startup) << "Runtime::InitNativeMethods exiting";
991}
992
993void Runtime::InitThreadGroups(Thread* self) {
994  JNIEnvExt* env = self->GetJniEnv();
995  ScopedJniEnvLocalRefState env_state(env);
996  main_thread_group_ =
997      env->NewGlobalRef(env->GetStaticObjectField(WellKnownClasses::java_lang_ThreadGroup,
998                                                  WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
999  CHECK(main_thread_group_ != NULL || IsCompiler());
1000  system_thread_group_ =
1001      env->NewGlobalRef(env->GetStaticObjectField(WellKnownClasses::java_lang_ThreadGroup,
1002                                                  WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
1003  CHECK(system_thread_group_ != NULL || IsCompiler());
1004}
1005
1006jobject Runtime::GetMainThreadGroup() const {
1007  CHECK(main_thread_group_ != NULL || IsCompiler());
1008  return main_thread_group_;
1009}
1010
1011jobject Runtime::GetSystemThreadGroup() const {
1012  CHECK(system_thread_group_ != NULL || IsCompiler());
1013  return system_thread_group_;
1014}
1015
1016jobject Runtime::GetSystemClassLoader() const {
1017  CHECK(system_class_loader_ != NULL || IsCompiler());
1018  return system_class_loader_;
1019}
1020
1021void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
1022#define REGISTER(FN) extern void FN(JNIEnv*); FN(env)
1023  // Register Throwable first so that registration of other native methods can throw exceptions
1024  REGISTER(register_java_lang_Throwable);
1025  REGISTER(register_dalvik_system_DexFile);
1026  REGISTER(register_dalvik_system_VMDebug);
1027  REGISTER(register_dalvik_system_VMRuntime);
1028  REGISTER(register_dalvik_system_VMStack);
1029  REGISTER(register_dalvik_system_Zygote);
1030  REGISTER(register_java_lang_Class);
1031  REGISTER(register_java_lang_DexCache);
1032  REGISTER(register_java_lang_Object);
1033  REGISTER(register_java_lang_Runtime);
1034  REGISTER(register_java_lang_String);
1035  REGISTER(register_java_lang_System);
1036  REGISTER(register_java_lang_Thread);
1037  REGISTER(register_java_lang_VMClassLoader);
1038  REGISTER(register_java_lang_reflect_Array);
1039  REGISTER(register_java_lang_reflect_Constructor);
1040  REGISTER(register_java_lang_reflect_Field);
1041  REGISTER(register_java_lang_reflect_Method);
1042  REGISTER(register_java_lang_reflect_Proxy);
1043  REGISTER(register_java_util_concurrent_atomic_AtomicLong);
1044  REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmServer);
1045  REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmVmInternal);
1046  REGISTER(register_sun_misc_Unsafe);
1047#undef REGISTER
1048}
1049
1050void Runtime::DumpForSigQuit(std::ostream& os) {
1051  GetClassLinker()->DumpForSigQuit(os);
1052  GetInternTable()->DumpForSigQuit(os);
1053  GetJavaVM()->DumpForSigQuit(os);
1054  GetHeap()->DumpForSigQuit(os);
1055  os << "\n";
1056
1057  thread_list_->DumpForSigQuit(os);
1058  BaseMutex::DumpAll(os);
1059}
1060
1061void Runtime::DumpLockHolders(std::ostream& os) {
1062  uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
1063  pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
1064  pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
1065  pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
1066  if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
1067    os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
1068       << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
1069       << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
1070       << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
1071  }
1072}
1073
1074void Runtime::SetStatsEnabled(bool new_state) {
1075  if (new_state == true) {
1076    GetStats()->Clear(~0);
1077    // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1078    Thread::Current()->GetStats()->Clear(~0);
1079    GetInstrumentation()->InstrumentQuickAllocEntryPoints();
1080  } else {
1081    GetInstrumentation()->UninstrumentQuickAllocEntryPoints();
1082  }
1083  stats_enabled_ = new_state;
1084}
1085
1086void Runtime::ResetStats(int kinds) {
1087  GetStats()->Clear(kinds & 0xffff);
1088  // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1089  Thread::Current()->GetStats()->Clear(kinds >> 16);
1090}
1091
1092int32_t Runtime::GetStat(int kind) {
1093  RuntimeStats* stats;
1094  if (kind < (1<<16)) {
1095    stats = GetStats();
1096  } else {
1097    stats = Thread::Current()->GetStats();
1098    kind >>= 16;
1099  }
1100  switch (kind) {
1101  case KIND_ALLOCATED_OBJECTS:
1102    return stats->allocated_objects;
1103  case KIND_ALLOCATED_BYTES:
1104    return stats->allocated_bytes;
1105  case KIND_FREED_OBJECTS:
1106    return stats->freed_objects;
1107  case KIND_FREED_BYTES:
1108    return stats->freed_bytes;
1109  case KIND_GC_INVOCATIONS:
1110    return stats->gc_for_alloc_count;
1111  case KIND_CLASS_INIT_COUNT:
1112    return stats->class_init_count;
1113  case KIND_CLASS_INIT_TIME:
1114    // Convert ns to us, reduce to 32 bits.
1115    return static_cast<int>(stats->class_init_time_ns / 1000);
1116  case KIND_EXT_ALLOCATED_OBJECTS:
1117  case KIND_EXT_ALLOCATED_BYTES:
1118  case KIND_EXT_FREED_OBJECTS:
1119  case KIND_EXT_FREED_BYTES:
1120    return 0;  // backward compatibility
1121  default:
1122    LOG(FATAL) << "Unknown statistic " << kind;
1123    return -1;  // unreachable
1124  }
1125}
1126
1127void Runtime::BlockSignals() {
1128  SignalSet signals;
1129  signals.Add(SIGPIPE);
1130  // SIGQUIT is used to dump the runtime's state (including stack traces).
1131  signals.Add(SIGQUIT);
1132  // SIGUSR1 is used to initiate a GC.
1133  signals.Add(SIGUSR1);
1134  signals.Block();
1135}
1136
1137bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
1138                                  bool create_peer) {
1139  bool success = Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != NULL;
1140  if (thread_name == NULL) {
1141    LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
1142  }
1143  return success;
1144}
1145
1146void Runtime::DetachCurrentThread() {
1147  Thread* self = Thread::Current();
1148  if (self == NULL) {
1149    LOG(FATAL) << "attempting to detach thread that is not attached";
1150  }
1151  if (self->HasManagedStack()) {
1152    LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
1153  }
1154  thread_list_->Unregister(self);
1155}
1156
1157  mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() const {
1158  if (pre_allocated_OutOfMemoryError_ == NULL) {
1159    LOG(ERROR) << "Failed to return pre-allocated OOME";
1160  }
1161  return pre_allocated_OutOfMemoryError_;
1162}
1163
1164void Runtime::VisitConcurrentRoots(RootVisitor* visitor, void* arg, bool only_dirty,
1165                                   bool clean_dirty) {
1166  intern_table_->VisitRoots(visitor, arg, only_dirty, clean_dirty);
1167  class_linker_->VisitRoots(visitor, arg, only_dirty, clean_dirty);
1168}
1169
1170void Runtime::VisitNonThreadRoots(RootVisitor* visitor, void* arg) {
1171  java_vm_->VisitRoots(visitor, arg);
1172  if (pre_allocated_OutOfMemoryError_ != nullptr) {
1173    pre_allocated_OutOfMemoryError_ = reinterpret_cast<mirror::Throwable*>(
1174        visitor(pre_allocated_OutOfMemoryError_, arg));
1175    DCHECK(pre_allocated_OutOfMemoryError_ != nullptr);
1176  }
1177  resolution_method_ = reinterpret_cast<mirror::ArtMethod*>(visitor(resolution_method_, arg));
1178  DCHECK(resolution_method_ != nullptr);
1179  imt_conflict_method_ = reinterpret_cast<mirror::ArtMethod*>(visitor(imt_conflict_method_, arg));
1180  DCHECK(imt_conflict_method_ != nullptr);
1181  default_imt_ = reinterpret_cast<mirror::ObjectArray<mirror::ArtMethod>*>(visitor(default_imt_, arg));
1182  DCHECK(default_imt_ != nullptr);
1183  for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1184    callee_save_methods_[i] = reinterpret_cast<mirror::ArtMethod*>(
1185        visitor(callee_save_methods_[i], arg));
1186    DCHECK(callee_save_methods_[i] != nullptr);
1187  }
1188}
1189
1190void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor, void* arg) {
1191  thread_list_->VisitRoots(visitor, arg);
1192  VisitNonThreadRoots(visitor, arg);
1193}
1194
1195void Runtime::VisitRoots(RootVisitor* visitor, void* arg, bool only_dirty, bool clean_dirty) {
1196  VisitConcurrentRoots(visitor, arg, only_dirty, clean_dirty);
1197  VisitNonConcurrentRoots(visitor, arg);
1198}
1199
1200mirror::ObjectArray<mirror::ArtMethod>* Runtime::CreateDefaultImt(ClassLinker* cl) {
1201  Thread* self = Thread::Current();
1202  SirtRef<mirror::ObjectArray<mirror::ArtMethod> > imtable(self, cl->AllocArtMethodArray(self, 64));
1203  mirror::ArtMethod* imt_conflict_method = Runtime::Current()->GetImtConflictMethod();
1204  for (size_t i = 0; i < 64; i++) {
1205    imtable->Set(i, imt_conflict_method);
1206  }
1207  return imtable.get();
1208}
1209
1210mirror::ArtMethod* Runtime::CreateImtConflictMethod() {
1211  mirror::Class* method_class = mirror::ArtMethod::GetJavaLangReflectArtMethod();
1212  Thread* self = Thread::Current();
1213  SirtRef<mirror::ArtMethod>
1214      method(self, down_cast<mirror::ArtMethod*>(method_class->AllocObject(self)));
1215  method->SetDeclaringClass(method_class);
1216  // TODO: use a special method for imt conflict method saves
1217  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1218  // When compiling, the code pointer will get set later when the image is loaded.
1219  Runtime* r = Runtime::Current();
1220  ClassLinker* cl = r->GetClassLinker();
1221  method->SetEntryPointFromCompiledCode(r->IsCompiler() ? NULL : GetImtConflictTrampoline(cl));
1222  return method.get();
1223}
1224
1225mirror::ArtMethod* Runtime::CreateResolutionMethod() {
1226  mirror::Class* method_class = mirror::ArtMethod::GetJavaLangReflectArtMethod();
1227  Thread* self = Thread::Current();
1228  SirtRef<mirror::ArtMethod>
1229      method(self, down_cast<mirror::ArtMethod*>(method_class->AllocObject(self)));
1230  method->SetDeclaringClass(method_class);
1231  // TODO: use a special method for resolution method saves
1232  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1233  // When compiling, the code pointer will get set later when the image is loaded.
1234  Runtime* r = Runtime::Current();
1235  ClassLinker* cl = r->GetClassLinker();
1236  method->SetEntryPointFromCompiledCode(r->IsCompiler() ? NULL : GetResolutionTrampoline(cl));
1237  return method.get();
1238}
1239
1240mirror::ArtMethod* Runtime::CreateCalleeSaveMethod(InstructionSet instruction_set,
1241                                                        CalleeSaveType type) {
1242  mirror::Class* method_class = mirror::ArtMethod::GetJavaLangReflectArtMethod();
1243  Thread* self = Thread::Current();
1244  SirtRef<mirror::ArtMethod>
1245      method(self, down_cast<mirror::ArtMethod*>(method_class->AllocObject(self)));
1246  method->SetDeclaringClass(method_class);
1247  // TODO: use a special method for callee saves
1248  method->SetDexMethodIndex(DexFile::kDexNoIndex);
1249  method->SetEntryPointFromCompiledCode(NULL);
1250  if ((instruction_set == kThumb2) || (instruction_set == kArm)) {
1251    uint32_t ref_spills = (1 << art::arm::R5) | (1 << art::arm::R6)  | (1 << art::arm::R7) |
1252                          (1 << art::arm::R8) | (1 << art::arm::R10) | (1 << art::arm::R11);
1253    uint32_t arg_spills = (1 << art::arm::R1) | (1 << art::arm::R2) | (1 << art::arm::R3);
1254    uint32_t all_spills = (1 << art::arm::R4) | (1 << art::arm::R9);
1255    uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills : 0) |
1256                           (type == kSaveAll ? all_spills : 0) | (1 << art::arm::LR);
1257    uint32_t fp_all_spills = (1 << art::arm::S0)  | (1 << art::arm::S1)  | (1 << art::arm::S2) |
1258                             (1 << art::arm::S3)  | (1 << art::arm::S4)  | (1 << art::arm::S5) |
1259                             (1 << art::arm::S6)  | (1 << art::arm::S7)  | (1 << art::arm::S8) |
1260                             (1 << art::arm::S9)  | (1 << art::arm::S10) | (1 << art::arm::S11) |
1261                             (1 << art::arm::S12) | (1 << art::arm::S13) | (1 << art::arm::S14) |
1262                             (1 << art::arm::S15) | (1 << art::arm::S16) | (1 << art::arm::S17) |
1263                             (1 << art::arm::S18) | (1 << art::arm::S19) | (1 << art::arm::S20) |
1264                             (1 << art::arm::S21) | (1 << art::arm::S22) | (1 << art::arm::S23) |
1265                             (1 << art::arm::S24) | (1 << art::arm::S25) | (1 << art::arm::S26) |
1266                             (1 << art::arm::S27) | (1 << art::arm::S28) | (1 << art::arm::S29) |
1267                             (1 << art::arm::S30) | (1 << art::arm::S31);
1268    uint32_t fp_spills = type == kSaveAll ? fp_all_spills : 0;
1269    size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
1270                                 __builtin_popcount(fp_spills) /* fprs */ +
1271                                 1 /* Method* */) * kPointerSize, kStackAlignment);
1272    method->SetFrameSizeInBytes(frame_size);
1273    method->SetCoreSpillMask(core_spills);
1274    method->SetFpSpillMask(fp_spills);
1275  } else if (instruction_set == kMips) {
1276    uint32_t ref_spills = (1 << art::mips::S2) | (1 << art::mips::S3) | (1 << art::mips::S4) |
1277                          (1 << art::mips::S5) | (1 << art::mips::S6) | (1 << art::mips::S7) |
1278                          (1 << art::mips::GP) | (1 << art::mips::FP);
1279    uint32_t arg_spills = (1 << art::mips::A1) | (1 << art::mips::A2) | (1 << art::mips::A3);
1280    uint32_t all_spills = (1 << art::mips::S0) | (1 << art::mips::S1);
1281    uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills : 0) |
1282                           (type == kSaveAll ? all_spills : 0) | (1 << art::mips::RA);
1283    size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
1284                                (type == kRefsAndArgs ? 0 : 3) + 1 /* Method* */) *
1285                                kPointerSize, kStackAlignment);
1286    method->SetFrameSizeInBytes(frame_size);
1287    method->SetCoreSpillMask(core_spills);
1288    method->SetFpSpillMask(0);
1289  } else if (instruction_set == kX86) {
1290    uint32_t ref_spills = (1 << art::x86::EBP) | (1 << art::x86::ESI) | (1 << art::x86::EDI);
1291    uint32_t arg_spills = (1 << art::x86::ECX) | (1 << art::x86::EDX) | (1 << art::x86::EBX);
1292    uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills : 0) |
1293                         (1 << art::x86::kNumberOfCpuRegisters);  // fake return address callee save
1294    size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
1295                                 1 /* Method* */) * kPointerSize, kStackAlignment);
1296    method->SetFrameSizeInBytes(frame_size);
1297    method->SetCoreSpillMask(core_spills);
1298    method->SetFpSpillMask(0);
1299  } else {
1300    UNIMPLEMENTED(FATAL);
1301  }
1302  return method.get();
1303}
1304
1305void Runtime::DisallowNewSystemWeaks() {
1306  monitor_list_->DisallowNewMonitors();
1307  intern_table_->DisallowNewInterns();
1308  java_vm_->DisallowNewWeakGlobals();
1309}
1310
1311void Runtime::AllowNewSystemWeaks() {
1312  monitor_list_->AllowNewMonitors();
1313  intern_table_->AllowNewInterns();
1314  java_vm_->AllowNewWeakGlobals();
1315}
1316
1317void Runtime::SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type) {
1318  DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1319  callee_save_methods_[type] = method;
1320}
1321
1322const std::vector<const DexFile*>& Runtime::GetCompileTimeClassPath(jobject class_loader) {
1323  if (class_loader == NULL) {
1324    return GetClassLinker()->GetBootClassPath();
1325  }
1326  CHECK(UseCompileTimeClassPath());
1327  CompileTimeClassPaths::const_iterator it = compile_time_class_paths_.find(class_loader);
1328  CHECK(it != compile_time_class_paths_.end());
1329  return it->second;
1330}
1331
1332void Runtime::SetCompileTimeClassPath(jobject class_loader, std::vector<const DexFile*>& class_path) {
1333  CHECK(!IsStarted());
1334  use_compile_time_class_path_ = true;
1335  compile_time_class_paths_.Put(class_loader, class_path);
1336}
1337
1338}  // namespace art
1339