src/share/vm/runtime/thread.cpp

Tue, 13 Feb 2018 15:48:23 +0100

author
rwestberg
date
Tue, 13 Feb 2018 15:48:23 +0100
changeset 9864
f066260954ae
parent 9858
b985cbb00e68
child 9868
69fb91513217
permissions
-rw-r--r--

8041626: Shutdown tracing event
Reviewed-by: dholmes, alanb, rriggs

     1 /*
     2  * Copyright (c) 1997, 2018, 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  */
    25 #include "precompiled.hpp"
    26 #include "classfile/classLoader.hpp"
    27 #include "classfile/javaClasses.hpp"
    28 #include "classfile/systemDictionary.hpp"
    29 #include "classfile/vmSymbols.hpp"
    30 #include "code/scopeDesc.hpp"
    31 #include "compiler/compileBroker.hpp"
    32 #include "interpreter/interpreter.hpp"
    33 #include "interpreter/linkResolver.hpp"
    34 #include "interpreter/oopMapCache.hpp"
    35 #include "jfr/jfrEvents.hpp"
    36 #include "jfr/support/jfrThreadId.hpp"
    37 #include "jvmtifiles/jvmtiEnv.hpp"
    38 #include "memory/gcLocker.inline.hpp"
    39 #include "memory/metaspaceShared.hpp"
    40 #include "memory/oopFactory.hpp"
    41 #include "memory/universe.inline.hpp"
    42 #include "oops/instanceKlass.hpp"
    43 #include "oops/objArrayOop.hpp"
    44 #include "oops/oop.inline.hpp"
    45 #include "oops/symbol.hpp"
    46 #include "prims/jvm_misc.hpp"
    47 #include "prims/jvmtiExport.hpp"
    48 #include "prims/jvmtiThreadState.hpp"
    49 #include "prims/privilegedStack.hpp"
    50 #include "runtime/arguments.hpp"
    51 #include "runtime/biasedLocking.hpp"
    52 #include "runtime/deoptimization.hpp"
    53 #include "runtime/fprofiler.hpp"
    54 #include "runtime/frame.inline.hpp"
    55 #include "runtime/init.hpp"
    56 #include "runtime/interfaceSupport.hpp"
    57 #include "runtime/java.hpp"
    58 #include "runtime/javaCalls.hpp"
    59 #include "runtime/jniPeriodicChecker.hpp"
    60 #include "runtime/memprofiler.hpp"
    61 #include "runtime/mutexLocker.hpp"
    62 #include "runtime/objectMonitor.hpp"
    63 #include "runtime/orderAccess.inline.hpp"
    64 #include "runtime/osThread.hpp"
    65 #include "runtime/safepoint.hpp"
    66 #include "runtime/sharedRuntime.hpp"
    67 #include "runtime/statSampler.hpp"
    68 #include "runtime/stubRoutines.hpp"
    69 #include "runtime/task.hpp"
    70 #include "runtime/thread.inline.hpp"
    71 #include "runtime/threadCritical.hpp"
    72 #include "runtime/threadLocalStorage.hpp"
    73 #include "runtime/vframe.hpp"
    74 #include "runtime/vframeArray.hpp"
    75 #include "runtime/vframe_hp.hpp"
    76 #include "runtime/vmThread.hpp"
    77 #include "runtime/vm_operations.hpp"
    78 #include "services/attachListener.hpp"
    79 #include "services/management.hpp"
    80 #include "services/memTracker.hpp"
    81 #include "services/threadService.hpp"
    82 #include "utilities/defaultStream.hpp"
    83 #include "utilities/dtrace.hpp"
    84 #include "utilities/events.hpp"
    85 #include "utilities/preserveException.hpp"
    86 #include "utilities/macros.hpp"
    87 #ifdef TARGET_OS_FAMILY_linux
    88 # include "os_linux.inline.hpp"
    89 #endif
    90 #ifdef TARGET_OS_FAMILY_solaris
    91 # include "os_solaris.inline.hpp"
    92 #endif
    93 #ifdef TARGET_OS_FAMILY_windows
    94 # include "os_windows.inline.hpp"
    95 #endif
    96 #ifdef TARGET_OS_FAMILY_bsd
    97 # include "os_bsd.inline.hpp"
    98 #endif
    99 #if INCLUDE_ALL_GCS
   100 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
   101 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
   102 #include "gc_implementation/parallelScavenge/pcTasks.hpp"
   103 #endif // INCLUDE_ALL_GCS
   104 #ifdef COMPILER1
   105 #include "c1/c1_Compiler.hpp"
   106 #endif
   107 #ifdef COMPILER2
   108 #include "opto/c2compiler.hpp"
   109 #include "opto/idealGraphPrinter.hpp"
   110 #endif
   111 #if INCLUDE_RTM_OPT
   112 #include "runtime/rtmLocking.hpp"
   113 #endif
   114 #if INCLUDE_JFR
   115 #include "jfr/jfr.hpp"
   116 #endif
   118 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
   120 #ifdef DTRACE_ENABLED
   122 // Only bother with this argument setup if dtrace is available
   124 #ifndef USDT2
   125 HS_DTRACE_PROBE_DECL(hotspot, vm__init__begin);
   126 HS_DTRACE_PROBE_DECL(hotspot, vm__init__end);
   127 HS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t,
   128   intptr_t, intptr_t, bool);
   129 HS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t,
   130   intptr_t, intptr_t, bool);
   132 #define DTRACE_THREAD_PROBE(probe, javathread)                             \
   133   {                                                                        \
   134     ResourceMark rm(this);                                                 \
   135     int len = 0;                                                           \
   136     const char* name = (javathread)->get_thread_name();                    \
   137     len = strlen(name);                                                    \
   138     HS_DTRACE_PROBE5(hotspot, thread__##probe,                             \
   139       name, len,                                                           \
   140       java_lang_Thread::thread_id((javathread)->threadObj()),              \
   141       (javathread)->osthread()->thread_id(),                               \
   142       java_lang_Thread::is_daemon((javathread)->threadObj()));             \
   143   }
   145 #else /* USDT2 */
   147 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
   148 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
   150 #define DTRACE_THREAD_PROBE(probe, javathread)                             \
   151   {                                                                        \
   152     ResourceMark rm(this);                                                 \
   153     int len = 0;                                                           \
   154     const char* name = (javathread)->get_thread_name();                    \
   155     len = strlen(name);                                                    \
   156     HOTSPOT_THREAD_PROBE_##probe(  /* probe = start, stop */               \
   157       (char *) name, len,                                                           \
   158       java_lang_Thread::thread_id((javathread)->threadObj()),              \
   159       (uintptr_t) (javathread)->osthread()->thread_id(),                               \
   160       java_lang_Thread::is_daemon((javathread)->threadObj()));             \
   161   }
   163 #endif /* USDT2 */
   165 #else //  ndef DTRACE_ENABLED
   167 #define DTRACE_THREAD_PROBE(probe, javathread)
   169 #endif // ndef DTRACE_ENABLED
   172 // Class hierarchy
   173 // - Thread
   174 //   - VMThread
   175 //   - WatcherThread
   176 //   - ConcurrentMarkSweepThread
   177 //   - JavaThread
   178 //     - CompilerThread
   180 // ======= Thread ========
   181 // Support for forcing alignment of thread objects for biased locking
   182 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
   183   if (UseBiasedLocking) {
   184     const int alignment = markOopDesc::biased_lock_alignment;
   185     size_t aligned_size = size + (alignment - sizeof(intptr_t));
   186     void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
   187                                           : AllocateHeap(aligned_size, flags, CURRENT_PC,
   188                                               AllocFailStrategy::RETURN_NULL);
   189     void* aligned_addr     = (void*) align_size_up((intptr_t) real_malloc_addr, alignment);
   190     assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
   191            ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
   192            "JavaThread alignment code overflowed allocated storage");
   193     if (TraceBiasedLocking) {
   194       if (aligned_addr != real_malloc_addr)
   195         tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
   196                       real_malloc_addr, aligned_addr);
   197     }
   198     ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
   199     return aligned_addr;
   200   } else {
   201     return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
   202                        : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
   203   }
   204 }
   206 void Thread::operator delete(void* p) {
   207   if (UseBiasedLocking) {
   208     void* real_malloc_addr = ((Thread*) p)->_real_malloc_address;
   209     FreeHeap(real_malloc_addr, mtThread);
   210   } else {
   211     FreeHeap(p, mtThread);
   212   }
   213 }
   216 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
   217 // JavaThread
   220 Thread::Thread() {
   221   // stack and get_thread
   222   set_stack_base(NULL);
   223   set_stack_size(0);
   224   set_self_raw_id(0);
   225   set_lgrp_id(-1);
   227   // allocated data structures
   228   set_osthread(NULL);
   229   set_resource_area(new (mtThread)ResourceArea());
   230   DEBUG_ONLY(_current_resource_mark = NULL;)
   231   set_handle_area(new (mtThread) HandleArea(NULL));
   232   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
   233   set_active_handles(NULL);
   234   set_free_handle_block(NULL);
   235   set_last_handle_mark(NULL);
   237   // This initial value ==> never claimed.
   238   _oops_do_parity = 0;
   240   _metadata_on_stack_buffer = NULL;
   242   // the handle mark links itself to last_handle_mark
   243   new HandleMark(this);
   245   // plain initialization
   246   debug_only(_owned_locks = NULL;)
   247   debug_only(_allow_allocation_count = 0;)
   248   NOT_PRODUCT(_allow_safepoint_count = 0;)
   249   NOT_PRODUCT(_skip_gcalot = false;)
   250   _jvmti_env_iteration_count = 0;
   251   set_allocated_bytes(0);
   252   _vm_operation_started_count = 0;
   253   _vm_operation_completed_count = 0;
   254   _current_pending_monitor = NULL;
   255   _current_pending_monitor_is_from_java = true;
   256   _current_waiting_monitor = NULL;
   257   _num_nested_signal = 0;
   258   omFreeList = NULL ;
   259   omFreeCount = 0 ;
   260   omFreeProvision = 32 ;
   261   omInUseList = NULL ;
   262   omInUseCount = 0 ;
   264 #ifdef ASSERT
   265   _visited_for_critical_count = false;
   266 #endif
   268   _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true);
   269   _suspend_flags = 0;
   271   // thread-specific hashCode stream generator state - Marsaglia shift-xor form
   272   _hashStateX = os::random() ;
   273   _hashStateY = 842502087 ;
   274   _hashStateZ = 0x8767 ;    // (int)(3579807591LL & 0xffff) ;
   275   _hashStateW = 273326509 ;
   277   _OnTrap   = 0 ;
   278   _schedctl = NULL ;
   279   _Stalled  = 0 ;
   280   _TypeTag  = 0x2BAD ;
   282   // Many of the following fields are effectively final - immutable
   283   // Note that nascent threads can't use the Native Monitor-Mutex
   284   // construct until the _MutexEvent is initialized ...
   285   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
   286   // we might instead use a stack of ParkEvents that we could provision on-demand.
   287   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
   288   // and ::Release()
   289   _ParkEvent   = ParkEvent::Allocate (this) ;
   290   _SleepEvent  = ParkEvent::Allocate (this) ;
   291   _MutexEvent  = ParkEvent::Allocate (this) ;
   292   _MuxEvent    = ParkEvent::Allocate (this) ;
   294 #ifdef CHECK_UNHANDLED_OOPS
   295   if (CheckUnhandledOops) {
   296     _unhandled_oops = new UnhandledOops(this);
   297   }
   298 #endif // CHECK_UNHANDLED_OOPS
   299 #ifdef ASSERT
   300   if (UseBiasedLocking) {
   301     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
   302     assert(this == _real_malloc_address ||
   303            this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
   304            "bug in forced alignment of thread objects");
   305   }
   306 #endif /* ASSERT */
   307 }
   309 void Thread::initialize_thread_local_storage() {
   310   // Note: Make sure this method only calls
   311   // non-blocking operations. Otherwise, it might not work
   312   // with the thread-startup/safepoint interaction.
   314   // During Java thread startup, safepoint code should allow this
   315   // method to complete because it may need to allocate memory to
   316   // store information for the new thread.
   318   // initialize structure dependent on thread local storage
   319   ThreadLocalStorage::set_thread(this);
   320 }
   322 void Thread::record_stack_base_and_size() {
   323   set_stack_base(os::current_stack_base());
   324   set_stack_size(os::current_stack_size());
   325   if (is_Java_thread()) {
   326     ((JavaThread*) this)->set_stack_overflow_limit();
   327   }
   328   // CR 7190089: on Solaris, primordial thread's stack is adjusted
   329   // in initialize_thread(). Without the adjustment, stack size is
   330   // incorrect if stack is set to unlimited (ulimit -s unlimited).
   331   // So far, only Solaris has real implementation of initialize_thread().
   332   //
   333   // set up any platform-specific state.
   334   os::initialize_thread(this);
   336 #if INCLUDE_NMT
   337   // record thread's native stack, stack grows downward
   338   address stack_low_addr = stack_base() - stack_size();
   339   MemTracker::record_thread_stack(stack_low_addr, stack_size());
   340 #endif // INCLUDE_NMT
   341 }
   344 Thread::~Thread() {
   345   // Reclaim the objectmonitors from the omFreeList of the moribund thread.
   346   ObjectSynchronizer::omFlush (this) ;
   348   JFR_ONLY(Jfr::on_thread_destruct(this);)
   350   // stack_base can be NULL if the thread is never started or exited before
   351   // record_stack_base_and_size called. Although, we would like to ensure
   352   // that all started threads do call record_stack_base_and_size(), there is
   353   // not proper way to enforce that.
   354 #if INCLUDE_NMT
   355   if (_stack_base != NULL) {
   356     address low_stack_addr = stack_base() - stack_size();
   357     MemTracker::release_thread_stack(low_stack_addr, stack_size());
   358 #ifdef ASSERT
   359     set_stack_base(NULL);
   360 #endif
   361   }
   362 #endif // INCLUDE_NMT
   364   // deallocate data structures
   365   delete resource_area();
   366   // since the handle marks are using the handle area, we have to deallocated the root
   367   // handle mark before deallocating the thread's handle area,
   368   assert(last_handle_mark() != NULL, "check we have an element");
   369   delete last_handle_mark();
   370   assert(last_handle_mark() == NULL, "check we have reached the end");
   372   // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
   373   // We NULL out the fields for good hygiene.
   374   ParkEvent::Release (_ParkEvent)   ; _ParkEvent   = NULL ;
   375   ParkEvent::Release (_SleepEvent)  ; _SleepEvent  = NULL ;
   376   ParkEvent::Release (_MutexEvent)  ; _MutexEvent  = NULL ;
   377   ParkEvent::Release (_MuxEvent)    ; _MuxEvent    = NULL ;
   379   delete handle_area();
   380   delete metadata_handles();
   382   // osthread() can be NULL, if creation of thread failed.
   383   if (osthread() != NULL) os::free_thread(osthread());
   385   delete _SR_lock;
   387   // clear thread local storage if the Thread is deleting itself
   388   if (this == Thread::current()) {
   389     ThreadLocalStorage::set_thread(NULL);
   390   } else {
   391     // In the case where we're not the current thread, invalidate all the
   392     // caches in case some code tries to get the current thread or the
   393     // thread that was destroyed, and gets stale information.
   394     ThreadLocalStorage::invalidate_all();
   395   }
   396   CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
   397 }
   399 // NOTE: dummy function for assertion purpose.
   400 void Thread::run() {
   401   ShouldNotReachHere();
   402 }
   404 #ifdef ASSERT
   405 // Private method to check for dangling thread pointer
   406 void check_for_dangling_thread_pointer(Thread *thread) {
   407  assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
   408          "possibility of dangling Thread pointer");
   409 }
   410 #endif
   413 #ifndef PRODUCT
   414 // Tracing method for basic thread operations
   415 void Thread::trace(const char* msg, const Thread* const thread) {
   416   if (!TraceThreadEvents) return;
   417   ResourceMark rm;
   418   ThreadCritical tc;
   419   const char *name = "non-Java thread";
   420   int prio = -1;
   421   if (thread->is_Java_thread()
   422       && !thread->is_Compiler_thread()) {
   423     // The Threads_lock must be held to get information about
   424     // this thread but may not be in some situations when
   425     // tracing  thread events.
   426     bool release_Threads_lock = false;
   427     if (!Threads_lock->owned_by_self()) {
   428       Threads_lock->lock();
   429       release_Threads_lock = true;
   430     }
   431     JavaThread* jt = (JavaThread *)thread;
   432     name = (char *)jt->get_thread_name();
   433     oop thread_oop = jt->threadObj();
   434     if (thread_oop != NULL) {
   435       prio = java_lang_Thread::priority(thread_oop);
   436     }
   437     if (release_Threads_lock) {
   438       Threads_lock->unlock();
   439     }
   440   }
   441   tty->print_cr("Thread::%s " INTPTR_FORMAT " [%lx] %s (prio: %d)", msg, thread, thread->osthread()->thread_id(), name, prio);
   442 }
   443 #endif
   446 ThreadPriority Thread::get_priority(const Thread* const thread) {
   447   trace("get priority", thread);
   448   ThreadPriority priority;
   449   // Can return an error!
   450   (void)os::get_priority(thread, priority);
   451   assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
   452   return priority;
   453 }
   455 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
   456   trace("set priority", thread);
   457   debug_only(check_for_dangling_thread_pointer(thread);)
   458   // Can return an error!
   459   (void)os::set_priority(thread, priority);
   460 }
   463 void Thread::start(Thread* thread) {
   464   trace("start", thread);
   465   // Start is different from resume in that its safety is guaranteed by context or
   466   // being called from a Java method synchronized on the Thread object.
   467   if (!DisableStartThread) {
   468     if (thread->is_Java_thread()) {
   469       // Initialize the thread state to RUNNABLE before starting this thread.
   470       // Can not set it after the thread started because we do not know the
   471       // exact thread state at that time. It could be in MONITOR_WAIT or
   472       // in SLEEPING or some other state.
   473       java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
   474                                           java_lang_Thread::RUNNABLE);
   475     }
   476     os::start_thread(thread);
   477   }
   478 }
   480 // Enqueue a VM_Operation to do the job for us - sometime later
   481 void Thread::send_async_exception(oop java_thread, oop java_throwable) {
   482   VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
   483   VMThread::execute(vm_stop);
   484 }
   487 //
   488 // Check if an external suspend request has completed (or has been
   489 // cancelled). Returns true if the thread is externally suspended and
   490 // false otherwise.
   491 //
   492 // The bits parameter returns information about the code path through
   493 // the routine. Useful for debugging:
   494 //
   495 // set in is_ext_suspend_completed():
   496 // 0x00000001 - routine was entered
   497 // 0x00000010 - routine return false at end
   498 // 0x00000100 - thread exited (return false)
   499 // 0x00000200 - suspend request cancelled (return false)
   500 // 0x00000400 - thread suspended (return true)
   501 // 0x00001000 - thread is in a suspend equivalent state (return true)
   502 // 0x00002000 - thread is native and walkable (return true)
   503 // 0x00004000 - thread is native_trans and walkable (needed retry)
   504 //
   505 // set in wait_for_ext_suspend_completion():
   506 // 0x00010000 - routine was entered
   507 // 0x00020000 - suspend request cancelled before loop (return false)
   508 // 0x00040000 - thread suspended before loop (return true)
   509 // 0x00080000 - suspend request cancelled in loop (return false)
   510 // 0x00100000 - thread suspended in loop (return true)
   511 // 0x00200000 - suspend not completed during retry loop (return false)
   512 //
   514 // Helper class for tracing suspend wait debug bits.
   515 //
   516 // 0x00000100 indicates that the target thread exited before it could
   517 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
   518 // 0x00080000 each indicate a cancelled suspend request so they don't
   519 // count as wait failures either.
   520 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
   522 class TraceSuspendDebugBits : public StackObj {
   523  private:
   524   JavaThread * jt;
   525   bool         is_wait;
   526   bool         called_by_wait;  // meaningful when !is_wait
   527   uint32_t *   bits;
   529  public:
   530   TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
   531                         uint32_t *_bits) {
   532     jt             = _jt;
   533     is_wait        = _is_wait;
   534     called_by_wait = _called_by_wait;
   535     bits           = _bits;
   536   }
   538   ~TraceSuspendDebugBits() {
   539     if (!is_wait) {
   540 #if 1
   541       // By default, don't trace bits for is_ext_suspend_completed() calls.
   542       // That trace is very chatty.
   543       return;
   544 #else
   545       if (!called_by_wait) {
   546         // If tracing for is_ext_suspend_completed() is enabled, then only
   547         // trace calls to it from wait_for_ext_suspend_completion()
   548         return;
   549       }
   550 #endif
   551     }
   553     if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
   554       if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
   555         MutexLocker ml(Threads_lock);  // needed for get_thread_name()
   556         ResourceMark rm;
   558         tty->print_cr(
   559             "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
   560             jt->get_thread_name(), *bits);
   562         guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
   563       }
   564     }
   565   }
   566 };
   567 #undef DEBUG_FALSE_BITS
   570 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits) {
   571   TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
   573   bool did_trans_retry = false;  // only do thread_in_native_trans retry once
   574   bool do_trans_retry;           // flag to force the retry
   576   *bits |= 0x00000001;
   578   do {
   579     do_trans_retry = false;
   581     if (is_exiting()) {
   582       // Thread is in the process of exiting. This is always checked
   583       // first to reduce the risk of dereferencing a freed JavaThread.
   584       *bits |= 0x00000100;
   585       return false;
   586     }
   588     if (!is_external_suspend()) {
   589       // Suspend request is cancelled. This is always checked before
   590       // is_ext_suspended() to reduce the risk of a rogue resume
   591       // confusing the thread that made the suspend request.
   592       *bits |= 0x00000200;
   593       return false;
   594     }
   596     if (is_ext_suspended()) {
   597       // thread is suspended
   598       *bits |= 0x00000400;
   599       return true;
   600     }
   602     // Now that we no longer do hard suspends of threads running
   603     // native code, the target thread can be changing thread state
   604     // while we are in this routine:
   605     //
   606     //   _thread_in_native -> _thread_in_native_trans -> _thread_blocked
   607     //
   608     // We save a copy of the thread state as observed at this moment
   609     // and make our decision about suspend completeness based on the
   610     // copy. This closes the race where the thread state is seen as
   611     // _thread_in_native_trans in the if-thread_blocked check, but is
   612     // seen as _thread_blocked in if-thread_in_native_trans check.
   613     JavaThreadState save_state = thread_state();
   615     if (save_state == _thread_blocked && is_suspend_equivalent()) {
   616       // If the thread's state is _thread_blocked and this blocking
   617       // condition is known to be equivalent to a suspend, then we can
   618       // consider the thread to be externally suspended. This means that
   619       // the code that sets _thread_blocked has been modified to do
   620       // self-suspension if the blocking condition releases. We also
   621       // used to check for CONDVAR_WAIT here, but that is now covered by
   622       // the _thread_blocked with self-suspension check.
   623       //
   624       // Return true since we wouldn't be here unless there was still an
   625       // external suspend request.
   626       *bits |= 0x00001000;
   627       return true;
   628     } else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
   629       // Threads running native code will self-suspend on native==>VM/Java
   630       // transitions. If its stack is walkable (should always be the case
   631       // unless this function is called before the actual java_suspend()
   632       // call), then the wait is done.
   633       *bits |= 0x00002000;
   634       return true;
   635     } else if (!called_by_wait && !did_trans_retry &&
   636                save_state == _thread_in_native_trans &&
   637                frame_anchor()->walkable()) {
   638       // The thread is transitioning from thread_in_native to another
   639       // thread state. check_safepoint_and_suspend_for_native_trans()
   640       // will force the thread to self-suspend. If it hasn't gotten
   641       // there yet we may have caught the thread in-between the native
   642       // code check above and the self-suspend. Lucky us. If we were
   643       // called by wait_for_ext_suspend_completion(), then it
   644       // will be doing the retries so we don't have to.
   645       //
   646       // Since we use the saved thread state in the if-statement above,
   647       // there is a chance that the thread has already transitioned to
   648       // _thread_blocked by the time we get here. In that case, we will
   649       // make a single unnecessary pass through the logic below. This
   650       // doesn't hurt anything since we still do the trans retry.
   652       *bits |= 0x00004000;
   654       // Once the thread leaves thread_in_native_trans for another
   655       // thread state, we break out of this retry loop. We shouldn't
   656       // need this flag to prevent us from getting back here, but
   657       // sometimes paranoia is good.
   658       did_trans_retry = true;
   660       // We wait for the thread to transition to a more usable state.
   661       for (int i = 1; i <= SuspendRetryCount; i++) {
   662         // We used to do an "os::yield_all(i)" call here with the intention
   663         // that yielding would increase on each retry. However, the parameter
   664         // is ignored on Linux which means the yield didn't scale up. Waiting
   665         // on the SR_lock below provides a much more predictable scale up for
   666         // the delay. It also provides a simple/direct point to check for any
   667         // safepoint requests from the VMThread
   669         // temporarily drops SR_lock while doing wait with safepoint check
   670         // (if we're a JavaThread - the WatcherThread can also call this)
   671         // and increase delay with each retry
   672         SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
   674         // check the actual thread state instead of what we saved above
   675         if (thread_state() != _thread_in_native_trans) {
   676           // the thread has transitioned to another thread state so
   677           // try all the checks (except this one) one more time.
   678           do_trans_retry = true;
   679           break;
   680         }
   681       } // end retry loop
   684     }
   685   } while (do_trans_retry);
   687   *bits |= 0x00000010;
   688   return false;
   689 }
   691 //
   692 // Wait for an external suspend request to complete (or be cancelled).
   693 // Returns true if the thread is externally suspended and false otherwise.
   694 //
   695 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
   696        uint32_t *bits) {
   697   TraceSuspendDebugBits tsdb(this, true /* is_wait */,
   698                              false /* !called_by_wait */, bits);
   700   // local flag copies to minimize SR_lock hold time
   701   bool is_suspended;
   702   bool pending;
   703   uint32_t reset_bits;
   705   // set a marker so is_ext_suspend_completed() knows we are the caller
   706   *bits |= 0x00010000;
   708   // We use reset_bits to reinitialize the bits value at the top of
   709   // each retry loop. This allows the caller to make use of any
   710   // unused bits for their own marking purposes.
   711   reset_bits = *bits;
   713   {
   714     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
   715     is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
   716                                             delay, bits);
   717     pending = is_external_suspend();
   718   }
   719   // must release SR_lock to allow suspension to complete
   721   if (!pending) {
   722     // A cancelled suspend request is the only false return from
   723     // is_ext_suspend_completed() that keeps us from entering the
   724     // retry loop.
   725     *bits |= 0x00020000;
   726     return false;
   727   }
   729   if (is_suspended) {
   730     *bits |= 0x00040000;
   731     return true;
   732   }
   734   for (int i = 1; i <= retries; i++) {
   735     *bits = reset_bits;  // reinit to only track last retry
   737     // We used to do an "os::yield_all(i)" call here with the intention
   738     // that yielding would increase on each retry. However, the parameter
   739     // is ignored on Linux which means the yield didn't scale up. Waiting
   740     // on the SR_lock below provides a much more predictable scale up for
   741     // the delay. It also provides a simple/direct point to check for any
   742     // safepoint requests from the VMThread
   744     {
   745       MutexLocker ml(SR_lock());
   746       // wait with safepoint check (if we're a JavaThread - the WatcherThread
   747       // can also call this)  and increase delay with each retry
   748       SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
   750       is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
   751                                               delay, bits);
   753       // It is possible for the external suspend request to be cancelled
   754       // (by a resume) before the actual suspend operation is completed.
   755       // Refresh our local copy to see if we still need to wait.
   756       pending = is_external_suspend();
   757     }
   759     if (!pending) {
   760       // A cancelled suspend request is the only false return from
   761       // is_ext_suspend_completed() that keeps us from staying in the
   762       // retry loop.
   763       *bits |= 0x00080000;
   764       return false;
   765     }
   767     if (is_suspended) {
   768       *bits |= 0x00100000;
   769       return true;
   770     }
   771   } // end retry loop
   773   // thread did not suspend after all our retries
   774   *bits |= 0x00200000;
   775   return false;
   776 }
   778 #ifndef PRODUCT
   779 void JavaThread::record_jump(address target, address instr, const char* file, int line) {
   781   // This should not need to be atomic as the only way for simultaneous
   782   // updates is via interrupts. Even then this should be rare or non-existant
   783   // and we don't care that much anyway.
   785   int index = _jmp_ring_index;
   786   _jmp_ring_index = (index + 1 ) & (jump_ring_buffer_size - 1);
   787   _jmp_ring[index]._target = (intptr_t) target;
   788   _jmp_ring[index]._instruction = (intptr_t) instr;
   789   _jmp_ring[index]._file = file;
   790   _jmp_ring[index]._line = line;
   791 }
   792 #endif /* PRODUCT */
   794 // Called by flat profiler
   795 // Callers have already called wait_for_ext_suspend_completion
   796 // The assertion for that is currently too complex to put here:
   797 bool JavaThread::profile_last_Java_frame(frame* _fr) {
   798   bool gotframe = false;
   799   // self suspension saves needed state.
   800   if (has_last_Java_frame() && _anchor.walkable()) {
   801      *_fr = pd_last_frame();
   802      gotframe = true;
   803   }
   804   return gotframe;
   805 }
   807 void Thread::interrupt(Thread* thread) {
   808   trace("interrupt", thread);
   809   debug_only(check_for_dangling_thread_pointer(thread);)
   810   os::interrupt(thread);
   811 }
   813 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) {
   814   trace("is_interrupted", thread);
   815   debug_only(check_for_dangling_thread_pointer(thread);)
   816   // Note:  If clear_interrupted==false, this simply fetches and
   817   // returns the value of the field osthread()->interrupted().
   818   return os::is_interrupted(thread, clear_interrupted);
   819 }
   822 // GC Support
   823 bool Thread::claim_oops_do_par_case(int strong_roots_parity) {
   824   jint thread_parity = _oops_do_parity;
   825   if (thread_parity != strong_roots_parity) {
   826     jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity);
   827     if (res == thread_parity) {
   828       return true;
   829     } else {
   830       guarantee(res == strong_roots_parity, "Or else what?");
   831       assert(SharedHeap::heap()->workers()->active_workers() > 0,
   832          "Should only fail when parallel.");
   833       return false;
   834     }
   835   }
   836   assert(SharedHeap::heap()->workers()->active_workers() > 0,
   837          "Should only fail when parallel.");
   838   return false;
   839 }
   841 void Thread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
   842   active_handles()->oops_do(f);
   843   // Do oop for ThreadShadow
   844   f->do_oop((oop*)&_pending_exception);
   845   handle_area()->oops_do(f);
   846 }
   848 void Thread::nmethods_do(CodeBlobClosure* cf) {
   849   // no nmethods in a generic thread...
   850 }
   852 void Thread::metadata_do(void f(Metadata*)) {
   853   if (metadata_handles() != NULL) {
   854     for (int i = 0; i< metadata_handles()->length(); i++) {
   855       f(metadata_handles()->at(i));
   856     }
   857   }
   858 }
   860 void Thread::print_on(outputStream* st) const {
   861   // get_priority assumes osthread initialized
   862   if (osthread() != NULL) {
   863     int os_prio;
   864     if (os::get_native_priority(this, &os_prio) == OS_OK) {
   865       st->print("os_prio=%d ", os_prio);
   866     }
   867     st->print("tid=" INTPTR_FORMAT " ", this);
   868     ext().print_on(st);
   869     osthread()->print_on(st);
   870   }
   871   debug_only(if (WizardMode) print_owned_locks_on(st);)
   872 }
   874 // Thread::print_on_error() is called by fatal error handler. Don't use
   875 // any lock or allocate memory.
   876 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
   877   if      (is_VM_thread())                  st->print("VMThread");
   878   else if (is_Compiler_thread())            st->print("CompilerThread");
   879   else if (is_Java_thread())                st->print("JavaThread");
   880   else if (is_GC_task_thread())             st->print("GCTaskThread");
   881   else if (is_Watcher_thread())             st->print("WatcherThread");
   882   else if (is_ConcurrentGC_thread())        st->print("ConcurrentGCThread");
   883   else st->print("Thread");
   885   st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
   886             _stack_base - _stack_size, _stack_base);
   888   if (osthread()) {
   889     st->print(" [id=%d]", osthread()->thread_id());
   890   }
   891 }
   893 #ifdef ASSERT
   894 void Thread::print_owned_locks_on(outputStream* st) const {
   895   Monitor *cur = _owned_locks;
   896   if (cur == NULL) {
   897     st->print(" (no locks) ");
   898   } else {
   899     st->print_cr(" Locks owned:");
   900     while(cur) {
   901       cur->print_on(st);
   902       cur = cur->next();
   903     }
   904   }
   905 }
   907 static int ref_use_count  = 0;
   909 bool Thread::owns_locks_but_compiled_lock() const {
   910   for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
   911     if (cur != Compile_lock) return true;
   912   }
   913   return false;
   914 }
   917 #endif
   919 #ifndef PRODUCT
   921 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
   922 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
   923 // no threads which allow_vm_block's are held
   924 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
   925     // Check if current thread is allowed to block at a safepoint
   926     if (!(_allow_safepoint_count == 0))
   927       fatal("Possible safepoint reached by thread that does not allow it");
   928     if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
   929       fatal("LEAF method calling lock?");
   930     }
   932 #ifdef ASSERT
   933     if (potential_vm_operation && is_Java_thread()
   934         && !Universe::is_bootstrapping()) {
   935       // Make sure we do not hold any locks that the VM thread also uses.
   936       // This could potentially lead to deadlocks
   937       for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
   938         // Threads_lock is special, since the safepoint synchronization will not start before this is
   939         // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
   940         // since it is used to transfer control between JavaThreads and the VMThread
   941         // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first!
   942         if ( (cur->allow_vm_block() &&
   943               cur != Threads_lock &&
   944               cur != Compile_lock &&               // Temporary: should not be necessary when we get spearate compilation
   945               cur != VMOperationRequest_lock &&
   946               cur != VMOperationQueue_lock) ||
   947               cur->rank() == Mutex::special) {
   948           fatal(err_msg("Thread holding lock at safepoint that vm can block on: %s", cur->name()));
   949         }
   950       }
   951     }
   953     if (GCALotAtAllSafepoints) {
   954       // We could enter a safepoint here and thus have a gc
   955       InterfaceSupport::check_gc_alot();
   956     }
   957 #endif
   958 }
   959 #endif
   961 bool Thread::is_in_stack(address adr) const {
   962   assert(Thread::current() == this, "is_in_stack can only be called from current thread");
   963   address end = os::current_stack_pointer();
   964   // Allow non Java threads to call this without stack_base
   965   if (_stack_base == NULL) return true;
   966   if (stack_base() >= adr && adr >= end) return true;
   968   return false;
   969 }
   972 bool Thread::is_in_usable_stack(address adr) const {
   973   size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0;
   974   size_t usable_stack_size = _stack_size - stack_guard_size;
   976   return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
   977 }
   980 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
   981 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
   982 // used for compilation in the future. If that change is made, the need for these methods
   983 // should be revisited, and they should be removed if possible.
   985 bool Thread::is_lock_owned(address adr) const {
   986   return on_local_stack(adr);
   987 }
   989 bool Thread::set_as_starting_thread() {
   990  // NOTE: this must be called inside the main thread.
   991   return os::create_main_thread((JavaThread*)this);
   992 }
   994 static void initialize_class(Symbol* class_name, TRAPS) {
   995   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
   996   InstanceKlass::cast(klass)->initialize(CHECK);
   997 }
  1000 // Creates the initial ThreadGroup
  1001 static Handle create_initial_thread_group(TRAPS) {
  1002   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ThreadGroup(), true, CHECK_NH);
  1003   instanceKlassHandle klass (THREAD, k);
  1005   Handle system_instance = klass->allocate_instance_handle(CHECK_NH);
  1007     JavaValue result(T_VOID);
  1008     JavaCalls::call_special(&result,
  1009                             system_instance,
  1010                             klass,
  1011                             vmSymbols::object_initializer_name(),
  1012                             vmSymbols::void_method_signature(),
  1013                             CHECK_NH);
  1015   Universe::set_system_thread_group(system_instance());
  1017   Handle main_instance = klass->allocate_instance_handle(CHECK_NH);
  1019     JavaValue result(T_VOID);
  1020     Handle string = java_lang_String::create_from_str("main", CHECK_NH);
  1021     JavaCalls::call_special(&result,
  1022                             main_instance,
  1023                             klass,
  1024                             vmSymbols::object_initializer_name(),
  1025                             vmSymbols::threadgroup_string_void_signature(),
  1026                             system_instance,
  1027                             string,
  1028                             CHECK_NH);
  1030   return main_instance;
  1033 // Creates the initial Thread
  1034 static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) {
  1035   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL);
  1036   instanceKlassHandle klass (THREAD, k);
  1037   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
  1039   java_lang_Thread::set_thread(thread_oop(), thread);
  1040   java_lang_Thread::set_priority(thread_oop(), NormPriority);
  1041   thread->set_threadObj(thread_oop());
  1043   Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
  1045   JavaValue result(T_VOID);
  1046   JavaCalls::call_special(&result, thread_oop,
  1047                                    klass,
  1048                                    vmSymbols::object_initializer_name(),
  1049                                    vmSymbols::threadgroup_string_void_signature(),
  1050                                    thread_group,
  1051                                    string,
  1052                                    CHECK_NULL);
  1053   return thread_oop();
  1056 static void call_initializeSystemClass(TRAPS) {
  1057   Klass* k =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
  1058   instanceKlassHandle klass (THREAD, k);
  1060   JavaValue result(T_VOID);
  1061   JavaCalls::call_static(&result, klass, vmSymbols::initializeSystemClass_name(),
  1062                                          vmSymbols::void_method_signature(), CHECK);
  1065 char java_runtime_name[128] = "";
  1066 char java_runtime_version[128] = "";
  1068 // extract the JRE name from sun.misc.Version.java_runtime_name
  1069 static const char* get_java_runtime_name(TRAPS) {
  1070   Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
  1071                                       Handle(), Handle(), CHECK_AND_CLEAR_NULL);
  1072   fieldDescriptor fd;
  1073   bool found = k != NULL &&
  1074                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
  1075                                                         vmSymbols::string_signature(), &fd);
  1076   if (found) {
  1077     oop name_oop = k->java_mirror()->obj_field(fd.offset());
  1078     if (name_oop == NULL)
  1079       return NULL;
  1080     const char* name = java_lang_String::as_utf8_string(name_oop,
  1081                                                         java_runtime_name,
  1082                                                         sizeof(java_runtime_name));
  1083     return name;
  1084   } else {
  1085     return NULL;
  1089 // extract the JRE version from sun.misc.Version.java_runtime_version
  1090 static const char* get_java_runtime_version(TRAPS) {
  1091   Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
  1092                                       Handle(), Handle(), CHECK_AND_CLEAR_NULL);
  1093   fieldDescriptor fd;
  1094   bool found = k != NULL &&
  1095                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(),
  1096                                                         vmSymbols::string_signature(), &fd);
  1097   if (found) {
  1098     oop name_oop = k->java_mirror()->obj_field(fd.offset());
  1099     if (name_oop == NULL)
  1100       return NULL;
  1101     const char* name = java_lang_String::as_utf8_string(name_oop,
  1102                                                         java_runtime_version,
  1103                                                         sizeof(java_runtime_version));
  1104     return name;
  1105   } else {
  1106     return NULL;
  1110 // General purpose hook into Java code, run once when the VM is initialized.
  1111 // The Java library method itself may be changed independently from the VM.
  1112 static void call_postVMInitHook(TRAPS) {
  1113   Klass* k = SystemDictionary::resolve_or_null(vmSymbols::sun_misc_PostVMInitHook(), THREAD);
  1114   instanceKlassHandle klass (THREAD, k);
  1115   if (klass.not_null()) {
  1116     JavaValue result(T_VOID);
  1117     JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
  1118                                            vmSymbols::void_method_signature(),
  1119                                            CHECK);
  1123 static void reset_vm_info_property(TRAPS) {
  1124   // the vm info string
  1125   ResourceMark rm(THREAD);
  1126   const char *vm_info = VM_Version::vm_info_string();
  1128   // java.lang.System class
  1129   Klass* k =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
  1130   instanceKlassHandle klass (THREAD, k);
  1132   // setProperty arguments
  1133   Handle key_str    = java_lang_String::create_from_str("java.vm.info", CHECK);
  1134   Handle value_str  = java_lang_String::create_from_str(vm_info, CHECK);
  1136   // return value
  1137   JavaValue r(T_OBJECT);
  1139   // public static String setProperty(String key, String value);
  1140   JavaCalls::call_static(&r,
  1141                          klass,
  1142                          vmSymbols::setProperty_name(),
  1143                          vmSymbols::string_string_string_signature(),
  1144                          key_str,
  1145                          value_str,
  1146                          CHECK);
  1150 void JavaThread::allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS) {
  1151   assert(thread_group.not_null(), "thread group should be specified");
  1152   assert(threadObj() == NULL, "should only create Java thread object once");
  1154   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
  1155   instanceKlassHandle klass (THREAD, k);
  1156   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
  1158   java_lang_Thread::set_thread(thread_oop(), this);
  1159   java_lang_Thread::set_priority(thread_oop(), NormPriority);
  1160   set_threadObj(thread_oop());
  1162   JavaValue result(T_VOID);
  1163   if (thread_name != NULL) {
  1164     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
  1165     // Thread gets assigned specified name and null target
  1166     JavaCalls::call_special(&result,
  1167                             thread_oop,
  1168                             klass,
  1169                             vmSymbols::object_initializer_name(),
  1170                             vmSymbols::threadgroup_string_void_signature(),
  1171                             thread_group, // Argument 1
  1172                             name,         // Argument 2
  1173                             THREAD);
  1174   } else {
  1175     // Thread gets assigned name "Thread-nnn" and null target
  1176     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
  1177     JavaCalls::call_special(&result,
  1178                             thread_oop,
  1179                             klass,
  1180                             vmSymbols::object_initializer_name(),
  1181                             vmSymbols::threadgroup_runnable_void_signature(),
  1182                             thread_group, // Argument 1
  1183                             Handle(),     // Argument 2
  1184                             THREAD);
  1188   if (daemon) {
  1189       java_lang_Thread::set_daemon(thread_oop());
  1192   if (HAS_PENDING_EXCEPTION) {
  1193     return;
  1196   KlassHandle group(this, SystemDictionary::ThreadGroup_klass());
  1197   Handle threadObj(this, this->threadObj());
  1199   JavaCalls::call_special(&result,
  1200                          thread_group,
  1201                          group,
  1202                          vmSymbols::add_method_name(),
  1203                          vmSymbols::thread_void_signature(),
  1204                          threadObj,          // Arg 1
  1205                          THREAD);
  1210 // NamedThread --  non-JavaThread subclasses with multiple
  1211 // uniquely named instances should derive from this.
  1212 NamedThread::NamedThread() : Thread() {
  1213   _name = NULL;
  1214   _processed_thread = NULL;
  1217 NamedThread::~NamedThread() {
  1218   if (_name != NULL) {
  1219     FREE_C_HEAP_ARRAY(char, _name, mtThread);
  1220     _name = NULL;
  1224 void NamedThread::set_name(const char* format, ...) {
  1225   guarantee(_name == NULL, "Only get to set name once.");
  1226   _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
  1227   guarantee(_name != NULL, "alloc failure");
  1228   va_list ap;
  1229   va_start(ap, format);
  1230   jio_vsnprintf(_name, max_name_len, format, ap);
  1231   va_end(ap);
  1234 // ======= WatcherThread ========
  1236 // The watcher thread exists to simulate timer interrupts.  It should
  1237 // be replaced by an abstraction over whatever native support for
  1238 // timer interrupts exists on the platform.
  1240 WatcherThread* WatcherThread::_watcher_thread   = NULL;
  1241 bool WatcherThread::_startable = false;
  1242 volatile bool  WatcherThread::_should_terminate = false;
  1244 WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) {
  1245   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
  1246   if (os::create_thread(this, os::watcher_thread)) {
  1247     _watcher_thread = this;
  1249     // Set the watcher thread to the highest OS priority which should not be
  1250     // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
  1251     // is created. The only normal thread using this priority is the reference
  1252     // handler thread, which runs for very short intervals only.
  1253     // If the VMThread's priority is not lower than the WatcherThread profiling
  1254     // will be inaccurate.
  1255     os::set_priority(this, MaxPriority);
  1256     if (!DisableStartThread) {
  1257       os::start_thread(this);
  1262 int WatcherThread::sleep() const {
  1263   MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
  1265   // remaining will be zero if there are no tasks,
  1266   // causing the WatcherThread to sleep until a task is
  1267   // enrolled
  1268   int remaining = PeriodicTask::time_to_wait();
  1269   int time_slept = 0;
  1271   // we expect this to timeout - we only ever get unparked when
  1272   // we should terminate or when a new task has been enrolled
  1273   OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
  1275   jlong time_before_loop = os::javaTimeNanos();
  1277   for (;;) {
  1278     bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag, remaining);
  1279     jlong now = os::javaTimeNanos();
  1281     if (remaining == 0) {
  1282         // if we didn't have any tasks we could have waited for a long time
  1283         // consider the time_slept zero and reset time_before_loop
  1284         time_slept = 0;
  1285         time_before_loop = now;
  1286     } else {
  1287         // need to recalulate since we might have new tasks in _tasks
  1288         time_slept = (int) ((now - time_before_loop) / 1000000);
  1291     // Change to task list or spurious wakeup of some kind
  1292     if (timedout || _should_terminate) {
  1293         break;
  1296     remaining = PeriodicTask::time_to_wait();
  1297     if (remaining == 0) {
  1298         // Last task was just disenrolled so loop around and wait until
  1299         // another task gets enrolled
  1300         continue;
  1303     remaining -= time_slept;
  1304     if (remaining <= 0)
  1305       break;
  1308   return time_slept;
  1311 void WatcherThread::run() {
  1312   assert(this == watcher_thread(), "just checking");
  1314   this->record_stack_base_and_size();
  1315   this->initialize_thread_local_storage();
  1316   this->set_native_thread_name(this->name());
  1317   this->set_active_handles(JNIHandleBlock::allocate_block());
  1318   while(!_should_terminate) {
  1319     assert(watcher_thread() == Thread::current(),  "thread consistency check");
  1320     assert(watcher_thread() == this,  "thread consistency check");
  1322     // Calculate how long it'll be until the next PeriodicTask work
  1323     // should be done, and sleep that amount of time.
  1324     int time_waited = sleep();
  1326     if (is_error_reported()) {
  1327       // A fatal error has happened, the error handler(VMError::report_and_die)
  1328       // should abort JVM after creating an error log file. However in some
  1329       // rare cases, the error handler itself might deadlock. Here we try to
  1330       // kill JVM if the fatal error handler fails to abort in 2 minutes.
  1331       //
  1332       // This code is in WatcherThread because WatcherThread wakes up
  1333       // periodically so the fatal error handler doesn't need to do anything;
  1334       // also because the WatcherThread is less likely to crash than other
  1335       // threads.
  1337       for (;;) {
  1338         if (!ShowMessageBoxOnError
  1339          && (OnError == NULL || OnError[0] == '\0')
  1340          && Arguments::abort_hook() == NULL) {
  1341              os::sleep(this, 2 * 60 * 1000, false);
  1342              fdStream err(defaultStream::output_fd());
  1343              err.print_raw_cr("# [ timer expired, abort... ]");
  1344              // skip atexit/vm_exit/vm_abort hooks
  1345              os::die();
  1348         // Wake up 5 seconds later, the fatal handler may reset OnError or
  1349         // ShowMessageBoxOnError when it is ready to abort.
  1350         os::sleep(this, 5 * 1000, false);
  1354     PeriodicTask::real_time_tick(time_waited);
  1357   // Signal that it is terminated
  1359     MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
  1360     _watcher_thread = NULL;
  1361     Terminator_lock->notify();
  1364   // Thread destructor usually does this..
  1365   ThreadLocalStorage::set_thread(NULL);
  1368 void WatcherThread::start() {
  1369   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
  1371   if (watcher_thread() == NULL && _startable) {
  1372     _should_terminate = false;
  1373     // Create the single instance of WatcherThread
  1374     new WatcherThread();
  1378 void WatcherThread::make_startable() {
  1379   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
  1380   _startable = true;
  1383 void WatcherThread::stop() {
  1385     MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
  1386     _should_terminate = true;
  1387     OrderAccess::fence();  // ensure WatcherThread sees update in main loop
  1389     WatcherThread* watcher = watcher_thread();
  1390     if (watcher != NULL)
  1391       watcher->unpark();
  1394   // it is ok to take late safepoints here, if needed
  1395   MutexLocker mu(Terminator_lock);
  1397   while(watcher_thread() != NULL) {
  1398     // This wait should make safepoint checks, wait without a timeout,
  1399     // and wait as a suspend-equivalent condition.
  1400     //
  1401     // Note: If the FlatProfiler is running, then this thread is waiting
  1402     // for the WatcherThread to terminate and the WatcherThread, via the
  1403     // FlatProfiler task, is waiting for the external suspend request on
  1404     // this thread to complete. wait_for_ext_suspend_completion() will
  1405     // eventually timeout, but that takes time. Making this wait a
  1406     // suspend-equivalent condition solves that timeout problem.
  1407     //
  1408     Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
  1409                           Mutex::_as_suspend_equivalent_flag);
  1413 void WatcherThread::unpark() {
  1414   MutexLockerEx ml(PeriodicTask_lock->owned_by_self() ? NULL : PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
  1415   PeriodicTask_lock->notify();
  1418 void WatcherThread::print_on(outputStream* st) const {
  1419   st->print("\"%s\" ", name());
  1420   Thread::print_on(st);
  1421   st->cr();
  1424 // ======= JavaThread ========
  1426 // A JavaThread is a normal Java thread
  1428 void JavaThread::initialize() {
  1429   // Initialize fields
  1431   // Set the claimed par_id to UINT_MAX (ie not claiming any par_ids)
  1432   set_claimed_par_id(UINT_MAX);
  1434   set_saved_exception_pc(NULL);
  1435   set_threadObj(NULL);
  1436   _anchor.clear();
  1437   set_entry_point(NULL);
  1438   set_jni_functions(jni_functions());
  1439   set_callee_target(NULL);
  1440   set_vm_result(NULL);
  1441   set_vm_result_2(NULL);
  1442   set_vframe_array_head(NULL);
  1443   set_vframe_array_last(NULL);
  1444   set_deferred_locals(NULL);
  1445   set_deopt_mark(NULL);
  1446   set_deopt_nmethod(NULL);
  1447   clear_must_deopt_id();
  1448   set_monitor_chunks(NULL);
  1449   set_next(NULL);
  1450   set_thread_state(_thread_new);
  1451   _terminated = _not_terminated;
  1452   _privileged_stack_top = NULL;
  1453   _array_for_gc = NULL;
  1454   _suspend_equivalent = false;
  1455   _in_deopt_handler = 0;
  1456   _doing_unsafe_access = false;
  1457   _stack_guard_state = stack_guard_unused;
  1458   (void)const_cast<oop&>(_exception_oop = oop(NULL));
  1459   _exception_pc  = 0;
  1460   _exception_handler_pc = 0;
  1461   _is_method_handle_return = 0;
  1462   _jvmti_thread_state= NULL;
  1463   _should_post_on_exceptions_flag = JNI_FALSE;
  1464   _jvmti_get_loaded_classes_closure = NULL;
  1465   _interp_only_mode    = 0;
  1466   _special_runtime_exit_condition = _no_async_condition;
  1467   _pending_async_exception = NULL;
  1468   _thread_stat = NULL;
  1469   _thread_stat = new ThreadStatistics();
  1470   _blocked_on_compilation = false;
  1471   _jni_active_critical = 0;
  1472   _pending_jni_exception_check_fn = NULL;
  1473   _do_not_unlock_if_synchronized = false;
  1474   _cached_monitor_info = NULL;
  1475   _parker = Parker::Allocate(this) ;
  1477 #ifndef PRODUCT
  1478   _jmp_ring_index = 0;
  1479   for (int ji = 0 ; ji < jump_ring_buffer_size ; ji++ ) {
  1480     record_jump(NULL, NULL, NULL, 0);
  1482 #endif /* PRODUCT */
  1484   set_thread_profiler(NULL);
  1485   if (FlatProfiler::is_active()) {
  1486     // This is where we would decide to either give each thread it's own profiler
  1487     // or use one global one from FlatProfiler,
  1488     // or up to some count of the number of profiled threads, etc.
  1489     ThreadProfiler* pp = new ThreadProfiler();
  1490     pp->engage();
  1491     set_thread_profiler(pp);
  1494   // Setup safepoint state info for this thread
  1495   ThreadSafepointState::create(this);
  1497   debug_only(_java_call_counter = 0);
  1499   // JVMTI PopFrame support
  1500   _popframe_condition = popframe_inactive;
  1501   _popframe_preserved_args = NULL;
  1502   _popframe_preserved_args_size = 0;
  1503   _frames_to_pop_failed_realloc = 0;
  1505   pd_initialize();
  1508 #if INCLUDE_ALL_GCS
  1509 SATBMarkQueueSet JavaThread::_satb_mark_queue_set;
  1510 DirtyCardQueueSet JavaThread::_dirty_card_queue_set;
  1511 #endif // INCLUDE_ALL_GCS
  1513 JavaThread::JavaThread(bool is_attaching_via_jni) :
  1514   Thread()
  1515 #if INCLUDE_ALL_GCS
  1516   , _satb_mark_queue(&_satb_mark_queue_set),
  1517   _dirty_card_queue(&_dirty_card_queue_set)
  1518 #endif // INCLUDE_ALL_GCS
  1520   initialize();
  1521   if (is_attaching_via_jni) {
  1522     _jni_attach_state = _attaching_via_jni;
  1523   } else {
  1524     _jni_attach_state = _not_attaching_via_jni;
  1526   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
  1529 bool JavaThread::reguard_stack(address cur_sp) {
  1530   if (_stack_guard_state != stack_guard_yellow_disabled) {
  1531     return true; // Stack already guarded or guard pages not needed.
  1534   if (register_stack_overflow()) {
  1535     // For those architectures which have separate register and
  1536     // memory stacks, we must check the register stack to see if
  1537     // it has overflowed.
  1538     return false;
  1541   // Java code never executes within the yellow zone: the latter is only
  1542   // there to provoke an exception during stack banging.  If java code
  1543   // is executing there, either StackShadowPages should be larger, or
  1544   // some exception code in c1, c2 or the interpreter isn't unwinding
  1545   // when it should.
  1546   guarantee(cur_sp > stack_yellow_zone_base(), "not enough space to reguard - increase StackShadowPages");
  1548   enable_stack_yellow_zone();
  1549   return true;
  1552 bool JavaThread::reguard_stack(void) {
  1553   return reguard_stack(os::current_stack_pointer());
  1557 void JavaThread::block_if_vm_exited() {
  1558   if (_terminated == _vm_exited) {
  1559     // _vm_exited is set at safepoint, and Threads_lock is never released
  1560     // we will block here forever
  1561     Threads_lock->lock_without_safepoint_check();
  1562     ShouldNotReachHere();
  1567 // Remove this ifdef when C1 is ported to the compiler interface.
  1568 static void compiler_thread_entry(JavaThread* thread, TRAPS);
  1570 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
  1571   Thread()
  1572 #if INCLUDE_ALL_GCS
  1573   , _satb_mark_queue(&_satb_mark_queue_set),
  1574   _dirty_card_queue(&_dirty_card_queue_set)
  1575 #endif // INCLUDE_ALL_GCS
  1577   if (TraceThreadEvents) {
  1578     tty->print_cr("creating thread %p", this);
  1580   initialize();
  1581   _jni_attach_state = _not_attaching_via_jni;
  1582   set_entry_point(entry_point);
  1583   // Create the native thread itself.
  1584   // %note runtime_23
  1585   os::ThreadType thr_type = os::java_thread;
  1586   thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
  1587                                                      os::java_thread;
  1588   os::create_thread(this, thr_type, stack_sz);
  1589   // The _osthread may be NULL here because we ran out of memory (too many threads active).
  1590   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
  1591   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
  1592   // the exception consists of creating the exception object & initializing it, initialization
  1593   // will leave the VM via a JavaCall and then all locks must be unlocked).
  1594   //
  1595   // The thread is still suspended when we reach here. Thread must be explicit started
  1596   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
  1597   // by calling Threads:add. The reason why this is not done here, is because the thread
  1598   // object must be fully initialized (take a look at JVM_Start)
  1601 JavaThread::~JavaThread() {
  1602   if (TraceThreadEvents) {
  1603       tty->print_cr("terminate thread %p", this);
  1606   // JSR166 -- return the parker to the free list
  1607   Parker::Release(_parker);
  1608   _parker = NULL ;
  1610   // Free any remaining  previous UnrollBlock
  1611   vframeArray* old_array = vframe_array_last();
  1613   if (old_array != NULL) {
  1614     Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
  1615     old_array->set_unroll_block(NULL);
  1616     delete old_info;
  1617     delete old_array;
  1620   GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
  1621   if (deferred != NULL) {
  1622     // This can only happen if thread is destroyed before deoptimization occurs.
  1623     assert(deferred->length() != 0, "empty array!");
  1624     do {
  1625       jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
  1626       deferred->remove_at(0);
  1627       // individual jvmtiDeferredLocalVariableSet are CHeapObj's
  1628       delete dlv;
  1629     } while (deferred->length() != 0);
  1630     delete deferred;
  1633   // All Java related clean up happens in exit
  1634   ThreadSafepointState::destroy(this);
  1635   if (_thread_profiler != NULL) delete _thread_profiler;
  1636   if (_thread_stat != NULL) delete _thread_stat;
  1640 // The first routine called by a new Java thread
  1641 void JavaThread::run() {
  1642   // initialize thread-local alloc buffer related fields
  1643   this->initialize_tlab();
  1645   // used to test validitity of stack trace backs
  1646   this->record_base_of_stack_pointer();
  1648   // Record real stack base and size.
  1649   this->record_stack_base_and_size();
  1651   // Initialize thread local storage; set before calling MutexLocker
  1652   this->initialize_thread_local_storage();
  1654   this->create_stack_guard_pages();
  1656   this->cache_global_variables();
  1658   // Thread is now sufficient initialized to be handled by the safepoint code as being
  1659   // in the VM. Change thread state from _thread_new to _thread_in_vm
  1660   ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
  1662   assert(JavaThread::current() == this, "sanity check");
  1663   assert(!Thread::current()->owns_locks(), "sanity check");
  1665   DTRACE_THREAD_PROBE(start, this);
  1667   // This operation might block. We call that after all safepoint checks for a new thread has
  1668   // been completed.
  1669   this->set_active_handles(JNIHandleBlock::allocate_block());
  1671   if (JvmtiExport::should_post_thread_life()) {
  1672     JvmtiExport::post_thread_start(this);
  1675   EventThreadStart event;
  1676   if (event.should_commit()) {
  1677     event.set_thread(JFR_THREAD_ID(this));
  1678      event.commit();
  1681   // We call another function to do the rest so we are sure that the stack addresses used
  1682   // from there will be lower than the stack base just computed
  1683   thread_main_inner();
  1685   // Note, thread is no longer valid at this point!
  1689 void JavaThread::thread_main_inner() {
  1690   assert(JavaThread::current() == this, "sanity check");
  1691   assert(this->threadObj() != NULL, "just checking");
  1693   // Execute thread entry point unless this thread has a pending exception
  1694   // or has been stopped before starting.
  1695   // Note: Due to JVM_StopThread we can have pending exceptions already!
  1696   if (!this->has_pending_exception() &&
  1697       !java_lang_Thread::is_stillborn(this->threadObj())) {
  1699       ResourceMark rm(this);
  1700       this->set_native_thread_name(this->get_thread_name());
  1702     HandleMark hm(this);
  1703     this->entry_point()(this, this);
  1706   DTRACE_THREAD_PROBE(stop, this);
  1708   this->exit(false);
  1709   delete this;
  1713 static void ensure_join(JavaThread* thread) {
  1714   // We do not need to grap the Threads_lock, since we are operating on ourself.
  1715   Handle threadObj(thread, thread->threadObj());
  1716   assert(threadObj.not_null(), "java thread object must exist");
  1717   ObjectLocker lock(threadObj, thread);
  1718   // Ignore pending exception (ThreadDeath), since we are exiting anyway
  1719   thread->clear_pending_exception();
  1720   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
  1721   java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
  1722   // Clear the native thread instance - this makes isAlive return false and allows the join()
  1723   // to complete once we've done the notify_all below
  1724   java_lang_Thread::set_thread(threadObj(), NULL);
  1725   lock.notify_all(thread);
  1726   // Ignore pending exception (ThreadDeath), since we are exiting anyway
  1727   thread->clear_pending_exception();
  1731 // For any new cleanup additions, please check to see if they need to be applied to
  1732 // cleanup_failed_attach_current_thread as well.
  1733 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
  1734   assert(this == JavaThread::current(),  "thread consistency check");
  1736   HandleMark hm(this);
  1737   Handle uncaught_exception(this, this->pending_exception());
  1738   this->clear_pending_exception();
  1739   Handle threadObj(this, this->threadObj());
  1740   assert(threadObj.not_null(), "Java thread object should be created");
  1742   if (get_thread_profiler() != NULL) {
  1743     get_thread_profiler()->disengage();
  1744     ResourceMark rm;
  1745     get_thread_profiler()->print(get_thread_name());
  1749   // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
  1751     EXCEPTION_MARK;
  1753     CLEAR_PENDING_EXCEPTION;
  1755   // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This
  1756   // has to be fixed by a runtime query method
  1757   if (!destroy_vm || JDK_Version::is_jdk12x_version()) {
  1758     // JSR-166: change call from from ThreadGroup.uncaughtException to
  1759     // java.lang.Thread.dispatchUncaughtException
  1760     if (uncaught_exception.not_null()) {
  1761       Handle group(this, java_lang_Thread::threadGroup(threadObj()));
  1763         EXCEPTION_MARK;
  1764         // Check if the method Thread.dispatchUncaughtException() exists. If so
  1765         // call it.  Otherwise we have an older library without the JSR-166 changes,
  1766         // so call ThreadGroup.uncaughtException()
  1767         KlassHandle recvrKlass(THREAD, threadObj->klass());
  1768         CallInfo callinfo;
  1769         KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
  1770         LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass,
  1771                                            vmSymbols::dispatchUncaughtException_name(),
  1772                                            vmSymbols::throwable_void_signature(),
  1773                                            KlassHandle(), false, false, THREAD);
  1774         CLEAR_PENDING_EXCEPTION;
  1775         methodHandle method = callinfo.selected_method();
  1776         if (method.not_null()) {
  1777           JavaValue result(T_VOID);
  1778           JavaCalls::call_virtual(&result,
  1779                                   threadObj, thread_klass,
  1780                                   vmSymbols::dispatchUncaughtException_name(),
  1781                                   vmSymbols::throwable_void_signature(),
  1782                                   uncaught_exception,
  1783                                   THREAD);
  1784         } else {
  1785           KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass());
  1786           JavaValue result(T_VOID);
  1787           JavaCalls::call_virtual(&result,
  1788                                   group, thread_group,
  1789                                   vmSymbols::uncaughtException_name(),
  1790                                   vmSymbols::thread_throwable_void_signature(),
  1791                                   threadObj,           // Arg 1
  1792                                   uncaught_exception,  // Arg 2
  1793                                   THREAD);
  1795         if (HAS_PENDING_EXCEPTION) {
  1796           ResourceMark rm(this);
  1797           jio_fprintf(defaultStream::error_stream(),
  1798                 "\nException: %s thrown from the UncaughtExceptionHandler"
  1799                 " in thread \"%s\"\n",
  1800                 pending_exception()->klass()->external_name(),
  1801                 get_thread_name());
  1802           CLEAR_PENDING_EXCEPTION;
  1807     // Called before the java thread exit since we want to read info
  1808     // from java_lang_Thread object
  1809     EventThreadEnd event;
  1810     if (event.should_commit()) {
  1811       event.set_thread(JFR_THREAD_ID(this));
  1812       event.commit();
  1815     // Call after last event on thread
  1816     JFR_ONLY(Jfr::on_thread_exit(this);)
  1818     // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
  1819     // the execution of the method. If that is not enough, then we don't really care. Thread.stop
  1820     // is deprecated anyhow.
  1821     if (!is_Compiler_thread()) {
  1822       int count = 3;
  1823       while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
  1824         EXCEPTION_MARK;
  1825         JavaValue result(T_VOID);
  1826         KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
  1827         JavaCalls::call_virtual(&result,
  1828                               threadObj, thread_klass,
  1829                               vmSymbols::exit_method_name(),
  1830                               vmSymbols::void_method_signature(),
  1831                               THREAD);
  1832         CLEAR_PENDING_EXCEPTION;
  1835     // notify JVMTI
  1836     if (JvmtiExport::should_post_thread_life()) {
  1837       JvmtiExport::post_thread_end(this);
  1840     // We have notified the agents that we are exiting, before we go on,
  1841     // we must check for a pending external suspend request and honor it
  1842     // in order to not surprise the thread that made the suspend request.
  1843     while (true) {
  1845         MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  1846         if (!is_external_suspend()) {
  1847           set_terminated(_thread_exiting);
  1848           ThreadService::current_thread_exiting(this);
  1849           break;
  1851         // Implied else:
  1852         // Things get a little tricky here. We have a pending external
  1853         // suspend request, but we are holding the SR_lock so we
  1854         // can't just self-suspend. So we temporarily drop the lock
  1855         // and then self-suspend.
  1858       ThreadBlockInVM tbivm(this);
  1859       java_suspend_self();
  1861       // We're done with this suspend request, but we have to loop around
  1862       // and check again. Eventually we will get SR_lock without a pending
  1863       // external suspend request and will be able to mark ourselves as
  1864       // exiting.
  1866     // no more external suspends are allowed at this point
  1867   } else {
  1868     // before_exit() has already posted JVMTI THREAD_END events
  1871   // Notify waiters on thread object. This has to be done after exit() is called
  1872   // on the thread (if the thread is the last thread in a daemon ThreadGroup the
  1873   // group should have the destroyed bit set before waiters are notified).
  1874   ensure_join(this);
  1875   assert(!this->has_pending_exception(), "ensure_join should have cleared");
  1877   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
  1878   // held by this thread must be released.  A detach operation must only
  1879   // get here if there are no Java frames on the stack.  Therefore, any
  1880   // owned monitors at this point MUST be JNI-acquired monitors which are
  1881   // pre-inflated and in the monitor cache.
  1882   //
  1883   // ensure_join() ignores IllegalThreadStateExceptions, and so does this.
  1884   if (exit_type == jni_detach && JNIDetachReleasesMonitors) {
  1885     assert(!this->has_last_Java_frame(), "detaching with Java frames?");
  1886     ObjectSynchronizer::release_monitors_owned_by_thread(this);
  1887     assert(!this->has_pending_exception(), "release_monitors should have cleared");
  1890   // These things needs to be done while we are still a Java Thread. Make sure that thread
  1891   // is in a consistent state, in case GC happens
  1892   assert(_privileged_stack_top == NULL, "must be NULL when we get here");
  1894   if (active_handles() != NULL) {
  1895     JNIHandleBlock* block = active_handles();
  1896     set_active_handles(NULL);
  1897     JNIHandleBlock::release_block(block);
  1900   if (free_handle_block() != NULL) {
  1901     JNIHandleBlock* block = free_handle_block();
  1902     set_free_handle_block(NULL);
  1903     JNIHandleBlock::release_block(block);
  1906   // These have to be removed while this is still a valid thread.
  1907   remove_stack_guard_pages();
  1909   if (UseTLAB) {
  1910     tlab().make_parsable(true);  // retire TLAB
  1913   if (JvmtiEnv::environments_might_exist()) {
  1914     JvmtiExport::cleanup_thread(this);
  1917   // We must flush any deferred card marks before removing a thread from
  1918   // the list of active threads.
  1919   Universe::heap()->flush_deferred_store_barrier(this);
  1920   assert(deferred_card_mark().is_empty(), "Should have been flushed");
  1922 #if INCLUDE_ALL_GCS
  1923   // We must flush the G1-related buffers before removing a thread
  1924   // from the list of active threads. We must do this after any deferred
  1925   // card marks have been flushed (above) so that any entries that are
  1926   // added to the thread's dirty card queue as a result are not lost.
  1927   if (UseG1GC) {
  1928     flush_barrier_queues();
  1930 #endif // INCLUDE_ALL_GCS
  1932   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
  1933   Threads::remove(this);
  1936 #if INCLUDE_ALL_GCS
  1937 // Flush G1-related queues.
  1938 void JavaThread::flush_barrier_queues() {
  1939   satb_mark_queue().flush();
  1940   dirty_card_queue().flush();
  1943 void JavaThread::initialize_queues() {
  1944   assert(!SafepointSynchronize::is_at_safepoint(),
  1945          "we should not be at a safepoint");
  1947   ObjPtrQueue& satb_queue = satb_mark_queue();
  1948   SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
  1949   // The SATB queue should have been constructed with its active
  1950   // field set to false.
  1951   assert(!satb_queue.is_active(), "SATB queue should not be active");
  1952   assert(satb_queue.is_empty(), "SATB queue should be empty");
  1953   // If we are creating the thread during a marking cycle, we should
  1954   // set the active field of the SATB queue to true.
  1955   if (satb_queue_set.is_active()) {
  1956     satb_queue.set_active(true);
  1959   DirtyCardQueue& dirty_queue = dirty_card_queue();
  1960   // The dirty card queue should have been constructed with its
  1961   // active field set to true.
  1962   assert(dirty_queue.is_active(), "dirty card queue should be active");
  1964 #endif // INCLUDE_ALL_GCS
  1966 void JavaThread::cleanup_failed_attach_current_thread() {
  1967   if (get_thread_profiler() != NULL) {
  1968     get_thread_profiler()->disengage();
  1969     ResourceMark rm;
  1970     get_thread_profiler()->print(get_thread_name());
  1973   if (active_handles() != NULL) {
  1974     JNIHandleBlock* block = active_handles();
  1975     set_active_handles(NULL);
  1976     JNIHandleBlock::release_block(block);
  1979   if (free_handle_block() != NULL) {
  1980     JNIHandleBlock* block = free_handle_block();
  1981     set_free_handle_block(NULL);
  1982     JNIHandleBlock::release_block(block);
  1985   // These have to be removed while this is still a valid thread.
  1986   remove_stack_guard_pages();
  1988   if (UseTLAB) {
  1989     tlab().make_parsable(true);  // retire TLAB, if any
  1992 #if INCLUDE_ALL_GCS
  1993   if (UseG1GC) {
  1994     flush_barrier_queues();
  1996 #endif // INCLUDE_ALL_GCS
  1998   Threads::remove(this);
  1999   delete this;
  2005 JavaThread* JavaThread::active() {
  2006   Thread* thread = ThreadLocalStorage::thread();
  2007   assert(thread != NULL, "just checking");
  2008   if (thread->is_Java_thread()) {
  2009     return (JavaThread*) thread;
  2010   } else {
  2011     assert(thread->is_VM_thread(), "this must be a vm thread");
  2012     VM_Operation* op = ((VMThread*) thread)->vm_operation();
  2013     JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
  2014     assert(ret->is_Java_thread(), "must be a Java thread");
  2015     return ret;
  2019 bool JavaThread::is_lock_owned(address adr) const {
  2020   if (Thread::is_lock_owned(adr)) return true;
  2022   for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
  2023     if (chunk->contains(adr)) return true;
  2026   return false;
  2030 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
  2031   chunk->set_next(monitor_chunks());
  2032   set_monitor_chunks(chunk);
  2035 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
  2036   guarantee(monitor_chunks() != NULL, "must be non empty");
  2037   if (monitor_chunks() == chunk) {
  2038     set_monitor_chunks(chunk->next());
  2039   } else {
  2040     MonitorChunk* prev = monitor_chunks();
  2041     while (prev->next() != chunk) prev = prev->next();
  2042     prev->set_next(chunk->next());
  2046 // JVM support.
  2048 // Note: this function shouldn't block if it's called in
  2049 // _thread_in_native_trans state (such as from
  2050 // check_special_condition_for_native_trans()).
  2051 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
  2053   if (has_last_Java_frame() && has_async_condition()) {
  2054     // If we are at a polling page safepoint (not a poll return)
  2055     // then we must defer async exception because live registers
  2056     // will be clobbered by the exception path. Poll return is
  2057     // ok because the call we a returning from already collides
  2058     // with exception handling registers and so there is no issue.
  2059     // (The exception handling path kills call result registers but
  2060     //  this is ok since the exception kills the result anyway).
  2062     if (is_at_poll_safepoint()) {
  2063       // if the code we are returning to has deoptimized we must defer
  2064       // the exception otherwise live registers get clobbered on the
  2065       // exception path before deoptimization is able to retrieve them.
  2066       //
  2067       RegisterMap map(this, false);
  2068       frame caller_fr = last_frame().sender(&map);
  2069       assert(caller_fr.is_compiled_frame(), "what?");
  2070       if (caller_fr.is_deoptimized_frame()) {
  2071         if (TraceExceptions) {
  2072           ResourceMark rm;
  2073           tty->print_cr("deferred async exception at compiled safepoint");
  2075         return;
  2080   JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
  2081   if (condition == _no_async_condition) {
  2082     // Conditions have changed since has_special_runtime_exit_condition()
  2083     // was called:
  2084     // - if we were here only because of an external suspend request,
  2085     //   then that was taken care of above (or cancelled) so we are done
  2086     // - if we were here because of another async request, then it has
  2087     //   been cleared between the has_special_runtime_exit_condition()
  2088     //   and now so again we are done
  2089     return;
  2092   // Check for pending async. exception
  2093   if (_pending_async_exception != NULL) {
  2094     // Only overwrite an already pending exception, if it is not a threadDeath.
  2095     if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
  2097       // We cannot call Exceptions::_throw(...) here because we cannot block
  2098       set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
  2100       if (TraceExceptions) {
  2101         ResourceMark rm;
  2102         tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this);
  2103         if (has_last_Java_frame() ) {
  2104           frame f = last_frame();
  2105           tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp());
  2107         tty->print_cr(" of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name());
  2109       _pending_async_exception = NULL;
  2110       clear_has_async_exception();
  2114   if (check_unsafe_error &&
  2115       condition == _async_unsafe_access_error && !has_pending_exception()) {
  2116     condition = _no_async_condition;  // done
  2117     switch (thread_state()) {
  2118     case _thread_in_vm:
  2120         JavaThread* THREAD = this;
  2121         THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
  2123     case _thread_in_native:
  2125         ThreadInVMfromNative tiv(this);
  2126         JavaThread* THREAD = this;
  2127         THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
  2129     case _thread_in_Java:
  2131         ThreadInVMfromJava tiv(this);
  2132         JavaThread* THREAD = this;
  2133         THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
  2135     default:
  2136       ShouldNotReachHere();
  2140   assert(condition == _no_async_condition || has_pending_exception() ||
  2141          (!check_unsafe_error && condition == _async_unsafe_access_error),
  2142          "must have handled the async condition, if no exception");
  2145 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
  2146   //
  2147   // Check for pending external suspend. Internal suspend requests do
  2148   // not use handle_special_runtime_exit_condition().
  2149   // If JNIEnv proxies are allowed, don't self-suspend if the target
  2150   // thread is not the current thread. In older versions of jdbx, jdbx
  2151   // threads could call into the VM with another thread's JNIEnv so we
  2152   // can be here operating on behalf of a suspended thread (4432884).
  2153   bool do_self_suspend = is_external_suspend_with_lock();
  2154   if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) {
  2155     //
  2156     // Because thread is external suspended the safepoint code will count
  2157     // thread as at a safepoint. This can be odd because we can be here
  2158     // as _thread_in_Java which would normally transition to _thread_blocked
  2159     // at a safepoint. We would like to mark the thread as _thread_blocked
  2160     // before calling java_suspend_self like all other callers of it but
  2161     // we must then observe proper safepoint protocol. (We can't leave
  2162     // _thread_blocked with a safepoint in progress). However we can be
  2163     // here as _thread_in_native_trans so we can't use a normal transition
  2164     // constructor/destructor pair because they assert on that type of
  2165     // transition. We could do something like:
  2166     //
  2167     // JavaThreadState state = thread_state();
  2168     // set_thread_state(_thread_in_vm);
  2169     // {
  2170     //   ThreadBlockInVM tbivm(this);
  2171     //   java_suspend_self()
  2172     // }
  2173     // set_thread_state(_thread_in_vm_trans);
  2174     // if (safepoint) block;
  2175     // set_thread_state(state);
  2176     //
  2177     // but that is pretty messy. Instead we just go with the way the
  2178     // code has worked before and note that this is the only path to
  2179     // java_suspend_self that doesn't put the thread in _thread_blocked
  2180     // mode.
  2182     frame_anchor()->make_walkable(this);
  2183     java_suspend_self();
  2185     // We might be here for reasons in addition to the self-suspend request
  2186     // so check for other async requests.
  2189   if (check_asyncs) {
  2190     check_and_handle_async_exceptions();
  2193   JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)
  2196 void JavaThread::send_thread_stop(oop java_throwable)  {
  2197   assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
  2198   assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
  2199   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
  2201   // Do not throw asynchronous exceptions against the compiler thread
  2202   // (the compiler thread should not be a Java thread -- fix in 1.4.2)
  2203   if (is_Compiler_thread()) return;
  2206     // Actually throw the Throwable against the target Thread - however
  2207     // only if there is no thread death exception installed already.
  2208     if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
  2209       // If the topmost frame is a runtime stub, then we are calling into
  2210       // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
  2211       // must deoptimize the caller before continuing, as the compiled  exception handler table
  2212       // may not be valid
  2213       if (has_last_Java_frame()) {
  2214         frame f = last_frame();
  2215         if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
  2216           // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
  2217           RegisterMap reg_map(this, UseBiasedLocking);
  2218           frame compiled_frame = f.sender(&reg_map);
  2219           if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
  2220             Deoptimization::deoptimize(this, compiled_frame, &reg_map);
  2225       // Set async. pending exception in thread.
  2226       set_pending_async_exception(java_throwable);
  2228       if (TraceExceptions) {
  2229        ResourceMark rm;
  2230        tty->print_cr("Pending Async. exception installed of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name());
  2232       // for AbortVMOnException flag
  2233       NOT_PRODUCT(Exceptions::debug_check_abort(InstanceKlass::cast(_pending_async_exception->klass())->external_name()));
  2238   // Interrupt thread so it will wake up from a potential wait()
  2239   Thread::interrupt(this);
  2242 // External suspension mechanism.
  2243 //
  2244 // Tell the VM to suspend a thread when ever it knows that it does not hold on
  2245 // to any VM_locks and it is at a transition
  2246 // Self-suspension will happen on the transition out of the vm.
  2247 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
  2248 //
  2249 // Guarantees on return:
  2250 //   + Target thread will not execute any new bytecode (that's why we need to
  2251 //     force a safepoint)
  2252 //   + Target thread will not enter any new monitors
  2253 //
  2254 void JavaThread::java_suspend() {
  2255   { MutexLocker mu(Threads_lock);
  2256     if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) {
  2257        return;
  2261   { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2262     if (!is_external_suspend()) {
  2263       // a racing resume has cancelled us; bail out now
  2264       return;
  2267     // suspend is done
  2268     uint32_t debug_bits = 0;
  2269     // Warning: is_ext_suspend_completed() may temporarily drop the
  2270     // SR_lock to allow the thread to reach a stable thread state if
  2271     // it is currently in a transient thread state.
  2272     if (is_ext_suspend_completed(false /* !called_by_wait */,
  2273                                  SuspendRetryDelay, &debug_bits) ) {
  2274       return;
  2278   VM_ForceSafepoint vm_suspend;
  2279   VMThread::execute(&vm_suspend);
  2282 // Part II of external suspension.
  2283 // A JavaThread self suspends when it detects a pending external suspend
  2284 // request. This is usually on transitions. It is also done in places
  2285 // where continuing to the next transition would surprise the caller,
  2286 // e.g., monitor entry.
  2287 //
  2288 // Returns the number of times that the thread self-suspended.
  2289 //
  2290 // Note: DO NOT call java_suspend_self() when you just want to block current
  2291 //       thread. java_suspend_self() is the second stage of cooperative
  2292 //       suspension for external suspend requests and should only be used
  2293 //       to complete an external suspend request.
  2294 //
  2295 int JavaThread::java_suspend_self() {
  2296   int ret = 0;
  2298   // we are in the process of exiting so don't suspend
  2299   if (is_exiting()) {
  2300      clear_external_suspend();
  2301      return ret;
  2304   assert(_anchor.walkable() ||
  2305     (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
  2306     "must have walkable stack");
  2308   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2310   assert(!this->is_ext_suspended(),
  2311     "a thread trying to self-suspend should not already be suspended");
  2313   if (this->is_suspend_equivalent()) {
  2314     // If we are self-suspending as a result of the lifting of a
  2315     // suspend equivalent condition, then the suspend_equivalent
  2316     // flag is not cleared until we set the ext_suspended flag so
  2317     // that wait_for_ext_suspend_completion() returns consistent
  2318     // results.
  2319     this->clear_suspend_equivalent();
  2322   // A racing resume may have cancelled us before we grabbed SR_lock
  2323   // above. Or another external suspend request could be waiting for us
  2324   // by the time we return from SR_lock()->wait(). The thread
  2325   // that requested the suspension may already be trying to walk our
  2326   // stack and if we return now, we can change the stack out from under
  2327   // it. This would be a "bad thing (TM)" and cause the stack walker
  2328   // to crash. We stay self-suspended until there are no more pending
  2329   // external suspend requests.
  2330   while (is_external_suspend()) {
  2331     ret++;
  2332     this->set_ext_suspended();
  2334     // _ext_suspended flag is cleared by java_resume()
  2335     while (is_ext_suspended()) {
  2336       this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
  2340   return ret;
  2343 #ifdef ASSERT
  2344 // verify the JavaThread has not yet been published in the Threads::list, and
  2345 // hence doesn't need protection from concurrent access at this stage
  2346 void JavaThread::verify_not_published() {
  2347   if (!Threads_lock->owned_by_self()) {
  2348    MutexLockerEx ml(Threads_lock,  Mutex::_no_safepoint_check_flag);
  2349    assert( !Threads::includes(this),
  2350            "java thread shouldn't have been published yet!");
  2352   else {
  2353    assert( !Threads::includes(this),
  2354            "java thread shouldn't have been published yet!");
  2357 #endif
  2359 // Slow path when the native==>VM/Java barriers detect a safepoint is in
  2360 // progress or when _suspend_flags is non-zero.
  2361 // Current thread needs to self-suspend if there is a suspend request and/or
  2362 // block if a safepoint is in progress.
  2363 // Async exception ISN'T checked.
  2364 // Note only the ThreadInVMfromNative transition can call this function
  2365 // directly and when thread state is _thread_in_native_trans
  2366 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
  2367   assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
  2369   JavaThread *curJT = JavaThread::current();
  2370   bool do_self_suspend = thread->is_external_suspend();
  2372   assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
  2374   // If JNIEnv proxies are allowed, don't self-suspend if the target
  2375   // thread is not the current thread. In older versions of jdbx, jdbx
  2376   // threads could call into the VM with another thread's JNIEnv so we
  2377   // can be here operating on behalf of a suspended thread (4432884).
  2378   if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) {
  2379     JavaThreadState state = thread->thread_state();
  2381     // We mark this thread_blocked state as a suspend-equivalent so
  2382     // that a caller to is_ext_suspend_completed() won't be confused.
  2383     // The suspend-equivalent state is cleared by java_suspend_self().
  2384     thread->set_suspend_equivalent();
  2386     // If the safepoint code sees the _thread_in_native_trans state, it will
  2387     // wait until the thread changes to other thread state. There is no
  2388     // guarantee on how soon we can obtain the SR_lock and complete the
  2389     // self-suspend request. It would be a bad idea to let safepoint wait for
  2390     // too long. Temporarily change the state to _thread_blocked to
  2391     // let the VM thread know that this thread is ready for GC. The problem
  2392     // of changing thread state is that safepoint could happen just after
  2393     // java_suspend_self() returns after being resumed, and VM thread will
  2394     // see the _thread_blocked state. We must check for safepoint
  2395     // after restoring the state and make sure we won't leave while a safepoint
  2396     // is in progress.
  2397     thread->set_thread_state(_thread_blocked);
  2398     thread->java_suspend_self();
  2399     thread->set_thread_state(state);
  2400     // Make sure new state is seen by VM thread
  2401     if (os::is_MP()) {
  2402       if (UseMembar) {
  2403         // Force a fence between the write above and read below
  2404         OrderAccess::fence();
  2405       } else {
  2406         // Must use this rather than serialization page in particular on Windows
  2407         InterfaceSupport::serialize_memory(thread);
  2412   if (SafepointSynchronize::do_call_back()) {
  2413     // If we are safepointing, then block the caller which may not be
  2414     // the same as the target thread (see above).
  2415     SafepointSynchronize::block(curJT);
  2418   if (thread->is_deopt_suspend()) {
  2419     thread->clear_deopt_suspend();
  2420     RegisterMap map(thread, false);
  2421     frame f = thread->last_frame();
  2422     while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
  2423       f = f.sender(&map);
  2425     if (f.id() == thread->must_deopt_id()) {
  2426       thread->clear_must_deopt_id();
  2427       f.deoptimize(thread);
  2428     } else {
  2429       fatal("missed deoptimization!");
  2433   JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(thread);)
  2436 // Slow path when the native==>VM/Java barriers detect a safepoint is in
  2437 // progress or when _suspend_flags is non-zero.
  2438 // Current thread needs to self-suspend if there is a suspend request and/or
  2439 // block if a safepoint is in progress.
  2440 // Also check for pending async exception (not including unsafe access error).
  2441 // Note only the native==>VM/Java barriers can call this function and when
  2442 // thread state is _thread_in_native_trans.
  2443 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
  2444   check_safepoint_and_suspend_for_native_trans(thread);
  2446   if (thread->has_async_exception()) {
  2447     // We are in _thread_in_native_trans state, don't handle unsafe
  2448     // access error since that may block.
  2449     thread->check_and_handle_async_exceptions(false);
  2453 // This is a variant of the normal
  2454 // check_special_condition_for_native_trans with slightly different
  2455 // semantics for use by critical native wrappers.  It does all the
  2456 // normal checks but also performs the transition back into
  2457 // thread_in_Java state.  This is required so that critical natives
  2458 // can potentially block and perform a GC if they are the last thread
  2459 // exiting the GC_locker.
  2460 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) {
  2461   check_special_condition_for_native_trans(thread);
  2463   // Finish the transition
  2464   thread->set_thread_state(_thread_in_Java);
  2466   if (thread->do_critical_native_unlock()) {
  2467     ThreadInVMfromJavaNoAsyncException tiv(thread);
  2468     GC_locker::unlock_critical(thread);
  2469     thread->clear_critical_native_unlock();
  2473 // We need to guarantee the Threads_lock here, since resumes are not
  2474 // allowed during safepoint synchronization
  2475 // Can only resume from an external suspension
  2476 void JavaThread::java_resume() {
  2477   assert_locked_or_safepoint(Threads_lock);
  2479   // Sanity check: thread is gone, has started exiting or the thread
  2480   // was not externally suspended.
  2481   if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) {
  2482     return;
  2485   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2487   clear_external_suspend();
  2489   if (is_ext_suspended()) {
  2490     clear_ext_suspended();
  2491     SR_lock()->notify_all();
  2495 void JavaThread::create_stack_guard_pages() {
  2496   if (!os::uses_stack_guard_pages() ||
  2497       _stack_guard_state != stack_guard_unused ||
  2498       (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) {
  2499       if (TraceThreadEvents) {
  2500         tty->print_cr("Stack guard page creation for thread "
  2501                       UINTX_FORMAT " disabled", os::current_thread_id());
  2503     return;
  2505   address low_addr = stack_base() - stack_size();
  2506   size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
  2508   int allocate = os::allocate_stack_guard_pages();
  2509   // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
  2511   if (allocate && !os::create_stack_guard_pages((char *) low_addr, len)) {
  2512     warning("Attempt to allocate stack guard pages failed.");
  2513     return;
  2516   if (os::guard_memory((char *) low_addr, len)) {
  2517     _stack_guard_state = stack_guard_enabled;
  2518   } else {
  2519     warning("Attempt to protect stack guard pages failed.");
  2520     if (os::uncommit_memory((char *) low_addr, len)) {
  2521       warning("Attempt to deallocate stack guard pages failed.");
  2526 void JavaThread::remove_stack_guard_pages() {
  2527   assert(Thread::current() == this, "from different thread");
  2528   if (_stack_guard_state == stack_guard_unused) return;
  2529   address low_addr = stack_base() - stack_size();
  2530   size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
  2532   if (os::allocate_stack_guard_pages()) {
  2533     if (os::remove_stack_guard_pages((char *) low_addr, len)) {
  2534       _stack_guard_state = stack_guard_unused;
  2535     } else {
  2536       warning("Attempt to deallocate stack guard pages failed.");
  2538   } else {
  2539     if (_stack_guard_state == stack_guard_unused) return;
  2540     if (os::unguard_memory((char *) low_addr, len)) {
  2541       _stack_guard_state = stack_guard_unused;
  2542     } else {
  2543         warning("Attempt to unprotect stack guard pages failed.");
  2548 void JavaThread::enable_stack_yellow_zone() {
  2549   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
  2550   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
  2552   // The base notation is from the stacks point of view, growing downward.
  2553   // We need to adjust it to work correctly with guard_memory()
  2554   address base = stack_yellow_zone_base() - stack_yellow_zone_size();
  2556   guarantee(base < stack_base(),"Error calculating stack yellow zone");
  2557   guarantee(base < os::current_stack_pointer(),"Error calculating stack yellow zone");
  2559   if (os::guard_memory((char *) base, stack_yellow_zone_size())) {
  2560     _stack_guard_state = stack_guard_enabled;
  2561   } else {
  2562     warning("Attempt to guard stack yellow zone failed.");
  2564   enable_register_stack_guard();
  2567 void JavaThread::disable_stack_yellow_zone() {
  2568   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
  2569   assert(_stack_guard_state != stack_guard_yellow_disabled, "already disabled");
  2571   // Simply return if called for a thread that does not use guard pages.
  2572   if (_stack_guard_state == stack_guard_unused) return;
  2574   // The base notation is from the stacks point of view, growing downward.
  2575   // We need to adjust it to work correctly with guard_memory()
  2576   address base = stack_yellow_zone_base() - stack_yellow_zone_size();
  2578   if (os::unguard_memory((char *)base, stack_yellow_zone_size())) {
  2579     _stack_guard_state = stack_guard_yellow_disabled;
  2580   } else {
  2581     warning("Attempt to unguard stack yellow zone failed.");
  2583   disable_register_stack_guard();
  2586 void JavaThread::enable_stack_red_zone() {
  2587   // The base notation is from the stacks point of view, growing downward.
  2588   // We need to adjust it to work correctly with guard_memory()
  2589   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
  2590   address base = stack_red_zone_base() - stack_red_zone_size();
  2592   guarantee(base < stack_base(),"Error calculating stack red zone");
  2593   guarantee(base < os::current_stack_pointer(),"Error calculating stack red zone");
  2595   if(!os::guard_memory((char *) base, stack_red_zone_size())) {
  2596     warning("Attempt to guard stack red zone failed.");
  2600 void JavaThread::disable_stack_red_zone() {
  2601   // The base notation is from the stacks point of view, growing downward.
  2602   // We need to adjust it to work correctly with guard_memory()
  2603   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
  2604   address base = stack_red_zone_base() - stack_red_zone_size();
  2605   if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
  2606     warning("Attempt to unguard stack red zone failed.");
  2610 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
  2611   // ignore is there is no stack
  2612   if (!has_last_Java_frame()) return;
  2613   // traverse the stack frames. Starts from top frame.
  2614   for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2615     frame* fr = fst.current();
  2616     f(fr, fst.register_map());
  2621 #ifndef PRODUCT
  2622 // Deoptimization
  2623 // Function for testing deoptimization
  2624 void JavaThread::deoptimize() {
  2625   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
  2626   StackFrameStream fst(this, UseBiasedLocking);
  2627   bool deopt = false;           // Dump stack only if a deopt actually happens.
  2628   bool only_at = strlen(DeoptimizeOnlyAt) > 0;
  2629   // Iterate over all frames in the thread and deoptimize
  2630   for(; !fst.is_done(); fst.next()) {
  2631     if(fst.current()->can_be_deoptimized()) {
  2633       if (only_at) {
  2634         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
  2635         // consists of comma or carriage return separated numbers so
  2636         // search for the current bci in that string.
  2637         address pc = fst.current()->pc();
  2638         nmethod* nm =  (nmethod*) fst.current()->cb();
  2639         ScopeDesc* sd = nm->scope_desc_at( pc);
  2640         char buffer[8];
  2641         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
  2642         size_t len = strlen(buffer);
  2643         const char * found = strstr(DeoptimizeOnlyAt, buffer);
  2644         while (found != NULL) {
  2645           if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
  2646               (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
  2647             // Check that the bci found is bracketed by terminators.
  2648             break;
  2650           found = strstr(found + 1, buffer);
  2652         if (!found) {
  2653           continue;
  2657       if (DebugDeoptimization && !deopt) {
  2658         deopt = true; // One-time only print before deopt
  2659         tty->print_cr("[BEFORE Deoptimization]");
  2660         trace_frames();
  2661         trace_stack();
  2663       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
  2667   if (DebugDeoptimization && deopt) {
  2668     tty->print_cr("[AFTER Deoptimization]");
  2669     trace_frames();
  2674 // Make zombies
  2675 void JavaThread::make_zombies() {
  2676   for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2677     if (fst.current()->can_be_deoptimized()) {
  2678       // it is a Java nmethod
  2679       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
  2680       nm->make_not_entrant();
  2684 #endif // PRODUCT
  2687 void JavaThread::deoptimized_wrt_marked_nmethods() {
  2688   if (!has_last_Java_frame()) return;
  2689   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
  2690   StackFrameStream fst(this, UseBiasedLocking);
  2691   for(; !fst.is_done(); fst.next()) {
  2692     if (fst.current()->should_be_deoptimized()) {
  2693       if (LogCompilation && xtty != NULL) {
  2694         nmethod* nm = fst.current()->cb()->as_nmethod_or_null();
  2695         xtty->elem("deoptimized thread='" UINTX_FORMAT "' compile_id='%d'",
  2696                    this->name(), nm != NULL ? nm->compile_id() : -1);
  2699       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
  2705 // GC support
  2706 static void frame_gc_epilogue(frame* f, const RegisterMap* map) { f->gc_epilogue(); }
  2708 void JavaThread::gc_epilogue() {
  2709   frames_do(frame_gc_epilogue);
  2713 static void frame_gc_prologue(frame* f, const RegisterMap* map) { f->gc_prologue(); }
  2715 void JavaThread::gc_prologue() {
  2716   frames_do(frame_gc_prologue);
  2719 // If the caller is a NamedThread, then remember, in the current scope,
  2720 // the given JavaThread in its _processed_thread field.
  2721 class RememberProcessedThread: public StackObj {
  2722   NamedThread* _cur_thr;
  2723 public:
  2724   RememberProcessedThread(JavaThread* jthr) {
  2725     Thread* thread = Thread::current();
  2726     if (thread->is_Named_thread()) {
  2727       _cur_thr = (NamedThread *)thread;
  2728       _cur_thr->set_processed_thread(jthr);
  2729     } else {
  2730       _cur_thr = NULL;
  2734   ~RememberProcessedThread() {
  2735     if (_cur_thr) {
  2736       _cur_thr->set_processed_thread(NULL);
  2739 };
  2741 void JavaThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
  2742   // Verify that the deferred card marks have been flushed.
  2743   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
  2745   // The ThreadProfiler oops_do is done from FlatProfiler::oops_do
  2746   // since there may be more than one thread using each ThreadProfiler.
  2748   // Traverse the GCHandles
  2749   Thread::oops_do(f, cld_f, cf);
  2751   assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
  2752           (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
  2754   if (has_last_Java_frame()) {
  2755     // Record JavaThread to GC thread
  2756     RememberProcessedThread rpt(this);
  2758     // Traverse the privileged stack
  2759     if (_privileged_stack_top != NULL) {
  2760       _privileged_stack_top->oops_do(f);
  2763     // traverse the registered growable array
  2764     if (_array_for_gc != NULL) {
  2765       for (int index = 0; index < _array_for_gc->length(); index++) {
  2766         f->do_oop(_array_for_gc->adr_at(index));
  2770     // Traverse the monitor chunks
  2771     for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
  2772       chunk->oops_do(f);
  2775     // Traverse the execution stack
  2776     for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2777       fst.current()->oops_do(f, cld_f, cf, fst.register_map());
  2781   // callee_target is never live across a gc point so NULL it here should
  2782   // it still contain a methdOop.
  2784   set_callee_target(NULL);
  2786   assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
  2787   // If we have deferred set_locals there might be oops waiting to be
  2788   // written
  2789   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
  2790   if (list != NULL) {
  2791     for (int i = 0; i < list->length(); i++) {
  2792       list->at(i)->oops_do(f);
  2796   // Traverse instance variables at the end since the GC may be moving things
  2797   // around using this function
  2798   f->do_oop((oop*) &_threadObj);
  2799   f->do_oop((oop*) &_vm_result);
  2800   f->do_oop((oop*) &_exception_oop);
  2801   f->do_oop((oop*) &_pending_async_exception);
  2803   if (jvmti_thread_state() != NULL) {
  2804     jvmti_thread_state()->oops_do(f);
  2808 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
  2809   Thread::nmethods_do(cf);  // (super method is a no-op)
  2811   assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
  2812           (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
  2814   if (has_last_Java_frame()) {
  2815     // Traverse the execution stack
  2816     for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2817       fst.current()->nmethods_do(cf);
  2822 void JavaThread::metadata_do(void f(Metadata*)) {
  2823   Thread::metadata_do(f);
  2824   if (has_last_Java_frame()) {
  2825     // Traverse the execution stack to call f() on the methods in the stack
  2826     for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2827       fst.current()->metadata_do(f);
  2829   } else if (is_Compiler_thread()) {
  2830     // need to walk ciMetadata in current compile tasks to keep alive.
  2831     CompilerThread* ct = (CompilerThread*)this;
  2832     if (ct->env() != NULL) {
  2833       ct->env()->metadata_do(f);
  2838 // Printing
  2839 const char* _get_thread_state_name(JavaThreadState _thread_state) {
  2840   switch (_thread_state) {
  2841   case _thread_uninitialized:     return "_thread_uninitialized";
  2842   case _thread_new:               return "_thread_new";
  2843   case _thread_new_trans:         return "_thread_new_trans";
  2844   case _thread_in_native:         return "_thread_in_native";
  2845   case _thread_in_native_trans:   return "_thread_in_native_trans";
  2846   case _thread_in_vm:             return "_thread_in_vm";
  2847   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
  2848   case _thread_in_Java:           return "_thread_in_Java";
  2849   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
  2850   case _thread_blocked:           return "_thread_blocked";
  2851   case _thread_blocked_trans:     return "_thread_blocked_trans";
  2852   default:                        return "unknown thread state";
  2856 #ifndef PRODUCT
  2857 void JavaThread::print_thread_state_on(outputStream *st) const {
  2858   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
  2859 };
  2860 void JavaThread::print_thread_state() const {
  2861   print_thread_state_on(tty);
  2862 };
  2863 #endif // PRODUCT
  2865 // Called by Threads::print() for VM_PrintThreads operation
  2866 void JavaThread::print_on(outputStream *st) const {
  2867   st->print("\"%s\" ", get_thread_name());
  2868   oop thread_oop = threadObj();
  2869   if (thread_oop != NULL) {
  2870     st->print("#" INT64_FORMAT " ", java_lang_Thread::thread_id(thread_oop));
  2871     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
  2872     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
  2874   Thread::print_on(st);
  2875   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
  2876   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
  2877   if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) {
  2878     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
  2880 #ifndef PRODUCT
  2881   print_thread_state_on(st);
  2882   _safepoint_state->print_on(st);
  2883 #endif // PRODUCT
  2886 // Called by fatal error handler. The difference between this and
  2887 // JavaThread::print() is that we can't grab lock or allocate memory.
  2888 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
  2889   st->print("JavaThread \"%s\"",  get_thread_name_string(buf, buflen));
  2890   oop thread_obj = threadObj();
  2891   if (thread_obj != NULL) {
  2892      if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
  2894   st->print(" [");
  2895   st->print("%s", _get_thread_state_name(_thread_state));
  2896   if (osthread()) {
  2897     st->print(", id=%d", osthread()->thread_id());
  2899   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
  2900             _stack_base - _stack_size, _stack_base);
  2901   st->print("]");
  2902   return;
  2905 // Verification
  2907 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
  2909 void JavaThread::verify() {
  2910   // Verify oops in the thread.
  2911   oops_do(&VerifyOopClosure::verify_oop, NULL, NULL);
  2913   // Verify the stack frames.
  2914   frames_do(frame_verify);
  2917 // CR 6300358 (sub-CR 2137150)
  2918 // Most callers of this method assume that it can't return NULL but a
  2919 // thread may not have a name whilst it is in the process of attaching to
  2920 // the VM - see CR 6412693, and there are places where a JavaThread can be
  2921 // seen prior to having it's threadObj set (eg JNI attaching threads and
  2922 // if vm exit occurs during initialization). These cases can all be accounted
  2923 // for such that this method never returns NULL.
  2924 const char* JavaThread::get_thread_name() const {
  2925 #ifdef ASSERT
  2926   // early safepoints can hit while current thread does not yet have TLS
  2927   if (!SafepointSynchronize::is_at_safepoint()) {
  2928     Thread *cur = Thread::current();
  2929     if (!(cur->is_Java_thread() && cur == this)) {
  2930       // Current JavaThreads are allowed to get their own name without
  2931       // the Threads_lock.
  2932       assert_locked_or_safepoint(Threads_lock);
  2935 #endif // ASSERT
  2936     return get_thread_name_string();
  2939 // Returns a non-NULL representation of this thread's name, or a suitable
  2940 // descriptive string if there is no set name
  2941 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
  2942   const char* name_str;
  2943   oop thread_obj = threadObj();
  2944   if (thread_obj != NULL) {
  2945     oop name = java_lang_Thread::name(thread_obj);
  2946     if (name != NULL) {
  2947       if (buf == NULL) {
  2948         name_str = java_lang_String::as_utf8_string(name);
  2950       else {
  2951         name_str = java_lang_String::as_utf8_string(name, buf, buflen);
  2954     else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
  2955       name_str = "<no-name - thread is attaching>";
  2957     else {
  2958       name_str = Thread::name();
  2961   else {
  2962     name_str = Thread::name();
  2964   assert(name_str != NULL, "unexpected NULL thread name");
  2965   return name_str;
  2969 const char* JavaThread::get_threadgroup_name() const {
  2970   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
  2971   oop thread_obj = threadObj();
  2972   if (thread_obj != NULL) {
  2973     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
  2974     if (thread_group != NULL) {
  2975       typeArrayOop name = java_lang_ThreadGroup::name(thread_group);
  2976       // ThreadGroup.name can be null
  2977       if (name != NULL) {
  2978         const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
  2979         return str;
  2983   return NULL;
  2986 const char* JavaThread::get_parent_name() const {
  2987   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
  2988   oop thread_obj = threadObj();
  2989   if (thread_obj != NULL) {
  2990     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
  2991     if (thread_group != NULL) {
  2992       oop parent = java_lang_ThreadGroup::parent(thread_group);
  2993       if (parent != NULL) {
  2994         typeArrayOop name = java_lang_ThreadGroup::name(parent);
  2995         // ThreadGroup.name can be null
  2996         if (name != NULL) {
  2997           const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
  2998           return str;
  3003   return NULL;
  3006 ThreadPriority JavaThread::java_priority() const {
  3007   oop thr_oop = threadObj();
  3008   if (thr_oop == NULL) return NormPriority; // Bootstrapping
  3009   ThreadPriority priority = java_lang_Thread::priority(thr_oop);
  3010   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
  3011   return priority;
  3014 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
  3016   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
  3017   // Link Java Thread object <-> C++ Thread
  3019   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
  3020   // and put it into a new Handle.  The Handle "thread_oop" can then
  3021   // be used to pass the C++ thread object to other methods.
  3023   // Set the Java level thread object (jthread) field of the
  3024   // new thread (a JavaThread *) to C++ thread object using the
  3025   // "thread_oop" handle.
  3027   // Set the thread field (a JavaThread *) of the
  3028   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
  3030   Handle thread_oop(Thread::current(),
  3031                     JNIHandles::resolve_non_null(jni_thread));
  3032   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
  3033     "must be initialized");
  3034   set_threadObj(thread_oop());
  3035   java_lang_Thread::set_thread(thread_oop(), this);
  3037   if (prio == NoPriority) {
  3038     prio = java_lang_Thread::priority(thread_oop());
  3039     assert(prio != NoPriority, "A valid priority should be present");
  3042   // Push the Java priority down to the native thread; needs Threads_lock
  3043   Thread::set_priority(this, prio);
  3045   prepare_ext();
  3047   // Add the new thread to the Threads list and set it in motion.
  3048   // We must have threads lock in order to call Threads::add.
  3049   // It is crucial that we do not block before the thread is
  3050   // added to the Threads list for if a GC happens, then the java_thread oop
  3051   // will not be visited by GC.
  3052   Threads::add(this);
  3055 oop JavaThread::current_park_blocker() {
  3056   // Support for JSR-166 locks
  3057   oop thread_oop = threadObj();
  3058   if (thread_oop != NULL &&
  3059       JDK_Version::current().supports_thread_park_blocker()) {
  3060     return java_lang_Thread::park_blocker(thread_oop);
  3062   return NULL;
  3066 void JavaThread::print_stack_on(outputStream* st) {
  3067   if (!has_last_Java_frame()) return;
  3068   ResourceMark rm;
  3069   HandleMark   hm;
  3071   RegisterMap reg_map(this);
  3072   vframe* start_vf = last_java_vframe(&reg_map);
  3073   int count = 0;
  3074   for (vframe* f = start_vf; f; f = f->sender() ) {
  3075     if (f->is_java_frame()) {
  3076       javaVFrame* jvf = javaVFrame::cast(f);
  3077       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
  3079       // Print out lock information
  3080       if (JavaMonitorsInStackTrace) {
  3081         jvf->print_lock_info_on(st, count);
  3083     } else {
  3084       // Ignore non-Java frames
  3087     // Bail-out case for too deep stacks
  3088     count++;
  3089     if (MaxJavaStackTraceDepth == count) return;
  3094 // JVMTI PopFrame support
  3095 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
  3096   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
  3097   if (in_bytes(size_in_bytes) != 0) {
  3098     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
  3099     _popframe_preserved_args_size = in_bytes(size_in_bytes);
  3100     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
  3104 void* JavaThread::popframe_preserved_args() {
  3105   return _popframe_preserved_args;
  3108 ByteSize JavaThread::popframe_preserved_args_size() {
  3109   return in_ByteSize(_popframe_preserved_args_size);
  3112 WordSize JavaThread::popframe_preserved_args_size_in_words() {
  3113   int sz = in_bytes(popframe_preserved_args_size());
  3114   assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
  3115   return in_WordSize(sz / wordSize);
  3118 void JavaThread::popframe_free_preserved_args() {
  3119   assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
  3120   FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args, mtThread);
  3121   _popframe_preserved_args = NULL;
  3122   _popframe_preserved_args_size = 0;
  3125 #ifndef PRODUCT
  3127 void JavaThread::trace_frames() {
  3128   tty->print_cr("[Describe stack]");
  3129   int frame_no = 1;
  3130   for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  3131     tty->print("  %d. ", frame_no++);
  3132     fst.current()->print_value_on(tty,this);
  3133     tty->cr();
  3137 class PrintAndVerifyOopClosure: public OopClosure {
  3138  protected:
  3139   template <class T> inline void do_oop_work(T* p) {
  3140     oop obj = oopDesc::load_decode_heap_oop(p);
  3141     if (obj == NULL) return;
  3142     tty->print(INTPTR_FORMAT ": ", p);
  3143     if (obj->is_oop_or_null()) {
  3144       if (obj->is_objArray()) {
  3145         tty->print_cr("valid objArray: " INTPTR_FORMAT, (oopDesc*) obj);
  3146       } else {
  3147         obj->print();
  3149     } else {
  3150       tty->print_cr("invalid oop: " INTPTR_FORMAT, (oopDesc*) obj);
  3152     tty->cr();
  3154  public:
  3155   virtual void do_oop(oop* p) { do_oop_work(p); }
  3156   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
  3157 };
  3160 static void oops_print(frame* f, const RegisterMap *map) {
  3161   PrintAndVerifyOopClosure print;
  3162   f->print_value();
  3163   f->oops_do(&print, NULL, NULL, (RegisterMap*)map);
  3166 // Print our all the locations that contain oops and whether they are
  3167 // valid or not.  This useful when trying to find the oldest frame
  3168 // where an oop has gone bad since the frame walk is from youngest to
  3169 // oldest.
  3170 void JavaThread::trace_oops() {
  3171   tty->print_cr("[Trace oops]");
  3172   frames_do(oops_print);
  3176 #ifdef ASSERT
  3177 // Print or validate the layout of stack frames
  3178 void JavaThread::print_frame_layout(int depth, bool validate_only) {
  3179   ResourceMark rm;
  3180   PRESERVE_EXCEPTION_MARK;
  3181   FrameValues values;
  3182   int frame_no = 0;
  3183   for(StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
  3184     fst.current()->describe(values, ++frame_no);
  3185     if (depth == frame_no) break;
  3187   if (validate_only) {
  3188     values.validate();
  3189   } else {
  3190     tty->print_cr("[Describe stack layout]");
  3191     values.print(this);
  3194 #endif
  3196 void JavaThread::trace_stack_from(vframe* start_vf) {
  3197   ResourceMark rm;
  3198   int vframe_no = 1;
  3199   for (vframe* f = start_vf; f; f = f->sender() ) {
  3200     if (f->is_java_frame()) {
  3201       javaVFrame::cast(f)->print_activation(vframe_no++);
  3202     } else {
  3203       f->print();
  3205     if (vframe_no > StackPrintLimit) {
  3206       tty->print_cr("...<more frames>...");
  3207       return;
  3213 void JavaThread::trace_stack() {
  3214   if (!has_last_Java_frame()) return;
  3215   ResourceMark rm;
  3216   HandleMark   hm;
  3217   RegisterMap reg_map(this);
  3218   trace_stack_from(last_java_vframe(&reg_map));
  3222 #endif // PRODUCT
  3225 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
  3226   assert(reg_map != NULL, "a map must be given");
  3227   frame f = last_frame();
  3228   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender() ) {
  3229     if (vf->is_java_frame()) return javaVFrame::cast(vf);
  3231   return NULL;
  3235 Klass* JavaThread::security_get_caller_class(int depth) {
  3236   vframeStream vfst(this);
  3237   vfst.security_get_caller_frame(depth);
  3238   if (!vfst.at_end()) {
  3239     return vfst.method()->method_holder();
  3241   return NULL;
  3244 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
  3245   assert(thread->is_Compiler_thread(), "must be compiler thread");
  3246   CompileBroker::compiler_thread_loop();
  3249 // Create a CompilerThread
  3250 CompilerThread::CompilerThread(CompileQueue* queue, CompilerCounters* counters)
  3251 : JavaThread(&compiler_thread_entry) {
  3252   _env   = NULL;
  3253   _log   = NULL;
  3254   _task  = NULL;
  3255   _queue = queue;
  3256   _counters = counters;
  3257   _buffer_blob = NULL;
  3258   _scanned_nmethod = NULL;
  3259   _compiler = NULL;
  3261   // Compiler uses resource area for compilation, let's bias it to mtCompiler
  3262   resource_area()->bias_to(mtCompiler);
  3264 #ifndef PRODUCT
  3265   _ideal_graph_printer = NULL;
  3266 #endif
  3269 void CompilerThread::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
  3270   JavaThread::oops_do(f, cld_f, cf);
  3271   if (_scanned_nmethod != NULL && cf != NULL) {
  3272     // Safepoints can occur when the sweeper is scanning an nmethod so
  3273     // process it here to make sure it isn't unloaded in the middle of
  3274     // a scan.
  3275     cf->do_code_blob(_scanned_nmethod);
  3280 // ======= Threads ========
  3282 // The Threads class links together all active threads, and provides
  3283 // operations over all threads.  It is protected by its own Mutex
  3284 // lock, which is also used in other contexts to protect thread
  3285 // operations from having the thread being operated on from exiting
  3286 // and going away unexpectedly (e.g., safepoint synchronization)
  3288 JavaThread* Threads::_thread_list = NULL;
  3289 int         Threads::_number_of_threads = 0;
  3290 int         Threads::_number_of_non_daemon_threads = 0;
  3291 int         Threads::_return_code = 0;
  3292 size_t      JavaThread::_stack_size_at_create = 0;
  3293 #ifdef ASSERT
  3294 bool        Threads::_vm_complete = false;
  3295 #endif
  3297 // All JavaThreads
  3298 #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
  3300 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
  3301 void Threads::threads_do(ThreadClosure* tc) {
  3302   assert_locked_or_safepoint(Threads_lock);
  3303   // ALL_JAVA_THREADS iterates through all JavaThreads
  3304   ALL_JAVA_THREADS(p) {
  3305     tc->do_thread(p);
  3307   // Someday we could have a table or list of all non-JavaThreads.
  3308   // For now, just manually iterate through them.
  3309   tc->do_thread(VMThread::vm_thread());
  3310   Universe::heap()->gc_threads_do(tc);
  3311   WatcherThread *wt = WatcherThread::watcher_thread();
  3312   // Strictly speaking, the following NULL check isn't sufficient to make sure
  3313   // the data for WatcherThread is still valid upon being examined. However,
  3314   // considering that WatchThread terminates when the VM is on the way to
  3315   // exit at safepoint, the chance of the above is extremely small. The right
  3316   // way to prevent termination of WatcherThread would be to acquire
  3317   // Terminator_lock, but we can't do that without violating the lock rank
  3318   // checking in some cases.
  3319   if (wt != NULL)
  3320     tc->do_thread(wt);
  3322 #if INCLUDE_JFR
  3323   Thread* sampler_thread = Jfr::sampler_thread();
  3324   if (sampler_thread != NULL) {
  3325     tc->do_thread(sampler_thread);
  3328 #endif
  3330   // If CompilerThreads ever become non-JavaThreads, add them here
  3333 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
  3335   extern void JDK_Version_init();
  3337   // Preinitialize version info.
  3338   VM_Version::early_initialize();
  3340   // Check version
  3341   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
  3343   // Initialize the output stream module
  3344   ostream_init();
  3346   // Process java launcher properties.
  3347   Arguments::process_sun_java_launcher_properties(args);
  3349   // Initialize the os module before using TLS
  3350   os::init();
  3352   // Initialize system properties.
  3353   Arguments::init_system_properties();
  3355   // So that JDK version can be used as a discrimintor when parsing arguments
  3356   JDK_Version_init();
  3358   // Update/Initialize System properties after JDK version number is known
  3359   Arguments::init_version_specific_system_properties();
  3361   // Parse arguments
  3362   // Note: this internally calls os::init_container_support()
  3363   jint parse_result = Arguments::parse(args);
  3364   if (parse_result != JNI_OK) return parse_result;
  3366   os::init_before_ergo();
  3368   jint ergo_result = Arguments::apply_ergo();
  3369   if (ergo_result != JNI_OK) return ergo_result;
  3371   if (PauseAtStartup) {
  3372     os::pause();
  3375 #ifndef USDT2
  3376   HS_DTRACE_PROBE(hotspot, vm__init__begin);
  3377 #else /* USDT2 */
  3378   HOTSPOT_VM_INIT_BEGIN();
  3379 #endif /* USDT2 */
  3381   // Record VM creation timing statistics
  3382   TraceVmCreationTime create_vm_timer;
  3383   create_vm_timer.start();
  3385   // Timing (must come after argument parsing)
  3386   TraceTime timer("Create VM", TraceStartupTime);
  3388   // Initialize the os module after parsing the args
  3389   jint os_init_2_result = os::init_2();
  3390   if (os_init_2_result != JNI_OK) return os_init_2_result;
  3392   jint adjust_after_os_result = Arguments::adjust_after_os();
  3393   if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
  3395   // intialize TLS
  3396   ThreadLocalStorage::init();
  3398   // Initialize output stream logging
  3399   ostream_init_log();
  3401   // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
  3402   // Must be before create_vm_init_agents()
  3403   if (Arguments::init_libraries_at_startup()) {
  3404     convert_vm_init_libraries_to_agents();
  3407   // Launch -agentlib/-agentpath and converted -Xrun agents
  3408   if (Arguments::init_agents_at_startup()) {
  3409     create_vm_init_agents();
  3412   // Initialize Threads state
  3413   _thread_list = NULL;
  3414   _number_of_threads = 0;
  3415   _number_of_non_daemon_threads = 0;
  3417   // Initialize global data structures and create system classes in heap
  3418   vm_init_globals();
  3420   // Attach the main thread to this os thread
  3421   JavaThread* main_thread = new JavaThread();
  3422   main_thread->set_thread_state(_thread_in_vm);
  3423   // must do this before set_active_handles and initialize_thread_local_storage
  3424   // Note: on solaris initialize_thread_local_storage() will (indirectly)
  3425   // change the stack size recorded here to one based on the java thread
  3426   // stacksize. This adjusted size is what is used to figure the placement
  3427   // of the guard pages.
  3428   main_thread->record_stack_base_and_size();
  3429   main_thread->initialize_thread_local_storage();
  3431   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
  3433   if (!main_thread->set_as_starting_thread()) {
  3434     vm_shutdown_during_initialization(
  3435       "Failed necessary internal allocation. Out of swap space");
  3436     delete main_thread;
  3437     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
  3438     return JNI_ENOMEM;
  3441   // Enable guard page *after* os::create_main_thread(), otherwise it would
  3442   // crash Linux VM, see notes in os_linux.cpp.
  3443   main_thread->create_stack_guard_pages();
  3445   // Initialize Java-Level synchronization subsystem
  3446   ObjectMonitor::Initialize() ;
  3448   // Initialize global modules
  3449   jint status = init_globals();
  3450   if (status != JNI_OK) {
  3451     delete main_thread;
  3452     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
  3453     return status;
  3456   JFR_ONLY(Jfr::on_vm_init();)
  3458   // Should be done after the heap is fully created
  3459   main_thread->cache_global_variables();
  3461   HandleMark hm;
  3463   { MutexLocker mu(Threads_lock);
  3464     Threads::add(main_thread);
  3467   // Any JVMTI raw monitors entered in onload will transition into
  3468   // real raw monitor. VM is setup enough here for raw monitor enter.
  3469   JvmtiExport::transition_pending_onload_raw_monitors();
  3471   // Create the VMThread
  3472   { TraceTime timer("Start VMThread", TraceStartupTime);
  3473     VMThread::create();
  3474     Thread* vmthread = VMThread::vm_thread();
  3476     if (!os::create_thread(vmthread, os::vm_thread))
  3477       vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
  3479     // Wait for the VM thread to become ready, and VMThread::run to initialize
  3480     // Monitors can have spurious returns, must always check another state flag
  3482       MutexLocker ml(Notify_lock);
  3483       os::start_thread(vmthread);
  3484       while (vmthread->active_handles() == NULL) {
  3485         Notify_lock->wait();
  3490   assert (Universe::is_fully_initialized(), "not initialized");
  3491   if (VerifyDuringStartup) {
  3492     // Make sure we're starting with a clean slate.
  3493     VM_Verify verify_op;
  3494     VMThread::execute(&verify_op);
  3497   EXCEPTION_MARK;
  3499   // At this point, the Universe is initialized, but we have not executed
  3500   // any byte code.  Now is a good time (the only time) to dump out the
  3501   // internal state of the JVM for sharing.
  3502   if (DumpSharedSpaces) {
  3503     MetaspaceShared::preload_and_dump(CHECK_0);
  3504     ShouldNotReachHere();
  3507   // Always call even when there are not JVMTI environments yet, since environments
  3508   // may be attached late and JVMTI must track phases of VM execution
  3509   JvmtiExport::enter_start_phase();
  3511   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
  3512   JvmtiExport::post_vm_start();
  3515     TraceTime timer("Initialize java.lang classes", TraceStartupTime);
  3517     if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
  3518       create_vm_init_libraries();
  3521     initialize_class(vmSymbols::java_lang_String(), CHECK_0);
  3523     // Initialize java_lang.System (needed before creating the thread)
  3524     initialize_class(vmSymbols::java_lang_System(), CHECK_0);
  3525     initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
  3526     Handle thread_group = create_initial_thread_group(CHECK_0);
  3527     Universe::set_main_thread_group(thread_group());
  3528     initialize_class(vmSymbols::java_lang_Thread(), CHECK_0);
  3529     oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0);
  3530     main_thread->set_threadObj(thread_object);
  3531     // Set thread status to running since main thread has
  3532     // been started and running.
  3533     java_lang_Thread::set_thread_status(thread_object,
  3534                                         java_lang_Thread::RUNNABLE);
  3536     // The VM creates & returns objects of this class. Make sure it's initialized.
  3537     initialize_class(vmSymbols::java_lang_Class(), CHECK_0);
  3539     // The VM preresolves methods to these classes. Make sure that they get initialized
  3540     initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK_0);
  3541     initialize_class(vmSymbols::java_lang_ref_Finalizer(),  CHECK_0);
  3542     call_initializeSystemClass(CHECK_0);
  3544     // get the Java runtime name after java.lang.System is initialized
  3545     JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
  3546     JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
  3548     // an instance of OutOfMemory exception has been allocated earlier
  3549     initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK_0);
  3550     initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK_0);
  3551     initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK_0);
  3552     initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK_0);
  3553     initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK_0);
  3554     initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK_0);
  3555     initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK_0);
  3556     initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK_0);
  3559   // See        : bugid 4211085.
  3560   // Background : the static initializer of java.lang.Compiler tries to read
  3561   //              property"java.compiler" and read & write property "java.vm.info".
  3562   //              When a security manager is installed through the command line
  3563   //              option "-Djava.security.manager", the above properties are not
  3564   //              readable and the static initializer for java.lang.Compiler fails
  3565   //              resulting in a NoClassDefFoundError.  This can happen in any
  3566   //              user code which calls methods in java.lang.Compiler.
  3567   // Hack :       the hack is to pre-load and initialize this class, so that only
  3568   //              system domains are on the stack when the properties are read.
  3569   //              Currently even the AWT code has calls to methods in java.lang.Compiler.
  3570   //              On the classic VM, java.lang.Compiler is loaded very early to load the JIT.
  3571   // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and
  3572   //              read and write"java.vm.info" in the default policy file. See bugid 4211383
  3573   //              Once that is done, we should remove this hack.
  3574   initialize_class(vmSymbols::java_lang_Compiler(), CHECK_0);
  3576   // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to
  3577   // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot
  3578   // compiler does not get loaded through java.lang.Compiler).  "java -version" with the
  3579   // hotspot vm says "nojit" all the time which is confusing.  So, we reset it here.
  3580   // This should also be taken out as soon as 4211383 gets fixed.
  3581   reset_vm_info_property(CHECK_0);
  3583   quicken_jni_functions();
  3585   // Set flag that basic initialization has completed. Used by exceptions and various
  3586   // debug stuff, that does not work until all basic classes have been initialized.
  3587   set_init_completed();
  3589   Metaspace::post_initialize();
  3591 #ifndef USDT2
  3592   HS_DTRACE_PROBE(hotspot, vm__init__end);
  3593 #else /* USDT2 */
  3594   HOTSPOT_VM_INIT_END();
  3595 #endif /* USDT2 */
  3597   // record VM initialization completion time
  3598 #if INCLUDE_MANAGEMENT
  3599   Management::record_vm_init_completed();
  3600 #endif // INCLUDE_MANAGEMENT
  3602   // Compute system loader. Note that this has to occur after set_init_completed, since
  3603   // valid exceptions may be thrown in the process.
  3604   // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
  3605   // set_init_completed has just been called, causing exceptions not to be shortcut
  3606   // anymore. We call vm_exit_during_initialization directly instead.
  3607   SystemDictionary::compute_java_system_loader(THREAD);
  3608   if (HAS_PENDING_EXCEPTION) {
  3609     vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
  3612 #if INCLUDE_ALL_GCS
  3613   // Support for ConcurrentMarkSweep. This should be cleaned up
  3614   // and better encapsulated. The ugly nested if test would go away
  3615   // once things are properly refactored. XXX YSR
  3616   if (UseConcMarkSweepGC || UseG1GC) {
  3617     if (UseConcMarkSweepGC) {
  3618       ConcurrentMarkSweepThread::makeSurrogateLockerThread(THREAD);
  3619     } else {
  3620       ConcurrentMarkThread::makeSurrogateLockerThread(THREAD);
  3622     if (HAS_PENDING_EXCEPTION) {
  3623       vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
  3626 #endif // INCLUDE_ALL_GCS
  3628   // Always call even when there are not JVMTI environments yet, since environments
  3629   // may be attached late and JVMTI must track phases of VM execution
  3630   JvmtiExport::enter_live_phase();
  3632   // Signal Dispatcher needs to be started before VMInit event is posted
  3633   os::signal_init();
  3635   // Start Attach Listener if +StartAttachListener or it can't be started lazily
  3636   if (!DisableAttachMechanism) {
  3637     AttachListener::vm_start();
  3638     if (StartAttachListener || AttachListener::init_at_startup()) {
  3639       AttachListener::init();
  3643   // Launch -Xrun agents
  3644   // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
  3645   // back-end can launch with -Xdebug -Xrunjdwp.
  3646   if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
  3647     create_vm_init_libraries();
  3650   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
  3651   JvmtiExport::post_vm_initialized();
  3653   JFR_ONLY(Jfr::on_vm_start();)
  3655   if (CleanChunkPoolAsync) {
  3656     Chunk::start_chunk_pool_cleaner_task();
  3659   // initialize compiler(s)
  3660 #if defined(COMPILER1) || defined(COMPILER2) || defined(SHARK)
  3661   CompileBroker::compilation_init();
  3662 #endif
  3664   if (EnableInvokeDynamic) {
  3665     // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
  3666     // It is done after compilers are initialized, because otherwise compilations of
  3667     // signature polymorphic MH intrinsics can be missed
  3668     // (see SystemDictionary::find_method_handle_intrinsic).
  3669     initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK_0);
  3670     initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK_0);
  3671     initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK_0);
  3674 #if INCLUDE_MANAGEMENT
  3675   Management::initialize(THREAD);
  3676 #endif // INCLUDE_MANAGEMENT
  3678   if (HAS_PENDING_EXCEPTION) {
  3679     // management agent fails to start possibly due to
  3680     // configuration problem and is responsible for printing
  3681     // stack trace if appropriate. Simply exit VM.
  3682     vm_exit(1);
  3685   if (Arguments::has_profile())       FlatProfiler::engage(main_thread, true);
  3686   if (MemProfiling)                   MemProfiler::engage();
  3687   StatSampler::engage();
  3688   if (CheckJNICalls)                  JniPeriodicChecker::engage();
  3690   BiasedLocking::init();
  3692 #if INCLUDE_RTM_OPT
  3693   RTMLockingCounters::init();
  3694 #endif
  3696   if (JDK_Version::current().post_vm_init_hook_enabled()) {
  3697     call_postVMInitHook(THREAD);
  3698     // The Java side of PostVMInitHook.run must deal with all
  3699     // exceptions and provide means of diagnosis.
  3700     if (HAS_PENDING_EXCEPTION) {
  3701       CLEAR_PENDING_EXCEPTION;
  3706       MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
  3707       // Make sure the watcher thread can be started by WatcherThread::start()
  3708       // or by dynamic enrollment.
  3709       WatcherThread::make_startable();
  3710       // Start up the WatcherThread if there are any periodic tasks
  3711       // NOTE:  All PeriodicTasks should be registered by now. If they
  3712       //   aren't, late joiners might appear to start slowly (we might
  3713       //   take a while to process their first tick).
  3714       if (PeriodicTask::num_tasks() > 0) {
  3715           WatcherThread::start();
  3719   create_vm_timer.end();
  3720 #ifdef ASSERT
  3721   _vm_complete = true;
  3722 #endif
  3723   return JNI_OK;
  3726 // type for the Agent_OnLoad and JVM_OnLoad entry points
  3727 extern "C" {
  3728   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
  3730 // Find a command line agent library and return its entry point for
  3731 //         -agentlib:  -agentpath:   -Xrun
  3732 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
  3733 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_symbols[], size_t num_symbol_entries) {
  3734   OnLoadEntry_t on_load_entry = NULL;
  3735   void *library = NULL;
  3737   if (!agent->valid()) {
  3738     char buffer[JVM_MAXPATHLEN];
  3739     char ebuf[1024];
  3740     const char *name = agent->name();
  3741     const char *msg = "Could not find agent library ";
  3743     // First check to see if agent is statically linked into executable
  3744     if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
  3745       library = agent->os_lib();
  3746     } else if (agent->is_absolute_path()) {
  3747       library = os::dll_load(name, ebuf, sizeof ebuf);
  3748       if (library == NULL) {
  3749         const char *sub_msg = " in absolute path, with error: ";
  3750         size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
  3751         char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
  3752         jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
  3753         // If we can't find the agent, exit.
  3754         vm_exit_during_initialization(buf, NULL);
  3755         FREE_C_HEAP_ARRAY(char, buf, mtThread);
  3757     } else {
  3758       // Try to load the agent from the standard dll directory
  3759       if (os::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(),
  3760                              name)) {
  3761         library = os::dll_load(buffer, ebuf, sizeof ebuf);
  3763       if (library == NULL) { // Try the local directory
  3764         char ns[1] = {0};
  3765         if (os::dll_build_name(buffer, sizeof(buffer), ns, name)) {
  3766           library = os::dll_load(buffer, ebuf, sizeof ebuf);
  3768         if (library == NULL) {
  3769           const char *sub_msg = " on the library path, with error: ";
  3770           size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
  3771           char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
  3772           jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
  3773           // If we can't find the agent, exit.
  3774           vm_exit_during_initialization(buf, NULL);
  3775           FREE_C_HEAP_ARRAY(char, buf, mtThread);
  3779     agent->set_os_lib(library);
  3780     agent->set_valid();
  3783   // Find the OnLoad function.
  3784   on_load_entry =
  3785     CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
  3786                                                           false,
  3787                                                           on_load_symbols,
  3788                                                           num_symbol_entries));
  3789   return on_load_entry;
  3792 // Find the JVM_OnLoad entry point
  3793 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
  3794   const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
  3795   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
  3798 // Find the Agent_OnLoad entry point
  3799 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
  3800   const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
  3801   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
  3804 // For backwards compatibility with -Xrun
  3805 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
  3806 // treated like -agentpath:
  3807 // Must be called before agent libraries are created
  3808 void Threads::convert_vm_init_libraries_to_agents() {
  3809   AgentLibrary* agent;
  3810   AgentLibrary* next;
  3812   for (agent = Arguments::libraries(); agent != NULL; agent = next) {
  3813     next = agent->next();  // cache the next agent now as this agent may get moved off this list
  3814     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
  3816     // If there is an JVM_OnLoad function it will get called later,
  3817     // otherwise see if there is an Agent_OnLoad
  3818     if (on_load_entry == NULL) {
  3819       on_load_entry = lookup_agent_on_load(agent);
  3820       if (on_load_entry != NULL) {
  3821         // switch it to the agent list -- so that Agent_OnLoad will be called,
  3822         // JVM_OnLoad won't be attempted and Agent_OnUnload will
  3823         Arguments::convert_library_to_agent(agent);
  3824       } else {
  3825         vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
  3831 // Create agents for -agentlib:  -agentpath:  and converted -Xrun
  3832 // Invokes Agent_OnLoad
  3833 // Called very early -- before JavaThreads exist
  3834 void Threads::create_vm_init_agents() {
  3835   extern struct JavaVM_ main_vm;
  3836   AgentLibrary* agent;
  3838   JvmtiExport::enter_onload_phase();
  3840   for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
  3841     OnLoadEntry_t  on_load_entry = lookup_agent_on_load(agent);
  3843     if (on_load_entry != NULL) {
  3844       // Invoke the Agent_OnLoad function
  3845       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
  3846       if (err != JNI_OK) {
  3847         vm_exit_during_initialization("agent library failed to init", agent->name());
  3849     } else {
  3850       vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
  3853   JvmtiExport::enter_primordial_phase();
  3856 extern "C" {
  3857   typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
  3860 void Threads::shutdown_vm_agents() {
  3861   // Send any Agent_OnUnload notifications
  3862   const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
  3863   size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
  3864   extern struct JavaVM_ main_vm;
  3865   for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
  3867     // Find the Agent_OnUnload function.
  3868     Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
  3869       os::find_agent_function(agent,
  3870       false,
  3871       on_unload_symbols,
  3872       num_symbol_entries));
  3874     // Invoke the Agent_OnUnload function
  3875     if (unload_entry != NULL) {
  3876       JavaThread* thread = JavaThread::current();
  3877       ThreadToNativeFromVM ttn(thread);
  3878       HandleMark hm(thread);
  3879       (*unload_entry)(&main_vm);
  3884 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
  3885 // Invokes JVM_OnLoad
  3886 void Threads::create_vm_init_libraries() {
  3887   extern struct JavaVM_ main_vm;
  3888   AgentLibrary* agent;
  3890   for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
  3891     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
  3893     if (on_load_entry != NULL) {
  3894       // Invoke the JVM_OnLoad function
  3895       JavaThread* thread = JavaThread::current();
  3896       ThreadToNativeFromVM ttn(thread);
  3897       HandleMark hm(thread);
  3898       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
  3899       if (err != JNI_OK) {
  3900         vm_exit_during_initialization("-Xrun library failed to init", agent->name());
  3902     } else {
  3903       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
  3908 JavaThread* Threads::find_java_thread_from_java_tid(jlong java_tid) {
  3909   assert(Threads_lock->owned_by_self(), "Must hold Threads_lock");
  3911   JavaThread* java_thread = NULL;
  3912   // Sequential search for now.  Need to do better optimization later.
  3913   for (JavaThread* thread = Threads::first(); thread != NULL; thread = thread->next()) {
  3914     oop tobj = thread->threadObj();
  3915     if (!thread->is_exiting() &&
  3916         tobj != NULL &&
  3917         java_tid == java_lang_Thread::thread_id(tobj)) {
  3918       java_thread = thread;
  3919       break;
  3922   return java_thread;
  3926 // Last thread running calls java.lang.Shutdown.shutdown()
  3927 void JavaThread::invoke_shutdown_hooks() {
  3928   HandleMark hm(this);
  3930   // We could get here with a pending exception, if so clear it now.
  3931   if (this->has_pending_exception()) {
  3932     this->clear_pending_exception();
  3935   EXCEPTION_MARK;
  3936   Klass* k =
  3937     SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
  3938                                       THREAD);
  3939   if (k != NULL) {
  3940     // SystemDictionary::resolve_or_null will return null if there was
  3941     // an exception.  If we cannot load the Shutdown class, just don't
  3942     // call Shutdown.shutdown() at all.  This will mean the shutdown hooks
  3943     // and finalizers (if runFinalizersOnExit is set) won't be run.
  3944     // Note that if a shutdown hook was registered or runFinalizersOnExit
  3945     // was called, the Shutdown class would have already been loaded
  3946     // (Runtime.addShutdownHook and runFinalizersOnExit will load it).
  3947     instanceKlassHandle shutdown_klass (THREAD, k);
  3948     JavaValue result(T_VOID);
  3949     JavaCalls::call_static(&result,
  3950                            shutdown_klass,
  3951                            vmSymbols::shutdown_method_name(),
  3952                            vmSymbols::void_method_signature(),
  3953                            THREAD);
  3955   CLEAR_PENDING_EXCEPTION;
  3958 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
  3959 // the program falls off the end of main(). Another VM exit path is through
  3960 // vm_exit() when the program calls System.exit() to return a value or when
  3961 // there is a serious error in VM. The two shutdown paths are not exactly
  3962 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
  3963 // and VM_Exit op at VM level.
  3964 //
  3965 // Shutdown sequence:
  3966 //   + Shutdown native memory tracking if it is on
  3967 //   + Wait until we are the last non-daemon thread to execute
  3968 //     <-- every thing is still working at this moment -->
  3969 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
  3970 //        shutdown hooks, run finalizers if finalization-on-exit
  3971 //   + Call before_exit(), prepare for VM exit
  3972 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
  3973 //        currently the only user of this mechanism is File.deleteOnExit())
  3974 //      > stop flat profiler, StatSampler, watcher thread, CMS threads,
  3975 //        post thread end and vm death events to JVMTI,
  3976 //        stop signal thread
  3977 //   + Call JavaThread::exit(), it will:
  3978 //      > release JNI handle blocks, remove stack guard pages
  3979 //      > remove this thread from Threads list
  3980 //     <-- no more Java code from this thread after this point -->
  3981 //   + Stop VM thread, it will bring the remaining VM to a safepoint and stop
  3982 //     the compiler threads at safepoint
  3983 //     <-- do not use anything that could get blocked by Safepoint -->
  3984 //   + Disable tracing at JNI/JVM barriers
  3985 //   + Set _vm_exited flag for threads that are still running native code
  3986 //   + Delete this thread
  3987 //   + Call exit_globals()
  3988 //      > deletes tty
  3989 //      > deletes PerfMemory resources
  3990 //   + Return to caller
  3992 bool Threads::destroy_vm() {
  3993   JavaThread* thread = JavaThread::current();
  3995 #ifdef ASSERT
  3996   _vm_complete = false;
  3997 #endif
  3998   // Wait until we are the last non-daemon thread to execute
  3999   { MutexLocker nu(Threads_lock);
  4000     while (Threads::number_of_non_daemon_threads() > 1 )
  4001       // This wait should make safepoint checks, wait without a timeout,
  4002       // and wait as a suspend-equivalent condition.
  4003       //
  4004       // Note: If the FlatProfiler is running and this thread is waiting
  4005       // for another non-daemon thread to finish, then the FlatProfiler
  4006       // is waiting for the external suspend request on this thread to
  4007       // complete. wait_for_ext_suspend_completion() will eventually
  4008       // timeout, but that takes time. Making this wait a suspend-
  4009       // equivalent condition solves that timeout problem.
  4010       //
  4011       Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
  4012                          Mutex::_as_suspend_equivalent_flag);
  4015   EventShutdown e;
  4016   if (e.should_commit()) {
  4017     e.set_reason("No remaining non-daemon Java threads");
  4018     e.commit();
  4021   // Hang forever on exit if we are reporting an error.
  4022   if (ShowMessageBoxOnError && is_error_reported()) {
  4023     os::infinite_sleep();
  4025   os::wait_for_keypress_at_exit();
  4027   if (JDK_Version::is_jdk12x_version()) {
  4028     // We are the last thread running, so check if finalizers should be run.
  4029     // For 1.3 or later this is done in thread->invoke_shutdown_hooks()
  4030     HandleMark rm(thread);
  4031     Universe::run_finalizers_on_exit();
  4032   } else {
  4033     // run Java level shutdown hooks
  4034     thread->invoke_shutdown_hooks();
  4037   before_exit(thread);
  4039   thread->exit(true);
  4041   // Stop VM thread.
  4043     // 4945125 The vm thread comes to a safepoint during exit.
  4044     // GC vm_operations can get caught at the safepoint, and the
  4045     // heap is unparseable if they are caught. Grab the Heap_lock
  4046     // to prevent this. The GC vm_operations will not be able to
  4047     // queue until after the vm thread is dead. After this point,
  4048     // we'll never emerge out of the safepoint before the VM exits.
  4050     MutexLocker ml(Heap_lock);
  4052     VMThread::wait_for_vm_thread_exit();
  4053     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
  4054     VMThread::destroy();
  4057   // clean up ideal graph printers
  4058 #if defined(COMPILER2) && !defined(PRODUCT)
  4059   IdealGraphPrinter::clean_up();
  4060 #endif
  4062   // Now, all Java threads are gone except daemon threads. Daemon threads
  4063   // running Java code or in VM are stopped by the Safepoint. However,
  4064   // daemon threads executing native code are still running.  But they
  4065   // will be stopped at native=>Java/VM barriers. Note that we can't
  4066   // simply kill or suspend them, as it is inherently deadlock-prone.
  4068 #ifndef PRODUCT
  4069   // disable function tracing at JNI/JVM barriers
  4070   TraceJNICalls = false;
  4071   TraceJVMCalls = false;
  4072   TraceRuntimeCalls = false;
  4073 #endif
  4075   VM_Exit::set_vm_exited();
  4077   notify_vm_shutdown();
  4079   delete thread;
  4081   // exit_globals() will delete tty
  4082   exit_globals();
  4084   return true;
  4088 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
  4089   if (version == JNI_VERSION_1_1) return JNI_TRUE;
  4090   return is_supported_jni_version(version);
  4094 jboolean Threads::is_supported_jni_version(jint version) {
  4095   if (version == JNI_VERSION_1_2) return JNI_TRUE;
  4096   if (version == JNI_VERSION_1_4) return JNI_TRUE;
  4097   if (version == JNI_VERSION_1_6) return JNI_TRUE;
  4098   if (version == JNI_VERSION_1_8) return JNI_TRUE;
  4099   return JNI_FALSE;
  4103 void Threads::add(JavaThread* p, bool force_daemon) {
  4104   // The threads lock must be owned at this point
  4105   assert_locked_or_safepoint(Threads_lock);
  4107   // See the comment for this method in thread.hpp for its purpose and
  4108   // why it is called here.
  4109   p->initialize_queues();
  4110   p->set_next(_thread_list);
  4111   _thread_list = p;
  4112   _number_of_threads++;
  4113   oop threadObj = p->threadObj();
  4114   bool daemon = true;
  4115   // Bootstrapping problem: threadObj can be null for initial
  4116   // JavaThread (or for threads attached via JNI)
  4117   if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
  4118     _number_of_non_daemon_threads++;
  4119     daemon = false;
  4122   ThreadService::add_thread(p, daemon);
  4124   // Possible GC point.
  4125   Events::log(p, "Thread added: " INTPTR_FORMAT, p);
  4128 void Threads::remove(JavaThread* p) {
  4129   // Extra scope needed for Thread_lock, so we can check
  4130   // that we do not remove thread without safepoint code notice
  4131   { MutexLocker ml(Threads_lock);
  4133     assert(includes(p), "p must be present");
  4135     JavaThread* current = _thread_list;
  4136     JavaThread* prev    = NULL;
  4138     while (current != p) {
  4139       prev    = current;
  4140       current = current->next();
  4143     if (prev) {
  4144       prev->set_next(current->next());
  4145     } else {
  4146       _thread_list = p->next();
  4148     _number_of_threads--;
  4149     oop threadObj = p->threadObj();
  4150     bool daemon = true;
  4151     if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
  4152       _number_of_non_daemon_threads--;
  4153       daemon = false;
  4155       // Only one thread left, do a notify on the Threads_lock so a thread waiting
  4156       // on destroy_vm will wake up.
  4157       if (number_of_non_daemon_threads() == 1)
  4158         Threads_lock->notify_all();
  4160     ThreadService::remove_thread(p, daemon);
  4162     // Make sure that safepoint code disregard this thread. This is needed since
  4163     // the thread might mess around with locks after this point. This can cause it
  4164     // to do callbacks into the safepoint code. However, the safepoint code is not aware
  4165     // of this thread since it is removed from the queue.
  4166     p->set_terminated_value();
  4167   } // unlock Threads_lock
  4169   // Since Events::log uses a lock, we grab it outside the Threads_lock
  4170   Events::log(p, "Thread exited: " INTPTR_FORMAT, p);
  4173 // Threads_lock must be held when this is called (or must be called during a safepoint)
  4174 bool Threads::includes(JavaThread* p) {
  4175   assert(Threads_lock->is_locked(), "sanity check");
  4176   ALL_JAVA_THREADS(q) {
  4177     if (q == p ) {
  4178       return true;
  4181   return false;
  4184 // Operations on the Threads list for GC.  These are not explicitly locked,
  4185 // but the garbage collector must provide a safe context for them to run.
  4186 // In particular, these things should never be called when the Threads_lock
  4187 // is held by some other thread. (Note: the Safepoint abstraction also
  4188 // uses the Threads_lock to gurantee this property. It also makes sure that
  4189 // all threads gets blocked when exiting or starting).
  4191 void Threads::oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
  4192   ALL_JAVA_THREADS(p) {
  4193     p->oops_do(f, cld_f, cf);
  4195   VMThread::vm_thread()->oops_do(f, cld_f, cf);
  4198 void Threads::possibly_parallel_oops_do(OopClosure* f, CLDClosure* cld_f, CodeBlobClosure* cf) {
  4199   // Introduce a mechanism allowing parallel threads to claim threads as
  4200   // root groups.  Overhead should be small enough to use all the time,
  4201   // even in sequential code.
  4202   SharedHeap* sh = SharedHeap::heap();
  4203   // Cannot yet substitute active_workers for n_par_threads
  4204   // because of G1CollectedHeap::verify() use of
  4205   // SharedHeap::process_roots().  n_par_threads == 0 will
  4206   // turn off parallelism in process_roots while active_workers
  4207   // is being used for parallelism elsewhere.
  4208   bool is_par = sh->n_par_threads() > 0;
  4209   assert(!is_par ||
  4210          (SharedHeap::heap()->n_par_threads() ==
  4211           SharedHeap::heap()->workers()->active_workers()), "Mismatch");
  4212   int cp = SharedHeap::heap()->strong_roots_parity();
  4213   ALL_JAVA_THREADS(p) {
  4214     if (p->claim_oops_do(is_par, cp)) {
  4215       p->oops_do(f, cld_f, cf);
  4218   VMThread* vmt = VMThread::vm_thread();
  4219   if (vmt->claim_oops_do(is_par, cp)) {
  4220     vmt->oops_do(f, cld_f, cf);
  4224 #if INCLUDE_ALL_GCS
  4225 // Used by ParallelScavenge
  4226 void Threads::create_thread_roots_tasks(GCTaskQueue* q) {
  4227   ALL_JAVA_THREADS(p) {
  4228     q->enqueue(new ThreadRootsTask(p));
  4230   q->enqueue(new ThreadRootsTask(VMThread::vm_thread()));
  4233 // Used by Parallel Old
  4234 void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) {
  4235   ALL_JAVA_THREADS(p) {
  4236     q->enqueue(new ThreadRootsMarkingTask(p));
  4238   q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread()));
  4240 #endif // INCLUDE_ALL_GCS
  4242 void Threads::nmethods_do(CodeBlobClosure* cf) {
  4243   ALL_JAVA_THREADS(p) {
  4244     p->nmethods_do(cf);
  4246   VMThread::vm_thread()->nmethods_do(cf);
  4249 void Threads::metadata_do(void f(Metadata*)) {
  4250   ALL_JAVA_THREADS(p) {
  4251     p->metadata_do(f);
  4255 void Threads::gc_epilogue() {
  4256   ALL_JAVA_THREADS(p) {
  4257     p->gc_epilogue();
  4261 void Threads::gc_prologue() {
  4262   ALL_JAVA_THREADS(p) {
  4263     p->gc_prologue();
  4267 void Threads::deoptimized_wrt_marked_nmethods() {
  4268   ALL_JAVA_THREADS(p) {
  4269     p->deoptimized_wrt_marked_nmethods();
  4274 // Get count Java threads that are waiting to enter the specified monitor.
  4275 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
  4276   address monitor, bool doLock) {
  4277   assert(doLock || SafepointSynchronize::is_at_safepoint(),
  4278     "must grab Threads_lock or be at safepoint");
  4279   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
  4281   int i = 0;
  4283     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  4284     ALL_JAVA_THREADS(p) {
  4285       if (p->is_Compiler_thread()) continue;
  4287       address pending = (address)p->current_pending_monitor();
  4288       if (pending == monitor) {             // found a match
  4289         if (i < count) result->append(p);   // save the first count matches
  4290         i++;
  4294   return result;
  4298 JavaThread *Threads::owning_thread_from_monitor_owner(address owner, bool doLock) {
  4299   assert(doLock ||
  4300          Threads_lock->owned_by_self() ||
  4301          SafepointSynchronize::is_at_safepoint(),
  4302          "must grab Threads_lock or be at safepoint");
  4304   // NULL owner means not locked so we can skip the search
  4305   if (owner == NULL) return NULL;
  4308     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  4309     ALL_JAVA_THREADS(p) {
  4310       // first, see if owner is the address of a Java thread
  4311       if (owner == (address)p) return p;
  4314   // Cannot assert on lack of success here since this function may be
  4315   // used by code that is trying to report useful problem information
  4316   // like deadlock detection.
  4317   if (UseHeavyMonitors) return NULL;
  4319   //
  4320   // If we didn't find a matching Java thread and we didn't force use of
  4321   // heavyweight monitors, then the owner is the stack address of the
  4322   // Lock Word in the owning Java thread's stack.
  4323   //
  4324   JavaThread* the_owner = NULL;
  4326     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  4327     ALL_JAVA_THREADS(q) {
  4328       if (q->is_lock_owned(owner)) {
  4329         the_owner = q;
  4330         break;
  4334   // cannot assert on lack of success here; see above comment
  4335   return the_owner;
  4338 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
  4339 void Threads::print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks) {
  4340   char buf[32];
  4341   st->print_cr("%s", os::local_time_string(buf, sizeof(buf)));
  4343   st->print_cr("Full thread dump %s (%s %s):",
  4344                 Abstract_VM_Version::vm_name(),
  4345                 Abstract_VM_Version::vm_release(),
  4346                 Abstract_VM_Version::vm_info_string()
  4347                );
  4348   st->cr();
  4350 #if INCLUDE_ALL_GCS
  4351   // Dump concurrent locks
  4352   ConcurrentLocksDump concurrent_locks;
  4353   if (print_concurrent_locks) {
  4354     concurrent_locks.dump_at_safepoint();
  4356 #endif // INCLUDE_ALL_GCS
  4358   ALL_JAVA_THREADS(p) {
  4359     ResourceMark rm;
  4360     p->print_on(st);
  4361     if (print_stacks) {
  4362       if (internal_format) {
  4363         p->trace_stack();
  4364       } else {
  4365         p->print_stack_on(st);
  4368     st->cr();
  4369 #if INCLUDE_ALL_GCS
  4370     if (print_concurrent_locks) {
  4371       concurrent_locks.print_locks_on(p, st);
  4373 #endif // INCLUDE_ALL_GCS
  4376   VMThread::vm_thread()->print_on(st);
  4377   st->cr();
  4378   Universe::heap()->print_gc_threads_on(st);
  4379   WatcherThread* wt = WatcherThread::watcher_thread();
  4380   if (wt != NULL) {
  4381     wt->print_on(st);
  4382     st->cr();
  4384   CompileBroker::print_compiler_threads_on(st);
  4385   st->flush();
  4388 // Threads::print_on_error() is called by fatal error handler. It's possible
  4389 // that VM is not at safepoint and/or current thread is inside signal handler.
  4390 // Don't print stack trace, as the stack may not be walkable. Don't allocate
  4391 // memory (even in resource area), it might deadlock the error handler.
  4392 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, int buflen) {
  4393   bool found_current = false;
  4394   st->print_cr("Java Threads: ( => current thread )");
  4395   ALL_JAVA_THREADS(thread) {
  4396     bool is_current = (current == thread);
  4397     found_current = found_current || is_current;
  4399     st->print("%s", is_current ? "=>" : "  ");
  4401     st->print(PTR_FORMAT, thread);
  4402     st->print(" ");
  4403     thread->print_on_error(st, buf, buflen);
  4404     st->cr();
  4406   st->cr();
  4408   st->print_cr("Other Threads:");
  4409   if (VMThread::vm_thread()) {
  4410     bool is_current = (current == VMThread::vm_thread());
  4411     found_current = found_current || is_current;
  4412     st->print("%s", current == VMThread::vm_thread() ? "=>" : "  ");
  4414     st->print(PTR_FORMAT, VMThread::vm_thread());
  4415     st->print(" ");
  4416     VMThread::vm_thread()->print_on_error(st, buf, buflen);
  4417     st->cr();
  4419   WatcherThread* wt = WatcherThread::watcher_thread();
  4420   if (wt != NULL) {
  4421     bool is_current = (current == wt);
  4422     found_current = found_current || is_current;
  4423     st->print("%s", is_current ? "=>" : "  ");
  4425     st->print(PTR_FORMAT, wt);
  4426     st->print(" ");
  4427     wt->print_on_error(st, buf, buflen);
  4428     st->cr();
  4430   if (!found_current) {
  4431     st->cr();
  4432     st->print("=>" PTR_FORMAT " (exited) ", current);
  4433     current->print_on_error(st, buf, buflen);
  4434     st->cr();
  4438 // Internal SpinLock and Mutex
  4439 // Based on ParkEvent
  4441 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
  4442 //
  4443 // We employ SpinLocks _only for low-contention, fixed-length
  4444 // short-duration critical sections where we're concerned
  4445 // about native mutex_t or HotSpot Mutex:: latency.
  4446 // The mux construct provides a spin-then-block mutual exclusion
  4447 // mechanism.
  4448 //
  4449 // Testing has shown that contention on the ListLock guarding gFreeList
  4450 // is common.  If we implement ListLock as a simple SpinLock it's common
  4451 // for the JVM to devolve to yielding with little progress.  This is true
  4452 // despite the fact that the critical sections protected by ListLock are
  4453 // extremely short.
  4454 //
  4455 // TODO-FIXME: ListLock should be of type SpinLock.
  4456 // We should make this a 1st-class type, integrated into the lock
  4457 // hierarchy as leaf-locks.  Critically, the SpinLock structure
  4458 // should have sufficient padding to avoid false-sharing and excessive
  4459 // cache-coherency traffic.
  4462 typedef volatile int SpinLockT ;
  4464 void Thread::SpinAcquire (volatile int * adr, const char * LockName) {
  4465   if (Atomic::cmpxchg (1, adr, 0) == 0) {
  4466      return ;   // normal fast-path return
  4469   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
  4470   TEVENT (SpinAcquire - ctx) ;
  4471   int ctr = 0 ;
  4472   int Yields = 0 ;
  4473   for (;;) {
  4474      while (*adr != 0) {
  4475         ++ctr ;
  4476         if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
  4477            if (Yields > 5) {
  4478              os::naked_short_sleep(1);
  4479            } else {
  4480              os::NakedYield() ;
  4481              ++Yields ;
  4483         } else {
  4484            SpinPause() ;
  4487      if (Atomic::cmpxchg (1, adr, 0) == 0) return ;
  4491 void Thread::SpinRelease (volatile int * adr) {
  4492   assert (*adr != 0, "invariant") ;
  4493   OrderAccess::fence() ;      // guarantee at least release consistency.
  4494   // Roach-motel semantics.
  4495   // It's safe if subsequent LDs and STs float "up" into the critical section,
  4496   // but prior LDs and STs within the critical section can't be allowed
  4497   // to reorder or float past the ST that releases the lock.
  4498   *adr = 0 ;
  4501 // muxAcquire and muxRelease:
  4502 //
  4503 // *  muxAcquire and muxRelease support a single-word lock-word construct.
  4504 //    The LSB of the word is set IFF the lock is held.
  4505 //    The remainder of the word points to the head of a singly-linked list
  4506 //    of threads blocked on the lock.
  4507 //
  4508 // *  The current implementation of muxAcquire-muxRelease uses its own
  4509 //    dedicated Thread._MuxEvent instance.  If we're interested in
  4510 //    minimizing the peak number of extant ParkEvent instances then
  4511 //    we could eliminate _MuxEvent and "borrow" _ParkEvent as long
  4512 //    as certain invariants were satisfied.  Specifically, care would need
  4513 //    to be taken with regards to consuming unpark() "permits".
  4514 //    A safe rule of thumb is that a thread would never call muxAcquire()
  4515 //    if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
  4516 //    park().  Otherwise the _ParkEvent park() operation in muxAcquire() could
  4517 //    consume an unpark() permit intended for monitorenter, for instance.
  4518 //    One way around this would be to widen the restricted-range semaphore
  4519 //    implemented in park().  Another alternative would be to provide
  4520 //    multiple instances of the PlatformEvent() for each thread.  One
  4521 //    instance would be dedicated to muxAcquire-muxRelease, for instance.
  4522 //
  4523 // *  Usage:
  4524 //    -- Only as leaf locks
  4525 //    -- for short-term locking only as muxAcquire does not perform
  4526 //       thread state transitions.
  4527 //
  4528 // Alternatives:
  4529 // *  We could implement muxAcquire and muxRelease with MCS or CLH locks
  4530 //    but with parking or spin-then-park instead of pure spinning.
  4531 // *  Use Taura-Oyama-Yonenzawa locks.
  4532 // *  It's possible to construct a 1-0 lock if we encode the lockword as
  4533 //    (List,LockByte).  Acquire will CAS the full lockword while Release
  4534 //    will STB 0 into the LockByte.  The 1-0 scheme admits stranding, so
  4535 //    acquiring threads use timers (ParkTimed) to detect and recover from
  4536 //    the stranding window.  Thread/Node structures must be aligned on 256-byte
  4537 //    boundaries by using placement-new.
  4538 // *  Augment MCS with advisory back-link fields maintained with CAS().
  4539 //    Pictorially:  LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
  4540 //    The validity of the backlinks must be ratified before we trust the value.
  4541 //    If the backlinks are invalid the exiting thread must back-track through the
  4542 //    the forward links, which are always trustworthy.
  4543 // *  Add a successor indication.  The LockWord is currently encoded as
  4544 //    (List, LOCKBIT:1).  We could also add a SUCCBIT or an explicit _succ variable
  4545 //    to provide the usual futile-wakeup optimization.
  4546 //    See RTStt for details.
  4547 // *  Consider schedctl.sc_nopreempt to cover the critical section.
  4548 //
  4551 typedef volatile intptr_t MutexT ;      // Mux Lock-word
  4552 enum MuxBits { LOCKBIT = 1 } ;
  4554 void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) {
  4555   intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
  4556   if (w == 0) return ;
  4557   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4558      return ;
  4561   TEVENT (muxAcquire - Contention) ;
  4562   ParkEvent * const Self = Thread::current()->_MuxEvent ;
  4563   assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ;
  4564   for (;;) {
  4565      int its = (os::is_MP() ? 100 : 0) + 1 ;
  4567      // Optional spin phase: spin-then-park strategy
  4568      while (--its >= 0) {
  4569        w = *Lock ;
  4570        if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4571           return ;
  4575      Self->reset() ;
  4576      Self->OnList = intptr_t(Lock) ;
  4577      // The following fence() isn't _strictly necessary as the subsequent
  4578      // CAS() both serializes execution and ratifies the fetched *Lock value.
  4579      OrderAccess::fence();
  4580      for (;;) {
  4581         w = *Lock ;
  4582         if ((w & LOCKBIT) == 0) {
  4583             if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4584                 Self->OnList = 0 ;   // hygiene - allows stronger asserts
  4585                 return ;
  4587             continue ;      // Interference -- *Lock changed -- Just retry
  4589         assert (w & LOCKBIT, "invariant") ;
  4590         Self->ListNext = (ParkEvent *) (w & ~LOCKBIT );
  4591         if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ;
  4594      while (Self->OnList != 0) {
  4595         Self->park() ;
  4600 void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) {
  4601   intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
  4602   if (w == 0) return ;
  4603   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4604     return ;
  4607   TEVENT (muxAcquire - Contention) ;
  4608   ParkEvent * ReleaseAfter = NULL ;
  4609   if (ev == NULL) {
  4610     ev = ReleaseAfter = ParkEvent::Allocate (NULL) ;
  4612   assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ;
  4613   for (;;) {
  4614     guarantee (ev->OnList == 0, "invariant") ;
  4615     int its = (os::is_MP() ? 100 : 0) + 1 ;
  4617     // Optional spin phase: spin-then-park strategy
  4618     while (--its >= 0) {
  4619       w = *Lock ;
  4620       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4621         if (ReleaseAfter != NULL) {
  4622           ParkEvent::Release (ReleaseAfter) ;
  4624         return ;
  4628     ev->reset() ;
  4629     ev->OnList = intptr_t(Lock) ;
  4630     // The following fence() isn't _strictly necessary as the subsequent
  4631     // CAS() both serializes execution and ratifies the fetched *Lock value.
  4632     OrderAccess::fence();
  4633     for (;;) {
  4634       w = *Lock ;
  4635       if ((w & LOCKBIT) == 0) {
  4636         if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4637           ev->OnList = 0 ;
  4638           // We call ::Release while holding the outer lock, thus
  4639           // artificially lengthening the critical section.
  4640           // Consider deferring the ::Release() until the subsequent unlock(),
  4641           // after we've dropped the outer lock.
  4642           if (ReleaseAfter != NULL) {
  4643             ParkEvent::Release (ReleaseAfter) ;
  4645           return ;
  4647         continue ;      // Interference -- *Lock changed -- Just retry
  4649       assert (w & LOCKBIT, "invariant") ;
  4650       ev->ListNext = (ParkEvent *) (w & ~LOCKBIT );
  4651       if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ;
  4654     while (ev->OnList != 0) {
  4655       ev->park() ;
  4660 // Release() must extract a successor from the list and then wake that thread.
  4661 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
  4662 // similar to that used by ParkEvent::Allocate() and ::Release().  DMR-based
  4663 // Release() would :
  4664 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
  4665 // (B) Extract a successor from the private list "in-hand"
  4666 // (C) attempt to CAS() the residual back into *Lock over null.
  4667 //     If there were any newly arrived threads and the CAS() would fail.
  4668 //     In that case Release() would detach the RATs, re-merge the list in-hand
  4669 //     with the RATs and repeat as needed.  Alternately, Release() might
  4670 //     detach and extract a successor, but then pass the residual list to the wakee.
  4671 //     The wakee would be responsible for reattaching and remerging before it
  4672 //     competed for the lock.
  4673 //
  4674 // Both "pop" and DMR are immune from ABA corruption -- there can be
  4675 // multiple concurrent pushers, but only one popper or detacher.
  4676 // This implementation pops from the head of the list.  This is unfair,
  4677 // but tends to provide excellent throughput as hot threads remain hot.
  4678 // (We wake recently run threads first).
  4680 void Thread::muxRelease (volatile intptr_t * Lock)  {
  4681   for (;;) {
  4682     const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ;
  4683     assert (w & LOCKBIT, "invariant") ;
  4684     if (w == LOCKBIT) return ;
  4685     ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ;
  4686     assert (List != NULL, "invariant") ;
  4687     assert (List->OnList == intptr_t(Lock), "invariant") ;
  4688     ParkEvent * nxt = List->ListNext ;
  4690     // The following CAS() releases the lock and pops the head element.
  4691     if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) {
  4692       continue ;
  4694     List->OnList = 0 ;
  4695     OrderAccess::fence() ;
  4696     List->unpark () ;
  4697     return ;
  4702 void Threads::verify() {
  4703   ALL_JAVA_THREADS(p) {
  4704     p->verify();
  4706   VMThread* thread = VMThread::vm_thread();
  4707   if (thread != NULL) thread->verify();

mercurial