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