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