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