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