1 /* 2 * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #ifndef SHARE_VM_RUNTIME_THREAD_HPP 26 #define SHARE_VM_RUNTIME_THREAD_HPP 27 28 #include "jni.h" 29 #include "gc/shared/threadLocalAllocBuffer.hpp" 30 #include "memory/allocation.hpp" 31 #include "oops/oop.hpp" 32 #include "prims/jvmtiExport.hpp" 33 #include "runtime/frame.hpp" 34 #include "runtime/javaFrameAnchor.hpp" 35 #include "runtime/jniHandles.hpp" 36 #include "runtime/mutexLocker.hpp" 37 #include "runtime/os.hpp" 38 #include "runtime/osThread.hpp" 39 #include "runtime/park.hpp" 40 #include "runtime/safepoint.hpp" 41 #include "runtime/stubRoutines.hpp" 42 #include "runtime/threadLocalStorage.hpp" 43 #include "runtime/thread_ext.hpp" 44 #include "runtime/unhandledOops.hpp" 45 #include "trace/traceBackend.hpp" 46 #include "trace/traceMacros.hpp" 47 #include "utilities/align.hpp" 48 #include "utilities/exceptions.hpp" 49 #include "utilities/macros.hpp" 50 #if INCLUDE_ALL_GCS 51 #include "gc/g1/dirtyCardQueue.hpp" 52 #include "gc/g1/satbMarkQueue.hpp" 53 #endif // INCLUDE_ALL_GCS 54 #ifdef ZERO 55 # include "stack_zero.hpp" 56 #endif 57 58 class ThreadSafepointState; 59 class ThreadsList; 60 class NestedThreadsList; 61 62 class JvmtiThreadState; 63 class JvmtiGetLoadedClassesClosure; 64 class ThreadStatistics; 65 class ConcurrentLocksDump; 66 class ParkEvent; 67 class Parker; 68 69 class ciEnv; 70 class CompileThread; 71 class CompileLog; 72 class CompileTask; 73 class CompileQueue; 74 class CompilerCounters; 75 class vframeArray; 76 77 class DeoptResourceMark; 78 class jvmtiDeferredLocalVariableSet; 79 80 class GCTaskQueue; 81 class ThreadClosure; 82 class IdealGraphPrinter; 83 84 class Metadata; 85 template <class T, MEMFLAGS F> class ChunkedList; 86 typedef ChunkedList<Metadata*, mtInternal> MetadataOnStackBuffer; 87 88 DEBUG_ONLY(class ResourceMark;) 89 90 class WorkerThread; 91 92 // Class hierarchy 93 // - Thread 94 // - NamedThread 95 // - VMThread 96 // - ConcurrentGCThread 97 // - WorkerThread 98 // - GangWorker 99 // - GCTaskThread 100 // - JavaThread 101 // - various subclasses eg CompilerThread, ServiceThread 102 // - WatcherThread 103 104 class Thread: public ThreadShadow { 105 friend class Threads; 106 friend class VMStructs; 107 friend class JVMCIVMStructs; 108 private: 109 110 #ifndef USE_LIBRARY_BASED_TLS_ONLY 111 // Current thread is maintained as a thread-local variable 112 static THREAD_LOCAL_DECL Thread* _thr_current; 113 #endif 114 115 // Exception handling 116 // (Note: _pending_exception and friends are in ThreadShadow) 117 //oop _pending_exception; // pending exception for current thread 118 // const char* _exception_file; // file information for exception (debugging only) 119 // int _exception_line; // line information for exception (debugging only) 120 protected: 121 // Support for forcing alignment of thread objects for biased locking 122 void* _real_malloc_address; 123 // JavaThread lifecycle support: 124 friend class ScanHazardPtrGatherProtectedThreadsClosure; 125 friend class ScanHazardPtrGatherThreadsListClosure; 126 friend class ScanHazardPtrPrintMatchingThreadsClosure; 127 friend class ThreadsListHandle; 128 friend class ThreadsListSetter; 129 ThreadsList* volatile _threads_hazard_ptr; 130 ThreadsList* cmpxchg_threads_hazard_ptr(ThreadsList* exchange_value, ThreadsList* compare_value); 131 ThreadsList* get_threads_hazard_ptr(); 132 void set_threads_hazard_ptr(ThreadsList* new_list); 133 static bool is_hazard_ptr_tagged(ThreadsList* list) { 134 return (intptr_t(list) & intptr_t(1)) == intptr_t(1); 135 } 136 static ThreadsList* tag_hazard_ptr(ThreadsList* list) { 137 return (ThreadsList*)(intptr_t(list) | intptr_t(1)); 138 } 139 static ThreadsList* untag_hazard_ptr(ThreadsList* list) { 140 return (ThreadsList*)(intptr_t(list) & ~intptr_t(1)); 141 } 142 NestedThreadsList* _nested_threads_hazard_ptr; 143 NestedThreadsList* get_nested_threads_hazard_ptr() { 144 return _nested_threads_hazard_ptr; 145 } 146 void set_nested_threads_hazard_ptr(NestedThreadsList* value) { 147 assert(Threads_lock->owned_by_self(), 148 "must own Threads_lock for _nested_threads_hazard_ptr to be valid."); 149 _nested_threads_hazard_ptr = value; 150 } 151 // This field is enabled via -XX:+EnableThreadSMRStatistics: 152 uint _nested_threads_hazard_ptr_cnt; 153 void dec_nested_threads_hazard_ptr_cnt() { 154 assert(_nested_threads_hazard_ptr_cnt != 0, "mismatched {dec,inc}_nested_threads_hazard_ptr_cnt()"); 155 _nested_threads_hazard_ptr_cnt--; 156 } 157 void inc_nested_threads_hazard_ptr_cnt() { 158 _nested_threads_hazard_ptr_cnt++; 159 } 160 uint nested_threads_hazard_ptr_cnt() { 161 return _nested_threads_hazard_ptr_cnt; 162 } 163 164 public: 165 void* operator new(size_t size) throw() { return allocate(size, true); } 166 void* operator new(size_t size, const std::nothrow_t& nothrow_constant) throw() { 167 return allocate(size, false); } 168 void operator delete(void* p); 169 170 protected: 171 static void* allocate(size_t size, bool throw_excpt, MEMFLAGS flags = mtThread); 172 private: 173 174 // *************************************************************** 175 // Suspend and resume support 176 // *************************************************************** 177 // 178 // VM suspend/resume no longer exists - it was once used for various 179 // things including safepoints but was deprecated and finally removed 180 // in Java 7. Because VM suspension was considered "internal" Java-level 181 // suspension was considered "external", and this legacy naming scheme 182 // remains. 183 // 184 // External suspend/resume requests come from JVM_SuspendThread, 185 // JVM_ResumeThread, JVMTI SuspendThread, and finally JVMTI 186 // ResumeThread. External 187 // suspend requests cause _external_suspend to be set and external 188 // resume requests cause _external_suspend to be cleared. 189 // External suspend requests do not nest on top of other external 190 // suspend requests. The higher level APIs reject suspend requests 191 // for already suspended threads. 192 // 193 // The external_suspend 194 // flag is checked by has_special_runtime_exit_condition() and java thread 195 // will self-suspend when handle_special_runtime_exit_condition() is 196 // called. Most uses of the _thread_blocked state in JavaThreads are 197 // considered the same as being externally suspended; if the blocking 198 // condition lifts, the JavaThread will self-suspend. Other places 199 // where VM checks for external_suspend include: 200 // + mutex granting (do not enter monitors when thread is suspended) 201 // + state transitions from _thread_in_native 202 // 203 // In general, java_suspend() does not wait for an external suspend 204 // request to complete. When it returns, the only guarantee is that 205 // the _external_suspend field is true. 206 // 207 // wait_for_ext_suspend_completion() is used to wait for an external 208 // suspend request to complete. External suspend requests are usually 209 // followed by some other interface call that requires the thread to 210 // be quiescent, e.g., GetCallTrace(). By moving the "wait time" into 211 // the interface that requires quiescence, we give the JavaThread a 212 // chance to self-suspend before we need it to be quiescent. This 213 // improves overall suspend/query performance. 214 // 215 // _suspend_flags controls the behavior of java_ suspend/resume. 216 // It must be set under the protection of SR_lock. Read from the flag is 217 // OK without SR_lock as long as the value is only used as a hint. 218 // (e.g., check _external_suspend first without lock and then recheck 219 // inside SR_lock and finish the suspension) 220 // 221 // _suspend_flags is also overloaded for other "special conditions" so 222 // that a single check indicates whether any special action is needed 223 // eg. for async exceptions. 224 // ------------------------------------------------------------------- 225 // Notes: 226 // 1. The suspend/resume logic no longer uses ThreadState in OSThread 227 // but we still update its value to keep other part of the system (mainly 228 // JVMTI) happy. ThreadState is legacy code (see notes in 229 // osThread.hpp). 230 // 231 // 2. It would be more natural if set_external_suspend() is private and 232 // part of java_suspend(), but that probably would affect the suspend/query 233 // performance. Need more investigation on this. 234 235 // suspend/resume lock: used for self-suspend 236 Monitor* _SR_lock; 237 238 protected: 239 enum SuspendFlags { 240 // NOTE: avoid using the sign-bit as cc generates different test code 241 // when the sign-bit is used, and sometimes incorrectly - see CR 6398077 242 243 _external_suspend = 0x20000000U, // thread is asked to self suspend 244 _ext_suspended = 0x40000000U, // thread has self-suspended 245 _deopt_suspend = 0x10000000U, // thread needs to self suspend for deopt 246 247 _has_async_exception = 0x00000001U, // there is a pending async exception 248 _critical_native_unlock = 0x00000002U, // Must call back to unlock JNI critical lock 249 250 _trace_flag = 0x00000004U // call tracing backend 251 }; 252 253 // various suspension related flags - atomically updated 254 // overloaded for async exception checking in check_special_condition_for_native_trans. 255 volatile uint32_t _suspend_flags; 256 257 private: 258 int _num_nested_signal; 259 260 DEBUG_ONLY(bool _suspendible_thread;) 261 262 public: 263 void enter_signal_handler() { _num_nested_signal++; } 264 void leave_signal_handler() { _num_nested_signal--; } 265 bool is_inside_signal_handler() const { return _num_nested_signal > 0; } 266 267 #ifdef ASSERT 268 void set_suspendible_thread() { 269 _suspendible_thread = true; 270 } 271 272 void clear_suspendible_thread() { 273 _suspendible_thread = false; 274 } 275 276 bool is_suspendible_thread() { return _suspendible_thread; } 277 #endif 278 279 private: 280 // Active_handles points to a block of handles 281 JNIHandleBlock* _active_handles; 282 283 // One-element thread local free list 284 JNIHandleBlock* _free_handle_block; 285 286 // Point to the last handle mark 287 HandleMark* _last_handle_mark; 288 289 // The parity of the last strong_roots iteration in which this thread was 290 // claimed as a task. 291 int _oops_do_parity; 292 293 public: 294 void set_last_handle_mark(HandleMark* mark) { _last_handle_mark = mark; } 295 HandleMark* last_handle_mark() const { return _last_handle_mark; } 296 private: 297 298 // debug support for checking if code does allow safepoints or not 299 // GC points in the VM can happen because of allocation, invoking a VM operation, or blocking on 300 // mutex, or blocking on an object synchronizer (Java locking). 301 // If !allow_safepoint(), then an assertion failure will happen in any of the above cases 302 // If !allow_allocation(), then an assertion failure will happen during allocation 303 // (Hence, !allow_safepoint() => !allow_allocation()). 304 // 305 // The two classes NoSafepointVerifier and No_Allocation_Verifier are used to set these counters. 306 // 307 NOT_PRODUCT(int _allow_safepoint_count;) // If 0, thread allow a safepoint to happen 308 debug_only(int _allow_allocation_count;) // If 0, the thread is allowed to allocate oops. 309 310 // Used by SkipGCALot class. 311 NOT_PRODUCT(bool _skip_gcalot;) // Should we elide gc-a-lot? 312 313 friend class NoAllocVerifier; 314 friend class NoSafepointVerifier; 315 friend class PauseNoSafepointVerifier; 316 friend class GCLocker; 317 318 ThreadLocalAllocBuffer _tlab; // Thread-local eden 319 jlong _allocated_bytes; // Cumulative number of bytes allocated on 320 // the Java heap 321 322 mutable TRACE_DATA _trace_data; // Thread-local data for tracing 323 324 ThreadExt _ext; 325 326 int _vm_operation_started_count; // VM_Operation support 327 int _vm_operation_completed_count; // VM_Operation support 328 329 ObjectMonitor* _current_pending_monitor; // ObjectMonitor this thread 330 // is waiting to lock 331 bool _current_pending_monitor_is_from_java; // locking is from Java code 332 333 // ObjectMonitor on which this thread called Object.wait() 334 ObjectMonitor* _current_waiting_monitor; 335 336 // Private thread-local objectmonitor list - a simple cache organized as a SLL. 337 public: 338 ObjectMonitor* omFreeList; 339 int omFreeCount; // length of omFreeList 340 int omFreeProvision; // reload chunk size 341 ObjectMonitor* omInUseList; // SLL to track monitors in circulation 342 int omInUseCount; // length of omInUseList 343 344 #ifdef ASSERT 345 private: 346 bool _visited_for_critical_count; 347 348 public: 349 void set_visited_for_critical_count(bool z) { _visited_for_critical_count = z; } 350 bool was_visited_for_critical_count() const { return _visited_for_critical_count; } 351 #endif 352 353 public: 354 enum { 355 is_definitely_current_thread = true 356 }; 357 358 // Constructor 359 Thread(); 360 virtual ~Thread(); 361 362 // Manage Thread::current() 363 void initialize_thread_current(); 364 void clear_thread_current(); // TLS cleanup needed before threads terminate 365 366 public: 367 // thread entry point 368 virtual void run(); 369 370 // Testers 371 virtual bool is_VM_thread() const { return false; } 372 virtual bool is_Java_thread() const { return false; } 373 virtual bool is_Compiler_thread() const { return false; } 374 virtual bool is_Code_cache_sweeper_thread() const { return false; } 375 virtual bool is_hidden_from_external_view() const { return false; } 376 virtual bool is_jvmti_agent_thread() const { return false; } 377 // True iff the thread can perform GC operations at a safepoint. 378 // Generally will be true only of VM thread and parallel GC WorkGang 379 // threads. 380 virtual bool is_GC_task_thread() const { return false; } 381 virtual bool is_Watcher_thread() const { return false; } 382 virtual bool is_ConcurrentGC_thread() const { return false; } 383 virtual bool is_Named_thread() const { return false; } 384 virtual bool is_Worker_thread() const { return false; } 385 386 // Can this thread make Java upcalls 387 virtual bool can_call_java() const { return false; } 388 389 // Casts 390 virtual WorkerThread* as_Worker_thread() const { return NULL; } 391 392 virtual char* name() const { return (char*)"Unknown thread"; } 393 394 // Returns the current thread (ASSERTS if NULL) 395 static inline Thread* current(); 396 // Returns the current thread, or NULL if not attached 397 static inline Thread* current_or_null(); 398 // Returns the current thread, or NULL if not attached, and is 399 // safe for use from signal-handlers 400 static inline Thread* current_or_null_safe(); 401 402 // Common thread operations 403 #ifdef ASSERT 404 static void check_for_dangling_thread_pointer(Thread *thread); 405 #endif 406 static void set_priority(Thread* thread, ThreadPriority priority); 407 static ThreadPriority get_priority(const Thread* const thread); 408 static void start(Thread* thread); 409 static void interrupt(Thread* thr); 410 static bool is_interrupted(Thread* thr, bool clear_interrupted); 411 412 void set_native_thread_name(const char *name) { 413 assert(Thread::current() == this, "set_native_thread_name can only be called on the current thread"); 414 os::set_native_thread_name(name); 415 } 416 417 ObjectMonitor** omInUseList_addr() { return (ObjectMonitor **)&omInUseList; } 418 Monitor* SR_lock() const { return _SR_lock; } 419 420 bool has_async_exception() const { return (_suspend_flags & _has_async_exception) != 0; } 421 422 inline void set_suspend_flag(SuspendFlags f); 423 inline void clear_suspend_flag(SuspendFlags f); 424 425 inline void set_has_async_exception(); 426 inline void clear_has_async_exception(); 427 428 bool do_critical_native_unlock() const { return (_suspend_flags & _critical_native_unlock) != 0; } 429 430 inline void set_critical_native_unlock(); 431 inline void clear_critical_native_unlock(); 432 433 inline void set_trace_flag(); 434 inline void clear_trace_flag(); 435 436 // Support for Unhandled Oop detection 437 // Add the field for both, fastdebug and debug, builds to keep 438 // Thread's fields layout the same. 439 // Note: CHECK_UNHANDLED_OOPS is defined only for fastdebug build. 440 #ifdef CHECK_UNHANDLED_OOPS 441 private: 442 UnhandledOops* _unhandled_oops; 443 #elif defined(ASSERT) 444 private: 445 void* _unhandled_oops; 446 #endif 447 #ifdef CHECK_UNHANDLED_OOPS 448 public: 449 UnhandledOops* unhandled_oops() { return _unhandled_oops; } 450 // Mark oop safe for gc. It may be stack allocated but won't move. 451 void allow_unhandled_oop(oop *op) { 452 if (CheckUnhandledOops) unhandled_oops()->allow_unhandled_oop(op); 453 } 454 // Clear oops at safepoint so crashes point to unhandled oop violator 455 void clear_unhandled_oops() { 456 if (CheckUnhandledOops) unhandled_oops()->clear_unhandled_oops(); 457 } 458 #endif // CHECK_UNHANDLED_OOPS 459 460 public: 461 #ifndef PRODUCT 462 bool skip_gcalot() { return _skip_gcalot; } 463 void set_skip_gcalot(bool v) { _skip_gcalot = v; } 464 #endif 465 466 // Installs a pending exception to be inserted later 467 static void send_async_exception(oop thread_oop, oop java_throwable); 468 469 // Resource area 470 ResourceArea* resource_area() const { return _resource_area; } 471 void set_resource_area(ResourceArea* area) { _resource_area = area; } 472 473 OSThread* osthread() const { return _osthread; } 474 void set_osthread(OSThread* thread) { _osthread = thread; } 475 476 // JNI handle support 477 JNIHandleBlock* active_handles() const { return _active_handles; } 478 void set_active_handles(JNIHandleBlock* block) { _active_handles = block; } 479 JNIHandleBlock* free_handle_block() const { return _free_handle_block; } 480 void set_free_handle_block(JNIHandleBlock* block) { _free_handle_block = block; } 481 482 // Internal handle support 483 HandleArea* handle_area() const { return _handle_area; } 484 void set_handle_area(HandleArea* area) { _handle_area = area; } 485 486 GrowableArray<Metadata*>* metadata_handles() const { return _metadata_handles; } 487 void set_metadata_handles(GrowableArray<Metadata*>* handles){ _metadata_handles = handles; } 488 489 // Thread-Local Allocation Buffer (TLAB) support 490 ThreadLocalAllocBuffer& tlab() { return _tlab; } 491 void initialize_tlab() { 492 if (UseTLAB) { 493 tlab().initialize(); 494 } 495 } 496 497 jlong allocated_bytes() { return _allocated_bytes; } 498 void set_allocated_bytes(jlong value) { _allocated_bytes = value; } 499 void incr_allocated_bytes(jlong size) { _allocated_bytes += size; } 500 inline jlong cooked_allocated_bytes(); 501 502 TRACE_DEFINE_THREAD_TRACE_DATA_OFFSET; 503 TRACE_DATA* trace_data() const { return &_trace_data; } 504 bool is_trace_suspend() { return (_suspend_flags & _trace_flag) != 0; } 505 506 const ThreadExt& ext() const { return _ext; } 507 ThreadExt& ext() { return _ext; } 508 509 // VM operation support 510 int vm_operation_ticket() { return ++_vm_operation_started_count; } 511 int vm_operation_completed_count() { return _vm_operation_completed_count; } 512 void increment_vm_operation_completed_count() { _vm_operation_completed_count++; } 513 514 // For tracking the heavyweight monitor the thread is pending on. 515 ObjectMonitor* current_pending_monitor() { 516 return _current_pending_monitor; 517 } 518 void set_current_pending_monitor(ObjectMonitor* monitor) { 519 _current_pending_monitor = monitor; 520 } 521 void set_current_pending_monitor_is_from_java(bool from_java) { 522 _current_pending_monitor_is_from_java = from_java; 523 } 524 bool current_pending_monitor_is_from_java() { 525 return _current_pending_monitor_is_from_java; 526 } 527 528 // For tracking the ObjectMonitor on which this thread called Object.wait() 529 ObjectMonitor* current_waiting_monitor() { 530 return _current_waiting_monitor; 531 } 532 void set_current_waiting_monitor(ObjectMonitor* monitor) { 533 _current_waiting_monitor = monitor; 534 } 535 536 // GC support 537 // Apply "f->do_oop" to all root oops in "this". 538 // Used by JavaThread::oops_do. 539 // Apply "cf->do_code_blob" (if !NULL) to all code blobs active in frames 540 virtual void oops_do(OopClosure* f, CodeBlobClosure* cf); 541 542 // Handles the parallel case for the method below. 543 private: 544 bool claim_oops_do_par_case(int collection_parity); 545 public: 546 // Requires that "collection_parity" is that of the current roots 547 // iteration. If "is_par" is false, sets the parity of "this" to 548 // "collection_parity", and returns "true". If "is_par" is true, 549 // uses an atomic instruction to set the current threads parity to 550 // "collection_parity", if it is not already. Returns "true" iff the 551 // calling thread does the update, this indicates that the calling thread 552 // has claimed the thread's stack as a root groop in the current 553 // collection. 554 bool claim_oops_do(bool is_par, int collection_parity) { 555 if (!is_par) { 556 _oops_do_parity = collection_parity; 557 return true; 558 } else { 559 return claim_oops_do_par_case(collection_parity); 560 } 561 } 562 563 // jvmtiRedefineClasses support 564 void metadata_handles_do(void f(Metadata*)); 565 566 // Used by fast lock support 567 virtual bool is_lock_owned(address adr) const; 568 569 // Check if address is in the stack of the thread (not just for locks). 570 // Warning: the method can only be used on the running thread 571 bool is_in_stack(address adr) const; 572 // Check if address is in the usable part of the stack (excludes protected 573 // guard pages) 574 bool is_in_usable_stack(address adr) const; 575 576 // Sets this thread as starting thread. Returns failure if thread 577 // creation fails due to lack of memory, too many threads etc. 578 bool set_as_starting_thread(); 579 580 protected: 581 // OS data associated with the thread 582 OSThread* _osthread; // Platform-specific thread information 583 584 // Thread local resource area for temporary allocation within the VM 585 ResourceArea* _resource_area; 586 587 DEBUG_ONLY(ResourceMark* _current_resource_mark;) 588 589 // Thread local handle area for allocation of handles within the VM 590 HandleArea* _handle_area; 591 GrowableArray<Metadata*>* _metadata_handles; 592 593 // Support for stack overflow handling, get_thread, etc. 594 address _stack_base; 595 size_t _stack_size; 596 uintptr_t _self_raw_id; // used by get_thread (mutable) 597 int _lgrp_id; 598 599 public: 600 // Stack overflow support 601 address stack_base() const { assert(_stack_base != NULL,"Sanity check"); return _stack_base; } 602 void set_stack_base(address base) { _stack_base = base; } 603 size_t stack_size() const { return _stack_size; } 604 void set_stack_size(size_t size) { _stack_size = size; } 605 address stack_end() const { return stack_base() - stack_size(); } 606 void record_stack_base_and_size(); 607 608 bool on_local_stack(address adr) const { 609 // QQQ this has knowledge of direction, ought to be a stack method 610 return (_stack_base >= adr && adr >= stack_end()); 611 } 612 613 uintptr_t self_raw_id() { return _self_raw_id; } 614 void set_self_raw_id(uintptr_t value) { _self_raw_id = value; } 615 616 int lgrp_id() const { return _lgrp_id; } 617 void set_lgrp_id(int value) { _lgrp_id = value; } 618 619 // Printing 620 virtual void print_on(outputStream* st) const; 621 virtual void print_nested_threads_hazard_ptrs_on(outputStream* st) const; 622 void print() const { print_on(tty); } 623 virtual void print_on_error(outputStream* st, char* buf, int buflen) const; 624 void print_value_on(outputStream* st) const; 625 626 // Debug-only code 627 #ifdef ASSERT 628 private: 629 // Deadlock detection support for Mutex locks. List of locks own by thread. 630 Monitor* _owned_locks; 631 // Mutex::set_owner_implementation is the only place where _owned_locks is modified, 632 // thus the friendship 633 friend class Mutex; 634 friend class Monitor; 635 636 public: 637 void print_owned_locks_on(outputStream* st) const; 638 void print_owned_locks() const { print_owned_locks_on(tty); } 639 Monitor* owned_locks() const { return _owned_locks; } 640 bool owns_locks() const { return owned_locks() != NULL; } 641 bool owns_locks_but_compiled_lock() const; 642 int oops_do_parity() const { return _oops_do_parity; } 643 644 // Deadlock detection 645 bool allow_allocation() { return _allow_allocation_count == 0; } 646 ResourceMark* current_resource_mark() { return _current_resource_mark; } 647 void set_current_resource_mark(ResourceMark* rm) { _current_resource_mark = rm; } 648 #endif 649 650 void check_for_valid_safepoint_state(bool potential_vm_operation) PRODUCT_RETURN; 651 652 private: 653 volatile int _jvmti_env_iteration_count; 654 655 public: 656 void entering_jvmti_env_iteration() { ++_jvmti_env_iteration_count; } 657 void leaving_jvmti_env_iteration() { --_jvmti_env_iteration_count; } 658 bool is_inside_jvmti_env_iteration() { return _jvmti_env_iteration_count > 0; } 659 660 // Code generation 661 static ByteSize exception_file_offset() { return byte_offset_of(Thread, _exception_file); } 662 static ByteSize exception_line_offset() { return byte_offset_of(Thread, _exception_line); } 663 static ByteSize active_handles_offset() { return byte_offset_of(Thread, _active_handles); } 664 665 static ByteSize stack_base_offset() { return byte_offset_of(Thread, _stack_base); } 666 static ByteSize stack_size_offset() { return byte_offset_of(Thread, _stack_size); } 667 668 #define TLAB_FIELD_OFFSET(name) \ 669 static ByteSize tlab_##name##_offset() { return byte_offset_of(Thread, _tlab) + ThreadLocalAllocBuffer::name##_offset(); } 670 671 TLAB_FIELD_OFFSET(start) 672 TLAB_FIELD_OFFSET(end) 673 TLAB_FIELD_OFFSET(top) 674 TLAB_FIELD_OFFSET(pf_top) 675 TLAB_FIELD_OFFSET(size) // desired_size 676 TLAB_FIELD_OFFSET(refill_waste_limit) 677 TLAB_FIELD_OFFSET(number_of_refills) 678 TLAB_FIELD_OFFSET(fast_refill_waste) 679 TLAB_FIELD_OFFSET(slow_allocations) 680 681 #undef TLAB_FIELD_OFFSET 682 683 static ByteSize allocated_bytes_offset() { return byte_offset_of(Thread, _allocated_bytes); } 684 685 public: 686 volatile intptr_t _Stalled; 687 volatile int _TypeTag; 688 ParkEvent * _ParkEvent; // for synchronized() 689 ParkEvent * _SleepEvent; // for Thread.sleep 690 ParkEvent * _MutexEvent; // for native internal Mutex/Monitor 691 ParkEvent * _MuxEvent; // for low-level muxAcquire-muxRelease 692 int NativeSyncRecursion; // diagnostic 693 694 volatile int _OnTrap; // Resume-at IP delta 695 jint _hashStateW; // Marsaglia Shift-XOR thread-local RNG 696 jint _hashStateX; // thread-specific hashCode generator state 697 jint _hashStateY; 698 jint _hashStateZ; 699 void * _schedctl; 700 701 702 volatile jint rng[4]; // RNG for spin loop 703 704 // Low-level leaf-lock primitives used to implement synchronization 705 // and native monitor-mutex infrastructure. 706 // Not for general synchronization use. 707 static void SpinAcquire(volatile int * Lock, const char * Name); 708 static void SpinRelease(volatile int * Lock); 709 static void muxAcquire(volatile intptr_t * Lock, const char * Name); 710 static void muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev); 711 static void muxRelease(volatile intptr_t * Lock); 712 }; 713 714 // Inline implementation of Thread::current() 715 inline Thread* Thread::current() { 716 Thread* current = current_or_null(); 717 assert(current != NULL, "Thread::current() called on detached thread"); 718 return current; 719 } 720 721 inline Thread* Thread::current_or_null() { 722 #ifndef USE_LIBRARY_BASED_TLS_ONLY 723 return _thr_current; 724 #else 725 if (ThreadLocalStorage::is_initialized()) { 726 return ThreadLocalStorage::thread(); 727 } 728 return NULL; 729 #endif 730 } 731 732 inline Thread* Thread::current_or_null_safe() { 733 if (ThreadLocalStorage::is_initialized()) { 734 return ThreadLocalStorage::thread(); 735 } 736 return NULL; 737 } 738 739 // Name support for threads. non-JavaThread subclasses with multiple 740 // uniquely named instances should derive from this. 741 class NamedThread: public Thread { 742 friend class VMStructs; 743 enum { 744 max_name_len = 64 745 }; 746 private: 747 char* _name; 748 // log JavaThread being processed by oops_do 749 JavaThread* _processed_thread; 750 uint _gc_id; // The current GC id when a thread takes part in GC 751 752 public: 753 NamedThread(); 754 ~NamedThread(); 755 // May only be called once per thread. 756 void set_name(const char* format, ...) ATTRIBUTE_PRINTF(2, 3); 757 void initialize_named_thread(); 758 virtual bool is_Named_thread() const { return true; } 759 virtual char* name() const { return _name == NULL ? (char*)"Unknown Thread" : _name; } 760 JavaThread *processed_thread() { return _processed_thread; } 761 void set_processed_thread(JavaThread *thread) { _processed_thread = thread; } 762 virtual void print_on(outputStream* st) const; 763 764 void set_gc_id(uint gc_id) { _gc_id = gc_id; } 765 uint gc_id() { return _gc_id; } 766 }; 767 768 // Worker threads are named and have an id of an assigned work. 769 class WorkerThread: public NamedThread { 770 private: 771 uint _id; 772 public: 773 WorkerThread() : _id(0) { } 774 virtual bool is_Worker_thread() const { return true; } 775 776 virtual WorkerThread* as_Worker_thread() const { 777 assert(is_Worker_thread(), "Dubious cast to WorkerThread*?"); 778 return (WorkerThread*) this; 779 } 780 781 void set_id(uint work_id) { _id = work_id; } 782 uint id() const { return _id; } 783 }; 784 785 // A single WatcherThread is used for simulating timer interrupts. 786 class WatcherThread: public Thread { 787 friend class VMStructs; 788 public: 789 virtual void run(); 790 791 private: 792 static WatcherThread* _watcher_thread; 793 794 static bool _startable; 795 // volatile due to at least one lock-free read 796 volatile static bool _should_terminate; 797 public: 798 enum SomeConstants { 799 delay_interval = 10 // interrupt delay in milliseconds 800 }; 801 802 // Constructor 803 WatcherThread(); 804 805 // No destruction allowed 806 ~WatcherThread() { 807 guarantee(false, "WatcherThread deletion must fix the race with VM termination"); 808 } 809 810 // Tester 811 bool is_Watcher_thread() const { return true; } 812 813 // Printing 814 char* name() const { return (char*)"VM Periodic Task Thread"; } 815 void print_on(outputStream* st) const; 816 void unpark(); 817 818 // Returns the single instance of WatcherThread 819 static WatcherThread* watcher_thread() { return _watcher_thread; } 820 821 // Create and start the single instance of WatcherThread, or stop it on shutdown 822 static void start(); 823 static void stop(); 824 // Only allow start once the VM is sufficiently initialized 825 // Otherwise the first task to enroll will trigger the start 826 static void make_startable(); 827 private: 828 int sleep() const; 829 }; 830 831 832 class CompilerThread; 833 834 typedef void (*ThreadFunction)(JavaThread*, TRAPS); 835 836 class JavaThread: public Thread { 837 friend class VMStructs; 838 friend class JVMCIVMStructs; 839 friend class WhiteBox; 840 private: 841 JavaThread* _next; // The next thread in the Threads list 842 bool _on_thread_list; // Is set when this JavaThread is added to the Threads list 843 oop _threadObj; // The Java level thread object 844 845 #ifdef ASSERT 846 private: 847 int _java_call_counter; 848 849 public: 850 int java_call_counter() { return _java_call_counter; } 851 void inc_java_call_counter() { _java_call_counter++; } 852 void dec_java_call_counter() { 853 assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper"); 854 _java_call_counter--; 855 } 856 private: // restore original namespace restriction 857 #endif // ifdef ASSERT 858 859 #ifndef PRODUCT 860 public: 861 enum { 862 jump_ring_buffer_size = 16 863 }; 864 private: // restore original namespace restriction 865 #endif 866 867 JavaFrameAnchor _anchor; // Encapsulation of current java frame and it state 868 869 ThreadFunction _entry_point; 870 871 JNIEnv _jni_environment; 872 873 // Deopt support 874 DeoptResourceMark* _deopt_mark; // Holds special ResourceMark for deoptimization 875 876 intptr_t* _must_deopt_id; // id of frame that needs to be deopted once we 877 // transition out of native 878 CompiledMethod* _deopt_nmethod; // CompiledMethod that is currently being deoptimized 879 vframeArray* _vframe_array_head; // Holds the heap of the active vframeArrays 880 vframeArray* _vframe_array_last; // Holds last vFrameArray we popped 881 // Because deoptimization is lazy we must save jvmti requests to set locals 882 // in compiled frames until we deoptimize and we have an interpreter frame. 883 // This holds the pointer to array (yeah like there might be more than one) of 884 // description of compiled vframes that have locals that need to be updated. 885 GrowableArray<jvmtiDeferredLocalVariableSet*>* _deferred_locals_updates; 886 887 // Handshake value for fixing 6243940. We need a place for the i2c 888 // adapter to store the callee Method*. This value is NEVER live 889 // across a gc point so it does NOT have to be gc'd 890 // The handshake is open ended since we can't be certain that it will 891 // be NULLed. This is because we rarely ever see the race and end up 892 // in handle_wrong_method which is the backend of the handshake. See 893 // code in i2c adapters and handle_wrong_method. 894 895 Method* _callee_target; 896 897 // Used to pass back results to the interpreter or generated code running Java code. 898 oop _vm_result; // oop result is GC-preserved 899 Metadata* _vm_result_2; // non-oop result 900 901 // See ReduceInitialCardMarks: this holds the precise space interval of 902 // the most recent slow path allocation for which compiled code has 903 // elided card-marks for performance along the fast-path. 904 MemRegion _deferred_card_mark; 905 906 MonitorChunk* _monitor_chunks; // Contains the off stack monitors 907 // allocated during deoptimization 908 // and by JNI_MonitorEnter/Exit 909 910 // Async. requests support 911 enum AsyncRequests { 912 _no_async_condition = 0, 913 _async_exception, 914 _async_unsafe_access_error 915 }; 916 AsyncRequests _special_runtime_exit_condition; // Enum indicating pending async. request 917 oop _pending_async_exception; 918 919 // Safepoint support 920 public: // Expose _thread_state for SafeFetchInt() 921 volatile JavaThreadState _thread_state; 922 private: 923 ThreadSafepointState *_safepoint_state; // Holds information about a thread during a safepoint 924 address _saved_exception_pc; // Saved pc of instruction where last implicit exception happened 925 926 // JavaThread termination support 927 enum TerminatedTypes { 928 _not_terminated = 0xDEAD - 2, 929 _thread_exiting, // JavaThread::exit() has been called for this thread 930 _thread_terminated, // JavaThread is removed from thread list 931 _vm_exited // JavaThread is still executing native code, but VM is terminated 932 // only VM_Exit can set _vm_exited 933 }; 934 935 // In general a JavaThread's _terminated field transitions as follows: 936 // 937 // _not_terminated => _thread_exiting => _thread_terminated 938 // 939 // _vm_exited is a special value to cover the case of a JavaThread 940 // executing native code after the VM itself is terminated. 941 volatile TerminatedTypes _terminated; 942 // suspend/resume support 943 volatile bool _suspend_equivalent; // Suspend equivalent condition 944 jint _in_deopt_handler; // count of deoptimization 945 // handlers thread is in 946 volatile bool _doing_unsafe_access; // Thread may fault due to unsafe access 947 bool _do_not_unlock_if_synchronized; // Do not unlock the receiver of a synchronized method (since it was 948 // never locked) when throwing an exception. Used by interpreter only. 949 950 // JNI attach states: 951 enum JNIAttachStates { 952 _not_attaching_via_jni = 1, // thread is not attaching via JNI 953 _attaching_via_jni, // thread is attaching via JNI 954 _attached_via_jni // thread has attached via JNI 955 }; 956 957 // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni. 958 // A native thread that is attaching via JNI starts with a value 959 // of _attaching_via_jni and transitions to _attached_via_jni. 960 volatile JNIAttachStates _jni_attach_state; 961 962 public: 963 // State of the stack guard pages for this thread. 964 enum StackGuardState { 965 stack_guard_unused, // not needed 966 stack_guard_reserved_disabled, 967 stack_guard_yellow_reserved_disabled,// disabled (temporarily) after stack overflow 968 stack_guard_enabled // enabled 969 }; 970 971 private: 972 973 #if INCLUDE_JVMCI 974 // The _pending_* fields below are used to communicate extra information 975 // from an uncommon trap in JVMCI compiled code to the uncommon trap handler. 976 977 // Communicates the DeoptReason and DeoptAction of the uncommon trap 978 int _pending_deoptimization; 979 980 // Specifies whether the uncommon trap is to bci 0 of a synchronized method 981 // before the monitor has been acquired. 982 bool _pending_monitorenter; 983 984 // Specifies if the DeoptReason for the last uncommon trap was Reason_transfer_to_interpreter 985 bool _pending_transfer_to_interpreter; 986 987 // Guard for re-entrant call to JVMCIRuntime::adjust_comp_level 988 bool _adjusting_comp_level; 989 990 // An object that JVMCI compiled code can use to further describe and 991 // uniquely identify the speculative optimization guarded by the uncommon trap 992 oop _pending_failed_speculation; 993 994 // These fields are mutually exclusive in terms of live ranges. 995 union { 996 // Communicates the pc at which the most recent implicit exception occurred 997 // from the signal handler to a deoptimization stub. 998 address _implicit_exception_pc; 999 1000 // Communicates an alternative call target to an i2c stub from a JavaCall . 1001 address _alternate_call_target; 1002 } _jvmci; 1003 1004 // Support for high precision, thread sensitive counters in JVMCI compiled code. 1005 jlong* _jvmci_counters; 1006 1007 public: 1008 static jlong* _jvmci_old_thread_counters; 1009 static void collect_counters(typeArrayOop array); 1010 private: 1011 #endif // INCLUDE_JVMCI 1012 1013 StackGuardState _stack_guard_state; 1014 1015 // Precompute the limit of the stack as used in stack overflow checks. 1016 // We load it from here to simplify the stack overflow check in assembly. 1017 address _stack_overflow_limit; 1018 address _reserved_stack_activation; 1019 1020 // Compiler exception handling (NOTE: The _exception_oop is *NOT* the same as _pending_exception. It is 1021 // used to temp. parsing values into and out of the runtime system during exception handling for compiled 1022 // code) 1023 volatile oop _exception_oop; // Exception thrown in compiled code 1024 volatile address _exception_pc; // PC where exception happened 1025 volatile address _exception_handler_pc; // PC for handler of exception 1026 volatile int _is_method_handle_return; // true (== 1) if the current exception PC is a MethodHandle call site. 1027 1028 private: 1029 // support for JNI critical regions 1030 jint _jni_active_critical; // count of entries into JNI critical region 1031 1032 // Checked JNI: function name requires exception check 1033 char* _pending_jni_exception_check_fn; 1034 1035 // For deadlock detection. 1036 int _depth_first_number; 1037 1038 // JVMTI PopFrame support 1039 // This is set to popframe_pending to signal that top Java frame should be popped immediately 1040 int _popframe_condition; 1041 1042 // If reallocation of scalar replaced objects fails, we throw OOM 1043 // and during exception propagation, pop the top 1044 // _frames_to_pop_failed_realloc frames, the ones that reference 1045 // failed reallocations. 1046 int _frames_to_pop_failed_realloc; 1047 1048 #ifndef PRODUCT 1049 int _jmp_ring_index; 1050 struct { 1051 // We use intptr_t instead of address so debugger doesn't try and display strings 1052 intptr_t _target; 1053 intptr_t _instruction; 1054 const char* _file; 1055 int _line; 1056 } _jmp_ring[jump_ring_buffer_size]; 1057 #endif // PRODUCT 1058 1059 #if INCLUDE_ALL_GCS 1060 // Support for G1 barriers 1061 1062 SATBMarkQueue _satb_mark_queue; // Thread-local log for SATB barrier. 1063 // Set of all such queues. 1064 static SATBMarkQueueSet _satb_mark_queue_set; 1065 1066 DirtyCardQueue _dirty_card_queue; // Thread-local log for dirty cards. 1067 // Set of all such queues. 1068 static DirtyCardQueueSet _dirty_card_queue_set; 1069 1070 void flush_barrier_queues(); 1071 #endif // INCLUDE_ALL_GCS 1072 1073 friend class VMThread; 1074 friend class ThreadWaitTransition; 1075 friend class VM_Exit; 1076 1077 void initialize(); // Initialized the instance variables 1078 1079 public: 1080 // Constructor 1081 JavaThread(bool is_attaching_via_jni = false); // for main thread and JNI attached threads 1082 JavaThread(ThreadFunction entry_point, size_t stack_size = 0); 1083 ~JavaThread(); 1084 1085 #ifdef ASSERT 1086 // verify this JavaThread hasn't be published in the Threads::list yet 1087 void verify_not_published(); 1088 #endif 1089 1090 //JNI functiontable getter/setter for JVMTI jni function table interception API. 1091 void set_jni_functions(struct JNINativeInterface_* functionTable) { 1092 _jni_environment.functions = functionTable; 1093 } 1094 struct JNINativeInterface_* get_jni_functions() { 1095 return (struct JNINativeInterface_ *)_jni_environment.functions; 1096 } 1097 1098 // This function is called at thread creation to allow 1099 // platform specific thread variables to be initialized. 1100 void cache_global_variables(); 1101 1102 // Executes Shutdown.shutdown() 1103 void invoke_shutdown_hooks(); 1104 1105 // Cleanup on thread exit 1106 enum ExitType { 1107 normal_exit, 1108 jni_detach 1109 }; 1110 void exit(bool destroy_vm, ExitType exit_type = normal_exit); 1111 1112 void cleanup_failed_attach_current_thread(); 1113 1114 // Testers 1115 virtual bool is_Java_thread() const { return true; } 1116 virtual bool can_call_java() const { return true; } 1117 1118 // Thread chain operations 1119 JavaThread* next() const { return _next; } 1120 void set_next(JavaThread* p) { _next = p; } 1121 1122 // Thread oop. threadObj() can be NULL for initial JavaThread 1123 // (or for threads attached via JNI) 1124 oop threadObj() const { return _threadObj; } 1125 void set_threadObj(oop p) { _threadObj = p; } 1126 1127 ThreadPriority java_priority() const; // Read from threadObj() 1128 1129 // Prepare thread and add to priority queue. If a priority is 1130 // not specified, use the priority of the thread object. Threads_lock 1131 // must be held while this function is called. 1132 void prepare(jobject jni_thread, ThreadPriority prio=NoPriority); 1133 void prepare_ext(); 1134 1135 void set_saved_exception_pc(address pc) { _saved_exception_pc = pc; } 1136 address saved_exception_pc() { return _saved_exception_pc; } 1137 1138 1139 ThreadFunction entry_point() const { return _entry_point; } 1140 1141 // Allocates a new Java level thread object for this thread. thread_name may be NULL. 1142 void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS); 1143 1144 // Last frame anchor routines 1145 1146 JavaFrameAnchor* frame_anchor(void) { return &_anchor; } 1147 1148 // last_Java_sp 1149 bool has_last_Java_frame() const { return _anchor.has_last_Java_frame(); } 1150 intptr_t* last_Java_sp() const { return _anchor.last_Java_sp(); } 1151 1152 // last_Java_pc 1153 1154 address last_Java_pc(void) { return _anchor.last_Java_pc(); } 1155 1156 // Safepoint support 1157 #if !(defined(PPC64) || defined(AARCH64)) 1158 JavaThreadState thread_state() const { return _thread_state; } 1159 void set_thread_state(JavaThreadState s) { _thread_state = s; } 1160 #else 1161 // Use membars when accessing volatile _thread_state. See 1162 // Threads::create_vm() for size checks. 1163 inline JavaThreadState thread_state() const; 1164 inline void set_thread_state(JavaThreadState s); 1165 #endif 1166 ThreadSafepointState *safepoint_state() const { return _safepoint_state; } 1167 void set_safepoint_state(ThreadSafepointState *state) { _safepoint_state = state; } 1168 bool is_at_poll_safepoint() { return _safepoint_state->is_at_poll_safepoint(); } 1169 1170 // JavaThread termination and lifecycle support: 1171 void smr_delete(); 1172 bool on_thread_list() { return _on_thread_list; } 1173 void set_on_thread_list() { _on_thread_list = true; } 1174 1175 // thread has called JavaThread::exit() or is terminated 1176 bool is_exiting() const; 1177 // thread is terminated (no longer on the threads list); we compare 1178 // against the two non-terminated values so that a freed JavaThread 1179 // will also be considered terminated. 1180 bool check_is_terminated(TerminatedTypes l_terminated) const { 1181 return l_terminated != _not_terminated && l_terminated != _thread_exiting; 1182 } 1183 bool is_terminated(); 1184 void set_terminated(TerminatedTypes t); 1185 // special for Threads::remove() which is static: 1186 void set_terminated_value(); 1187 void block_if_vm_exited(); 1188 1189 bool doing_unsafe_access() { return _doing_unsafe_access; } 1190 void set_doing_unsafe_access(bool val) { _doing_unsafe_access = val; } 1191 1192 bool do_not_unlock_if_synchronized() { return _do_not_unlock_if_synchronized; } 1193 void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; } 1194 1195 // Suspend/resume support for JavaThread 1196 private: 1197 inline void set_ext_suspended(); 1198 inline void clear_ext_suspended(); 1199 1200 public: 1201 void java_suspend(); 1202 void java_resume(); 1203 int java_suspend_self(); 1204 1205 void check_and_wait_while_suspended() { 1206 assert(JavaThread::current() == this, "sanity check"); 1207 1208 bool do_self_suspend; 1209 do { 1210 // were we externally suspended while we were waiting? 1211 do_self_suspend = handle_special_suspend_equivalent_condition(); 1212 if (do_self_suspend) { 1213 // don't surprise the thread that suspended us by returning 1214 java_suspend_self(); 1215 set_suspend_equivalent(); 1216 } 1217 } while (do_self_suspend); 1218 } 1219 static void check_safepoint_and_suspend_for_native_trans(JavaThread *thread); 1220 // Check for async exception in addition to safepoint and suspend request. 1221 static void check_special_condition_for_native_trans(JavaThread *thread); 1222 1223 // Same as check_special_condition_for_native_trans but finishes the 1224 // transition into thread_in_Java mode so that it can potentially 1225 // block. 1226 static void check_special_condition_for_native_trans_and_transition(JavaThread *thread); 1227 1228 bool is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits); 1229 bool is_ext_suspend_completed_with_lock(uint32_t *bits) { 1230 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1231 // Warning: is_ext_suspend_completed() may temporarily drop the 1232 // SR_lock to allow the thread to reach a stable thread state if 1233 // it is currently in a transient thread state. 1234 return is_ext_suspend_completed(false /* !called_by_wait */, 1235 SuspendRetryDelay, bits); 1236 } 1237 1238 // We cannot allow wait_for_ext_suspend_completion() to run forever or 1239 // we could hang. SuspendRetryCount and SuspendRetryDelay are normally 1240 // passed as the count and delay parameters. Experiments with specific 1241 // calls to wait_for_ext_suspend_completion() can be done by passing 1242 // other values in the code. Experiments with all calls can be done 1243 // via the appropriate -XX options. 1244 bool wait_for_ext_suspend_completion(int count, int delay, uint32_t *bits); 1245 1246 // test for suspend - most (all?) of these should go away 1247 bool is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits); 1248 1249 inline void set_external_suspend(); 1250 inline void clear_external_suspend(); 1251 1252 inline void set_deopt_suspend(); 1253 inline void clear_deopt_suspend(); 1254 bool is_deopt_suspend() { return (_suspend_flags & _deopt_suspend) != 0; } 1255 1256 bool is_external_suspend() const { 1257 return (_suspend_flags & _external_suspend) != 0; 1258 } 1259 // Whenever a thread transitions from native to vm/java it must suspend 1260 // if external|deopt suspend is present. 1261 bool is_suspend_after_native() const { 1262 return (_suspend_flags & (_external_suspend | _deopt_suspend)) != 0; 1263 } 1264 1265 // external suspend request is completed 1266 bool is_ext_suspended() const { 1267 return (_suspend_flags & _ext_suspended) != 0; 1268 } 1269 1270 bool is_external_suspend_with_lock() const { 1271 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1272 return is_external_suspend(); 1273 } 1274 1275 // Special method to handle a pending external suspend request 1276 // when a suspend equivalent condition lifts. 1277 bool handle_special_suspend_equivalent_condition() { 1278 assert(is_suspend_equivalent(), 1279 "should only be called in a suspend equivalence condition"); 1280 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1281 bool ret = is_external_suspend(); 1282 if (!ret) { 1283 // not about to self-suspend so clear suspend equivalence 1284 clear_suspend_equivalent(); 1285 } 1286 // implied else: 1287 // We have a pending external suspend request so we leave the 1288 // suspend_equivalent flag set until java_suspend_self() sets 1289 // the ext_suspended flag and clears the suspend_equivalent 1290 // flag. This insures that wait_for_ext_suspend_completion() 1291 // will return consistent values. 1292 return ret; 1293 } 1294 1295 // utility methods to see if we are doing some kind of suspension 1296 bool is_being_ext_suspended() const { 1297 MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag); 1298 return is_ext_suspended() || is_external_suspend(); 1299 } 1300 1301 bool is_suspend_equivalent() const { return _suspend_equivalent; } 1302 1303 void set_suspend_equivalent() { _suspend_equivalent = true; } 1304 void clear_suspend_equivalent() { _suspend_equivalent = false; } 1305 1306 // Thread.stop support 1307 void send_thread_stop(oop throwable); 1308 AsyncRequests clear_special_runtime_exit_condition() { 1309 AsyncRequests x = _special_runtime_exit_condition; 1310 _special_runtime_exit_condition = _no_async_condition; 1311 return x; 1312 } 1313 1314 // Are any async conditions present? 1315 bool has_async_condition() { return (_special_runtime_exit_condition != _no_async_condition); } 1316 1317 void check_and_handle_async_exceptions(bool check_unsafe_error = true); 1318 1319 // these next two are also used for self-suspension and async exception support 1320 void handle_special_runtime_exit_condition(bool check_asyncs = true); 1321 1322 // Return true if JavaThread has an asynchronous condition or 1323 // if external suspension is requested. 1324 bool has_special_runtime_exit_condition() { 1325 // Because we don't use is_external_suspend_with_lock 1326 // it is possible that we won't see an asynchronous external suspend 1327 // request that has just gotten started, i.e., SR_lock grabbed but 1328 // _external_suspend field change either not made yet or not visible 1329 // yet. However, this is okay because the request is asynchronous and 1330 // we will see the new flag value the next time through. It's also 1331 // possible that the external suspend request is dropped after 1332 // we have checked is_external_suspend(), we will recheck its value 1333 // under SR_lock in java_suspend_self(). 1334 return (_special_runtime_exit_condition != _no_async_condition) || 1335 is_external_suspend() || is_trace_suspend(); 1336 } 1337 1338 void set_pending_unsafe_access_error() { _special_runtime_exit_condition = _async_unsafe_access_error; } 1339 1340 inline void set_pending_async_exception(oop e); 1341 1342 // Fast-locking support 1343 bool is_lock_owned(address adr) const; 1344 1345 // Accessors for vframe array top 1346 // The linked list of vframe arrays are sorted on sp. This means when we 1347 // unpack the head must contain the vframe array to unpack. 1348 void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; } 1349 vframeArray* vframe_array_head() const { return _vframe_array_head; } 1350 1351 // Side structure for deferring update of java frame locals until deopt occurs 1352 GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred_locals() const { return _deferred_locals_updates; } 1353 void set_deferred_locals(GrowableArray<jvmtiDeferredLocalVariableSet *>* vf) { _deferred_locals_updates = vf; } 1354 1355 // These only really exist to make debugging deopt problems simpler 1356 1357 void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; } 1358 vframeArray* vframe_array_last() const { return _vframe_array_last; } 1359 1360 // The special resourceMark used during deoptimization 1361 1362 void set_deopt_mark(DeoptResourceMark* value) { _deopt_mark = value; } 1363 DeoptResourceMark* deopt_mark(void) { return _deopt_mark; } 1364 1365 intptr_t* must_deopt_id() { return _must_deopt_id; } 1366 void set_must_deopt_id(intptr_t* id) { _must_deopt_id = id; } 1367 void clear_must_deopt_id() { _must_deopt_id = NULL; } 1368 1369 void set_deopt_compiled_method(CompiledMethod* nm) { _deopt_nmethod = nm; } 1370 CompiledMethod* deopt_compiled_method() { return _deopt_nmethod; } 1371 1372 Method* callee_target() const { return _callee_target; } 1373 void set_callee_target (Method* x) { _callee_target = x; } 1374 1375 // Oop results of vm runtime calls 1376 oop vm_result() const { return _vm_result; } 1377 void set_vm_result (oop x) { _vm_result = x; } 1378 1379 Metadata* vm_result_2() const { return _vm_result_2; } 1380 void set_vm_result_2 (Metadata* x) { _vm_result_2 = x; } 1381 1382 MemRegion deferred_card_mark() const { return _deferred_card_mark; } 1383 void set_deferred_card_mark(MemRegion mr) { _deferred_card_mark = mr; } 1384 1385 #if INCLUDE_JVMCI 1386 int pending_deoptimization() const { return _pending_deoptimization; } 1387 oop pending_failed_speculation() const { return _pending_failed_speculation; } 1388 bool adjusting_comp_level() const { return _adjusting_comp_level; } 1389 void set_adjusting_comp_level(bool b) { _adjusting_comp_level = b; } 1390 bool has_pending_monitorenter() const { return _pending_monitorenter; } 1391 void set_pending_monitorenter(bool b) { _pending_monitorenter = b; } 1392 void set_pending_deoptimization(int reason) { _pending_deoptimization = reason; } 1393 void set_pending_failed_speculation(oop failed_speculation) { _pending_failed_speculation = failed_speculation; } 1394 void set_pending_transfer_to_interpreter(bool b) { _pending_transfer_to_interpreter = b; } 1395 void set_jvmci_alternate_call_target(address a) { assert(_jvmci._alternate_call_target == NULL, "must be"); _jvmci._alternate_call_target = a; } 1396 void set_jvmci_implicit_exception_pc(address a) { assert(_jvmci._implicit_exception_pc == NULL, "must be"); _jvmci._implicit_exception_pc = a; } 1397 #endif // INCLUDE_JVMCI 1398 1399 // Exception handling for compiled methods 1400 oop exception_oop() const { return _exception_oop; } 1401 address exception_pc() const { return _exception_pc; } 1402 address exception_handler_pc() const { return _exception_handler_pc; } 1403 bool is_method_handle_return() const { return _is_method_handle_return == 1; } 1404 1405 void set_exception_oop(oop o) { (void)const_cast<oop&>(_exception_oop = o); } 1406 void set_exception_pc(address a) { _exception_pc = a; } 1407 void set_exception_handler_pc(address a) { _exception_handler_pc = a; } 1408 void set_is_method_handle_return(bool value) { _is_method_handle_return = value ? 1 : 0; } 1409 1410 void clear_exception_oop_and_pc() { 1411 set_exception_oop(NULL); 1412 set_exception_pc(NULL); 1413 } 1414 1415 // Stack overflow support 1416 // 1417 // (small addresses) 1418 // 1419 // -- <-- stack_end() --- 1420 // | | 1421 // | red pages | 1422 // | | 1423 // -- <-- stack_red_zone_base() | 1424 // | | 1425 // | guard 1426 // | yellow pages zone 1427 // | | 1428 // | | 1429 // -- <-- stack_yellow_zone_base() | 1430 // | | 1431 // | | 1432 // | reserved pages | 1433 // | | 1434 // -- <-- stack_reserved_zone_base() --- --- 1435 // /|\ shadow <-- stack_overflow_limit() (somewhere in here) 1436 // | zone 1437 // \|/ size 1438 // some untouched memory --- 1439 // 1440 // 1441 // -- 1442 // | 1443 // | shadow zone 1444 // | 1445 // -- 1446 // x frame n 1447 // -- 1448 // x frame n-1 1449 // x 1450 // -- 1451 // ... 1452 // 1453 // -- 1454 // x frame 0 1455 // -- <-- stack_base() 1456 // 1457 // (large addresses) 1458 // 1459 1460 private: 1461 // These values are derived from flags StackRedPages, StackYellowPages, 1462 // StackReservedPages and StackShadowPages. The zone size is determined 1463 // ergonomically if page_size > 4K. 1464 static size_t _stack_red_zone_size; 1465 static size_t _stack_yellow_zone_size; 1466 static size_t _stack_reserved_zone_size; 1467 static size_t _stack_shadow_zone_size; 1468 public: 1469 inline size_t stack_available(address cur_sp); 1470 1471 static size_t stack_red_zone_size() { 1472 assert(_stack_red_zone_size > 0, "Don't call this before the field is initialized."); 1473 return _stack_red_zone_size; 1474 } 1475 static void set_stack_red_zone_size(size_t s) { 1476 assert(is_aligned(s, os::vm_page_size()), 1477 "We can not protect if the red zone size is not page aligned."); 1478 assert(_stack_red_zone_size == 0, "This should be called only once."); 1479 _stack_red_zone_size = s; 1480 } 1481 address stack_red_zone_base() { 1482 return (address)(stack_end() + stack_red_zone_size()); 1483 } 1484 bool in_stack_red_zone(address a) { 1485 return a <= stack_red_zone_base() && a >= stack_end(); 1486 } 1487 1488 static size_t stack_yellow_zone_size() { 1489 assert(_stack_yellow_zone_size > 0, "Don't call this before the field is initialized."); 1490 return _stack_yellow_zone_size; 1491 } 1492 static void set_stack_yellow_zone_size(size_t s) { 1493 assert(is_aligned(s, os::vm_page_size()), 1494 "We can not protect if the yellow zone size is not page aligned."); 1495 assert(_stack_yellow_zone_size == 0, "This should be called only once."); 1496 _stack_yellow_zone_size = s; 1497 } 1498 1499 static size_t stack_reserved_zone_size() { 1500 // _stack_reserved_zone_size may be 0. This indicates the feature is off. 1501 return _stack_reserved_zone_size; 1502 } 1503 static void set_stack_reserved_zone_size(size_t s) { 1504 assert(is_aligned(s, os::vm_page_size()), 1505 "We can not protect if the reserved zone size is not page aligned."); 1506 assert(_stack_reserved_zone_size == 0, "This should be called only once."); 1507 _stack_reserved_zone_size = s; 1508 } 1509 address stack_reserved_zone_base() { 1510 return (address)(stack_end() + 1511 (stack_red_zone_size() + stack_yellow_zone_size() + stack_reserved_zone_size())); 1512 } 1513 bool in_stack_reserved_zone(address a) { 1514 return (a <= stack_reserved_zone_base()) && 1515 (a >= (address)((intptr_t)stack_reserved_zone_base() - stack_reserved_zone_size())); 1516 } 1517 1518 static size_t stack_yellow_reserved_zone_size() { 1519 return _stack_yellow_zone_size + _stack_reserved_zone_size; 1520 } 1521 bool in_stack_yellow_reserved_zone(address a) { 1522 return (a <= stack_reserved_zone_base()) && (a >= stack_red_zone_base()); 1523 } 1524 1525 // Size of red + yellow + reserved zones. 1526 static size_t stack_guard_zone_size() { 1527 return stack_red_zone_size() + stack_yellow_reserved_zone_size(); 1528 } 1529 1530 static size_t stack_shadow_zone_size() { 1531 assert(_stack_shadow_zone_size > 0, "Don't call this before the field is initialized."); 1532 return _stack_shadow_zone_size; 1533 } 1534 static void set_stack_shadow_zone_size(size_t s) { 1535 // The shadow area is not allocated or protected, so 1536 // it needs not be page aligned. 1537 // But the stack bang currently assumes that it is a 1538 // multiple of page size. This guarantees that the bang 1539 // loop touches all pages in the shadow zone. 1540 // This can be guaranteed differently, as well. E.g., if 1541 // the page size is a multiple of 4K, banging in 4K steps 1542 // suffices to touch all pages. (Some pages are banged 1543 // several times, though.) 1544 assert(is_aligned(s, os::vm_page_size()), 1545 "Stack bang assumes multiple of page size."); 1546 assert(_stack_shadow_zone_size == 0, "This should be called only once."); 1547 _stack_shadow_zone_size = s; 1548 } 1549 1550 void create_stack_guard_pages(); 1551 void remove_stack_guard_pages(); 1552 1553 void enable_stack_reserved_zone(); 1554 void disable_stack_reserved_zone(); 1555 void enable_stack_yellow_reserved_zone(); 1556 void disable_stack_yellow_reserved_zone(); 1557 void enable_stack_red_zone(); 1558 void disable_stack_red_zone(); 1559 1560 inline bool stack_guard_zone_unused(); 1561 inline bool stack_yellow_reserved_zone_disabled(); 1562 inline bool stack_reserved_zone_disabled(); 1563 inline bool stack_guards_enabled(); 1564 1565 address reserved_stack_activation() const { return _reserved_stack_activation; } 1566 void set_reserved_stack_activation(address addr) { 1567 assert(_reserved_stack_activation == stack_base() 1568 || _reserved_stack_activation == NULL 1569 || addr == stack_base(), "Must not be set twice"); 1570 _reserved_stack_activation = addr; 1571 } 1572 1573 // Attempt to reguard the stack after a stack overflow may have occurred. 1574 // Returns true if (a) guard pages are not needed on this thread, (b) the 1575 // pages are already guarded, or (c) the pages were successfully reguarded. 1576 // Returns false if there is not enough stack space to reguard the pages, in 1577 // which case the caller should unwind a frame and try again. The argument 1578 // should be the caller's (approximate) sp. 1579 bool reguard_stack(address cur_sp); 1580 // Similar to above but see if current stackpoint is out of the guard area 1581 // and reguard if possible. 1582 bool reguard_stack(void); 1583 1584 address stack_overflow_limit() { return _stack_overflow_limit; } 1585 void set_stack_overflow_limit() { 1586 _stack_overflow_limit = 1587 stack_end() + MAX2(JavaThread::stack_guard_zone_size(), JavaThread::stack_shadow_zone_size()); 1588 } 1589 1590 // Misc. accessors/mutators 1591 void set_do_not_unlock(void) { _do_not_unlock_if_synchronized = true; } 1592 void clr_do_not_unlock(void) { _do_not_unlock_if_synchronized = false; } 1593 bool do_not_unlock(void) { return _do_not_unlock_if_synchronized; } 1594 1595 #ifndef PRODUCT 1596 void record_jump(address target, address instr, const char* file, int line); 1597 #endif // PRODUCT 1598 1599 // For assembly stub generation 1600 static ByteSize threadObj_offset() { return byte_offset_of(JavaThread, _threadObj); } 1601 #ifndef PRODUCT 1602 static ByteSize jmp_ring_index_offset() { return byte_offset_of(JavaThread, _jmp_ring_index); } 1603 static ByteSize jmp_ring_offset() { return byte_offset_of(JavaThread, _jmp_ring); } 1604 #endif // PRODUCT 1605 static ByteSize jni_environment_offset() { return byte_offset_of(JavaThread, _jni_environment); } 1606 static ByteSize pending_jni_exception_check_fn_offset() { 1607 return byte_offset_of(JavaThread, _pending_jni_exception_check_fn); 1608 } 1609 static ByteSize last_Java_sp_offset() { 1610 return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset(); 1611 } 1612 static ByteSize last_Java_pc_offset() { 1613 return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset(); 1614 } 1615 static ByteSize frame_anchor_offset() { 1616 return byte_offset_of(JavaThread, _anchor); 1617 } 1618 static ByteSize callee_target_offset() { return byte_offset_of(JavaThread, _callee_target); } 1619 static ByteSize vm_result_offset() { return byte_offset_of(JavaThread, _vm_result); } 1620 static ByteSize vm_result_2_offset() { return byte_offset_of(JavaThread, _vm_result_2); } 1621 static ByteSize thread_state_offset() { return byte_offset_of(JavaThread, _thread_state); } 1622 static ByteSize saved_exception_pc_offset() { return byte_offset_of(JavaThread, _saved_exception_pc); } 1623 static ByteSize osthread_offset() { return byte_offset_of(JavaThread, _osthread); } 1624 #if INCLUDE_JVMCI 1625 static ByteSize pending_deoptimization_offset() { return byte_offset_of(JavaThread, _pending_deoptimization); } 1626 static ByteSize pending_monitorenter_offset() { return byte_offset_of(JavaThread, _pending_monitorenter); } 1627 static ByteSize pending_failed_speculation_offset() { return byte_offset_of(JavaThread, _pending_failed_speculation); } 1628 static ByteSize jvmci_alternate_call_target_offset() { return byte_offset_of(JavaThread, _jvmci._alternate_call_target); } 1629 static ByteSize jvmci_implicit_exception_pc_offset() { return byte_offset_of(JavaThread, _jvmci._implicit_exception_pc); } 1630 static ByteSize jvmci_counters_offset() { return byte_offset_of(JavaThread, _jvmci_counters); } 1631 #endif // INCLUDE_JVMCI 1632 static ByteSize exception_oop_offset() { return byte_offset_of(JavaThread, _exception_oop); } 1633 static ByteSize exception_pc_offset() { return byte_offset_of(JavaThread, _exception_pc); } 1634 static ByteSize exception_handler_pc_offset() { return byte_offset_of(JavaThread, _exception_handler_pc); } 1635 static ByteSize stack_overflow_limit_offset() { return byte_offset_of(JavaThread, _stack_overflow_limit); } 1636 static ByteSize is_method_handle_return_offset() { return byte_offset_of(JavaThread, _is_method_handle_return); } 1637 static ByteSize stack_guard_state_offset() { return byte_offset_of(JavaThread, _stack_guard_state); } 1638 static ByteSize reserved_stack_activation_offset() { return byte_offset_of(JavaThread, _reserved_stack_activation); } 1639 static ByteSize suspend_flags_offset() { return byte_offset_of(JavaThread, _suspend_flags); } 1640 1641 static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); } 1642 static ByteSize should_post_on_exceptions_flag_offset() { 1643 return byte_offset_of(JavaThread, _should_post_on_exceptions_flag); 1644 } 1645 1646 #if INCLUDE_ALL_GCS 1647 static ByteSize satb_mark_queue_offset() { return byte_offset_of(JavaThread, _satb_mark_queue); } 1648 static ByteSize dirty_card_queue_offset() { return byte_offset_of(JavaThread, _dirty_card_queue); } 1649 #endif // INCLUDE_ALL_GCS 1650 1651 // Returns the jni environment for this thread 1652 JNIEnv* jni_environment() { return &_jni_environment; } 1653 1654 static JavaThread* thread_from_jni_environment(JNIEnv* env) { 1655 JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset())); 1656 // Only return NULL if thread is off the thread list; starting to 1657 // exit should not return NULL. 1658 if (thread_from_jni_env->is_terminated()) { 1659 thread_from_jni_env->block_if_vm_exited(); 1660 return NULL; 1661 } else { 1662 return thread_from_jni_env; 1663 } 1664 } 1665 1666 // JNI critical regions. These can nest. 1667 bool in_critical() { return _jni_active_critical > 0; } 1668 bool in_last_critical() { return _jni_active_critical == 1; } 1669 void enter_critical() { 1670 assert(Thread::current() == this || 1671 (Thread::current()->is_VM_thread() && 1672 SafepointSynchronize::is_synchronizing()), 1673 "this must be current thread or synchronizing"); 1674 _jni_active_critical++; 1675 } 1676 void exit_critical() { 1677 assert(Thread::current() == this, "this must be current thread"); 1678 _jni_active_critical--; 1679 assert(_jni_active_critical >= 0, "JNI critical nesting problem?"); 1680 } 1681 1682 // Checked JNI: is the programmer required to check for exceptions, if so specify 1683 // which function name. Returning to a Java frame should implicitly clear the 1684 // pending check, this is done for Native->Java transitions (i.e. user JNI code). 1685 // VM->Java transistions are not cleared, it is expected that JNI code enclosed 1686 // within ThreadToNativeFromVM makes proper exception checks (i.e. VM internal). 1687 bool is_pending_jni_exception_check() const { return _pending_jni_exception_check_fn != NULL; } 1688 void clear_pending_jni_exception_check() { _pending_jni_exception_check_fn = NULL; } 1689 const char* get_pending_jni_exception_check() const { return _pending_jni_exception_check_fn; } 1690 void set_pending_jni_exception_check(const char* fn_name) { _pending_jni_exception_check_fn = (char*) fn_name; } 1691 1692 // For deadlock detection 1693 int depth_first_number() { return _depth_first_number; } 1694 void set_depth_first_number(int dfn) { _depth_first_number = dfn; } 1695 1696 private: 1697 void set_monitor_chunks(MonitorChunk* monitor_chunks) { _monitor_chunks = monitor_chunks; } 1698 1699 public: 1700 MonitorChunk* monitor_chunks() const { return _monitor_chunks; } 1701 void add_monitor_chunk(MonitorChunk* chunk); 1702 void remove_monitor_chunk(MonitorChunk* chunk); 1703 bool in_deopt_handler() const { return _in_deopt_handler > 0; } 1704 void inc_in_deopt_handler() { _in_deopt_handler++; } 1705 void dec_in_deopt_handler() { 1706 assert(_in_deopt_handler > 0, "mismatched deopt nesting"); 1707 if (_in_deopt_handler > 0) { // robustness 1708 _in_deopt_handler--; 1709 } 1710 } 1711 1712 private: 1713 void set_entry_point(ThreadFunction entry_point) { _entry_point = entry_point; } 1714 1715 public: 1716 1717 // Frame iteration; calls the function f for all frames on the stack 1718 void frames_do(void f(frame*, const RegisterMap*)); 1719 1720 // Memory operations 1721 void oops_do(OopClosure* f, CodeBlobClosure* cf); 1722 1723 // Sweeper operations 1724 virtual void nmethods_do(CodeBlobClosure* cf); 1725 1726 // RedefineClasses Support 1727 void metadata_do(void f(Metadata*)); 1728 1729 // Misc. operations 1730 char* name() const { return (char*)get_thread_name(); } 1731 void print_on(outputStream* st) const; 1732 void print_value(); 1733 void print_thread_state_on(outputStream*) const PRODUCT_RETURN; 1734 void print_thread_state() const PRODUCT_RETURN; 1735 void print_on_error(outputStream* st, char* buf, int buflen) const; 1736 void print_name_on_error(outputStream* st, char* buf, int buflen) const; 1737 void verify(); 1738 const char* get_thread_name() const; 1739 private: 1740 // factor out low-level mechanics for use in both normal and error cases 1741 const char* get_thread_name_string(char* buf = NULL, int buflen = 0) const; 1742 public: 1743 const char* get_threadgroup_name() const; 1744 const char* get_parent_name() const; 1745 1746 // Accessing frames 1747 frame last_frame() { 1748 _anchor.make_walkable(this); 1749 return pd_last_frame(); 1750 } 1751 javaVFrame* last_java_vframe(RegisterMap* reg_map); 1752 1753 // Returns method at 'depth' java or native frames down the stack 1754 // Used for security checks 1755 Klass* security_get_caller_class(int depth); 1756 1757 // Print stack trace in external format 1758 void print_stack_on(outputStream* st); 1759 void print_stack() { print_stack_on(tty); } 1760 1761 // Print stack traces in various internal formats 1762 void trace_stack() PRODUCT_RETURN; 1763 void trace_stack_from(vframe* start_vf) PRODUCT_RETURN; 1764 void trace_frames() PRODUCT_RETURN; 1765 void trace_oops() PRODUCT_RETURN; 1766 1767 // Print an annotated view of the stack frames 1768 void print_frame_layout(int depth = 0, bool validate_only = false) NOT_DEBUG_RETURN; 1769 void validate_frame_layout() { 1770 print_frame_layout(0, true); 1771 } 1772 1773 // Returns the number of stack frames on the stack 1774 int depth() const; 1775 1776 // Function for testing deoptimization 1777 void deoptimize(); 1778 void make_zombies(); 1779 1780 void deoptimized_wrt_marked_nmethods(); 1781 1782 public: 1783 // Returns the running thread as a JavaThread 1784 static inline JavaThread* current(); 1785 1786 // Returns the active Java thread. Do not use this if you know you are calling 1787 // from a JavaThread, as it's slower than JavaThread::current. If called from 1788 // the VMThread, it also returns the JavaThread that instigated the VMThread's 1789 // operation. You may not want that either. 1790 static JavaThread* active(); 1791 1792 inline CompilerThread* as_CompilerThread(); 1793 1794 public: 1795 virtual void run(); 1796 void thread_main_inner(); 1797 1798 private: 1799 // PRIVILEGED STACK 1800 PrivilegedElement* _privileged_stack_top; 1801 GrowableArray<oop>* _array_for_gc; 1802 public: 1803 1804 // Returns the privileged_stack information. 1805 PrivilegedElement* privileged_stack_top() const { return _privileged_stack_top; } 1806 void set_privileged_stack_top(PrivilegedElement *e) { _privileged_stack_top = e; } 1807 void register_array_for_gc(GrowableArray<oop>* array) { _array_for_gc = array; } 1808 1809 public: 1810 // Thread local information maintained by JVMTI. 1811 void set_jvmti_thread_state(JvmtiThreadState *value) { _jvmti_thread_state = value; } 1812 // A JvmtiThreadState is lazily allocated. This jvmti_thread_state() 1813 // getter is used to get this JavaThread's JvmtiThreadState if it has 1814 // one which means NULL can be returned. JvmtiThreadState::state_for() 1815 // is used to get the specified JavaThread's JvmtiThreadState if it has 1816 // one or it allocates a new JvmtiThreadState for the JavaThread and 1817 // returns it. JvmtiThreadState::state_for() will return NULL only if 1818 // the specified JavaThread is exiting. 1819 JvmtiThreadState *jvmti_thread_state() const { return _jvmti_thread_state; } 1820 static ByteSize jvmti_thread_state_offset() { return byte_offset_of(JavaThread, _jvmti_thread_state); } 1821 void set_jvmti_get_loaded_classes_closure(JvmtiGetLoadedClassesClosure* value) { _jvmti_get_loaded_classes_closure = value; } 1822 JvmtiGetLoadedClassesClosure* get_jvmti_get_loaded_classes_closure() const { return _jvmti_get_loaded_classes_closure; } 1823 1824 // JVMTI PopFrame support 1825 // Setting and clearing popframe_condition 1826 // All of these enumerated values are bits. popframe_pending 1827 // indicates that a PopFrame() has been requested and not yet been 1828 // completed. popframe_processing indicates that that PopFrame() is in 1829 // the process of being completed. popframe_force_deopt_reexecution_bit 1830 // indicates that special handling is required when returning to a 1831 // deoptimized caller. 1832 enum PopCondition { 1833 popframe_inactive = 0x00, 1834 popframe_pending_bit = 0x01, 1835 popframe_processing_bit = 0x02, 1836 popframe_force_deopt_reexecution_bit = 0x04 1837 }; 1838 PopCondition popframe_condition() { return (PopCondition) _popframe_condition; } 1839 void set_popframe_condition(PopCondition c) { _popframe_condition = c; } 1840 void set_popframe_condition_bit(PopCondition c) { _popframe_condition |= c; } 1841 void clear_popframe_condition() { _popframe_condition = popframe_inactive; } 1842 static ByteSize popframe_condition_offset() { return byte_offset_of(JavaThread, _popframe_condition); } 1843 bool has_pending_popframe() { return (popframe_condition() & popframe_pending_bit) != 0; } 1844 bool popframe_forcing_deopt_reexecution() { return (popframe_condition() & popframe_force_deopt_reexecution_bit) != 0; } 1845 void clear_popframe_forcing_deopt_reexecution() { _popframe_condition &= ~popframe_force_deopt_reexecution_bit; } 1846 #ifdef CC_INTERP 1847 bool pop_frame_pending(void) { return ((_popframe_condition & popframe_pending_bit) != 0); } 1848 void clr_pop_frame_pending(void) { _popframe_condition = popframe_inactive; } 1849 bool pop_frame_in_process(void) { return ((_popframe_condition & popframe_processing_bit) != 0); } 1850 void set_pop_frame_in_process(void) { _popframe_condition |= popframe_processing_bit; } 1851 void clr_pop_frame_in_process(void) { _popframe_condition &= ~popframe_processing_bit; } 1852 #endif 1853 1854 int frames_to_pop_failed_realloc() const { return _frames_to_pop_failed_realloc; } 1855 void set_frames_to_pop_failed_realloc(int nb) { _frames_to_pop_failed_realloc = nb; } 1856 void dec_frames_to_pop_failed_realloc() { _frames_to_pop_failed_realloc--; } 1857 1858 private: 1859 // Saved incoming arguments to popped frame. 1860 // Used only when popped interpreted frame returns to deoptimized frame. 1861 void* _popframe_preserved_args; 1862 int _popframe_preserved_args_size; 1863 1864 public: 1865 void popframe_preserve_args(ByteSize size_in_bytes, void* start); 1866 void* popframe_preserved_args(); 1867 ByteSize popframe_preserved_args_size(); 1868 WordSize popframe_preserved_args_size_in_words(); 1869 void popframe_free_preserved_args(); 1870 1871 1872 private: 1873 JvmtiThreadState *_jvmti_thread_state; 1874 JvmtiGetLoadedClassesClosure* _jvmti_get_loaded_classes_closure; 1875 1876 // Used by the interpreter in fullspeed mode for frame pop, method 1877 // entry, method exit and single stepping support. This field is 1878 // only set to non-zero by the VM_EnterInterpOnlyMode VM operation. 1879 // It can be set to zero asynchronously (i.e., without a VM operation 1880 // or a lock) so we have to be very careful. 1881 int _interp_only_mode; 1882 1883 public: 1884 // used by the interpreter for fullspeed debugging support (see above) 1885 static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); } 1886 bool is_interp_only_mode() { return (_interp_only_mode != 0); } 1887 int get_interp_only_mode() { return _interp_only_mode; } 1888 void increment_interp_only_mode() { ++_interp_only_mode; } 1889 void decrement_interp_only_mode() { --_interp_only_mode; } 1890 1891 // support for cached flag that indicates whether exceptions need to be posted for this thread 1892 // if this is false, we can avoid deoptimizing when events are thrown 1893 // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything 1894 private: 1895 int _should_post_on_exceptions_flag; 1896 1897 public: 1898 int should_post_on_exceptions_flag() { return _should_post_on_exceptions_flag; } 1899 void set_should_post_on_exceptions_flag(int val) { _should_post_on_exceptions_flag = val; } 1900 1901 private: 1902 ThreadStatistics *_thread_stat; 1903 1904 public: 1905 ThreadStatistics* get_thread_stat() const { return _thread_stat; } 1906 1907 // Return a blocker object for which this thread is blocked parking. 1908 oop current_park_blocker(); 1909 1910 private: 1911 static size_t _stack_size_at_create; 1912 1913 public: 1914 static inline size_t stack_size_at_create(void) { 1915 return _stack_size_at_create; 1916 } 1917 static inline void set_stack_size_at_create(size_t value) { 1918 _stack_size_at_create = value; 1919 } 1920 1921 #if INCLUDE_ALL_GCS 1922 // SATB marking queue support 1923 SATBMarkQueue& satb_mark_queue() { return _satb_mark_queue; } 1924 static SATBMarkQueueSet& satb_mark_queue_set() { 1925 return _satb_mark_queue_set; 1926 } 1927 1928 // Dirty card queue support 1929 DirtyCardQueue& dirty_card_queue() { return _dirty_card_queue; } 1930 static DirtyCardQueueSet& dirty_card_queue_set() { 1931 return _dirty_card_queue_set; 1932 } 1933 #endif // INCLUDE_ALL_GCS 1934 1935 // This method initializes the SATB and dirty card queues before a 1936 // JavaThread is added to the Java thread list. Right now, we don't 1937 // have to do anything to the dirty card queue (it should have been 1938 // activated when the thread was created), but we have to activate 1939 // the SATB queue if the thread is created while a marking cycle is 1940 // in progress. The activation / de-activation of the SATB queues at 1941 // the beginning / end of a marking cycle is done during safepoints 1942 // so we have to make sure this method is called outside one to be 1943 // able to safely read the active field of the SATB queue set. Right 1944 // now, it is called just before the thread is added to the Java 1945 // thread list in the Threads::add() method. That method is holding 1946 // the Threads_lock which ensures we are outside a safepoint. We 1947 // cannot do the obvious and set the active field of the SATB queue 1948 // when the thread is created given that, in some cases, safepoints 1949 // might happen between the JavaThread constructor being called and the 1950 // thread being added to the Java thread list (an example of this is 1951 // when the structure for the DestroyJavaVM thread is created). 1952 #if INCLUDE_ALL_GCS 1953 void initialize_queues(); 1954 #else // INCLUDE_ALL_GCS 1955 void initialize_queues() { } 1956 #endif // INCLUDE_ALL_GCS 1957 1958 // Machine dependent stuff 1959 #include OS_CPU_HEADER(thread) 1960 1961 public: 1962 void set_blocked_on_compilation(bool value) { 1963 _blocked_on_compilation = value; 1964 } 1965 1966 bool blocked_on_compilation() { 1967 return _blocked_on_compilation; 1968 } 1969 protected: 1970 bool _blocked_on_compilation; 1971 1972 1973 // JSR166 per-thread parker 1974 private: 1975 Parker* _parker; 1976 public: 1977 Parker* parker() { return _parker; } 1978 1979 // Biased locking support 1980 private: 1981 GrowableArray<MonitorInfo*>* _cached_monitor_info; 1982 public: 1983 GrowableArray<MonitorInfo*>* cached_monitor_info() { return _cached_monitor_info; } 1984 void set_cached_monitor_info(GrowableArray<MonitorInfo*>* info) { _cached_monitor_info = info; } 1985 1986 // clearing/querying jni attach status 1987 bool is_attaching_via_jni() const { return _jni_attach_state == _attaching_via_jni; } 1988 bool has_attached_via_jni() const { return is_attaching_via_jni() || _jni_attach_state == _attached_via_jni; } 1989 inline void set_done_attaching_via_jni(); 1990 }; 1991 1992 // Inline implementation of JavaThread::current 1993 inline JavaThread* JavaThread::current() { 1994 Thread* thread = Thread::current(); 1995 assert(thread->is_Java_thread(), "just checking"); 1996 return (JavaThread*)thread; 1997 } 1998 1999 inline CompilerThread* JavaThread::as_CompilerThread() { 2000 assert(is_Compiler_thread(), "just checking"); 2001 return (CompilerThread*)this; 2002 } 2003 2004 // Dedicated thread to sweep the code cache 2005 class CodeCacheSweeperThread : public JavaThread { 2006 CompiledMethod* _scanned_compiled_method; // nmethod being scanned by the sweeper 2007 public: 2008 CodeCacheSweeperThread(); 2009 // Track the nmethod currently being scanned by the sweeper 2010 void set_scanned_compiled_method(CompiledMethod* cm) { 2011 assert(_scanned_compiled_method == NULL || cm == NULL, "should reset to NULL before writing a new value"); 2012 _scanned_compiled_method = cm; 2013 } 2014 2015 // Hide sweeper thread from external view. 2016 bool is_hidden_from_external_view() const { return true; } 2017 2018 bool is_Code_cache_sweeper_thread() const { return true; } 2019 2020 // Prevent GC from unloading _scanned_compiled_method 2021 void oops_do(OopClosure* f, CodeBlobClosure* cf); 2022 void nmethods_do(CodeBlobClosure* cf); 2023 }; 2024 2025 // A thread used for Compilation. 2026 class CompilerThread : public JavaThread { 2027 friend class VMStructs; 2028 private: 2029 CompilerCounters* _counters; 2030 2031 ciEnv* _env; 2032 CompileLog* _log; 2033 CompileTask* _task; 2034 CompileQueue* _queue; 2035 BufferBlob* _buffer_blob; 2036 2037 AbstractCompiler* _compiler; 2038 2039 public: 2040 2041 static CompilerThread* current(); 2042 2043 CompilerThread(CompileQueue* queue, CompilerCounters* counters); 2044 2045 bool is_Compiler_thread() const { return true; } 2046 2047 virtual bool can_call_java() const; 2048 2049 // Hide native compiler threads from external view. 2050 bool is_hidden_from_external_view() const { return !can_call_java(); } 2051 2052 void set_compiler(AbstractCompiler* c) { _compiler = c; } 2053 AbstractCompiler* compiler() const { return _compiler; } 2054 2055 CompileQueue* queue() const { return _queue; } 2056 CompilerCounters* counters() const { return _counters; } 2057 2058 // Get/set the thread's compilation environment. 2059 ciEnv* env() { return _env; } 2060 void set_env(ciEnv* env) { _env = env; } 2061 2062 BufferBlob* get_buffer_blob() const { return _buffer_blob; } 2063 void set_buffer_blob(BufferBlob* b) { _buffer_blob = b; } 2064 2065 // Get/set the thread's logging information 2066 CompileLog* log() { return _log; } 2067 void init_log(CompileLog* log) { 2068 // Set once, for good. 2069 assert(_log == NULL, "set only once"); 2070 _log = log; 2071 } 2072 2073 #ifndef PRODUCT 2074 private: 2075 IdealGraphPrinter *_ideal_graph_printer; 2076 public: 2077 IdealGraphPrinter *ideal_graph_printer() { return _ideal_graph_printer; } 2078 void set_ideal_graph_printer(IdealGraphPrinter *n) { _ideal_graph_printer = n; } 2079 #endif 2080 2081 // Get/set the thread's current task 2082 CompileTask* task() { return _task; } 2083 void set_task(CompileTask* task) { _task = task; } 2084 }; 2085 2086 inline CompilerThread* CompilerThread::current() { 2087 return JavaThread::current()->as_CompilerThread(); 2088 } 2089 2090 // The active thread queue. It also keeps track of the current used 2091 // thread priorities. 2092 class Threads: AllStatic { 2093 friend class VMStructs; 2094 private: 2095 // Safe Memory Reclamation (SMR) support: 2096 static Monitor* _smr_delete_lock; 2097 // The '_cnt', '_max' and '_times" fields are enabled via 2098 // -XX:+EnableThreadSMRStatistics: 2099 static uint _smr_delete_lock_wait_cnt; 2100 static uint _smr_delete_lock_wait_max; 2101 static volatile jint _smr_delete_notify; 2102 static volatile jint _smr_deleted_thread_cnt; 2103 static volatile jint _smr_deleted_thread_time_max; 2104 static volatile jint _smr_deleted_thread_times; 2105 static ThreadsList* volatile _smr_java_thread_list; 2106 static ThreadsList* get_smr_java_thread_list(); 2107 static ThreadsList* xchg_smr_java_thread_list(ThreadsList* new_list); 2108 static long _smr_java_thread_list_alloc_cnt; 2109 static long _smr_java_thread_list_free_cnt; 2110 static uint _smr_java_thread_list_max; 2111 static uint _smr_nested_thread_list_max; 2112 static volatile jint _smr_tlh_cnt; 2113 static volatile jint _smr_tlh_time_max; 2114 static volatile jint _smr_tlh_times; 2115 static ThreadsList* _smr_to_delete_list; 2116 static uint _smr_to_delete_list_cnt; 2117 static uint _smr_to_delete_list_max; 2118 2119 static JavaThread* _thread_list; 2120 static int _number_of_threads; 2121 static int _number_of_non_daemon_threads; 2122 static int _return_code; 2123 static int _thread_claim_parity; 2124 #ifdef ASSERT 2125 static bool _vm_complete; 2126 #endif 2127 2128 static void initialize_java_lang_classes(JavaThread* main_thread, TRAPS); 2129 static void initialize_jsr292_core_classes(TRAPS); 2130 2131 static void smr_free_list(ThreadsList* threads); 2132 2133 public: 2134 // Thread management 2135 // force_daemon is a concession to JNI, where we may need to add a 2136 // thread to the thread list before allocating its thread object 2137 static void add(JavaThread* p, bool force_daemon = false); 2138 static void remove(JavaThread* p); 2139 static void threads_do(ThreadClosure* tc); 2140 static void possibly_parallel_threads_do(bool is_par, ThreadClosure* tc); 2141 2142 // SMR support: 2143 template <class T> 2144 static void threads_do_smr(T *tc, Thread *self); 2145 static ThreadsList *acquire_stable_list(Thread *self, bool is_ThreadsListSetter); 2146 static ThreadsList *acquire_stable_list_fast_path(Thread *self); 2147 static ThreadsList *acquire_stable_list_nested_path(Thread *self); 2148 static void release_stable_list(Thread *self); 2149 static void release_stable_list_fast_path(Thread *self); 2150 static void release_stable_list_nested_path(Thread *self); 2151 static void release_stable_list_wake_up(char *log_str); 2152 static bool is_a_protected_JavaThread(JavaThread *thread); 2153 static bool is_a_protected_JavaThread_with_lock(JavaThread *thread) { 2154 MutexLockerEx ml(Threads_lock->owned_by_self() ? NULL : Threads_lock); 2155 return is_a_protected_JavaThread(thread); 2156 } 2157 static void smr_delete(JavaThread *thread); 2158 // The coordination between Threads::release_stable_list() and 2159 // Threads::smr_delete() uses the smr_delete_lock in order to 2160 // reduce the traffic on the Threads_lock. 2161 static Monitor* smr_delete_lock() { return _smr_delete_lock; } 2162 // The smr_delete_notify flag is used for proper double-check 2163 // locking in order to reduce the traffic on the smr_delete_lock. 2164 static bool smr_delete_notify(); 2165 static void set_smr_delete_notify(); 2166 static void clear_smr_delete_notify(); 2167 static void inc_smr_deleted_thread_cnt(); 2168 static void update_smr_deleted_thread_time_max(jint new_value); 2169 static void add_smr_deleted_thread_times(jint add_value); 2170 static void inc_smr_tlh_cnt(); 2171 static void update_smr_tlh_time_max(jint new_value); 2172 static void add_smr_tlh_times(jint add_value); 2173 2174 // Initializes the vm and creates the vm thread 2175 static jint create_vm(JavaVMInitArgs* args, bool* canTryAgain); 2176 static void convert_vm_init_libraries_to_agents(); 2177 static void create_vm_init_libraries(); 2178 static void create_vm_init_agents(); 2179 static void shutdown_vm_agents(); 2180 static bool destroy_vm(); 2181 // Supported VM versions via JNI 2182 // Includes JNI_VERSION_1_1 2183 static jboolean is_supported_jni_version_including_1_1(jint version); 2184 // Does not include JNI_VERSION_1_1 2185 static jboolean is_supported_jni_version(jint version); 2186 2187 // The "thread claim parity" provides a way for threads to be claimed 2188 // by parallel worker tasks. 2189 // 2190 // Each thread contains a a "parity" field. A task will claim the 2191 // thread only if its parity field is the same as the global parity, 2192 // which is updated by calling change_thread_claim_parity(). 2193 // 2194 // For this to work change_thread_claim_parity() needs to be called 2195 // exactly once in sequential code before starting parallel tasks 2196 // that should claim threads. 2197 // 2198 // New threads get their parity set to 0 and change_thread_claim_parity() 2199 // never set the global parity to 0. 2200 static int thread_claim_parity() { return _thread_claim_parity; } 2201 static void change_thread_claim_parity(); 2202 static void assert_all_threads_claimed() NOT_DEBUG_RETURN; 2203 2204 // Apply "f->do_oop" to all root oops in all threads. 2205 // This version may only be called by sequential code. 2206 static void oops_do(OopClosure* f, CodeBlobClosure* cf); 2207 // This version may be called by sequential or parallel code. 2208 static void possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf); 2209 // This creates a list of GCTasks, one per thread. 2210 static void create_thread_roots_tasks(GCTaskQueue* q); 2211 // This creates a list of GCTasks, one per thread, for marking objects. 2212 static void create_thread_roots_marking_tasks(GCTaskQueue* q); 2213 2214 // Apply "f->do_oop" to roots in all threads that 2215 // are part of compiled frames 2216 static void compiled_frame_oops_do(OopClosure* f, CodeBlobClosure* cf); 2217 2218 static void convert_hcode_pointers(); 2219 static void restore_hcode_pointers(); 2220 2221 // Sweeper 2222 static void nmethods_do(CodeBlobClosure* cf); 2223 2224 // RedefineClasses support 2225 static void metadata_do(void f(Metadata*)); 2226 static void metadata_handles_do(void f(Metadata*)); 2227 2228 #ifdef ASSERT 2229 static bool is_vm_complete() { return _vm_complete; } 2230 #endif 2231 2232 // Verification 2233 static void verify(); 2234 static void log_smr_statistics(); 2235 static void print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks); 2236 static void print_smr_info_on(outputStream* st); 2237 static void print_smr_info_elements_on(outputStream* st, ThreadsList* t_list); 2238 static void print(bool print_stacks, bool internal_format) { 2239 // this function is only used by debug.cpp 2240 print_on(tty, print_stacks, internal_format, false /* no concurrent lock printed */); 2241 } 2242 static void print_on_error(outputStream* st, Thread* current, char* buf, int buflen); 2243 static void print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf, 2244 int buflen, bool* found_current); 2245 static void print_threads_compiling(outputStream* st, char* buf, int buflen); 2246 2247 // Get Java threads that are waiting to enter a monitor. 2248 static GrowableArray<JavaThread*>* get_pending_threads(ThreadsList * t_list, 2249 int count, address monitor); 2250 2251 // Get owning Java thread from the monitor's owner field. 2252 static JavaThread *owning_thread_from_monitor_owner(ThreadsList * t_list, 2253 address owner); 2254 2255 // Number of threads on the active threads list 2256 static int number_of_threads() { return _number_of_threads; } 2257 // Number of non-daemon threads on the active threads list 2258 static int number_of_non_daemon_threads() { return _number_of_non_daemon_threads; } 2259 2260 // Deoptimizes all frames tied to marked nmethods 2261 static void deoptimized_wrt_marked_nmethods(); 2262 }; 2263 2264 2265 // Thread iterator 2266 class ThreadClosure: public StackObj { 2267 public: 2268 virtual void do_thread(Thread* thread) = 0; 2269 }; 2270 2271 class SignalHandlerMark: public StackObj { 2272 private: 2273 Thread* _thread; 2274 public: 2275 SignalHandlerMark(Thread* t) { 2276 _thread = t; 2277 if (_thread) _thread->enter_signal_handler(); 2278 } 2279 ~SignalHandlerMark() { 2280 if (_thread) _thread->leave_signal_handler(); 2281 _thread = NULL; 2282 } 2283 }; 2284 2285 2286 #endif // SHARE_VM_RUNTIME_THREAD_HPP