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