runtime.h revision b373e091eac39b1a79c11f2dcbd610af01e9e8a9
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#ifndef ART_RUNTIME_RUNTIME_H_ 18#define ART_RUNTIME_RUNTIME_H_ 19 20#include <jni.h> 21#include <stdio.h> 22 23#include <iosfwd> 24#include <string> 25#include <utility> 26#include <vector> 27 28#include "base/macros.h" 29#include "base/stringpiece.h" 30#include "gc/collector_type.h" 31#include "gc/heap.h" 32#include "globals.h" 33#include "instruction_set.h" 34#include "instrumentation.h" 35#include "jobject_comparator.h" 36#include "object_callbacks.h" 37#include "runtime_stats.h" 38#include "safe_map.h" 39#include "fault_handler.h" 40 41namespace art { 42 43namespace gc { 44 class Heap; 45} 46namespace mirror { 47 class ArtMethod; 48 class ClassLoader; 49 class Array; 50 template<class T> class ObjectArray; 51 template<class T> class PrimitiveArray; 52 typedef PrimitiveArray<int8_t> ByteArray; 53 class String; 54 class Throwable; 55} // namespace mirror 56namespace verifier { 57class MethodVerifier; 58} 59class ClassLinker; 60class CompilerCallbacks; 61class DexFile; 62class InternTable; 63class JavaVMExt; 64class MonitorList; 65class MonitorPool; 66class SignalCatcher; 67class ThreadList; 68class Trace; 69class Transaction; 70 71// Not all combinations of flags are valid. You may not visit all roots as well as the new roots 72// (no logical reason to do this). You also may not start logging new roots and stop logging new 73// roots (also no logical reason to do this). 74enum VisitRootFlags : uint8_t { 75 kVisitRootFlagAllRoots = 0x1, 76 kVisitRootFlagNewRoots = 0x2, 77 kVisitRootFlagStartLoggingNewRoots = 0x4, 78 kVisitRootFlagStopLoggingNewRoots = 0x8, 79 kVisitRootFlagClearRootLog = 0x10, 80}; 81 82class Runtime { 83 public: 84 typedef std::vector<std::pair<std::string, const void*> > Options; 85 86 // Creates and initializes a new runtime. 87 static bool Create(const Options& options, bool ignore_unrecognized) 88 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_); 89 90 bool IsCompiler() const { 91 return compiler_callbacks_ != nullptr; 92 } 93 94 CompilerCallbacks* GetCompilerCallbacks() { 95 return compiler_callbacks_; 96 } 97 98 bool IsZygote() const { 99 return is_zygote_; 100 } 101 102 bool IsExplicitGcDisabled() const { 103 return is_explicit_gc_disabled_; 104 } 105 106 const std::vector<std::string>& GetCompilerOptions() const { 107 return compiler_options_; 108 } 109 110 const std::vector<std::string>& GetImageCompilerOptions() const { 111 return image_compiler_options_; 112 } 113 114 // Starts a runtime, which may cause threads to be started and code to run. 115 bool Start() UNLOCK_FUNCTION(Locks::mutator_lock_); 116 117 bool IsShuttingDown(Thread* self); 118 bool IsShuttingDownLocked() const EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) { 119 return shutting_down_; 120 } 121 122 size_t NumberOfThreadsBeingBorn() const EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) { 123 return threads_being_born_; 124 } 125 126 void StartThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) { 127 threads_being_born_++; 128 } 129 130 void EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_); 131 132 bool IsStarted() const { 133 return started_; 134 } 135 136 bool IsFinishedStarting() const { 137 return finished_starting_; 138 } 139 140 static Runtime* Current() { 141 return instance_; 142 } 143 144 // Aborts semi-cleanly. Used in the implementation of LOG(FATAL), which most 145 // callers should prefer. 146 // This isn't marked ((noreturn)) because then gcc will merge multiple calls 147 // in a single function together. This reduces code size slightly, but means 148 // that the native stack trace we get may point at the wrong call site. 149 static void Abort() LOCKS_EXCLUDED(Locks::abort_lock_); 150 151 // Returns the "main" ThreadGroup, used when attaching user threads. 152 jobject GetMainThreadGroup() const; 153 154 // Returns the "system" ThreadGroup, used when attaching our internal threads. 155 jobject GetSystemThreadGroup() const; 156 157 // Returns the system ClassLoader which represents the CLASSPATH. 158 jobject GetSystemClassLoader() const; 159 160 // Attaches the calling native thread to the runtime. 161 bool AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group, 162 bool create_peer); 163 164 void CallExitHook(jint status); 165 166 // Detaches the current native thread from the runtime. 167 void DetachCurrentThread() LOCKS_EXCLUDED(Locks::mutator_lock_); 168 169 void DumpForSigQuit(std::ostream& os) 170 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 171 void DumpLockHolders(std::ostream& os); 172 173 ~Runtime(); 174 175 const std::string& GetBootClassPathString() const { 176 return boot_class_path_string_; 177 } 178 179 const std::string& GetClassPathString() const { 180 return class_path_string_; 181 } 182 183 ClassLinker* GetClassLinker() const { 184 return class_linker_; 185 } 186 187 size_t GetDefaultStackSize() const { 188 return default_stack_size_; 189 } 190 191 gc::Heap* GetHeap() const { 192 return heap_; 193 } 194 195 InternTable* GetInternTable() const { 196 DCHECK(intern_table_ != NULL); 197 return intern_table_; 198 } 199 200 JavaVMExt* GetJavaVM() const { 201 return java_vm_; 202 } 203 204 size_t GetMaxSpinsBeforeThinkLockInflation() const { 205 return max_spins_before_thin_lock_inflation_; 206 } 207 208 MonitorList* GetMonitorList() const { 209 return monitor_list_; 210 } 211 212 MonitorPool* GetMonitorPool() const { 213 return monitor_pool_; 214 } 215 216 mirror::Throwable* GetPreAllocatedOutOfMemoryError() const 217 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 218 219 const std::vector<std::string>& GetProperties() const { 220 return properties_; 221 } 222 223 ThreadList* GetThreadList() const { 224 return thread_list_; 225 } 226 227 static const char* GetVersion() { 228 return "2.0.0"; 229 } 230 231 void DisallowNewSystemWeaks() EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_); 232 void AllowNewSystemWeaks() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 233 234 // Visit all the roots. If only_dirty is true then non-dirty roots won't be visited. If 235 // clean_dirty is true then dirty roots will be marked as non-dirty after visiting. 236 void VisitRoots(RootCallback* visitor, void* arg, VisitRootFlags flags = kVisitRootFlagAllRoots) 237 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 238 239 // Visit all of the roots we can do safely do concurrently. 240 void VisitConcurrentRoots(RootCallback* visitor, void* arg, 241 VisitRootFlags flags = kVisitRootFlagAllRoots) 242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 243 244 // Visit all of the non thread roots, we can do this with mutators unpaused. 245 void VisitNonThreadRoots(RootCallback* visitor, void* arg) 246 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 247 248 // Visit all other roots which must be done with mutators suspended. 249 void VisitNonConcurrentRoots(RootCallback* visitor, void* arg) 250 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 251 252 // Sweep system weaks, the system weak is deleted if the visitor return nullptr. Otherwise, the 253 // system weak is updated to be the visitor's returned value. 254 void SweepSystemWeaks(IsMarkedCallback* visitor, void* arg) 255 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 256 257 // Constant roots are the roots which never change after the runtime is initialized, they only 258 // need to be visited once per GC cycle. 259 void VisitConstantRoots(RootCallback* callback, void* arg) 260 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 261 262 // Returns a special method that calls into a trampoline for runtime method resolution 263 mirror::ArtMethod* GetResolutionMethod() const { 264 CHECK(HasResolutionMethod()); 265 return resolution_method_; 266 } 267 268 bool HasResolutionMethod() const { 269 return resolution_method_ != NULL; 270 } 271 272 void SetResolutionMethod(mirror::ArtMethod* method) { 273 resolution_method_ = method; 274 } 275 276 mirror::ArtMethod* CreateResolutionMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 277 278 // Returns a special method that calls into a trampoline for runtime imt conflicts 279 mirror::ArtMethod* GetImtConflictMethod() const { 280 CHECK(HasImtConflictMethod()); 281 return imt_conflict_method_; 282 } 283 284 bool HasImtConflictMethod() const { 285 return imt_conflict_method_ != NULL; 286 } 287 288 void SetImtConflictMethod(mirror::ArtMethod* method) { 289 imt_conflict_method_ = method; 290 } 291 292 mirror::ArtMethod* CreateImtConflictMethod() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 293 294 // Returns an imt with every entry set to conflict, used as default imt for all classes. 295 mirror::ObjectArray<mirror::ArtMethod>* GetDefaultImt() const { 296 CHECK(HasDefaultImt()); 297 return default_imt_; 298 } 299 300 bool HasDefaultImt() const { 301 return default_imt_ != NULL; 302 } 303 304 void SetDefaultImt(mirror::ObjectArray<mirror::ArtMethod>* imt) { 305 default_imt_ = imt; 306 } 307 308 mirror::ObjectArray<mirror::ArtMethod>* CreateDefaultImt(ClassLinker* cl) 309 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 310 311 // Returns a special method that describes all callee saves being spilled to the stack. 312 enum CalleeSaveType { 313 kSaveAll, 314 kRefsOnly, 315 kRefsAndArgs, 316 kLastCalleeSaveType // Value used for iteration 317 }; 318 319 bool HasCalleeSaveMethod(CalleeSaveType type) const { 320 return callee_save_methods_[type] != NULL; 321 } 322 323 mirror::ArtMethod* GetCalleeSaveMethod(CalleeSaveType type) const { 324 DCHECK(HasCalleeSaveMethod(type)); 325 return callee_save_methods_[type]; 326 } 327 328 static size_t GetCalleeSaveMethodOffset(CalleeSaveType type) { 329 return OFFSETOF_MEMBER(Runtime, callee_save_methods_[type]); 330 } 331 332 void SetCalleeSaveMethod(mirror::ArtMethod* method, CalleeSaveType type); 333 334 mirror::ArtMethod* CreateCalleeSaveMethod(InstructionSet instruction_set, 335 CalleeSaveType type) 336 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 337 338 mirror::ArtMethod* CreateRefOnlyCalleeSaveMethod(InstructionSet instruction_set) 339 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 340 341 mirror::ArtMethod* CreateRefAndArgsCalleeSaveMethod(InstructionSet instruction_set) 342 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 343 344 int32_t GetStat(int kind); 345 346 RuntimeStats* GetStats() { 347 return &stats_; 348 } 349 350 bool HasStatsEnabled() const { 351 return stats_enabled_; 352 } 353 354 void ResetStats(int kinds); 355 356 void SetStatsEnabled(bool new_state); 357 358 bool PreZygoteFork(); 359 bool InitZygote(); 360 void DidForkFromZygote(); 361 362 instrumentation::Instrumentation* GetInstrumentation() { 363 return &instrumentation_; 364 } 365 366 bool UseCompileTimeClassPath() const { 367 return use_compile_time_class_path_; 368 } 369 370 void AddMethodVerifier(verifier::MethodVerifier* verifier) LOCKS_EXCLUDED(method_verifier_lock_); 371 void RemoveMethodVerifier(verifier::MethodVerifier* verifier) 372 LOCKS_EXCLUDED(method_verifier_lock_); 373 374 const std::vector<const DexFile*>& GetCompileTimeClassPath(jobject class_loader); 375 void SetCompileTimeClassPath(jobject class_loader, std::vector<const DexFile*>& class_path); 376 377 void StartProfiler(const char* appDir, const char* procName, bool startImmediately = false); 378 void UpdateProfilerState(int state); 379 380 // Transaction support. 381 bool IsActiveTransaction() const; 382 void EnterTransactionMode(Transaction* transaction); 383 void ExitTransactionMode(); 384 void RecordWriteField32(mirror::Object* obj, MemberOffset field_offset, uint32_t value, 385 bool is_volatile) const; 386 void RecordWriteField64(mirror::Object* obj, MemberOffset field_offset, uint64_t value, 387 bool is_volatile) const; 388 void RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset, 389 mirror::Object* value, bool is_volatile) const; 390 void RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const 391 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_); 392 void RecordStrongStringInsertion(mirror::String* s, uint32_t hash_code) const 393 EXCLUSIVE_LOCKS_REQUIRED(Locks::intern_table_lock_); 394 void RecordWeakStringInsertion(mirror::String* s, uint32_t hash_code) const 395 EXCLUSIVE_LOCKS_REQUIRED(Locks::intern_table_lock_); 396 void RecordStrongStringRemoval(mirror::String* s, uint32_t hash_code) const 397 EXCLUSIVE_LOCKS_REQUIRED(Locks::intern_table_lock_); 398 void RecordWeakStringRemoval(mirror::String* s, uint32_t hash_code) const 399 EXCLUSIVE_LOCKS_REQUIRED(Locks::intern_table_lock_); 400 401 void SetFaultMessage(const std::string& message); 402 // Only read by the signal handler, NO_THREAD_SAFETY_ANALYSIS to prevent lock order violations 403 // with the unexpected_signal_lock_. 404 const std::string& GetFaultMessage() NO_THREAD_SAFETY_ANALYSIS { 405 return fault_message_; 406 } 407 408 bool ExplicitNullChecks() const { 409 return null_pointer_handler_ == nullptr; 410 } 411 412 bool ExplicitSuspendChecks() const { 413 return suspend_handler_ == nullptr; 414 } 415 416 bool ExplicitStackOverflowChecks() const { 417 return stack_overflow_handler_ == nullptr; 418 } 419 420 private: 421 static void InitPlatformSignalHandlers(); 422 423 Runtime(); 424 425 void BlockSignals(); 426 427 bool Init(const Options& options, bool ignore_unrecognized) 428 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_); 429 void InitNativeMethods() LOCKS_EXCLUDED(Locks::mutator_lock_); 430 void InitThreadGroups(Thread* self); 431 void RegisterRuntimeNativeMethods(JNIEnv* env); 432 433 void StartDaemonThreads(); 434 void StartSignalCatcher(); 435 436 // NOTE: these must match the gc::ProcessState values as they come directly 437 // from the framework. 438 static constexpr int kProfileForground = 0; 439 static constexpr int kProfileBackgrouud = 1; 440 441 442 // A pointer to the active runtime or NULL. 443 static Runtime* instance_; 444 445 CompilerCallbacks* compiler_callbacks_; 446 bool is_zygote_; 447 bool is_concurrent_gc_enabled_; 448 bool is_explicit_gc_disabled_; 449 450 std::vector<std::string> compiler_options_; 451 std::vector<std::string> image_compiler_options_; 452 453 std::string boot_class_path_string_; 454 std::string class_path_string_; 455 std::vector<std::string> properties_; 456 457 // The default stack size for managed threads created by the runtime. 458 size_t default_stack_size_; 459 460 gc::Heap* heap_; 461 462 // The number of spins that are done before thread suspension is used to forcibly inflate. 463 size_t max_spins_before_thin_lock_inflation_; 464 MonitorList* monitor_list_; 465 MonitorPool* monitor_pool_; 466 467 ThreadList* thread_list_; 468 469 InternTable* intern_table_; 470 471 ClassLinker* class_linker_; 472 473 SignalCatcher* signal_catcher_; 474 std::string stack_trace_file_; 475 476 JavaVMExt* java_vm_; 477 478 mirror::Throwable* pre_allocated_OutOfMemoryError_; 479 480 mirror::ArtMethod* callee_save_methods_[kLastCalleeSaveType]; 481 482 mirror::ArtMethod* resolution_method_; 483 484 mirror::ArtMethod* imt_conflict_method_; 485 486 mirror::ObjectArray<mirror::ArtMethod>* default_imt_; 487 488 // Fault message, printed when we get a SIGSEGV. 489 Mutex fault_message_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; 490 std::string fault_message_ GUARDED_BY(fault_message_lock_); 491 492 // Method verifier set, used so that we can update their GC roots. 493 Mutex method_verifier_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; 494 std::set<verifier::MethodVerifier*> method_verifiers_; 495 496 // A non-zero value indicates that a thread has been created but not yet initialized. Guarded by 497 // the shutdown lock so that threads aren't born while we're shutting down. 498 size_t threads_being_born_ GUARDED_BY(Locks::runtime_shutdown_lock_); 499 500 // Waited upon until no threads are being born. 501 UniquePtr<ConditionVariable> shutdown_cond_ GUARDED_BY(Locks::runtime_shutdown_lock_); 502 503 // Set when runtime shutdown is past the point that new threads may attach. 504 bool shutting_down_ GUARDED_BY(Locks::runtime_shutdown_lock_); 505 506 // The runtime is starting to shutdown but is blocked waiting on shutdown_cond_. 507 bool shutting_down_started_ GUARDED_BY(Locks::runtime_shutdown_lock_); 508 509 bool started_; 510 511 // New flag added which tells us if the runtime has finished starting. If 512 // this flag is set then the Daemon threads are created and the class loader 513 // is created. This flag is needed for knowing if its safe to request CMS. 514 bool finished_starting_; 515 516 // Hooks supported by JNI_CreateJavaVM 517 jint (*vfprintf_)(FILE* stream, const char* format, va_list ap); 518 void (*exit_)(jint status); 519 void (*abort_)(); 520 521 bool stats_enabled_; 522 RuntimeStats stats_; 523 524 // Runtime profile support. 525 bool profile_; 526 std::string profile_output_filename_; 527 uint32_t profile_period_s_; // Generate profile every n seconds. 528 uint32_t profile_duration_s_; // Run profile for n seconds. 529 uint32_t profile_interval_us_; // Microseconds between samples. 530 double profile_backoff_coefficient_; // Coefficient to exponential backoff. 531 532 bool method_trace_; 533 std::string method_trace_file_; 534 size_t method_trace_file_size_; 535 instrumentation::Instrumentation instrumentation_; 536 537 typedef SafeMap<jobject, std::vector<const DexFile*>, JobjectComparator> CompileTimeClassPaths; 538 CompileTimeClassPaths compile_time_class_paths_; 539 bool use_compile_time_class_path_; 540 541 jobject main_thread_group_; 542 jobject system_thread_group_; 543 544 // As returned by ClassLoader.getSystemClassLoader(). 545 jobject system_class_loader_; 546 547 // If true, then we dump the GC cumulative timings on shutdown. 548 bool dump_gc_performance_on_shutdown_; 549 550 // Transaction used for pre-initializing classes at compilation time. 551 Transaction* preinitialization_transaction; 552 NullPointerHandler* null_pointer_handler_; 553 SuspensionHandler* suspend_handler_; 554 StackOverflowHandler* stack_overflow_handler_; 555 556 DISALLOW_COPY_AND_ASSIGN(Runtime); 557}; 558 559} // namespace art 560 561#endif // ART_RUNTIME_RUNTIME_H_ 562