runtime.cc revision c5f17732d8144491c642776b6b48c85dfadf4b52
15b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey/* 25b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * Copyright (C) 2011 The Android Open Source Project 35b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * 45b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * Licensed under the Apache License, Version 2.0 (the "License"); 55b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * you may not use this file except in compliance with the License. 65b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * You may obtain a copy of the License at 75b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * 85b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * http://www.apache.org/licenses/LICENSE-2.0 95b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * 105b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * Unless required by applicable law or agreed to in writing, software 115b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * distributed under the License is distributed on an "AS IS" BASIS, 125b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 135b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * See the License for the specific language governing permissions and 145b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey * limitations under the License. 155b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey */ 165b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 175b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "runtime.h" 185b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 195b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc 205b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <sys/mount.h> 215b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#ifdef __linux__ 225b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <linux/fs.h> 235b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#endif 245b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 255b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <signal.h> 265b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <sys/syscall.h> 275b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <valgrind.h> 285b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 295b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <cstdio> 305b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <cstdlib> 315b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <limits> 325b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <memory> 335b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <vector> 345b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include <fcntl.h> 355b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 365b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/arm/quick_method_frame_info_arm.h" 375b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/arm/registers_arm.h" 385b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/arm64/quick_method_frame_info_arm64.h" 395b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/arm64/registers_arm64.h" 405b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/mips/quick_method_frame_info_mips.h" 415b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/mips/registers_mips.h" 425b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/x86/quick_method_frame_info_x86.h" 435b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/x86/registers_x86.h" 445b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/x86_64/quick_method_frame_info_x86_64.h" 455b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "arch/x86_64/registers_x86_64.h" 465b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "atomic.h" 475b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "class_linker.h" 485b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "debugger.h" 495b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "fault_handler.h" 505b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "gc/accounting/card_table-inl.h" 515b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "gc/heap.h" 525b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "gc/space/space.h" 535b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "image.h" 545b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "instrumentation.h" 555b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "intern_table.h" 565b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "jni_internal.h" 575b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "mirror/art_field-inl.h" 585b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "mirror/art_method-inl.h" 595b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "mirror/array.h" 605b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "mirror/class-inl.h" 615b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "mirror/class_loader.h" 625b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "mirror/stack_trace_element.h" 635b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "mirror/throwable.h" 645b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "monitor.h" 655b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "parsed_options.h" 665b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "oat_file.h" 675b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "quick/quick_method_frame_info.h" 685b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "reflection.h" 695b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "ScopedLocalRef.h" 705b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "scoped_thread_state_change.h" 715b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "signal_catcher.h" 725b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "signal_set.h" 735b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "handle_scope-inl.h" 745b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "thread.h" 755b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "thread_list.h" 765b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "trace.h" 775b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "transaction.h" 785b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "profiler.h" 795b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "verifier/method_verifier.h" 805b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "well_known_classes.h" 815b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 825b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "JniConstants.h" // Last to avoid LOG redefinition in ics-mr1-plus-art. 835b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 845b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#ifdef HAVE_ANDROID_OS 855b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#include "cutils/properties.h" 865b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey#endif 875b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 885b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkeynamespace art { 895b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 905b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkeystatic constexpr bool kEnableJavaStackTraceHandler = true; 915b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkeyconst char* Runtime::kDefaultInstructionSetFeatures = 925b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey STRINGIFY(ART_DEFAULT_INSTRUCTION_SET_FEATURES); 935b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff SharkeyRuntime* Runtime::instance_ = NULL; 945b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 955b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff SharkeyRuntime::Runtime() 965b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey : pre_allocated_OutOfMemoryError_(nullptr), 975b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey resolution_method_(nullptr), 985b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey imt_conflict_method_(nullptr), 995b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey default_imt_(nullptr), 1005b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey instruction_set_(kNone), 1015b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey compiler_callbacks_(nullptr), 1025b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey is_zygote_(false), 1035b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey is_concurrent_gc_enabled_(true), 1045b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey is_explicit_gc_disabled_(false), 1055b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey default_stack_size_(0), 1065b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey heap_(nullptr), 1075b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation), 1085b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey monitor_list_(nullptr), 1095b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey monitor_pool_(nullptr), 1105b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey thread_list_(nullptr), 1115b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey intern_table_(nullptr), 1125b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey class_linker_(nullptr), 1135b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey signal_catcher_(nullptr), 1145b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey java_vm_(nullptr), 1155b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey fault_message_lock_("Fault message lock"), 1165b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey fault_message_(""), 1175b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey method_verifier_lock_("Method verifiers lock"), 1185b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey threads_being_born_(0), 1195b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)), 1205b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey shutting_down_(false), 1215b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey shutting_down_started_(false), 1225b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey started_(false), 1235b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey finished_starting_(false), 1245b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey vfprintf_(nullptr), 1255b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey exit_(nullptr), 1265b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey abort_(nullptr), 1275b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey stats_enabled_(false), 1285b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey running_on_valgrind_(RUNNING_ON_VALGRIND > 0), 1295b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey profiler_started_(false), 1305b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey method_trace_(false), 1315b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey method_trace_file_size_(0), 1325b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey instrumentation_(), 1335b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey use_compile_time_class_path_(false), 1345b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey main_thread_group_(nullptr), 1355b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey system_thread_group_(nullptr), 1365b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey system_class_loader_(nullptr), 1375b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey dump_gc_performance_on_shutdown_(false), 1385b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey preinitialization_transaction_(nullptr), 1395b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey null_pointer_handler_(nullptr), 1405b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey suspend_handler_(nullptr), 1415b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey stack_overflow_handler_(nullptr), 1425b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey verify_(false), 1435b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey target_sdk_version_(0) { 1445b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 1455b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey callee_save_methods_[i] = nullptr; 1465b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey } 1475b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey} 1485b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 1495b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff SharkeyRuntime::~Runtime() { 1505b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey if (dump_gc_performance_on_shutdown_) { 1515b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey // This can't be called from the Heap destructor below because it 1525b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey // could call RosAlloc::InspectAll() which needs the thread_list 1535b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey // to be still alive. 1545b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey heap_->DumpGcPerformanceInfo(LOG(INFO)); 1555b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey } 1565b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 1575b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey Thread* self = Thread::Current(); 1585b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey { 1595b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey MutexLock mu(self, *Locks::runtime_shutdown_lock_); 1605b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey shutting_down_started_ = true; 1615b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey while (threads_being_born_ > 0) { 1625b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey shutdown_cond_->Wait(self); 1635b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey } 1645b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey shutting_down_ = true; 1655b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey } 1665b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey // Shut down background profiler before the runtime exits. 1675b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey if (profiler_started_) { 1685b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey BackgroundMethodSamplingProfiler::Shutdown(); 1695b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey } 1705b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 1715b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey Trace::Shutdown(); 1725b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 1735b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey // Make sure to let the GC complete if it is running. 1745b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey heap_->WaitForGcToComplete(gc::kGcCauseBackground, self); 1755b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey heap_->DeleteThreadPool(); 1765b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 1775b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey // Make sure our internal threads are dead before we start tearing down things they're using. 1785b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey Dbg::StopJdwp(); 1795b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey delete signal_catcher_; 1805b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey 1815b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended. 1825b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey delete thread_list_; 1835b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey delete monitor_list_; 1845b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey delete monitor_pool_; 1855b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey delete class_linker_; 1865b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey delete heap_; 1875b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey delete intern_table_; 1885b78a3aa7741c3f44b676ccffa765cecee1cbd4cJeff Sharkey delete java_vm_; 189 Thread::Shutdown(); 190 QuasiAtomic::Shutdown(); 191 verifier::MethodVerifier::Shutdown(); 192 // TODO: acquire a static mutex on Runtime to avoid racing. 193 CHECK(instance_ == nullptr || instance_ == this); 194 instance_ = nullptr; 195 196 delete null_pointer_handler_; 197 delete suspend_handler_; 198 delete stack_overflow_handler_; 199} 200 201struct AbortState { 202 void Dump(std::ostream& os) NO_THREAD_SAFETY_ANALYSIS { 203 if (gAborting > 1) { 204 os << "Runtime aborting --- recursively, so no thread-specific detail!\n"; 205 return; 206 } 207 gAborting++; 208 os << "Runtime aborting...\n"; 209 if (Runtime::Current() == NULL) { 210 os << "(Runtime does not yet exist!)\n"; 211 return; 212 } 213 Thread* self = Thread::Current(); 214 if (self == nullptr) { 215 os << "(Aborting thread was not attached to runtime!)\n"; 216 DumpKernelStack(os, GetTid(), " kernel: ", false); 217 DumpNativeStack(os, GetTid(), " native: ", nullptr); 218 } else { 219 os << "Aborting thread:\n"; 220 if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) { 221 DumpThread(os, self); 222 } else { 223 if (Locks::mutator_lock_->SharedTryLock(self)) { 224 DumpThread(os, self); 225 Locks::mutator_lock_->SharedUnlock(self); 226 } 227 } 228 } 229 DumpAllThreads(os, self); 230 } 231 232 void DumpThread(std::ostream& os, Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 233 self->Dump(os); 234 if (self->IsExceptionPending()) { 235 ThrowLocation throw_location; 236 mirror::Throwable* exception = self->GetException(&throw_location); 237 os << "Pending exception " << PrettyTypeOf(exception) 238 << " thrown by '" << throw_location.Dump() << "'\n" 239 << exception->Dump(); 240 } 241 } 242 243 void DumpAllThreads(std::ostream& os, Thread* self) NO_THREAD_SAFETY_ANALYSIS { 244 bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self); 245 bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self); 246 if (!tll_already_held || !ml_already_held) { 247 os << "Dumping all threads without appropriate locks held:" 248 << (!tll_already_held ? " thread list lock" : "") 249 << (!ml_already_held ? " mutator lock" : "") 250 << "\n"; 251 } 252 os << "All threads:\n"; 253 Runtime::Current()->GetThreadList()->DumpLocked(os); 254 } 255}; 256 257void Runtime::Abort() { 258 gAborting++; // set before taking any locks 259 260 // Ensure that we don't have multiple threads trying to abort at once, 261 // which would result in significantly worse diagnostics. 262 MutexLock mu(Thread::Current(), *Locks::abort_lock_); 263 264 // Get any pending output out of the way. 265 fflush(NULL); 266 267 // Many people have difficulty distinguish aborts from crashes, 268 // so be explicit. 269 AbortState state; 270 LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state); 271 272 // Call the abort hook if we have one. 273 if (Runtime::Current() != NULL && Runtime::Current()->abort_ != NULL) { 274 LOG(INTERNAL_FATAL) << "Calling abort hook..."; 275 Runtime::Current()->abort_(); 276 // notreached 277 LOG(INTERNAL_FATAL) << "Unexpectedly returned from abort hook!"; 278 } 279 280#if defined(__GLIBC__) 281 // TODO: we ought to be able to use pthread_kill(3) here (or abort(3), 282 // which POSIX defines in terms of raise(3), which POSIX defines in terms 283 // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through 284 // libpthread, which means the stacks we dump would be useless. Calling 285 // tgkill(2) directly avoids that. 286 syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT); 287 // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM? 288 // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3). 289 exit(1); 290#else 291 abort(); 292#endif 293 // notreached 294} 295 296void Runtime::PreZygoteFork() { 297 heap_->PreZygoteFork(); 298} 299 300void Runtime::CallExitHook(jint status) { 301 if (exit_ != NULL) { 302 ScopedThreadStateChange tsc(Thread::Current(), kNative); 303 exit_(status); 304 LOG(WARNING) << "Exit hook returned instead of exiting!"; 305 } 306} 307 308void Runtime::SweepSystemWeaks(IsMarkedCallback* visitor, void* arg) { 309 GetInternTable()->SweepInternTableWeaks(visitor, arg); 310 GetMonitorList()->SweepMonitorList(visitor, arg); 311 GetJavaVM()->SweepJniWeakGlobals(visitor, arg); 312 Dbg::UpdateObjectPointers(visitor, arg); 313} 314 315bool Runtime::Create(const Options& options, bool ignore_unrecognized) { 316 // TODO: acquire a static mutex on Runtime to avoid racing. 317 if (Runtime::instance_ != NULL) { 318 return false; 319 } 320 InitLogging(NULL); // Calls Locks::Init() as a side effect. 321 instance_ = new Runtime; 322 if (!instance_->Init(options, ignore_unrecognized)) { 323 delete instance_; 324 instance_ = NULL; 325 return false; 326 } 327 return true; 328} 329 330jobject CreateSystemClassLoader() { 331 if (Runtime::Current()->UseCompileTimeClassPath()) { 332 return NULL; 333 } 334 335 ScopedObjectAccess soa(Thread::Current()); 336 ClassLinker* cl = Runtime::Current()->GetClassLinker(); 337 338 StackHandleScope<3> hs(soa.Self()); 339 Handle<mirror::Class> class_loader_class( 340 hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader))); 341 CHECK(cl->EnsureInitialized(class_loader_class, true, true)); 342 343 mirror::ArtMethod* getSystemClassLoader = 344 class_loader_class->FindDirectMethod("getSystemClassLoader", "()Ljava/lang/ClassLoader;"); 345 CHECK(getSystemClassLoader != NULL); 346 347 JValue result = InvokeWithJValues(soa, nullptr, soa.EncodeMethod(getSystemClassLoader), nullptr); 348 Handle<mirror::ClassLoader> class_loader( 349 hs.NewHandle(down_cast<mirror::ClassLoader*>(result.GetL()))); 350 CHECK(class_loader.Get() != nullptr); 351 JNIEnv* env = soa.Self()->GetJniEnv(); 352 ScopedLocalRef<jobject> system_class_loader(env, 353 soa.AddLocalReference<jobject>(class_loader.Get())); 354 CHECK(system_class_loader.get() != nullptr); 355 356 soa.Self()->SetClassLoaderOverride(class_loader.Get()); 357 358 Handle<mirror::Class> thread_class( 359 hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread))); 360 CHECK(cl->EnsureInitialized(thread_class, true, true)); 361 362 mirror::ArtField* contextClassLoader = 363 thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;"); 364 CHECK(contextClassLoader != NULL); 365 366 // We can't run in a transaction yet. 367 contextClassLoader->SetObject<false>(soa.Self()->GetPeer(), class_loader.Get()); 368 369 return env->NewGlobalRef(system_class_loader.get()); 370} 371 372std::string Runtime::GetCompilerExecutable() const { 373 if (!compiler_executable_.empty()) { 374 return compiler_executable_; 375 } 376 std::string compiler_executable(GetAndroidRoot()); 377 compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat"); 378 return compiler_executable; 379} 380 381bool Runtime::Start() { 382 VLOG(startup) << "Runtime::Start entering"; 383 384 // Restore main thread state to kNative as expected by native code. 385 Thread* self = Thread::Current(); 386 self->TransitionFromRunnableToSuspended(kNative); 387 388 started_ = true; 389 390 // InitNativeMethods needs to be after started_ so that the classes 391 // it touches will have methods linked to the oat file if necessary. 392 InitNativeMethods(); 393 394 // Initialize well known thread group values that may be accessed threads while attaching. 395 InitThreadGroups(self); 396 397 Thread::FinishStartup(); 398 399 if (is_zygote_) { 400 if (!InitZygote()) { 401 return false; 402 } 403 } else { 404 DidForkFromZygote(); 405 } 406 407 StartDaemonThreads(); 408 409 system_class_loader_ = CreateSystemClassLoader(); 410 411 { 412 ScopedObjectAccess soa(self); 413 self->GetJniEnv()->locals.AssertEmpty(); 414 } 415 416 VLOG(startup) << "Runtime::Start exiting"; 417 finished_starting_ = true; 418 419 if (profiler_options_.IsEnabled() && !profile_output_filename_.empty()) { 420 // User has asked for a profile using -Xenable-profiler. 421 // Create the profile file if it doesn't exist. 422 int fd = open(profile_output_filename_.c_str(), O_RDWR|O_CREAT|O_EXCL, 0660); 423 if (fd >= 0) { 424 close(fd); 425 } 426 StartProfiler(profile_output_filename_.c_str()); 427 } 428 429 return true; 430} 431 432void Runtime::EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) { 433 DCHECK_GT(threads_being_born_, 0U); 434 threads_being_born_--; 435 if (shutting_down_started_ && threads_being_born_ == 0) { 436 shutdown_cond_->Broadcast(Thread::Current()); 437 } 438} 439 440// Do zygote-mode-only initialization. 441bool Runtime::InitZygote() { 442#ifdef __linux__ 443 // zygote goes into its own process group 444 setpgid(0, 0); 445 446 // See storage config details at http://source.android.com/tech/storage/ 447 // Create private mount namespace shared by all children 448 if (unshare(CLONE_NEWNS) == -1) { 449 PLOG(WARNING) << "Failed to unshare()"; 450 return false; 451 } 452 453 // Mark rootfs as being a slave so that changes from default 454 // namespace only flow into our children. 455 if (mount("rootfs", "/", NULL, (MS_SLAVE | MS_REC), NULL) == -1) { 456 PLOG(WARNING) << "Failed to mount() rootfs as MS_SLAVE"; 457 return false; 458 } 459 460 // Create a staging tmpfs that is shared by our children; they will 461 // bind mount storage into their respective private namespaces, which 462 // are isolated from each other. 463 const char* target_base = getenv("EMULATED_STORAGE_TARGET"); 464 if (target_base != NULL) { 465 if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV, 466 "uid=0,gid=1028,mode=0751") == -1) { 467 LOG(WARNING) << "Failed to mount tmpfs to " << target_base; 468 return false; 469 } 470 } 471 472 return true; 473#else 474 UNIMPLEMENTED(FATAL); 475 return false; 476#endif 477} 478 479void Runtime::DidForkFromZygote() { 480 is_zygote_ = false; 481 482 // Create the thread pool. 483 heap_->CreateThreadPool(); 484 485 StartSignalCatcher(); 486 487 // Start the JDWP thread. If the command-line debugger flags specified "suspend=y", 488 // this will pause the runtime, so we probably want this to come last. 489 Dbg::StartJdwp(); 490} 491 492void Runtime::StartSignalCatcher() { 493 if (!is_zygote_) { 494 signal_catcher_ = new SignalCatcher(stack_trace_file_); 495 } 496} 497 498bool Runtime::IsShuttingDown(Thread* self) { 499 MutexLock mu(self, *Locks::runtime_shutdown_lock_); 500 return IsShuttingDownLocked(); 501} 502 503void Runtime::StartDaemonThreads() { 504 VLOG(startup) << "Runtime::StartDaemonThreads entering"; 505 506 Thread* self = Thread::Current(); 507 508 // Must be in the kNative state for calling native methods. 509 CHECK_EQ(self->GetState(), kNative); 510 511 JNIEnv* env = self->GetJniEnv(); 512 env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons, 513 WellKnownClasses::java_lang_Daemons_start); 514 if (env->ExceptionCheck()) { 515 env->ExceptionDescribe(); 516 LOG(FATAL) << "Error starting java.lang.Daemons"; 517 } 518 519 VLOG(startup) << "Runtime::StartDaemonThreads exiting"; 520} 521 522bool Runtime::Init(const Options& raw_options, bool ignore_unrecognized) { 523 CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize); 524 525 std::unique_ptr<ParsedOptions> options(ParsedOptions::Create(raw_options, ignore_unrecognized)); 526 if (options.get() == NULL) { 527 LOG(ERROR) << "Failed to parse options"; 528 return false; 529 } 530 VLOG(startup) << "Runtime::Init -verbose:startup enabled"; 531 532 QuasiAtomic::Startup(); 533 534 Monitor::Init(options->lock_profiling_threshold_, options->hook_is_sensitive_thread_); 535 536 boot_class_path_string_ = options->boot_class_path_string_; 537 class_path_string_ = options->class_path_string_; 538 properties_ = options->properties_; 539 540 compiler_callbacks_ = options->compiler_callbacks_; 541 is_zygote_ = options->is_zygote_; 542 is_explicit_gc_disabled_ = options->is_explicit_gc_disabled_; 543 544 vfprintf_ = options->hook_vfprintf_; 545 exit_ = options->hook_exit_; 546 abort_ = options->hook_abort_; 547 548 default_stack_size_ = options->stack_size_; 549 stack_trace_file_ = options->stack_trace_file_; 550 551 compiler_executable_ = options->compiler_executable_; 552 compiler_options_ = options->compiler_options_; 553 image_compiler_options_ = options->image_compiler_options_; 554 555 max_spins_before_thin_lock_inflation_ = options->max_spins_before_thin_lock_inflation_; 556 557 monitor_list_ = new MonitorList; 558 monitor_pool_ = MonitorPool::Create(); 559 thread_list_ = new ThreadList; 560 intern_table_ = new InternTable; 561 562 verify_ = options->verify_; 563 564 if (options->interpreter_only_) { 565 GetInstrumentation()->ForceInterpretOnly(); 566 } 567 568 bool implicit_checks_supported = false; 569 switch (kRuntimeISA) { 570 case kArm: 571 case kThumb2: 572 implicit_checks_supported = true; 573 break; 574 default: 575 break; 576 } 577 578 if (implicit_checks_supported && 579 (options->explicit_checks_ != (ParsedOptions::kExplicitSuspendCheck | 580 ParsedOptions::kExplicitNullCheck | 581 ParsedOptions::kExplicitStackOverflowCheck) || kEnableJavaStackTraceHandler)) { 582 fault_manager.Init(); 583 584 // These need to be in a specific order. The null point check handler must be 585 // after the suspend check and stack overflow check handlers. 586 if ((options->explicit_checks_ & ParsedOptions::kExplicitSuspendCheck) == 0) { 587 suspend_handler_ = new SuspensionHandler(&fault_manager); 588 } 589 590 if ((options->explicit_checks_ & ParsedOptions::kExplicitStackOverflowCheck) == 0) { 591 stack_overflow_handler_ = new StackOverflowHandler(&fault_manager); 592 } 593 594 if ((options->explicit_checks_ & ParsedOptions::kExplicitNullCheck) == 0) { 595 null_pointer_handler_ = new NullPointerHandler(&fault_manager); 596 } 597 598 if (kEnableJavaStackTraceHandler) { 599 new JavaStackTraceHandler(&fault_manager); 600 } 601 } 602 603 heap_ = new gc::Heap(options->heap_initial_size_, 604 options->heap_growth_limit_, 605 options->heap_min_free_, 606 options->heap_max_free_, 607 options->heap_target_utilization_, 608 options->foreground_heap_growth_multiplier_, 609 options->heap_maximum_size_, 610 options->image_, 611 options->image_isa_, 612 options->collector_type_, 613 options->background_collector_type_, 614 options->parallel_gc_threads_, 615 options->conc_gc_threads_, 616 options->low_memory_mode_, 617 options->long_pause_log_threshold_, 618 options->long_gc_log_threshold_, 619 options->ignore_max_footprint_, 620 options->use_tlab_, 621 options->verify_pre_gc_heap_, 622 options->verify_pre_sweeping_heap_, 623 options->verify_post_gc_heap_, 624 options->verify_pre_gc_rosalloc_, 625 options->verify_pre_sweeping_rosalloc_, 626 options->verify_post_gc_rosalloc_); 627 628 dump_gc_performance_on_shutdown_ = options->dump_gc_performance_on_shutdown_; 629 630 BlockSignals(); 631 InitPlatformSignalHandlers(); 632 633 java_vm_ = new JavaVMExt(this, options.get()); 634 635 Thread::Startup(); 636 637 // ClassLinker needs an attached thread, but we can't fully attach a thread without creating 638 // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main 639 // thread, we do not get a java peer. 640 Thread* self = Thread::Attach("main", false, NULL, false); 641 CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId); 642 CHECK(self != NULL); 643 644 // Set us to runnable so tools using a runtime can allocate and GC by default 645 self->TransitionFromSuspendedToRunnable(); 646 647 // Now we're attached, we can take the heap locks and validate the heap. 648 GetHeap()->EnableObjectValidation(); 649 650 CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U); 651 class_linker_ = new ClassLinker(intern_table_); 652 if (GetHeap()->HasImageSpace()) { 653 class_linker_->InitFromImage(); 654 if (kIsDebugBuild) { 655 GetHeap()->GetImageSpace()->VerifyImageAllocations(); 656 } 657 } else { 658 CHECK(options->boot_class_path_ != NULL); 659 CHECK_NE(options->boot_class_path_->size(), 0U); 660 class_linker_->InitFromCompiler(*options->boot_class_path_); 661 } 662 CHECK(class_linker_ != NULL); 663 verifier::MethodVerifier::Init(); 664 665 method_trace_ = options->method_trace_; 666 method_trace_file_ = options->method_trace_file_; 667 method_trace_file_size_ = options->method_trace_file_size_; 668 669 profile_output_filename_ = options->profile_output_filename_; 670 profiler_options_ = options->profiler_options_; 671 672 // TODO: move this to just be an Trace::Start argument 673 Trace::SetDefaultClockSource(options->profile_clock_source_); 674 675 if (options->method_trace_) { 676 Trace::Start(options->method_trace_file_.c_str(), -1, options->method_trace_file_size_, 0, 677 false, false, 0); 678 } 679 680 // Pre-allocate an OutOfMemoryError for the double-OOME case. 681 self->ThrowNewException(ThrowLocation(), "Ljava/lang/OutOfMemoryError;", 682 "OutOfMemoryError thrown while trying to throw OutOfMemoryError; " 683 "no stack available"); 684 pre_allocated_OutOfMemoryError_ = self->GetException(NULL); 685 self->ClearException(); 686 687 VLOG(startup) << "Runtime::Init exiting"; 688 return true; 689} 690 691void Runtime::InitNativeMethods() { 692 VLOG(startup) << "Runtime::InitNativeMethods entering"; 693 Thread* self = Thread::Current(); 694 JNIEnv* env = self->GetJniEnv(); 695 696 // Must be in the kNative state for calling native methods (JNI_OnLoad code). 697 CHECK_EQ(self->GetState(), kNative); 698 699 // First set up JniConstants, which is used by both the runtime's built-in native 700 // methods and libcore. 701 JniConstants::init(env); 702 WellKnownClasses::Init(env); 703 704 // Then set up the native methods provided by the runtime itself. 705 RegisterRuntimeNativeMethods(env); 706 707 // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad. 708 // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's 709 // the library that implements System.loadLibrary! 710 { 711 std::string mapped_name(StringPrintf(OS_SHARED_LIB_FORMAT_STR, "javacore")); 712 std::string reason; 713 self->TransitionFromSuspendedToRunnable(); 714 StackHandleScope<1> hs(self); 715 auto class_loader(hs.NewHandle<mirror::ClassLoader>(nullptr)); 716 if (!instance_->java_vm_->LoadNativeLibrary(mapped_name, class_loader, &reason)) { 717 LOG(FATAL) << "LoadNativeLibrary failed for \"" << mapped_name << "\": " << reason; 718 } 719 self->TransitionFromRunnableToSuspended(kNative); 720 } 721 722 // Initialize well known classes that may invoke runtime native methods. 723 WellKnownClasses::LateInit(env); 724 725 VLOG(startup) << "Runtime::InitNativeMethods exiting"; 726} 727 728void Runtime::InitThreadGroups(Thread* self) { 729 JNIEnvExt* env = self->GetJniEnv(); 730 ScopedJniEnvLocalRefState env_state(env); 731 main_thread_group_ = 732 env->NewGlobalRef(env->GetStaticObjectField( 733 WellKnownClasses::java_lang_ThreadGroup, 734 WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup)); 735 CHECK(main_thread_group_ != NULL || IsCompiler()); 736 system_thread_group_ = 737 env->NewGlobalRef(env->GetStaticObjectField( 738 WellKnownClasses::java_lang_ThreadGroup, 739 WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup)); 740 CHECK(system_thread_group_ != NULL || IsCompiler()); 741} 742 743jobject Runtime::GetMainThreadGroup() const { 744 CHECK(main_thread_group_ != NULL || IsCompiler()); 745 return main_thread_group_; 746} 747 748jobject Runtime::GetSystemThreadGroup() const { 749 CHECK(system_thread_group_ != NULL || IsCompiler()); 750 return system_thread_group_; 751} 752 753jobject Runtime::GetSystemClassLoader() const { 754 CHECK(system_class_loader_ != NULL || IsCompiler()); 755 return system_class_loader_; 756} 757 758void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) { 759#define REGISTER(FN) extern void FN(JNIEnv*); FN(env) 760 // Register Throwable first so that registration of other native methods can throw exceptions 761 REGISTER(register_java_lang_Throwable); 762 REGISTER(register_dalvik_system_DexFile); 763 REGISTER(register_dalvik_system_VMDebug); 764 REGISTER(register_dalvik_system_VMRuntime); 765 REGISTER(register_dalvik_system_VMStack); 766 REGISTER(register_dalvik_system_ZygoteHooks); 767 REGISTER(register_java_lang_Class); 768 REGISTER(register_java_lang_DexCache); 769 REGISTER(register_java_lang_Object); 770 REGISTER(register_java_lang_Runtime); 771 REGISTER(register_java_lang_String); 772 REGISTER(register_java_lang_System); 773 REGISTER(register_java_lang_Thread); 774 REGISTER(register_java_lang_VMClassLoader); 775 REGISTER(register_java_lang_ref_Reference); 776 REGISTER(register_java_lang_reflect_Array); 777 REGISTER(register_java_lang_reflect_Constructor); 778 REGISTER(register_java_lang_reflect_Field); 779 REGISTER(register_java_lang_reflect_Method); 780 REGISTER(register_java_lang_reflect_Proxy); 781 REGISTER(register_java_util_concurrent_atomic_AtomicLong); 782 REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmServer); 783 REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmVmInternal); 784 REGISTER(register_sun_misc_Unsafe); 785#undef REGISTER 786} 787 788void Runtime::DumpForSigQuit(std::ostream& os) { 789 GetClassLinker()->DumpForSigQuit(os); 790 GetInternTable()->DumpForSigQuit(os); 791 GetJavaVM()->DumpForSigQuit(os); 792 GetHeap()->DumpForSigQuit(os); 793 os << "\n"; 794 795 thread_list_->DumpForSigQuit(os); 796 BaseMutex::DumpAll(os); 797} 798 799void Runtime::DumpLockHolders(std::ostream& os) { 800 uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid(); 801 pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner(); 802 pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner(); 803 pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner(); 804 if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) { 805 os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n" 806 << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n" 807 << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n" 808 << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n"; 809 } 810} 811 812void Runtime::SetStatsEnabled(bool new_state) { 813 if (new_state == true) { 814 GetStats()->Clear(~0); 815 // TODO: wouldn't it make more sense to clear _all_ threads' stats? 816 Thread::Current()->GetStats()->Clear(~0); 817 GetInstrumentation()->InstrumentQuickAllocEntryPoints(); 818 } else { 819 GetInstrumentation()->UninstrumentQuickAllocEntryPoints(); 820 } 821 stats_enabled_ = new_state; 822} 823 824void Runtime::ResetStats(int kinds) { 825 GetStats()->Clear(kinds & 0xffff); 826 // TODO: wouldn't it make more sense to clear _all_ threads' stats? 827 Thread::Current()->GetStats()->Clear(kinds >> 16); 828} 829 830int32_t Runtime::GetStat(int kind) { 831 RuntimeStats* stats; 832 if (kind < (1<<16)) { 833 stats = GetStats(); 834 } else { 835 stats = Thread::Current()->GetStats(); 836 kind >>= 16; 837 } 838 switch (kind) { 839 case KIND_ALLOCATED_OBJECTS: 840 return stats->allocated_objects; 841 case KIND_ALLOCATED_BYTES: 842 return stats->allocated_bytes; 843 case KIND_FREED_OBJECTS: 844 return stats->freed_objects; 845 case KIND_FREED_BYTES: 846 return stats->freed_bytes; 847 case KIND_GC_INVOCATIONS: 848 return stats->gc_for_alloc_count; 849 case KIND_CLASS_INIT_COUNT: 850 return stats->class_init_count; 851 case KIND_CLASS_INIT_TIME: 852 // Convert ns to us, reduce to 32 bits. 853 return static_cast<int>(stats->class_init_time_ns / 1000); 854 case KIND_EXT_ALLOCATED_OBJECTS: 855 case KIND_EXT_ALLOCATED_BYTES: 856 case KIND_EXT_FREED_OBJECTS: 857 case KIND_EXT_FREED_BYTES: 858 return 0; // backward compatibility 859 default: 860 LOG(FATAL) << "Unknown statistic " << kind; 861 return -1; // unreachable 862 } 863} 864 865void Runtime::BlockSignals() { 866 SignalSet signals; 867 signals.Add(SIGPIPE); 868 // SIGQUIT is used to dump the runtime's state (including stack traces). 869 signals.Add(SIGQUIT); 870 // SIGUSR1 is used to initiate a GC. 871 signals.Add(SIGUSR1); 872 signals.Block(); 873} 874 875bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group, 876 bool create_peer) { 877 bool success = Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != NULL; 878 if (thread_name == NULL) { 879 LOG(WARNING) << *Thread::Current() << " attached without supplying a name"; 880 } 881 return success; 882} 883 884void Runtime::DetachCurrentThread() { 885 Thread* self = Thread::Current(); 886 if (self == NULL) { 887 LOG(FATAL) << "attempting to detach thread that is not attached"; 888 } 889 if (self->HasManagedStack()) { 890 LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code"; 891 } 892 thread_list_->Unregister(self); 893} 894 895 mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() const { 896 if (pre_allocated_OutOfMemoryError_ == NULL) { 897 LOG(ERROR) << "Failed to return pre-allocated OOME"; 898 } 899 return pre_allocated_OutOfMemoryError_; 900} 901 902void Runtime::VisitConstantRoots(RootCallback* callback, void* arg) { 903 // Visit the classes held as static in mirror classes, these can be visited concurrently and only 904 // need to be visited once per GC since they never change. 905 mirror::ArtField::VisitRoots(callback, arg); 906 mirror::ArtMethod::VisitRoots(callback, arg); 907 mirror::Class::VisitRoots(callback, arg); 908 mirror::StackTraceElement::VisitRoots(callback, arg); 909 mirror::String::VisitRoots(callback, arg); 910 mirror::Throwable::VisitRoots(callback, arg); 911 // Visit all the primitive array types classes. 912 mirror::PrimitiveArray<uint8_t>::VisitRoots(callback, arg); // BooleanArray 913 mirror::PrimitiveArray<int8_t>::VisitRoots(callback, arg); // ByteArray 914 mirror::PrimitiveArray<uint16_t>::VisitRoots(callback, arg); // CharArray 915 mirror::PrimitiveArray<double>::VisitRoots(callback, arg); // DoubleArray 916 mirror::PrimitiveArray<float>::VisitRoots(callback, arg); // FloatArray 917 mirror::PrimitiveArray<int32_t>::VisitRoots(callback, arg); // IntArray 918 mirror::PrimitiveArray<int64_t>::VisitRoots(callback, arg); // LongArray 919 mirror::PrimitiveArray<int16_t>::VisitRoots(callback, arg); // ShortArray 920} 921 922void Runtime::VisitConcurrentRoots(RootCallback* callback, void* arg, VisitRootFlags flags) { 923 intern_table_->VisitRoots(callback, arg, flags); 924 class_linker_->VisitRoots(callback, arg, flags); 925 Dbg::VisitRoots(callback, arg); 926 if ((flags & kVisitRootFlagNewRoots) == 0) { 927 // Guaranteed to have no new roots in the constant roots. 928 VisitConstantRoots(callback, arg); 929 } 930} 931 932void Runtime::VisitNonThreadRoots(RootCallback* callback, void* arg) { 933 java_vm_->VisitRoots(callback, arg); 934 if (pre_allocated_OutOfMemoryError_ != nullptr) { 935 callback(reinterpret_cast<mirror::Object**>(&pre_allocated_OutOfMemoryError_), arg, 0, 936 kRootVMInternal); 937 DCHECK(pre_allocated_OutOfMemoryError_ != nullptr); 938 } 939 callback(reinterpret_cast<mirror::Object**>(&resolution_method_), arg, 0, kRootVMInternal); 940 DCHECK(resolution_method_ != nullptr); 941 if (HasImtConflictMethod()) { 942 callback(reinterpret_cast<mirror::Object**>(&imt_conflict_method_), arg, 0, kRootVMInternal); 943 } 944 if (HasDefaultImt()) { 945 callback(reinterpret_cast<mirror::Object**>(&default_imt_), arg, 0, kRootVMInternal); 946 } 947 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 948 if (callee_save_methods_[i] != nullptr) { 949 callback(reinterpret_cast<mirror::Object**>(&callee_save_methods_[i]), arg, 0, 950 kRootVMInternal); 951 } 952 } 953 { 954 MutexLock mu(Thread::Current(), method_verifier_lock_); 955 for (verifier::MethodVerifier* verifier : method_verifiers_) { 956 verifier->VisitRoots(callback, arg); 957 } 958 } 959 if (preinitialization_transaction_ != nullptr) { 960 preinitialization_transaction_->VisitRoots(callback, arg); 961 } 962 instrumentation_.VisitRoots(callback, arg); 963} 964 965void Runtime::VisitNonConcurrentRoots(RootCallback* callback, void* arg) { 966 thread_list_->VisitRoots(callback, arg); 967 VisitNonThreadRoots(callback, arg); 968} 969 970void Runtime::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) { 971 VisitNonConcurrentRoots(callback, arg); 972 VisitConcurrentRoots(callback, arg, flags); 973} 974 975mirror::ObjectArray<mirror::ArtMethod>* Runtime::CreateDefaultImt(ClassLinker* cl) { 976 Thread* self = Thread::Current(); 977 StackHandleScope<1> hs(self); 978 Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable( 979 hs.NewHandle(cl->AllocArtMethodArray(self, 64))); 980 mirror::ArtMethod* imt_conflict_method = Runtime::Current()->GetImtConflictMethod(); 981 for (size_t i = 0; i < static_cast<size_t>(imtable->GetLength()); i++) { 982 imtable->Set<false>(i, imt_conflict_method); 983 } 984 return imtable.Get(); 985} 986 987mirror::ArtMethod* Runtime::CreateImtConflictMethod() { 988 Thread* self = Thread::Current(); 989 Runtime* runtime = Runtime::Current(); 990 ClassLinker* class_linker = runtime->GetClassLinker(); 991 StackHandleScope<1> hs(self); 992 Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self))); 993 method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod()); 994 // TODO: use a special method for imt conflict method saves. 995 method->SetDexMethodIndex(DexFile::kDexNoIndex); 996 // When compiling, the code pointer will get set later when the image is loaded. 997 if (runtime->IsCompiler()) { 998 method->SetEntryPointFromPortableCompiledCode(nullptr); 999 method->SetEntryPointFromQuickCompiledCode(nullptr); 1000 } else { 1001 method->SetEntryPointFromPortableCompiledCode(GetPortableImtConflictTrampoline(class_linker)); 1002 method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictTrampoline(class_linker)); 1003 } 1004 return method.Get(); 1005} 1006 1007mirror::ArtMethod* Runtime::CreateResolutionMethod() { 1008 Thread* self = Thread::Current(); 1009 Runtime* runtime = Runtime::Current(); 1010 ClassLinker* class_linker = runtime->GetClassLinker(); 1011 StackHandleScope<1> hs(self); 1012 Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self))); 1013 method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod()); 1014 // TODO: use a special method for resolution method saves 1015 method->SetDexMethodIndex(DexFile::kDexNoIndex); 1016 // When compiling, the code pointer will get set later when the image is loaded. 1017 if (runtime->IsCompiler()) { 1018 method->SetEntryPointFromPortableCompiledCode(nullptr); 1019 method->SetEntryPointFromQuickCompiledCode(nullptr); 1020 } else { 1021 method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline(class_linker)); 1022 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline(class_linker)); 1023 } 1024 return method.Get(); 1025} 1026 1027mirror::ArtMethod* Runtime::CreateCalleeSaveMethod(CalleeSaveType type) { 1028 Thread* self = Thread::Current(); 1029 Runtime* runtime = Runtime::Current(); 1030 ClassLinker* class_linker = runtime->GetClassLinker(); 1031 StackHandleScope<1> hs(self); 1032 Handle<mirror::ArtMethod> method(hs.NewHandle(class_linker->AllocArtMethod(self))); 1033 method->SetDeclaringClass(mirror::ArtMethod::GetJavaLangReflectArtMethod()); 1034 // TODO: use a special method for callee saves 1035 method->SetDexMethodIndex(DexFile::kDexNoIndex); 1036 method->SetEntryPointFromPortableCompiledCode(nullptr); 1037 method->SetEntryPointFromQuickCompiledCode(nullptr); 1038 DCHECK_NE(instruction_set_, kNone); 1039 return method.Get(); 1040} 1041 1042void Runtime::DisallowNewSystemWeaks() { 1043 monitor_list_->DisallowNewMonitors(); 1044 intern_table_->DisallowNewInterns(); 1045 java_vm_->DisallowNewWeakGlobals(); 1046 Dbg::DisallowNewObjectRegistryObjects(); 1047} 1048 1049void Runtime::AllowNewSystemWeaks() { 1050 monitor_list_->AllowNewMonitors(); 1051 intern_table_->AllowNewInterns(); 1052 java_vm_->AllowNewWeakGlobals(); 1053 Dbg::AllowNewObjectRegistryObjects(); 1054} 1055 1056void Runtime::SetInstructionSet(InstructionSet instruction_set) { 1057 instruction_set_ = instruction_set; 1058 if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) { 1059 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1060 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1061 callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type); 1062 } 1063 } else if (instruction_set_ == kMips) { 1064 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1065 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1066 callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type); 1067 } 1068 } else if (instruction_set_ == kX86) { 1069 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1070 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1071 callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type); 1072 } 1073 } else if (instruction_set_ == kX86_64) { 1074 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1075 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1076 callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type); 1077 } 1078 } else if (instruction_set_ == kArm64) { 1079 for (int i = 0; i != kLastCalleeSaveType; ++i) { 1080 CalleeSaveType type = static_cast<CalleeSaveType>(i); 1081 callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type); 1082 } 1083 } else { 1084 UNIMPLEMENTED(FATAL) << instruction_set_; 1085 } 1086} 1087 1088void Runtime::SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type) { 1089 DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType)); 1090 callee_save_methods_[type] = method; 1091} 1092 1093const std::vector<const DexFile*>& Runtime::GetCompileTimeClassPath(jobject class_loader) { 1094 if (class_loader == NULL) { 1095 return GetClassLinker()->GetBootClassPath(); 1096 } 1097 CHECK(UseCompileTimeClassPath()); 1098 CompileTimeClassPaths::const_iterator it = compile_time_class_paths_.find(class_loader); 1099 CHECK(it != compile_time_class_paths_.end()); 1100 return it->second; 1101} 1102 1103void Runtime::SetCompileTimeClassPath(jobject class_loader, 1104 std::vector<const DexFile*>& class_path) { 1105 CHECK(!IsStarted()); 1106 use_compile_time_class_path_ = true; 1107 compile_time_class_paths_.Put(class_loader, class_path); 1108} 1109 1110void Runtime::AddMethodVerifier(verifier::MethodVerifier* verifier) { 1111 DCHECK(verifier != nullptr); 1112 MutexLock mu(Thread::Current(), method_verifier_lock_); 1113 method_verifiers_.insert(verifier); 1114} 1115 1116void Runtime::RemoveMethodVerifier(verifier::MethodVerifier* verifier) { 1117 DCHECK(verifier != nullptr); 1118 MutexLock mu(Thread::Current(), method_verifier_lock_); 1119 auto it = method_verifiers_.find(verifier); 1120 CHECK(it != method_verifiers_.end()); 1121 method_verifiers_.erase(it); 1122} 1123 1124void Runtime::StartProfiler(const char* profile_output_filename) { 1125 profile_output_filename_ = profile_output_filename; 1126 profiler_started_ = 1127 BackgroundMethodSamplingProfiler::Start(profile_output_filename_, profiler_options_); 1128} 1129 1130// Transaction support. 1131void Runtime::EnterTransactionMode(Transaction* transaction) { 1132 DCHECK(IsCompiler()); 1133 DCHECK(transaction != nullptr); 1134 DCHECK(!IsActiveTransaction()); 1135 preinitialization_transaction_ = transaction; 1136} 1137 1138void Runtime::ExitTransactionMode() { 1139 DCHECK(IsCompiler()); 1140 DCHECK(IsActiveTransaction()); 1141 preinitialization_transaction_ = nullptr; 1142} 1143 1144void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset, 1145 uint32_t value, bool is_volatile) const { 1146 DCHECK(IsCompiler()); 1147 DCHECK(IsActiveTransaction()); 1148 preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile); 1149} 1150 1151void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset, 1152 uint64_t value, bool is_volatile) const { 1153 DCHECK(IsCompiler()); 1154 DCHECK(IsActiveTransaction()); 1155 preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile); 1156} 1157 1158void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset, 1159 mirror::Object* value, bool is_volatile) const { 1160 DCHECK(IsCompiler()); 1161 DCHECK(IsActiveTransaction()); 1162 preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile); 1163} 1164 1165void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const { 1166 DCHECK(IsCompiler()); 1167 DCHECK(IsActiveTransaction()); 1168 preinitialization_transaction_->RecordWriteArray(array, index, value); 1169} 1170 1171void Runtime::RecordStrongStringInsertion(mirror::String* s, uint32_t hash_code) const { 1172 DCHECK(IsCompiler()); 1173 DCHECK(IsActiveTransaction()); 1174 preinitialization_transaction_->RecordStrongStringInsertion(s, hash_code); 1175} 1176 1177void Runtime::RecordWeakStringInsertion(mirror::String* s, uint32_t hash_code) const { 1178 DCHECK(IsCompiler()); 1179 DCHECK(IsActiveTransaction()); 1180 preinitialization_transaction_->RecordWeakStringInsertion(s, hash_code); 1181} 1182 1183void Runtime::RecordStrongStringRemoval(mirror::String* s, uint32_t hash_code) const { 1184 DCHECK(IsCompiler()); 1185 DCHECK(IsActiveTransaction()); 1186 preinitialization_transaction_->RecordStrongStringRemoval(s, hash_code); 1187} 1188 1189void Runtime::RecordWeakStringRemoval(mirror::String* s, uint32_t hash_code) const { 1190 DCHECK(IsCompiler()); 1191 DCHECK(IsActiveTransaction()); 1192 preinitialization_transaction_->RecordWeakStringRemoval(s, hash_code); 1193} 1194 1195void Runtime::SetFaultMessage(const std::string& message) { 1196 MutexLock mu(Thread::Current(), fault_message_lock_); 1197 fault_message_ = message; 1198} 1199 1200void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv) 1201 const { 1202 if (GetInstrumentation()->InterpretOnly()) { 1203 argv->push_back("--compiler-filter=interpret-only"); 1204 } 1205 1206 argv->push_back("--runtime-arg"); 1207 std::string checkstr = "-implicit-checks"; 1208 1209 int nchecks = 0; 1210 char checksep = ':'; 1211 1212 if (!ExplicitNullChecks()) { 1213 checkstr += checksep; 1214 checksep = ','; 1215 checkstr += "null"; 1216 ++nchecks; 1217 } 1218 if (!ExplicitSuspendChecks()) { 1219 checkstr += checksep; 1220 checksep = ','; 1221 checkstr += "suspend"; 1222 ++nchecks; 1223 } 1224 1225 if (!ExplicitStackOverflowChecks()) { 1226 checkstr += checksep; 1227 checksep = ','; 1228 checkstr += "stack"; 1229 ++nchecks; 1230 } 1231 1232 if (nchecks == 0) { 1233 checkstr += ":none"; 1234 } 1235 argv->push_back(checkstr); 1236 1237 // Make the dex2oat instruction set match that of the launching runtime. If we have multiple 1238 // architecture support, dex2oat may be compiled as a different instruction-set than that 1239 // currently being executed. 1240 std::string instruction_set("--instruction-set="); 1241 instruction_set += GetInstructionSetString(kRuntimeISA); 1242 argv->push_back(instruction_set); 1243 1244 std::string features("--instruction-set-features="); 1245 features += GetDefaultInstructionSetFeatures(); 1246 argv->push_back(features); 1247} 1248 1249void Runtime::UpdateProfilerState(int state) { 1250 VLOG(profiler) << "Profiler state updated to " << state; 1251} 1252} // namespace art 1253