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