• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
67 namespace art {
68 
69 Runtime* Runtime::instance_ = NULL;
70 
Runtime()71 Runtime::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       threads_being_born_(0),
87       shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
88       shutting_down_(false),
89       shutting_down_started_(false),
90       started_(false),
91       finished_starting_(false),
92       vfprintf_(NULL),
93       exit_(NULL),
94       abort_(NULL),
95       stats_enabled_(false),
96       method_trace_(0),
97       method_trace_file_size_(0),
98       instrumentation_(),
99       use_compile_time_class_path_(false),
100       main_thread_group_(NULL),
101       system_thread_group_(NULL),
102       system_class_loader_(NULL) {
103   for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
104     callee_save_methods_[i] = NULL;
105   }
106 }
107 
~Runtime()108 Runtime::~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 
143 struct AbortState {
Dumpart::AbortState144   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 
DumpAllThreadsart::AbortState176   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 
Abort()190 void 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 
PreZygoteFork()229 bool Runtime::PreZygoteFork() {
230   heap_->PreZygoteFork();
231   return true;
232 }
233 
CallExitHook(jint status)234 void 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 //
ParseMemoryOption(const char * s,size_t div)256 size_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 
ParseIntegerOrDie(const std::string & s)308 size_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 
Create(const Options & options,bool ignore_unrecognized)322 Runtime::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->parallel_gc_threads_ = sysconf(_SC_NPROCESSORS_CONF) - 1;
343   // Only the main GC thread, no workers.
344   parsed->conc_gc_threads_ = 0;
345   parsed->stack_size_ = 0;  // 0 means default.
346   parsed->low_memory_mode_ = false;
347 
348   parsed->is_compiler_ = false;
349   parsed->is_zygote_ = false;
350   parsed->interpreter_only_ = false;
351   parsed->is_concurrent_gc_enabled_ = true;
352   parsed->is_explicit_gc_disabled_ = false;
353 
354   parsed->long_pause_log_threshold_ = gc::Heap::kDefaultLongPauseLogThreshold;
355   parsed->long_gc_log_threshold_ = gc::Heap::kDefaultLongGCLogThreshold;
356   parsed->ignore_max_footprint_ = false;
357 
358   parsed->lock_profiling_threshold_ = 0;
359   parsed->hook_is_sensitive_thread_ = NULL;
360 
361   parsed->hook_vfprintf_ = vfprintf;
362   parsed->hook_exit_ = exit;
363   parsed->hook_abort_ = NULL;  // We don't call abort(3) by default; see Runtime::Abort.
364 
365   parsed->compiler_filter_ = Runtime::kDefaultCompilerFilter;
366   parsed->huge_method_threshold_ = Runtime::kDefaultHugeMethodThreshold;
367   parsed->large_method_threshold_ = Runtime::kDefaultLargeMethodThreshold;
368   parsed->small_method_threshold_ = Runtime::kDefaultSmallMethodThreshold;
369   parsed->tiny_method_threshold_ = Runtime::kDefaultTinyMethodThreshold;
370   parsed->num_dex_methods_threshold_ = Runtime::kDefaultNumDexMethodsThreshold;
371 
372   parsed->sea_ir_mode_ = false;
373 //  gLogVerbosity.class_linker = true;  // TODO: don't check this in!
374 //  gLogVerbosity.compiler = true;  // TODO: don't check this in!
375 //  gLogVerbosity.verifier = true;  // TODO: don't check this in!
376 //  gLogVerbosity.heap = true;  // TODO: don't check this in!
377 //  gLogVerbosity.gc = true;  // TODO: don't check this in!
378 //  gLogVerbosity.jdwp = true;  // TODO: don't check this in!
379 //  gLogVerbosity.jni = true;  // TODO: don't check this in!
380 //  gLogVerbosity.monitor = true;  // TODO: don't check this in!
381 //  gLogVerbosity.startup = true;  // TODO: don't check this in!
382 //  gLogVerbosity.third_party_jni = true;  // TODO: don't check this in!
383 //  gLogVerbosity.threads = true;  // TODO: don't check this in!
384 
385   parsed->method_trace_ = false;
386   parsed->method_trace_file_ = "/data/method-trace-file.bin";
387   parsed->method_trace_file_size_ = 10 * MB;
388 
389   for (size_t i = 0; i < options.size(); ++i) {
390     const std::string option(options[i].first);
391     if (true && options[0].first == "-Xzygote") {
392       LOG(INFO) << "option[" << i << "]=" << option;
393     }
394     if (StartsWith(option, "-Xbootclasspath:")) {
395       parsed->boot_class_path_string_ = option.substr(strlen("-Xbootclasspath:")).data();
396     } else if (option == "-classpath" || option == "-cp") {
397       // TODO: support -Djava.class.path
398       i++;
399       if (i == options.size()) {
400         // TODO: usage
401         LOG(FATAL) << "Missing required class path value for " << option;
402         return NULL;
403       }
404       const StringPiece& value = options[i].first;
405       parsed->class_path_string_ = value.data();
406     } else if (option == "bootclasspath") {
407       parsed->boot_class_path_
408           = reinterpret_cast<const std::vector<const DexFile*>*>(options[i].second);
409     } else if (StartsWith(option, "-Ximage:")) {
410       parsed->image_ = option.substr(strlen("-Ximage:")).data();
411     } else if (StartsWith(option, "-Xcheck:jni")) {
412       parsed->check_jni_ = true;
413     } else if (StartsWith(option, "-Xrunjdwp:") || StartsWith(option, "-agentlib:jdwp=")) {
414       std::string tail(option.substr(option[1] == 'X' ? 10 : 15));
415       if (tail == "help" || !Dbg::ParseJdwpOptions(tail)) {
416         LOG(FATAL) << "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n"
417                    << "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n";
418         return NULL;
419       }
420     } else if (StartsWith(option, "-Xms")) {
421       size_t size = ParseMemoryOption(option.substr(strlen("-Xms")).c_str(), 1024);
422       if (size == 0) {
423         if (ignore_unrecognized) {
424           continue;
425         }
426         // TODO: usage
427         LOG(FATAL) << "Failed to parse " << option;
428         return NULL;
429       }
430       parsed->heap_initial_size_ = size;
431     } else if (StartsWith(option, "-Xmx")) {
432       size_t size = ParseMemoryOption(option.substr(strlen("-Xmx")).c_str(), 1024);
433       if (size == 0) {
434         if (ignore_unrecognized) {
435           continue;
436         }
437         // TODO: usage
438         LOG(FATAL) << "Failed to parse " << option;
439         return NULL;
440       }
441       parsed->heap_maximum_size_ = size;
442     } else if (StartsWith(option, "-XX:HeapGrowthLimit=")) {
443       size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapGrowthLimit=")).c_str(), 1024);
444       if (size == 0) {
445         if (ignore_unrecognized) {
446           continue;
447         }
448         // TODO: usage
449         LOG(FATAL) << "Failed to parse " << option;
450         return NULL;
451       }
452       parsed->heap_growth_limit_ = size;
453     } else if (StartsWith(option, "-XX:HeapMinFree=")) {
454       size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapMinFree=")).c_str(), 1024);
455       if (size == 0) {
456         if (ignore_unrecognized) {
457           continue;
458         }
459         // TODO: usage
460         LOG(FATAL) << "Failed to parse " << option;
461         return NULL;
462       }
463       parsed->heap_min_free_ = size;
464     } else if (StartsWith(option, "-XX:HeapMaxFree=")) {
465       size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapMaxFree=")).c_str(), 1024);
466       if (size == 0) {
467         if (ignore_unrecognized) {
468           continue;
469         }
470         // TODO: usage
471         LOG(FATAL) << "Failed to parse " << option;
472         return NULL;
473       }
474       parsed->heap_max_free_ = size;
475     } else if (StartsWith(option, "-XX:HeapTargetUtilization=")) {
476       std::istringstream iss(option.substr(strlen("-XX:HeapTargetUtilization=")));
477       double value;
478       iss >> value;
479       // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
480       const bool sane_val = iss.eof() && (value >= 0.1) && (value <= 0.9);
481       if (!sane_val) {
482         if (ignore_unrecognized) {
483           continue;
484         }
485         LOG(FATAL) << "Invalid option '" << option << "'";
486         return NULL;
487       }
488       parsed->heap_target_utilization_ = value;
489     } else if (StartsWith(option, "-XX:ParallelGCThreads=")) {
490       parsed->parallel_gc_threads_ =
491           ParseMemoryOption(option.substr(strlen("-XX:ParallelGCThreads=")).c_str(), 1024);
492     } else if (StartsWith(option, "-XX:ConcGCThreads=")) {
493       parsed->conc_gc_threads_ =
494           ParseMemoryOption(option.substr(strlen("-XX:ConcGCThreads=")).c_str(), 1024);
495     } else if (StartsWith(option, "-Xss")) {
496       size_t size = ParseMemoryOption(option.substr(strlen("-Xss")).c_str(), 1);
497       if (size == 0) {
498         if (ignore_unrecognized) {
499           continue;
500         }
501         // TODO: usage
502         LOG(FATAL) << "Failed to parse " << option;
503         return NULL;
504       }
505       parsed->stack_size_ = size;
506     } else if (option == "-XX:LongPauseLogThreshold") {
507       parsed->long_pause_log_threshold_ =
508           ParseMemoryOption(option.substr(strlen("-XX:LongPauseLogThreshold=")).c_str(), 1024);
509     } else if (option == "-XX:LongGCLogThreshold") {
510           parsed->long_gc_log_threshold_ =
511               ParseMemoryOption(option.substr(strlen("-XX:LongGCLogThreshold")).c_str(), 1024);
512     } else if (option == "-XX:IgnoreMaxFootprint") {
513       parsed->ignore_max_footprint_ = true;
514     } else if (option == "-XX:LowMemoryMode") {
515       parsed->low_memory_mode_ = true;
516     } else if (StartsWith(option, "-D")) {
517       parsed->properties_.push_back(option.substr(strlen("-D")));
518     } else if (StartsWith(option, "-Xjnitrace:")) {
519       parsed->jni_trace_ = option.substr(strlen("-Xjnitrace:"));
520     } else if (option == "compiler") {
521       parsed->is_compiler_ = true;
522     } else if (option == "-Xzygote") {
523       parsed->is_zygote_ = true;
524     } else if (option == "-Xint") {
525       parsed->interpreter_only_ = true;
526     } else if (StartsWith(option, "-Xgc:")) {
527       std::vector<std::string> gc_options;
528       Split(option.substr(strlen("-Xgc:")), ',', gc_options);
529       for (size_t i = 0; i < gc_options.size(); ++i) {
530         if (gc_options[i] == "noconcurrent") {
531           parsed->is_concurrent_gc_enabled_ = false;
532         } else if (gc_options[i] == "concurrent") {
533           parsed->is_concurrent_gc_enabled_ = true;
534         } else {
535           LOG(WARNING) << "Ignoring unknown -Xgc option: " << gc_options[i];
536         }
537       }
538     } else if (option == "-XX:+DisableExplicitGC") {
539       parsed->is_explicit_gc_disabled_ = true;
540     } else if (StartsWith(option, "-verbose:")) {
541       std::vector<std::string> verbose_options;
542       Split(option.substr(strlen("-verbose:")), ',', verbose_options);
543       for (size_t i = 0; i < verbose_options.size(); ++i) {
544         if (verbose_options[i] == "class") {
545           gLogVerbosity.class_linker = true;
546         } else if (verbose_options[i] == "verifier") {
547           gLogVerbosity.verifier = true;
548         } else if (verbose_options[i] == "compiler") {
549           gLogVerbosity.compiler = true;
550         } else if (verbose_options[i] == "heap") {
551           gLogVerbosity.heap = true;
552         } else if (verbose_options[i] == "gc") {
553           gLogVerbosity.gc = true;
554         } else if (verbose_options[i] == "jdwp") {
555           gLogVerbosity.jdwp = true;
556         } else if (verbose_options[i] == "jni") {
557           gLogVerbosity.jni = true;
558         } else if (verbose_options[i] == "monitor") {
559           gLogVerbosity.monitor = true;
560         } else if (verbose_options[i] == "startup") {
561           gLogVerbosity.startup = true;
562         } else if (verbose_options[i] == "third-party-jni") {
563           gLogVerbosity.third_party_jni = true;
564         } else if (verbose_options[i] == "threads") {
565           gLogVerbosity.threads = true;
566         } else {
567           LOG(WARNING) << "Ignoring unknown -verbose option: " << verbose_options[i];
568         }
569       }
570     } else if (StartsWith(option, "-Xjnigreflimit:")) {
571       // Silently ignored for backwards compatibility.
572     } else if (StartsWith(option, "-Xlockprofthreshold:")) {
573       parsed->lock_profiling_threshold_ = ParseIntegerOrDie(option);
574     } else if (StartsWith(option, "-Xstacktracefile:")) {
575       parsed->stack_trace_file_ = option.substr(strlen("-Xstacktracefile:"));
576     } else if (option == "sensitiveThread") {
577       parsed->hook_is_sensitive_thread_ = reinterpret_cast<bool (*)()>(const_cast<void*>(options[i].second));
578     } else if (option == "vfprintf") {
579       parsed->hook_vfprintf_ =
580           reinterpret_cast<int (*)(FILE *, const char*, va_list)>(const_cast<void*>(options[i].second));
581     } else if (option == "exit") {
582       parsed->hook_exit_ = reinterpret_cast<void(*)(jint)>(const_cast<void*>(options[i].second));
583     } else if (option == "abort") {
584       parsed->hook_abort_ = reinterpret_cast<void(*)()>(const_cast<void*>(options[i].second));
585     } else if (option == "host-prefix") {
586       parsed->host_prefix_ = reinterpret_cast<const char*>(options[i].second);
587     } else if (option == "-Xgenregmap" || option == "-Xgc:precise") {
588       // We silently ignore these for backwards compatibility.
589     } else if (option == "-Xmethod-trace") {
590       parsed->method_trace_ = true;
591     } else if (StartsWith(option, "-Xmethod-trace-file:")) {
592       parsed->method_trace_file_ = option.substr(strlen("-Xmethod-trace-file:"));
593     } else if (StartsWith(option, "-Xmethod-trace-file-size:")) {
594       parsed->method_trace_file_size_ = ParseIntegerOrDie(option);
595     } else if (option == "-Xprofile:threadcpuclock") {
596       Trace::SetDefaultClockSource(kProfilerClockSourceThreadCpu);
597     } else if (option == "-Xprofile:wallclock") {
598       Trace::SetDefaultClockSource(kProfilerClockSourceWall);
599     } else if (option == "-Xprofile:dualclock") {
600       Trace::SetDefaultClockSource(kProfilerClockSourceDual);
601     } else if (option == "-compiler-filter:interpret-only") {
602       parsed->compiler_filter_ = kInterpretOnly;
603     } else if (option == "-compiler-filter:space") {
604       parsed->compiler_filter_ = kSpace;
605     } else if (option == "-compiler-filter:balanced") {
606       parsed->compiler_filter_ = kBalanced;
607     } else if (option == "-compiler-filter:speed") {
608       parsed->compiler_filter_ = kSpeed;
609     } else if (option == "-compiler-filter:everything") {
610       parsed->compiler_filter_ = kEverything;
611     } else if (option == "-sea_ir") {
612       parsed->sea_ir_mode_ = true;
613     } else if (StartsWith(option, "-huge-method-max:")) {
614       parsed->huge_method_threshold_ = ParseIntegerOrDie(option);
615     } else if (StartsWith(option, "-large-method-max:")) {
616       parsed->large_method_threshold_ = ParseIntegerOrDie(option);
617     } else if (StartsWith(option, "-small-method-max:")) {
618       parsed->small_method_threshold_ = ParseIntegerOrDie(option);
619     } else if (StartsWith(option, "-tiny-method-max:")) {
620       parsed->tiny_method_threshold_ = ParseIntegerOrDie(option);
621     } else if (StartsWith(option, "-num-dex-methods-max:")) {
622       parsed->num_dex_methods_threshold_ = ParseIntegerOrDie(option);
623     } else {
624       if (!ignore_unrecognized) {
625         // TODO: print usage via vfprintf
626         LOG(ERROR) << "Unrecognized option " << option;
627         // TODO: this should exit, but for now tolerate unknown options
628         // return NULL;
629       }
630     }
631   }
632 
633   // If a reference to the dalvik core.jar snuck in, replace it with
634   // the art specific version. This can happen with on device
635   // boot.art/boot.oat generation by GenerateImage which relies on the
636   // value of BOOTCLASSPATH.
637   std::string core_jar("/core.jar");
638   size_t core_jar_pos = parsed->boot_class_path_string_.find(core_jar);
639   if (core_jar_pos != std::string::npos) {
640     parsed->boot_class_path_string_.replace(core_jar_pos, core_jar.size(), "/core-libart.jar");
641   }
642 
643   if (!parsed->is_compiler_ && parsed->image_.empty()) {
644     parsed->image_ += GetAndroidRoot();
645     parsed->image_ += "/framework/boot.art";
646   }
647   if (parsed->heap_growth_limit_ == 0) {
648     parsed->heap_growth_limit_ = parsed->heap_maximum_size_;
649   }
650 
651   return parsed.release();
652 }
653 
Create(const Options & options,bool ignore_unrecognized)654 bool Runtime::Create(const Options& options, bool ignore_unrecognized) {
655   // TODO: acquire a static mutex on Runtime to avoid racing.
656   if (Runtime::instance_ != NULL) {
657     return false;
658   }
659   InitLogging(NULL);  // Calls Locks::Init() as a side effect.
660   instance_ = new Runtime;
661   if (!instance_->Init(options, ignore_unrecognized)) {
662     delete instance_;
663     instance_ = NULL;
664     return false;
665   }
666   return true;
667 }
668 
CreateSystemClassLoader()669 jobject CreateSystemClassLoader() {
670   if (Runtime::Current()->UseCompileTimeClassPath()) {
671     return NULL;
672   }
673 
674   ScopedObjectAccess soa(Thread::Current());
675 
676   mirror::Class* class_loader_class =
677       soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader);
678   CHECK(Runtime::Current()->GetClassLinker()->EnsureInitialized(class_loader_class, true, true));
679 
680   mirror::ArtMethod* getSystemClassLoader =
681       class_loader_class->FindDirectMethod("getSystemClassLoader", "()Ljava/lang/ClassLoader;");
682   CHECK(getSystemClassLoader != NULL);
683 
684   JValue result;
685   ArgArray arg_array(NULL, 0);
686   InvokeWithArgArray(soa, getSystemClassLoader, &arg_array, &result, 'L');
687   mirror::ClassLoader* class_loader = down_cast<mirror::ClassLoader*>(result.GetL());
688   CHECK(class_loader != NULL);
689 
690   JNIEnv* env = soa.Self()->GetJniEnv();
691   ScopedLocalRef<jobject> system_class_loader(env, soa.AddLocalReference<jobject>(class_loader));
692   CHECK(system_class_loader.get() != NULL);
693 
694   soa.Self()->SetClassLoaderOverride(class_loader);
695 
696   mirror::Class* thread_class = soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread);
697   CHECK(Runtime::Current()->GetClassLinker()->EnsureInitialized(thread_class, true, true));
698 
699   mirror::ArtField* contextClassLoader = thread_class->FindDeclaredInstanceField("contextClassLoader",
700                                                                                  "Ljava/lang/ClassLoader;");
701   CHECK(contextClassLoader != NULL);
702 
703   contextClassLoader->SetObject(soa.Self()->GetPeer(), class_loader);
704 
705   return env->NewGlobalRef(system_class_loader.get());
706 }
707 
Start()708 bool Runtime::Start() {
709   VLOG(startup) << "Runtime::Start entering";
710 
711   CHECK(host_prefix_.empty()) << host_prefix_;
712 
713   // Restore main thread state to kNative as expected by native code.
714   Thread* self = Thread::Current();
715   self->TransitionFromRunnableToSuspended(kNative);
716 
717   started_ = true;
718 
719   // InitNativeMethods needs to be after started_ so that the classes
720   // it touches will have methods linked to the oat file if necessary.
721   InitNativeMethods();
722 
723   // Initialize well known thread group values that may be accessed threads while attaching.
724   InitThreadGroups(self);
725 
726   Thread::FinishStartup();
727 
728   if (is_zygote_) {
729     if (!InitZygote()) {
730       return false;
731     }
732   } else {
733     DidForkFromZygote();
734   }
735 
736   StartDaemonThreads();
737 
738   system_class_loader_ = CreateSystemClassLoader();
739 
740   self->GetJniEnv()->locals.AssertEmpty();
741 
742   VLOG(startup) << "Runtime::Start exiting";
743 
744   finished_starting_ = true;
745 
746   return true;
747 }
748 
EndThreadBirth()749 void Runtime::EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
750   DCHECK_GT(threads_being_born_, 0U);
751   threads_being_born_--;
752   if (shutting_down_started_ && threads_being_born_ == 0) {
753     shutdown_cond_->Broadcast(Thread::Current());
754   }
755 }
756 
757 // Do zygote-mode-only initialization.
InitZygote()758 bool Runtime::InitZygote() {
759   // zygote goes into its own process group
760   setpgid(0, 0);
761 
762   // See storage config details at http://source.android.com/tech/storage/
763   // Create private mount namespace shared by all children
764   if (unshare(CLONE_NEWNS) == -1) {
765     PLOG(WARNING) << "Failed to unshare()";
766     return false;
767   }
768 
769   // Mark rootfs as being a slave so that changes from default
770   // namespace only flow into our children.
771   if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) {
772     PLOG(WARNING) << "Failed to mount() rootfs as MS_SLAVE";
773     return false;
774   }
775 
776   // Create a staging tmpfs that is shared by our children; they will
777   // bind mount storage into their respective private namespaces, which
778   // are isolated from each other.
779   const char* target_base = getenv("EMULATED_STORAGE_TARGET");
780   if (target_base != NULL) {
781     if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
782               "uid=0,gid=1028,mode=0751") == -1) {
783       LOG(WARNING) << "Failed to mount tmpfs to " << target_base;
784       return false;
785     }
786   }
787 
788   return true;
789 }
790 
DidForkFromZygote()791 void Runtime::DidForkFromZygote() {
792   is_zygote_ = false;
793 
794   // Create the thread pool.
795   heap_->CreateThreadPool();
796 
797   StartSignalCatcher();
798 
799   // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
800   // this will pause the runtime, so we probably want this to come last.
801   Dbg::StartJdwp();
802 }
803 
StartSignalCatcher()804 void Runtime::StartSignalCatcher() {
805   if (!is_zygote_) {
806     signal_catcher_ = new SignalCatcher(stack_trace_file_);
807   }
808 }
809 
StartDaemonThreads()810 void Runtime::StartDaemonThreads() {
811   VLOG(startup) << "Runtime::StartDaemonThreads entering";
812 
813   Thread* self = Thread::Current();
814 
815   // Must be in the kNative state for calling native methods.
816   CHECK_EQ(self->GetState(), kNative);
817 
818   JNIEnv* env = self->GetJniEnv();
819   env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
820                             WellKnownClasses::java_lang_Daemons_start);
821   if (env->ExceptionCheck()) {
822     env->ExceptionDescribe();
823     LOG(FATAL) << "Error starting java.lang.Daemons";
824   }
825 
826   VLOG(startup) << "Runtime::StartDaemonThreads exiting";
827 }
828 
Init(const Options & raw_options,bool ignore_unrecognized)829 bool Runtime::Init(const Options& raw_options, bool ignore_unrecognized) {
830   CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
831 
832   UniquePtr<ParsedOptions> options(ParsedOptions::Create(raw_options, ignore_unrecognized));
833   if (options.get() == NULL) {
834     LOG(ERROR) << "Failed to parse options";
835     return false;
836   }
837   VLOG(startup) << "Runtime::Init -verbose:startup enabled";
838 
839   QuasiAtomic::Startup();
840 
841   Monitor::Init(options->lock_profiling_threshold_, options->hook_is_sensitive_thread_);
842 
843   host_prefix_ = options->host_prefix_;
844   boot_class_path_string_ = options->boot_class_path_string_;
845   class_path_string_ = options->class_path_string_;
846   properties_ = options->properties_;
847 
848   is_compiler_ = options->is_compiler_;
849   is_zygote_ = options->is_zygote_;
850   is_concurrent_gc_enabled_ = options->is_concurrent_gc_enabled_;
851   is_explicit_gc_disabled_ = options->is_explicit_gc_disabled_;
852 
853   compiler_filter_ = options->compiler_filter_;
854   huge_method_threshold_ = options->huge_method_threshold_;
855   large_method_threshold_ = options->large_method_threshold_;
856   small_method_threshold_ = options->small_method_threshold_;
857   tiny_method_threshold_ = options->tiny_method_threshold_;
858   num_dex_methods_threshold_ = options->num_dex_methods_threshold_;
859 
860   sea_ir_mode_ = options->sea_ir_mode_;
861   vfprintf_ = options->hook_vfprintf_;
862   exit_ = options->hook_exit_;
863   abort_ = options->hook_abort_;
864 
865   default_stack_size_ = options->stack_size_;
866   stack_trace_file_ = options->stack_trace_file_;
867 
868   monitor_list_ = new MonitorList;
869   thread_list_ = new ThreadList;
870   intern_table_ = new InternTable;
871 
872 
873   if (options->interpreter_only_) {
874     GetInstrumentation()->ForceInterpretOnly();
875   }
876 
877   heap_ = new gc::Heap(options->heap_initial_size_,
878                        options->heap_growth_limit_,
879                        options->heap_min_free_,
880                        options->heap_max_free_,
881                        options->heap_target_utilization_,
882                        options->heap_maximum_size_,
883                        options->image_,
884                        options->is_concurrent_gc_enabled_,
885                        options->parallel_gc_threads_,
886                        options->conc_gc_threads_,
887                        options->low_memory_mode_,
888                        options->long_pause_log_threshold_,
889                        options->long_gc_log_threshold_,
890                        options->ignore_max_footprint_);
891 
892   BlockSignals();
893   InitPlatformSignalHandlers();
894 
895   java_vm_ = new JavaVMExt(this, options.get());
896 
897   Thread::Startup();
898 
899   // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
900   // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
901   // thread, we do not get a java peer.
902   Thread* self = Thread::Attach("main", false, NULL, false);
903   CHECK_EQ(self->thin_lock_id_, ThreadList::kMainId);
904   CHECK(self != NULL);
905 
906   // Set us to runnable so tools using a runtime can allocate and GC by default
907   self->TransitionFromSuspendedToRunnable();
908 
909   // Now we're attached, we can take the heap locks and validate the heap.
910   GetHeap()->EnableObjectValidation();
911 
912   CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
913   if (GetHeap()->GetContinuousSpaces()[0]->IsImageSpace()) {
914     class_linker_ = ClassLinker::CreateFromImage(intern_table_);
915   } else {
916     CHECK(options->boot_class_path_ != NULL);
917     CHECK_NE(options->boot_class_path_->size(), 0U);
918     class_linker_ = ClassLinker::CreateFromCompiler(*options->boot_class_path_, intern_table_);
919   }
920   CHECK(class_linker_ != NULL);
921   verifier::MethodVerifier::Init();
922 
923   method_trace_ = options->method_trace_;
924   method_trace_file_ = options->method_trace_file_;
925   method_trace_file_size_ = options->method_trace_file_size_;
926 
927   if (options->method_trace_) {
928     Trace::Start(options->method_trace_file_.c_str(), -1, options->method_trace_file_size_, 0,
929                  false, false, 0);
930   }
931 
932   // Pre-allocate an OutOfMemoryError for the double-OOME case.
933   self->ThrowNewException(ThrowLocation(), "Ljava/lang/OutOfMemoryError;",
934                           "OutOfMemoryError thrown while trying to throw OutOfMemoryError; no stack available");
935   pre_allocated_OutOfMemoryError_ = self->GetException(NULL);
936   self->ClearException();
937 
938   VLOG(startup) << "Runtime::Init exiting";
939   return true;
940 }
941 
InitNativeMethods()942 void Runtime::InitNativeMethods() {
943   VLOG(startup) << "Runtime::InitNativeMethods entering";
944   Thread* self = Thread::Current();
945   JNIEnv* env = self->GetJniEnv();
946 
947   // Must be in the kNative state for calling native methods (JNI_OnLoad code).
948   CHECK_EQ(self->GetState(), kNative);
949 
950   // First set up JniConstants, which is used by both the runtime's built-in native
951   // methods and libcore.
952   JniConstants::init(env);
953   WellKnownClasses::Init(env);
954 
955   // Then set up the native methods provided by the runtime itself.
956   RegisterRuntimeNativeMethods(env);
957 
958   // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
959   // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
960   // the library that implements System.loadLibrary!
961   {
962     std::string mapped_name(StringPrintf(OS_SHARED_LIB_FORMAT_STR, "javacore"));
963     std::string reason;
964     self->TransitionFromSuspendedToRunnable();
965     if (!instance_->java_vm_->LoadNativeLibrary(mapped_name, NULL, reason)) {
966       LOG(FATAL) << "LoadNativeLibrary failed for \"" << mapped_name << "\": " << reason;
967     }
968     self->TransitionFromRunnableToSuspended(kNative);
969   }
970 
971   // Initialize well known classes that may invoke runtime native methods.
972   WellKnownClasses::LateInit(env);
973 
974   VLOG(startup) << "Runtime::InitNativeMethods exiting";
975 }
976 
InitThreadGroups(Thread * self)977 void Runtime::InitThreadGroups(Thread* self) {
978   JNIEnvExt* env = self->GetJniEnv();
979   ScopedJniEnvLocalRefState env_state(env);
980   main_thread_group_ =
981       env->NewGlobalRef(env->GetStaticObjectField(WellKnownClasses::java_lang_ThreadGroup,
982                                                   WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
983   CHECK(main_thread_group_ != NULL || IsCompiler());
984   system_thread_group_ =
985       env->NewGlobalRef(env->GetStaticObjectField(WellKnownClasses::java_lang_ThreadGroup,
986                                                   WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
987   CHECK(system_thread_group_ != NULL || IsCompiler());
988 }
989 
GetMainThreadGroup() const990 jobject Runtime::GetMainThreadGroup() const {
991   CHECK(main_thread_group_ != NULL || IsCompiler());
992   return main_thread_group_;
993 }
994 
GetSystemThreadGroup() const995 jobject Runtime::GetSystemThreadGroup() const {
996   CHECK(system_thread_group_ != NULL || IsCompiler());
997   return system_thread_group_;
998 }
999 
GetSystemClassLoader() const1000 jobject Runtime::GetSystemClassLoader() const {
1001   CHECK(system_class_loader_ != NULL || IsCompiler());
1002   return system_class_loader_;
1003 }
1004 
RegisterRuntimeNativeMethods(JNIEnv * env)1005 void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
1006 #define REGISTER(FN) extern void FN(JNIEnv*); FN(env)
1007   // Register Throwable first so that registration of other native methods can throw exceptions
1008   REGISTER(register_java_lang_Throwable);
1009   REGISTER(register_dalvik_system_DexFile);
1010   REGISTER(register_dalvik_system_VMDebug);
1011   REGISTER(register_dalvik_system_VMRuntime);
1012   REGISTER(register_dalvik_system_VMStack);
1013   REGISTER(register_dalvik_system_Zygote);
1014   REGISTER(register_java_lang_Class);
1015   REGISTER(register_java_lang_DexCache);
1016   REGISTER(register_java_lang_Object);
1017   REGISTER(register_java_lang_Runtime);
1018   REGISTER(register_java_lang_String);
1019   REGISTER(register_java_lang_System);
1020   REGISTER(register_java_lang_Thread);
1021   REGISTER(register_java_lang_VMClassLoader);
1022   REGISTER(register_java_lang_reflect_Array);
1023   REGISTER(register_java_lang_reflect_Constructor);
1024   REGISTER(register_java_lang_reflect_Field);
1025   REGISTER(register_java_lang_reflect_Method);
1026   REGISTER(register_java_lang_reflect_Proxy);
1027   REGISTER(register_java_util_concurrent_atomic_AtomicLong);
1028   REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmServer);
1029   REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmVmInternal);
1030   REGISTER(register_sun_misc_Unsafe);
1031 #undef REGISTER
1032 }
1033 
DumpForSigQuit(std::ostream & os)1034 void Runtime::DumpForSigQuit(std::ostream& os) {
1035   GetClassLinker()->DumpForSigQuit(os);
1036   GetInternTable()->DumpForSigQuit(os);
1037   GetJavaVM()->DumpForSigQuit(os);
1038   GetHeap()->DumpForSigQuit(os);
1039   os << "\n";
1040 
1041   thread_list_->DumpForSigQuit(os);
1042   BaseMutex::DumpAll(os);
1043 }
1044 
DumpLockHolders(std::ostream & os)1045 void Runtime::DumpLockHolders(std::ostream& os) {
1046   uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
1047   pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
1048   pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
1049   pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
1050   if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
1051     os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
1052        << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
1053        << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
1054        << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
1055   }
1056 }
1057 
SetStatsEnabled(bool new_state)1058 void Runtime::SetStatsEnabled(bool new_state) {
1059   if (new_state == true) {
1060     GetStats()->Clear(~0);
1061     // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1062     Thread::Current()->GetStats()->Clear(~0);
1063   }
1064   stats_enabled_ = new_state;
1065 }
1066 
ResetStats(int kinds)1067 void Runtime::ResetStats(int kinds) {
1068   GetStats()->Clear(kinds & 0xffff);
1069   // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1070   Thread::Current()->GetStats()->Clear(kinds >> 16);
1071 }
1072 
GetStat(int kind)1073 int32_t Runtime::GetStat(int kind) {
1074   RuntimeStats* stats;
1075   if (kind < (1<<16)) {
1076     stats = GetStats();
1077   } else {
1078     stats = Thread::Current()->GetStats();
1079     kind >>= 16;
1080   }
1081   switch (kind) {
1082   case KIND_ALLOCATED_OBJECTS:
1083     return stats->allocated_objects;
1084   case KIND_ALLOCATED_BYTES:
1085     return stats->allocated_bytes;
1086   case KIND_FREED_OBJECTS:
1087     return stats->freed_objects;
1088   case KIND_FREED_BYTES:
1089     return stats->freed_bytes;
1090   case KIND_GC_INVOCATIONS:
1091     return stats->gc_for_alloc_count;
1092   case KIND_CLASS_INIT_COUNT:
1093     return stats->class_init_count;
1094   case KIND_CLASS_INIT_TIME:
1095     // Convert ns to us, reduce to 32 bits.
1096     return static_cast<int>(stats->class_init_time_ns / 1000);
1097   case KIND_EXT_ALLOCATED_OBJECTS:
1098   case KIND_EXT_ALLOCATED_BYTES:
1099   case KIND_EXT_FREED_OBJECTS:
1100   case KIND_EXT_FREED_BYTES:
1101     return 0;  // backward compatibility
1102   default:
1103     LOG(FATAL) << "Unknown statistic " << kind;
1104     return -1;  // unreachable
1105   }
1106 }
1107 
BlockSignals()1108 void Runtime::BlockSignals() {
1109   SignalSet signals;
1110   signals.Add(SIGPIPE);
1111   // SIGQUIT is used to dump the runtime's state (including stack traces).
1112   signals.Add(SIGQUIT);
1113   // SIGUSR1 is used to initiate a GC.
1114   signals.Add(SIGUSR1);
1115   signals.Block();
1116 }
1117 
AttachCurrentThread(const char * thread_name,bool as_daemon,jobject thread_group,bool create_peer)1118 bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
1119                                   bool create_peer) {
1120   bool success = Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != NULL;
1121   if (thread_name == NULL) {
1122     LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
1123   }
1124   return success;
1125 }
1126 
DetachCurrentThread()1127 void Runtime::DetachCurrentThread() {
1128   Thread* self = Thread::Current();
1129   if (self == NULL) {
1130     LOG(FATAL) << "attempting to detach thread that is not attached";
1131   }
1132   if (self->HasManagedStack()) {
1133     LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
1134   }
1135   thread_list_->Unregister(self);
1136 }
1137 
GetPreAllocatedOutOfMemoryError() const1138   mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() const {
1139   if (pre_allocated_OutOfMemoryError_ == NULL) {
1140     LOG(ERROR) << "Failed to return pre-allocated OOME";
1141   }
1142   return pre_allocated_OutOfMemoryError_;
1143 }
1144 
VisitConcurrentRoots(RootVisitor * visitor,void * arg,bool only_dirty,bool clean_dirty)1145 void Runtime::VisitConcurrentRoots(RootVisitor* visitor, void* arg, bool only_dirty,
1146                                    bool clean_dirty) {
1147   intern_table_->VisitRoots(visitor, arg, only_dirty, clean_dirty);
1148   class_linker_->VisitRoots(visitor, arg, only_dirty, clean_dirty);
1149 }
1150 
VisitNonThreadRoots(RootVisitor * visitor,void * arg)1151 void Runtime::VisitNonThreadRoots(RootVisitor* visitor, void* arg) {
1152   java_vm_->VisitRoots(visitor, arg);
1153   if (pre_allocated_OutOfMemoryError_ != NULL) {
1154     visitor(pre_allocated_OutOfMemoryError_, arg);
1155   }
1156   visitor(resolution_method_, arg);
1157   for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1158     visitor(callee_save_methods_[i], arg);
1159   }
1160 }
1161 
VisitNonConcurrentRoots(RootVisitor * visitor,void * arg)1162 void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor, void* arg) {
1163   thread_list_->VisitRoots(visitor, arg);
1164   VisitNonThreadRoots(visitor, arg);
1165 }
1166 
VisitRoots(RootVisitor * visitor,void * arg,bool only_dirty,bool clean_dirty)1167 void Runtime::VisitRoots(RootVisitor* visitor, void* arg, bool only_dirty, bool clean_dirty) {
1168   VisitConcurrentRoots(visitor, arg, only_dirty, clean_dirty);
1169   VisitNonConcurrentRoots(visitor, arg);
1170 }
1171 
CreateResolutionMethod()1172 mirror::ArtMethod* Runtime::CreateResolutionMethod() {
1173   mirror::Class* method_class = mirror::ArtMethod::GetJavaLangReflectArtMethod();
1174   Thread* self = Thread::Current();
1175   SirtRef<mirror::ArtMethod>
1176       method(self, down_cast<mirror::ArtMethod*>(method_class->AllocObject(self)));
1177   method->SetDeclaringClass(method_class);
1178   // TODO: use a special method for resolution method saves
1179   method->SetDexMethodIndex(DexFile::kDexNoIndex);
1180   // When compiling, the code pointer will get set later when the image is loaded.
1181   Runtime* r = Runtime::Current();
1182   ClassLinker* cl = r->GetClassLinker();
1183   method->SetEntryPointFromCompiledCode(r->IsCompiler() ? NULL : GetResolutionTrampoline(cl));
1184   return method.get();
1185 }
1186 
CreateCalleeSaveMethod(InstructionSet instruction_set,CalleeSaveType type)1187 mirror::ArtMethod* Runtime::CreateCalleeSaveMethod(InstructionSet instruction_set,
1188                                                         CalleeSaveType type) {
1189   mirror::Class* method_class = mirror::ArtMethod::GetJavaLangReflectArtMethod();
1190   Thread* self = Thread::Current();
1191   SirtRef<mirror::ArtMethod>
1192       method(self, down_cast<mirror::ArtMethod*>(method_class->AllocObject(self)));
1193   method->SetDeclaringClass(method_class);
1194   // TODO: use a special method for callee saves
1195   method->SetDexMethodIndex(DexFile::kDexNoIndex);
1196   method->SetEntryPointFromCompiledCode(NULL);
1197   if ((instruction_set == kThumb2) || (instruction_set == kArm)) {
1198     uint32_t ref_spills = (1 << art::arm::R5) | (1 << art::arm::R6)  | (1 << art::arm::R7) |
1199                           (1 << art::arm::R8) | (1 << art::arm::R10) | (1 << art::arm::R11);
1200     uint32_t arg_spills = (1 << art::arm::R1) | (1 << art::arm::R2) | (1 << art::arm::R3);
1201     uint32_t all_spills = (1 << art::arm::R4) | (1 << art::arm::R9);
1202     uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills : 0) |
1203                            (type == kSaveAll ? all_spills : 0) | (1 << art::arm::LR);
1204     uint32_t fp_all_spills = (1 << art::arm::S0)  | (1 << art::arm::S1)  | (1 << art::arm::S2) |
1205                              (1 << art::arm::S3)  | (1 << art::arm::S4)  | (1 << art::arm::S5) |
1206                              (1 << art::arm::S6)  | (1 << art::arm::S7)  | (1 << art::arm::S8) |
1207                              (1 << art::arm::S9)  | (1 << art::arm::S10) | (1 << art::arm::S11) |
1208                              (1 << art::arm::S12) | (1 << art::arm::S13) | (1 << art::arm::S14) |
1209                              (1 << art::arm::S15) | (1 << art::arm::S16) | (1 << art::arm::S17) |
1210                              (1 << art::arm::S18) | (1 << art::arm::S19) | (1 << art::arm::S20) |
1211                              (1 << art::arm::S21) | (1 << art::arm::S22) | (1 << art::arm::S23) |
1212                              (1 << art::arm::S24) | (1 << art::arm::S25) | (1 << art::arm::S26) |
1213                              (1 << art::arm::S27) | (1 << art::arm::S28) | (1 << art::arm::S29) |
1214                              (1 << art::arm::S30) | (1 << art::arm::S31);
1215     uint32_t fp_spills = type == kSaveAll ? fp_all_spills : 0;
1216     size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
1217                                  __builtin_popcount(fp_spills) /* fprs */ +
1218                                  1 /* Method* */) * kPointerSize, kStackAlignment);
1219     method->SetFrameSizeInBytes(frame_size);
1220     method->SetCoreSpillMask(core_spills);
1221     method->SetFpSpillMask(fp_spills);
1222   } else if (instruction_set == kMips) {
1223     uint32_t ref_spills = (1 << art::mips::S2) | (1 << art::mips::S3) | (1 << art::mips::S4) |
1224                           (1 << art::mips::S5) | (1 << art::mips::S6) | (1 << art::mips::S7) |
1225                           (1 << art::mips::GP) | (1 << art::mips::FP);
1226     uint32_t arg_spills = (1 << art::mips::A1) | (1 << art::mips::A2) | (1 << art::mips::A3);
1227     uint32_t all_spills = (1 << art::mips::S0) | (1 << art::mips::S1);
1228     uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills : 0) |
1229                            (type == kSaveAll ? all_spills : 0) | (1 << art::mips::RA);
1230     size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
1231                                 (type == kRefsAndArgs ? 0 : 3) + 1 /* Method* */) *
1232                                 kPointerSize, kStackAlignment);
1233     method->SetFrameSizeInBytes(frame_size);
1234     method->SetCoreSpillMask(core_spills);
1235     method->SetFpSpillMask(0);
1236   } else if (instruction_set == kX86) {
1237     uint32_t ref_spills = (1 << art::x86::EBP) | (1 << art::x86::ESI) | (1 << art::x86::EDI);
1238     uint32_t arg_spills = (1 << art::x86::ECX) | (1 << art::x86::EDX) | (1 << art::x86::EBX);
1239     uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills : 0) |
1240                          (1 << art::x86::kNumberOfCpuRegisters);  // fake return address callee save
1241     size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
1242                                  1 /* Method* */) * kPointerSize, kStackAlignment);
1243     method->SetFrameSizeInBytes(frame_size);
1244     method->SetCoreSpillMask(core_spills);
1245     method->SetFpSpillMask(0);
1246   } else {
1247     UNIMPLEMENTED(FATAL);
1248   }
1249   return method.get();
1250 }
1251 
DisallowNewSystemWeaks()1252 void Runtime::DisallowNewSystemWeaks() {
1253   monitor_list_->DisallowNewMonitors();
1254   intern_table_->DisallowNewInterns();
1255   java_vm_->DisallowNewWeakGlobals();
1256 }
1257 
AllowNewSystemWeaks()1258 void Runtime::AllowNewSystemWeaks() {
1259   monitor_list_->AllowNewMonitors();
1260   intern_table_->AllowNewInterns();
1261   java_vm_->AllowNewWeakGlobals();
1262 }
1263 
SetCalleeSaveMethod(mirror::ArtMethod * method,CalleeSaveType type)1264 void Runtime::SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type) {
1265   DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1266   callee_save_methods_[type] = method;
1267 }
1268 
GetCompileTimeClassPath(jobject class_loader)1269 const std::vector<const DexFile*>& Runtime::GetCompileTimeClassPath(jobject class_loader) {
1270   if (class_loader == NULL) {
1271     return GetClassLinker()->GetBootClassPath();
1272   }
1273   CHECK(UseCompileTimeClassPath());
1274   CompileTimeClassPaths::const_iterator it = compile_time_class_paths_.find(class_loader);
1275   CHECK(it != compile_time_class_paths_.end());
1276   return it->second;
1277 }
1278 
SetCompileTimeClassPath(jobject class_loader,std::vector<const DexFile * > & class_path)1279 void Runtime::SetCompileTimeClassPath(jobject class_loader, std::vector<const DexFile*>& class_path) {
1280   CHECK(!IsStarted());
1281   use_compile_time_class_path_ = true;
1282   compile_time_class_paths_.Put(class_loader, class_path);
1283 }
1284 
1285 }  // namespace art
1286