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