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