src/share/vm/runtime/thread.cpp

Mon, 17 Sep 2012 10:20:04 -0400

author
zgu
date
Mon, 17 Sep 2012 10:20:04 -0400
changeset 4079
716e6ef4482a
parent 4057
6dfc6a541338
child 4080
c088e2e95e69
permissions
-rw-r--r--

7190089: NMT ON: NMT failed assertion on thread's stack base address
Summary: Solaris only, record stack info to NMT after stack size adjustment was made for primordial threads
Reviewed-by: kvn, acorn, coleenp

     1 /*
     2  * Copyright (c) 1997, 2012, 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 "jvmtifiles/jvmtiEnv.hpp"
    36 #include "memory/gcLocker.inline.hpp"
    37 #include "memory/metaspaceShared.hpp"
    38 #include "memory/oopFactory.hpp"
    39 #include "memory/universe.inline.hpp"
    40 #include "oops/instanceKlass.hpp"
    41 #include "oops/objArrayOop.hpp"
    42 #include "oops/oop.inline.hpp"
    43 #include "oops/symbol.hpp"
    44 #include "prims/jvm_misc.hpp"
    45 #include "prims/jvmtiExport.hpp"
    46 #include "prims/jvmtiThreadState.hpp"
    47 #include "prims/privilegedStack.hpp"
    48 #include "runtime/aprofiler.hpp"
    49 #include "runtime/arguments.hpp"
    50 #include "runtime/biasedLocking.hpp"
    51 #include "runtime/deoptimization.hpp"
    52 #include "runtime/fprofiler.hpp"
    53 #include "runtime/frame.inline.hpp"
    54 #include "runtime/init.hpp"
    55 #include "runtime/interfaceSupport.hpp"
    56 #include "runtime/java.hpp"
    57 #include "runtime/javaCalls.hpp"
    58 #include "runtime/jniPeriodicChecker.hpp"
    59 #include "runtime/memprofiler.hpp"
    60 #include "runtime/mutexLocker.hpp"
    61 #include "runtime/objectMonitor.hpp"
    62 #include "runtime/osThread.hpp"
    63 #include "runtime/safepoint.hpp"
    64 #include "runtime/sharedRuntime.hpp"
    65 #include "runtime/statSampler.hpp"
    66 #include "runtime/stubRoutines.hpp"
    67 #include "runtime/task.hpp"
    68 #include "runtime/threadCritical.hpp"
    69 #include "runtime/threadLocalStorage.hpp"
    70 #include "runtime/vframe.hpp"
    71 #include "runtime/vframeArray.hpp"
    72 #include "runtime/vframe_hp.hpp"
    73 #include "runtime/vmThread.hpp"
    74 #include "runtime/vm_operations.hpp"
    75 #include "services/attachListener.hpp"
    76 #include "services/management.hpp"
    77 #include "services/memTracker.hpp"
    78 #include "services/threadService.hpp"
    79 #include "trace/traceEventTypes.hpp"
    80 #include "utilities/defaultStream.hpp"
    81 #include "utilities/dtrace.hpp"
    82 #include "utilities/events.hpp"
    83 #include "utilities/preserveException.hpp"
    84 #ifdef TARGET_OS_FAMILY_linux
    85 # include "os_linux.inline.hpp"
    86 # include "thread_linux.inline.hpp"
    87 #endif
    88 #ifdef TARGET_OS_FAMILY_solaris
    89 # include "os_solaris.inline.hpp"
    90 # include "thread_solaris.inline.hpp"
    91 #endif
    92 #ifdef TARGET_OS_FAMILY_windows
    93 # include "os_windows.inline.hpp"
    94 # include "thread_windows.inline.hpp"
    95 #endif
    96 #ifdef TARGET_OS_FAMILY_bsd
    97 # include "os_bsd.inline.hpp"
    98 # include "thread_bsd.inline.hpp"
    99 #endif
   100 #ifndef SERIALGC
   101 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
   102 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
   103 #include "gc_implementation/parallelScavenge/pcTasks.hpp"
   104 #endif
   105 #ifdef COMPILER1
   106 #include "c1/c1_Compiler.hpp"
   107 #endif
   108 #ifdef COMPILER2
   109 #include "opto/c2compiler.hpp"
   110 #include "opto/idealGraphPrinter.hpp"
   111 #endif
   113 #ifdef DTRACE_ENABLED
   115 // Only bother with this argument setup if dtrace is available
   117 #ifndef USDT2
   118 HS_DTRACE_PROBE_DECL(hotspot, vm__init__begin);
   119 HS_DTRACE_PROBE_DECL(hotspot, vm__init__end);
   120 HS_DTRACE_PROBE_DECL5(hotspot, thread__start, char*, intptr_t,
   121   intptr_t, intptr_t, bool);
   122 HS_DTRACE_PROBE_DECL5(hotspot, thread__stop, char*, intptr_t,
   123   intptr_t, intptr_t, bool);
   125 #define DTRACE_THREAD_PROBE(probe, javathread)                             \
   126   {                                                                        \
   127     ResourceMark rm(this);                                                 \
   128     int len = 0;                                                           \
   129     const char* name = (javathread)->get_thread_name();                    \
   130     len = strlen(name);                                                    \
   131     HS_DTRACE_PROBE5(hotspot, thread__##probe,                             \
   132       name, len,                                                           \
   133       java_lang_Thread::thread_id((javathread)->threadObj()),              \
   134       (javathread)->osthread()->thread_id(),                               \
   135       java_lang_Thread::is_daemon((javathread)->threadObj()));             \
   136   }
   138 #else /* USDT2 */
   140 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_PROBE_START
   141 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_PROBE_STOP
   143 #define DTRACE_THREAD_PROBE(probe, javathread)                             \
   144   {                                                                        \
   145     ResourceMark rm(this);                                                 \
   146     int len = 0;                                                           \
   147     const char* name = (javathread)->get_thread_name();                    \
   148     len = strlen(name);                                                    \
   149     HOTSPOT_THREAD_PROBE_##probe(  /* probe = start, stop */               \
   150       (char *) name, len,                                                           \
   151       java_lang_Thread::thread_id((javathread)->threadObj()),              \
   152       (uintptr_t) (javathread)->osthread()->thread_id(),                               \
   153       java_lang_Thread::is_daemon((javathread)->threadObj()));             \
   154   }
   156 #endif /* USDT2 */
   158 #else //  ndef DTRACE_ENABLED
   160 #define DTRACE_THREAD_PROBE(probe, javathread)
   162 #endif // ndef DTRACE_ENABLED
   165 // Class hierarchy
   166 // - Thread
   167 //   - VMThread
   168 //   - WatcherThread
   169 //   - ConcurrentMarkSweepThread
   170 //   - JavaThread
   171 //     - CompilerThread
   173 // ======= Thread ========
   174 // Support for forcing alignment of thread objects for biased locking
   175 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
   176   if (UseBiasedLocking) {
   177     const int alignment = markOopDesc::biased_lock_alignment;
   178     size_t aligned_size = size + (alignment - sizeof(intptr_t));
   179     void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
   180                                           : os::malloc(aligned_size, flags, CURRENT_PC);
   181     void* aligned_addr     = (void*) align_size_up((intptr_t) real_malloc_addr, alignment);
   182     assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
   183            ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
   184            "JavaThread alignment code overflowed allocated storage");
   185     if (TraceBiasedLocking) {
   186       if (aligned_addr != real_malloc_addr)
   187         tty->print_cr("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
   188                       real_malloc_addr, aligned_addr);
   189     }
   190     ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
   191     return aligned_addr;
   192   } else {
   193     return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
   194                        : os::malloc(size, flags, CURRENT_PC);
   195   }
   196 }
   198 void Thread::operator delete(void* p) {
   199   if (UseBiasedLocking) {
   200     void* real_malloc_addr = ((Thread*) p)->_real_malloc_address;
   201     FreeHeap(real_malloc_addr, mtThread);
   202   } else {
   203     FreeHeap(p, mtThread);
   204   }
   205 }
   208 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
   209 // JavaThread
   212 Thread::Thread() {
   213   // stack and get_thread
   214   set_stack_base(NULL);
   215   set_stack_size(0);
   216   set_self_raw_id(0);
   217   set_lgrp_id(-1);
   219   // allocated data structures
   220   set_osthread(NULL);
   221   set_resource_area(new (mtThread)ResourceArea());
   222   set_handle_area(new (mtThread) HandleArea(NULL));
   223   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(300, true));
   224   set_active_handles(NULL);
   225   set_free_handle_block(NULL);
   226   set_last_handle_mark(NULL);
   228   // This initial value ==> never claimed.
   229   _oops_do_parity = 0;
   231   // the handle mark links itself to last_handle_mark
   232   new HandleMark(this);
   234   // plain initialization
   235   debug_only(_owned_locks = NULL;)
   236   debug_only(_allow_allocation_count = 0;)
   237   NOT_PRODUCT(_allow_safepoint_count = 0;)
   238   NOT_PRODUCT(_skip_gcalot = false;)
   239   CHECK_UNHANDLED_OOPS_ONLY(_gc_locked_out_count = 0;)
   240   _jvmti_env_iteration_count = 0;
   241   set_allocated_bytes(0);
   242   set_trace_buffer(NULL);
   243   _vm_operation_started_count = 0;
   244   _vm_operation_completed_count = 0;
   245   _current_pending_monitor = NULL;
   246   _current_pending_monitor_is_from_java = true;
   247   _current_waiting_monitor = NULL;
   248   _num_nested_signal = 0;
   249   omFreeList = NULL ;
   250   omFreeCount = 0 ;
   251   omFreeProvision = 32 ;
   252   omInUseList = NULL ;
   253   omInUseCount = 0 ;
   255 #ifdef ASSERT
   256   _visited_for_critical_count = false;
   257 #endif
   259   _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true);
   260   _suspend_flags = 0;
   262   // thread-specific hashCode stream generator state - Marsaglia shift-xor form
   263   _hashStateX = os::random() ;
   264   _hashStateY = 842502087 ;
   265   _hashStateZ = 0x8767 ;    // (int)(3579807591LL & 0xffff) ;
   266   _hashStateW = 273326509 ;
   268   _OnTrap   = 0 ;
   269   _schedctl = NULL ;
   270   _Stalled  = 0 ;
   271   _TypeTag  = 0x2BAD ;
   273   // Many of the following fields are effectively final - immutable
   274   // Note that nascent threads can't use the Native Monitor-Mutex
   275   // construct until the _MutexEvent is initialized ...
   276   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
   277   // we might instead use a stack of ParkEvents that we could provision on-demand.
   278   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
   279   // and ::Release()
   280   _ParkEvent   = ParkEvent::Allocate (this) ;
   281   _SleepEvent  = ParkEvent::Allocate (this) ;
   282   _MutexEvent  = ParkEvent::Allocate (this) ;
   283   _MuxEvent    = ParkEvent::Allocate (this) ;
   285 #ifdef CHECK_UNHANDLED_OOPS
   286   if (CheckUnhandledOops) {
   287     _unhandled_oops = new UnhandledOops(this);
   288   }
   289 #endif // CHECK_UNHANDLED_OOPS
   290 #ifdef ASSERT
   291   if (UseBiasedLocking) {
   292     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
   293     assert(this == _real_malloc_address ||
   294            this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
   295            "bug in forced alignment of thread objects");
   296   }
   297 #endif /* ASSERT */
   298 }
   300 void Thread::initialize_thread_local_storage() {
   301   // Note: Make sure this method only calls
   302   // non-blocking operations. Otherwise, it might not work
   303   // with the thread-startup/safepoint interaction.
   305   // During Java thread startup, safepoint code should allow this
   306   // method to complete because it may need to allocate memory to
   307   // store information for the new thread.
   309   // initialize structure dependent on thread local storage
   310   ThreadLocalStorage::set_thread(this);
   311 }
   313 void Thread::record_stack_base_and_size() {
   314   set_stack_base(os::current_stack_base());
   315   set_stack_size(os::current_stack_size());
   316   // CR 7190089: on Solaris, primordial thread's stack is adjusted
   317   // in initialize_thread(). Without the adjustment, stack size is
   318   // incorrect if stack is set to unlimited (ulimit -s unlimited).
   319   // So far, only Solaris has real implementation of initialize_thread().
   320   //
   321   // set up any platform-specific state.
   322   os::initialize_thread(this);
   324    // record thread's native stack, stack grows downward
   325   if (MemTracker::is_on()) {
   326     address stack_low_addr = stack_base() - stack_size();
   327     MemTracker::record_thread_stack(stack_low_addr, stack_size(), this,
   328       CURRENT_PC);
   329   }
   330 }
   333 Thread::~Thread() {
   334   // Reclaim the objectmonitors from the omFreeList of the moribund thread.
   335   ObjectSynchronizer::omFlush (this) ;
   337   // stack_base can be NULL if the thread is never started or exited before
   338   // record_stack_base_and_size called. Although, we would like to ensure
   339   // that all started threads do call record_stack_base_and_size(), there is
   340   // not proper way to enforce that.
   341   if (_stack_base != NULL) {
   342     address low_stack_addr = stack_base() - stack_size();
   343     MemTracker::release_thread_stack(low_stack_addr, stack_size(), this);
   344   }
   346   // deallocate data structures
   347   delete resource_area();
   348   // since the handle marks are using the handle area, we have to deallocated the root
   349   // handle mark before deallocating the thread's handle area,
   350   assert(last_handle_mark() != NULL, "check we have an element");
   351   delete last_handle_mark();
   352   assert(last_handle_mark() == NULL, "check we have reached the end");
   354   // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
   355   // We NULL out the fields for good hygiene.
   356   ParkEvent::Release (_ParkEvent)   ; _ParkEvent   = NULL ;
   357   ParkEvent::Release (_SleepEvent)  ; _SleepEvent  = NULL ;
   358   ParkEvent::Release (_MutexEvent)  ; _MutexEvent  = NULL ;
   359   ParkEvent::Release (_MuxEvent)    ; _MuxEvent    = NULL ;
   361   delete handle_area();
   362   delete metadata_handles();
   364   // osthread() can be NULL, if creation of thread failed.
   365   if (osthread() != NULL) os::free_thread(osthread());
   367   delete _SR_lock;
   369   // clear thread local storage if the Thread is deleting itself
   370   if (this == Thread::current()) {
   371     ThreadLocalStorage::set_thread(NULL);
   372   } else {
   373     // In the case where we're not the current thread, invalidate all the
   374     // caches in case some code tries to get the current thread or the
   375     // thread that was destroyed, and gets stale information.
   376     ThreadLocalStorage::invalidate_all();
   377   }
   378   CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
   379 }
   381 // NOTE: dummy function for assertion purpose.
   382 void Thread::run() {
   383   ShouldNotReachHere();
   384 }
   386 #ifdef ASSERT
   387 // Private method to check for dangling thread pointer
   388 void check_for_dangling_thread_pointer(Thread *thread) {
   389  assert(!thread->is_Java_thread() || Thread::current() == thread || Threads_lock->owned_by_self(),
   390          "possibility of dangling Thread pointer");
   391 }
   392 #endif
   395 #ifndef PRODUCT
   396 // Tracing method for basic thread operations
   397 void Thread::trace(const char* msg, const Thread* const thread) {
   398   if (!TraceThreadEvents) return;
   399   ResourceMark rm;
   400   ThreadCritical tc;
   401   const char *name = "non-Java thread";
   402   int prio = -1;
   403   if (thread->is_Java_thread()
   404       && !thread->is_Compiler_thread()) {
   405     // The Threads_lock must be held to get information about
   406     // this thread but may not be in some situations when
   407     // tracing  thread events.
   408     bool release_Threads_lock = false;
   409     if (!Threads_lock->owned_by_self()) {
   410       Threads_lock->lock();
   411       release_Threads_lock = true;
   412     }
   413     JavaThread* jt = (JavaThread *)thread;
   414     name = (char *)jt->get_thread_name();
   415     oop thread_oop = jt->threadObj();
   416     if (thread_oop != NULL) {
   417       prio = java_lang_Thread::priority(thread_oop);
   418     }
   419     if (release_Threads_lock) {
   420       Threads_lock->unlock();
   421     }
   422   }
   423   tty->print_cr("Thread::%s " INTPTR_FORMAT " [%lx] %s (prio: %d)", msg, thread, thread->osthread()->thread_id(), name, prio);
   424 }
   425 #endif
   428 ThreadPriority Thread::get_priority(const Thread* const thread) {
   429   trace("get priority", thread);
   430   ThreadPriority priority;
   431   // Can return an error!
   432   (void)os::get_priority(thread, priority);
   433   assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
   434   return priority;
   435 }
   437 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
   438   trace("set priority", thread);
   439   debug_only(check_for_dangling_thread_pointer(thread);)
   440   // Can return an error!
   441   (void)os::set_priority(thread, priority);
   442 }
   445 void Thread::start(Thread* thread) {
   446   trace("start", thread);
   447   // Start is different from resume in that its safety is guaranteed by context or
   448   // being called from a Java method synchronized on the Thread object.
   449   if (!DisableStartThread) {
   450     if (thread->is_Java_thread()) {
   451       // Initialize the thread state to RUNNABLE before starting this thread.
   452       // Can not set it after the thread started because we do not know the
   453       // exact thread state at that time. It could be in MONITOR_WAIT or
   454       // in SLEEPING or some other state.
   455       java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
   456                                           java_lang_Thread::RUNNABLE);
   457     }
   458     os::start_thread(thread);
   459   }
   460 }
   462 // Enqueue a VM_Operation to do the job for us - sometime later
   463 void Thread::send_async_exception(oop java_thread, oop java_throwable) {
   464   VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
   465   VMThread::execute(vm_stop);
   466 }
   469 //
   470 // Check if an external suspend request has completed (or has been
   471 // cancelled). Returns true if the thread is externally suspended and
   472 // false otherwise.
   473 //
   474 // The bits parameter returns information about the code path through
   475 // the routine. Useful for debugging:
   476 //
   477 // set in is_ext_suspend_completed():
   478 // 0x00000001 - routine was entered
   479 // 0x00000010 - routine return false at end
   480 // 0x00000100 - thread exited (return false)
   481 // 0x00000200 - suspend request cancelled (return false)
   482 // 0x00000400 - thread suspended (return true)
   483 // 0x00001000 - thread is in a suspend equivalent state (return true)
   484 // 0x00002000 - thread is native and walkable (return true)
   485 // 0x00004000 - thread is native_trans and walkable (needed retry)
   486 //
   487 // set in wait_for_ext_suspend_completion():
   488 // 0x00010000 - routine was entered
   489 // 0x00020000 - suspend request cancelled before loop (return false)
   490 // 0x00040000 - thread suspended before loop (return true)
   491 // 0x00080000 - suspend request cancelled in loop (return false)
   492 // 0x00100000 - thread suspended in loop (return true)
   493 // 0x00200000 - suspend not completed during retry loop (return false)
   494 //
   496 // Helper class for tracing suspend wait debug bits.
   497 //
   498 // 0x00000100 indicates that the target thread exited before it could
   499 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
   500 // 0x00080000 each indicate a cancelled suspend request so they don't
   501 // count as wait failures either.
   502 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
   504 class TraceSuspendDebugBits : public StackObj {
   505  private:
   506   JavaThread * jt;
   507   bool         is_wait;
   508   bool         called_by_wait;  // meaningful when !is_wait
   509   uint32_t *   bits;
   511  public:
   512   TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
   513                         uint32_t *_bits) {
   514     jt             = _jt;
   515     is_wait        = _is_wait;
   516     called_by_wait = _called_by_wait;
   517     bits           = _bits;
   518   }
   520   ~TraceSuspendDebugBits() {
   521     if (!is_wait) {
   522 #if 1
   523       // By default, don't trace bits for is_ext_suspend_completed() calls.
   524       // That trace is very chatty.
   525       return;
   526 #else
   527       if (!called_by_wait) {
   528         // If tracing for is_ext_suspend_completed() is enabled, then only
   529         // trace calls to it from wait_for_ext_suspend_completion()
   530         return;
   531       }
   532 #endif
   533     }
   535     if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
   536       if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
   537         MutexLocker ml(Threads_lock);  // needed for get_thread_name()
   538         ResourceMark rm;
   540         tty->print_cr(
   541             "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
   542             jt->get_thread_name(), *bits);
   544         guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
   545       }
   546     }
   547   }
   548 };
   549 #undef DEBUG_FALSE_BITS
   552 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay, uint32_t *bits) {
   553   TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
   555   bool did_trans_retry = false;  // only do thread_in_native_trans retry once
   556   bool do_trans_retry;           // flag to force the retry
   558   *bits |= 0x00000001;
   560   do {
   561     do_trans_retry = false;
   563     if (is_exiting()) {
   564       // Thread is in the process of exiting. This is always checked
   565       // first to reduce the risk of dereferencing a freed JavaThread.
   566       *bits |= 0x00000100;
   567       return false;
   568     }
   570     if (!is_external_suspend()) {
   571       // Suspend request is cancelled. This is always checked before
   572       // is_ext_suspended() to reduce the risk of a rogue resume
   573       // confusing the thread that made the suspend request.
   574       *bits |= 0x00000200;
   575       return false;
   576     }
   578     if (is_ext_suspended()) {
   579       // thread is suspended
   580       *bits |= 0x00000400;
   581       return true;
   582     }
   584     // Now that we no longer do hard suspends of threads running
   585     // native code, the target thread can be changing thread state
   586     // while we are in this routine:
   587     //
   588     //   _thread_in_native -> _thread_in_native_trans -> _thread_blocked
   589     //
   590     // We save a copy of the thread state as observed at this moment
   591     // and make our decision about suspend completeness based on the
   592     // copy. This closes the race where the thread state is seen as
   593     // _thread_in_native_trans in the if-thread_blocked check, but is
   594     // seen as _thread_blocked in if-thread_in_native_trans check.
   595     JavaThreadState save_state = thread_state();
   597     if (save_state == _thread_blocked && is_suspend_equivalent()) {
   598       // If the thread's state is _thread_blocked and this blocking
   599       // condition is known to be equivalent to a suspend, then we can
   600       // consider the thread to be externally suspended. This means that
   601       // the code that sets _thread_blocked has been modified to do
   602       // self-suspension if the blocking condition releases. We also
   603       // used to check for CONDVAR_WAIT here, but that is now covered by
   604       // the _thread_blocked with self-suspension check.
   605       //
   606       // Return true since we wouldn't be here unless there was still an
   607       // external suspend request.
   608       *bits |= 0x00001000;
   609       return true;
   610     } else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
   611       // Threads running native code will self-suspend on native==>VM/Java
   612       // transitions. If its stack is walkable (should always be the case
   613       // unless this function is called before the actual java_suspend()
   614       // call), then the wait is done.
   615       *bits |= 0x00002000;
   616       return true;
   617     } else if (!called_by_wait && !did_trans_retry &&
   618                save_state == _thread_in_native_trans &&
   619                frame_anchor()->walkable()) {
   620       // The thread is transitioning from thread_in_native to another
   621       // thread state. check_safepoint_and_suspend_for_native_trans()
   622       // will force the thread to self-suspend. If it hasn't gotten
   623       // there yet we may have caught the thread in-between the native
   624       // code check above and the self-suspend. Lucky us. If we were
   625       // called by wait_for_ext_suspend_completion(), then it
   626       // will be doing the retries so we don't have to.
   627       //
   628       // Since we use the saved thread state in the if-statement above,
   629       // there is a chance that the thread has already transitioned to
   630       // _thread_blocked by the time we get here. In that case, we will
   631       // make a single unnecessary pass through the logic below. This
   632       // doesn't hurt anything since we still do the trans retry.
   634       *bits |= 0x00004000;
   636       // Once the thread leaves thread_in_native_trans for another
   637       // thread state, we break out of this retry loop. We shouldn't
   638       // need this flag to prevent us from getting back here, but
   639       // sometimes paranoia is good.
   640       did_trans_retry = true;
   642       // We wait for the thread to transition to a more usable state.
   643       for (int i = 1; i <= SuspendRetryCount; i++) {
   644         // We used to do an "os::yield_all(i)" call here with the intention
   645         // that yielding would increase on each retry. However, the parameter
   646         // is ignored on Linux which means the yield didn't scale up. Waiting
   647         // on the SR_lock below provides a much more predictable scale up for
   648         // the delay. It also provides a simple/direct point to check for any
   649         // safepoint requests from the VMThread
   651         // temporarily drops SR_lock while doing wait with safepoint check
   652         // (if we're a JavaThread - the WatcherThread can also call this)
   653         // and increase delay with each retry
   654         SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
   656         // check the actual thread state instead of what we saved above
   657         if (thread_state() != _thread_in_native_trans) {
   658           // the thread has transitioned to another thread state so
   659           // try all the checks (except this one) one more time.
   660           do_trans_retry = true;
   661           break;
   662         }
   663       } // end retry loop
   666     }
   667   } while (do_trans_retry);
   669   *bits |= 0x00000010;
   670   return false;
   671 }
   673 //
   674 // Wait for an external suspend request to complete (or be cancelled).
   675 // Returns true if the thread is externally suspended and false otherwise.
   676 //
   677 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
   678        uint32_t *bits) {
   679   TraceSuspendDebugBits tsdb(this, true /* is_wait */,
   680                              false /* !called_by_wait */, bits);
   682   // local flag copies to minimize SR_lock hold time
   683   bool is_suspended;
   684   bool pending;
   685   uint32_t reset_bits;
   687   // set a marker so is_ext_suspend_completed() knows we are the caller
   688   *bits |= 0x00010000;
   690   // We use reset_bits to reinitialize the bits value at the top of
   691   // each retry loop. This allows the caller to make use of any
   692   // unused bits for their own marking purposes.
   693   reset_bits = *bits;
   695   {
   696     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
   697     is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
   698                                             delay, bits);
   699     pending = is_external_suspend();
   700   }
   701   // must release SR_lock to allow suspension to complete
   703   if (!pending) {
   704     // A cancelled suspend request is the only false return from
   705     // is_ext_suspend_completed() that keeps us from entering the
   706     // retry loop.
   707     *bits |= 0x00020000;
   708     return false;
   709   }
   711   if (is_suspended) {
   712     *bits |= 0x00040000;
   713     return true;
   714   }
   716   for (int i = 1; i <= retries; i++) {
   717     *bits = reset_bits;  // reinit to only track last retry
   719     // We used to do an "os::yield_all(i)" call here with the intention
   720     // that yielding would increase on each retry. However, the parameter
   721     // is ignored on Linux which means the yield didn't scale up. Waiting
   722     // on the SR_lock below provides a much more predictable scale up for
   723     // the delay. It also provides a simple/direct point to check for any
   724     // safepoint requests from the VMThread
   726     {
   727       MutexLocker ml(SR_lock());
   728       // wait with safepoint check (if we're a JavaThread - the WatcherThread
   729       // can also call this)  and increase delay with each retry
   730       SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
   732       is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
   733                                               delay, bits);
   735       // It is possible for the external suspend request to be cancelled
   736       // (by a resume) before the actual suspend operation is completed.
   737       // Refresh our local copy to see if we still need to wait.
   738       pending = is_external_suspend();
   739     }
   741     if (!pending) {
   742       // A cancelled suspend request is the only false return from
   743       // is_ext_suspend_completed() that keeps us from staying in the
   744       // retry loop.
   745       *bits |= 0x00080000;
   746       return false;
   747     }
   749     if (is_suspended) {
   750       *bits |= 0x00100000;
   751       return true;
   752     }
   753   } // end retry loop
   755   // thread did not suspend after all our retries
   756   *bits |= 0x00200000;
   757   return false;
   758 }
   760 #ifndef PRODUCT
   761 void JavaThread::record_jump(address target, address instr, const char* file, int line) {
   763   // This should not need to be atomic as the only way for simultaneous
   764   // updates is via interrupts. Even then this should be rare or non-existant
   765   // and we don't care that much anyway.
   767   int index = _jmp_ring_index;
   768   _jmp_ring_index = (index + 1 ) & (jump_ring_buffer_size - 1);
   769   _jmp_ring[index]._target = (intptr_t) target;
   770   _jmp_ring[index]._instruction = (intptr_t) instr;
   771   _jmp_ring[index]._file = file;
   772   _jmp_ring[index]._line = line;
   773 }
   774 #endif /* PRODUCT */
   776 // Called by flat profiler
   777 // Callers have already called wait_for_ext_suspend_completion
   778 // The assertion for that is currently too complex to put here:
   779 bool JavaThread::profile_last_Java_frame(frame* _fr) {
   780   bool gotframe = false;
   781   // self suspension saves needed state.
   782   if (has_last_Java_frame() && _anchor.walkable()) {
   783      *_fr = pd_last_frame();
   784      gotframe = true;
   785   }
   786   return gotframe;
   787 }
   789 void Thread::interrupt(Thread* thread) {
   790   trace("interrupt", thread);
   791   debug_only(check_for_dangling_thread_pointer(thread);)
   792   os::interrupt(thread);
   793 }
   795 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) {
   796   trace("is_interrupted", thread);
   797   debug_only(check_for_dangling_thread_pointer(thread);)
   798   // Note:  If clear_interrupted==false, this simply fetches and
   799   // returns the value of the field osthread()->interrupted().
   800   return os::is_interrupted(thread, clear_interrupted);
   801 }
   804 // GC Support
   805 bool Thread::claim_oops_do_par_case(int strong_roots_parity) {
   806   jint thread_parity = _oops_do_parity;
   807   if (thread_parity != strong_roots_parity) {
   808     jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity);
   809     if (res == thread_parity) {
   810       return true;
   811     } else {
   812       guarantee(res == strong_roots_parity, "Or else what?");
   813       assert(SharedHeap::heap()->workers()->active_workers() > 0,
   814          "Should only fail when parallel.");
   815       return false;
   816     }
   817   }
   818   assert(SharedHeap::heap()->workers()->active_workers() > 0,
   819          "Should only fail when parallel.");
   820   return false;
   821 }
   823 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
   824   active_handles()->oops_do(f);
   825   // Do oop for ThreadShadow
   826   f->do_oop((oop*)&_pending_exception);
   827   handle_area()->oops_do(f);
   828 }
   830 void Thread::nmethods_do(CodeBlobClosure* cf) {
   831   // no nmethods in a generic thread...
   832 }
   834 void Thread::metadata_do(void f(Metadata*)) {
   835   if (metadata_handles() != NULL) {
   836     for (int i = 0; i< metadata_handles()->length(); i++) {
   837       f(metadata_handles()->at(i));
   838     }
   839   }
   840 }
   842 void Thread::print_on(outputStream* st) const {
   843   // get_priority assumes osthread initialized
   844   if (osthread() != NULL) {
   845     st->print("prio=%d tid=" INTPTR_FORMAT " ", get_priority(this), this);
   846     osthread()->print_on(st);
   847   }
   848   debug_only(if (WizardMode) print_owned_locks_on(st);)
   849 }
   851 // Thread::print_on_error() is called by fatal error handler. Don't use
   852 // any lock or allocate memory.
   853 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
   854   if      (is_VM_thread())                  st->print("VMThread");
   855   else if (is_Compiler_thread())            st->print("CompilerThread");
   856   else if (is_Java_thread())                st->print("JavaThread");
   857   else if (is_GC_task_thread())             st->print("GCTaskThread");
   858   else if (is_Watcher_thread())             st->print("WatcherThread");
   859   else if (is_ConcurrentGC_thread())        st->print("ConcurrentGCThread");
   860   else st->print("Thread");
   862   st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
   863             _stack_base - _stack_size, _stack_base);
   865   if (osthread()) {
   866     st->print(" [id=%d]", osthread()->thread_id());
   867   }
   868 }
   870 #ifdef ASSERT
   871 void Thread::print_owned_locks_on(outputStream* st) const {
   872   Monitor *cur = _owned_locks;
   873   if (cur == NULL) {
   874     st->print(" (no locks) ");
   875   } else {
   876     st->print_cr(" Locks owned:");
   877     while(cur) {
   878       cur->print_on(st);
   879       cur = cur->next();
   880     }
   881   }
   882 }
   884 static int ref_use_count  = 0;
   886 bool Thread::owns_locks_but_compiled_lock() const {
   887   for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
   888     if (cur != Compile_lock) return true;
   889   }
   890   return false;
   891 }
   894 #endif
   896 #ifndef PRODUCT
   898 // The flag: potential_vm_operation notifies if this particular safepoint state could potential
   899 // invoke the vm-thread (i.e., and oop allocation). In that case, we also have to make sure that
   900 // no threads which allow_vm_block's are held
   901 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
   902     // Check if current thread is allowed to block at a safepoint
   903     if (!(_allow_safepoint_count == 0))
   904       fatal("Possible safepoint reached by thread that does not allow it");
   905     if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
   906       fatal("LEAF method calling lock?");
   907     }
   909 #ifdef ASSERT
   910     if (potential_vm_operation && is_Java_thread()
   911         && !Universe::is_bootstrapping()) {
   912       // Make sure we do not hold any locks that the VM thread also uses.
   913       // This could potentially lead to deadlocks
   914       for(Monitor *cur = _owned_locks; cur; cur = cur->next()) {
   915         // Threads_lock is special, since the safepoint synchronization will not start before this is
   916         // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
   917         // since it is used to transfer control between JavaThreads and the VMThread
   918         // Do not *exclude* any locks unless you are absolutly sure it is correct. Ask someone else first!
   919         if ( (cur->allow_vm_block() &&
   920               cur != Threads_lock &&
   921               cur != Compile_lock &&               // Temporary: should not be necessary when we get spearate compilation
   922               cur != VMOperationRequest_lock &&
   923               cur != VMOperationQueue_lock) ||
   924               cur->rank() == Mutex::special) {
   925           warning("Thread holding lock at safepoint that vm can block on: %s", cur->name());
   926         }
   927       }
   928     }
   930     if (GCALotAtAllSafepoints) {
   931       // We could enter a safepoint here and thus have a gc
   932       InterfaceSupport::check_gc_alot();
   933     }
   934 #endif
   935 }
   936 #endif
   938 bool Thread::is_in_stack(address adr) const {
   939   assert(Thread::current() == this, "is_in_stack can only be called from current thread");
   940   address end = os::current_stack_pointer();
   941   // Allow non Java threads to call this without stack_base
   942   if (_stack_base == NULL) return true;
   943   if (stack_base() >= adr && adr >= end) return true;
   945   return false;
   946 }
   949 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
   950 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
   951 // used for compilation in the future. If that change is made, the need for these methods
   952 // should be revisited, and they should be removed if possible.
   954 bool Thread::is_lock_owned(address adr) const {
   955   return on_local_stack(adr);
   956 }
   958 bool Thread::set_as_starting_thread() {
   959  // NOTE: this must be called inside the main thread.
   960   return os::create_main_thread((JavaThread*)this);
   961 }
   963 static void initialize_class(Symbol* class_name, TRAPS) {
   964   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
   965   InstanceKlass::cast(klass)->initialize(CHECK);
   966 }
   969 // Creates the initial ThreadGroup
   970 static Handle create_initial_thread_group(TRAPS) {
   971   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_ThreadGroup(), true, CHECK_NH);
   972   instanceKlassHandle klass (THREAD, k);
   974   Handle system_instance = klass->allocate_instance_handle(CHECK_NH);
   975   {
   976     JavaValue result(T_VOID);
   977     JavaCalls::call_special(&result,
   978                             system_instance,
   979                             klass,
   980                             vmSymbols::object_initializer_name(),
   981                             vmSymbols::void_method_signature(),
   982                             CHECK_NH);
   983   }
   984   Universe::set_system_thread_group(system_instance());
   986   Handle main_instance = klass->allocate_instance_handle(CHECK_NH);
   987   {
   988     JavaValue result(T_VOID);
   989     Handle string = java_lang_String::create_from_str("main", CHECK_NH);
   990     JavaCalls::call_special(&result,
   991                             main_instance,
   992                             klass,
   993                             vmSymbols::object_initializer_name(),
   994                             vmSymbols::threadgroup_string_void_signature(),
   995                             system_instance,
   996                             string,
   997                             CHECK_NH);
   998   }
   999   return main_instance;
  1002 // Creates the initial Thread
  1003 static oop create_initial_thread(Handle thread_group, JavaThread* thread, TRAPS) {
  1004   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK_NULL);
  1005   instanceKlassHandle klass (THREAD, k);
  1006   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK_NULL);
  1008   java_lang_Thread::set_thread(thread_oop(), thread);
  1009   java_lang_Thread::set_priority(thread_oop(), NormPriority);
  1010   thread->set_threadObj(thread_oop());
  1012   Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
  1014   JavaValue result(T_VOID);
  1015   JavaCalls::call_special(&result, thread_oop,
  1016                                    klass,
  1017                                    vmSymbols::object_initializer_name(),
  1018                                    vmSymbols::threadgroup_string_void_signature(),
  1019                                    thread_group,
  1020                                    string,
  1021                                    CHECK_NULL);
  1022   return thread_oop();
  1025 static void call_initializeSystemClass(TRAPS) {
  1026   Klass* k =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
  1027   instanceKlassHandle klass (THREAD, k);
  1029   JavaValue result(T_VOID);
  1030   JavaCalls::call_static(&result, klass, vmSymbols::initializeSystemClass_name(),
  1031                                          vmSymbols::void_method_signature(), CHECK);
  1034 char java_runtime_name[128] = "";
  1036 // extract the JRE name from sun.misc.Version.java_runtime_name
  1037 static const char* get_java_runtime_name(TRAPS) {
  1038   Klass* k = SystemDictionary::find(vmSymbols::sun_misc_Version(),
  1039                                       Handle(), Handle(), CHECK_AND_CLEAR_NULL);
  1040   fieldDescriptor fd;
  1041   bool found = k != NULL &&
  1042                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
  1043                                                         vmSymbols::string_signature(), &fd);
  1044   if (found) {
  1045     oop name_oop = k->java_mirror()->obj_field(fd.offset());
  1046     if (name_oop == NULL)
  1047       return NULL;
  1048     const char* name = java_lang_String::as_utf8_string(name_oop,
  1049                                                         java_runtime_name,
  1050                                                         sizeof(java_runtime_name));
  1051     return name;
  1052   } else {
  1053     return NULL;
  1057 // General purpose hook into Java code, run once when the VM is initialized.
  1058 // The Java library method itself may be changed independently from the VM.
  1059 static void call_postVMInitHook(TRAPS) {
  1060   Klass* k = SystemDictionary::PostVMInitHook_klass();
  1061   instanceKlassHandle klass (THREAD, k);
  1062   if (klass.not_null()) {
  1063     JavaValue result(T_VOID);
  1064     JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
  1065                                            vmSymbols::void_method_signature(),
  1066                                            CHECK);
  1070 static void reset_vm_info_property(TRAPS) {
  1071   // the vm info string
  1072   ResourceMark rm(THREAD);
  1073   const char *vm_info = VM_Version::vm_info_string();
  1075   // java.lang.System class
  1076   Klass* k =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
  1077   instanceKlassHandle klass (THREAD, k);
  1079   // setProperty arguments
  1080   Handle key_str    = java_lang_String::create_from_str("java.vm.info", CHECK);
  1081   Handle value_str  = java_lang_String::create_from_str(vm_info, CHECK);
  1083   // return value
  1084   JavaValue r(T_OBJECT);
  1086   // public static String setProperty(String key, String value);
  1087   JavaCalls::call_static(&r,
  1088                          klass,
  1089                          vmSymbols::setProperty_name(),
  1090                          vmSymbols::string_string_string_signature(),
  1091                          key_str,
  1092                          value_str,
  1093                          CHECK);
  1097 void JavaThread::allocate_threadObj(Handle thread_group, char* thread_name, bool daemon, TRAPS) {
  1098   assert(thread_group.not_null(), "thread group should be specified");
  1099   assert(threadObj() == NULL, "should only create Java thread object once");
  1101   Klass* k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_Thread(), true, CHECK);
  1102   instanceKlassHandle klass (THREAD, k);
  1103   instanceHandle thread_oop = klass->allocate_instance_handle(CHECK);
  1105   java_lang_Thread::set_thread(thread_oop(), this);
  1106   java_lang_Thread::set_priority(thread_oop(), NormPriority);
  1107   set_threadObj(thread_oop());
  1109   JavaValue result(T_VOID);
  1110   if (thread_name != NULL) {
  1111     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
  1112     // Thread gets assigned specified name and null target
  1113     JavaCalls::call_special(&result,
  1114                             thread_oop,
  1115                             klass,
  1116                             vmSymbols::object_initializer_name(),
  1117                             vmSymbols::threadgroup_string_void_signature(),
  1118                             thread_group, // Argument 1
  1119                             name,         // Argument 2
  1120                             THREAD);
  1121   } else {
  1122     // Thread gets assigned name "Thread-nnn" and null target
  1123     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
  1124     JavaCalls::call_special(&result,
  1125                             thread_oop,
  1126                             klass,
  1127                             vmSymbols::object_initializer_name(),
  1128                             vmSymbols::threadgroup_runnable_void_signature(),
  1129                             thread_group, // Argument 1
  1130                             Handle(),     // Argument 2
  1131                             THREAD);
  1135   if (daemon) {
  1136       java_lang_Thread::set_daemon(thread_oop());
  1139   if (HAS_PENDING_EXCEPTION) {
  1140     return;
  1143   KlassHandle group(this, SystemDictionary::ThreadGroup_klass());
  1144   Handle threadObj(this, this->threadObj());
  1146   JavaCalls::call_special(&result,
  1147                          thread_group,
  1148                          group,
  1149                          vmSymbols::add_method_name(),
  1150                          vmSymbols::thread_void_signature(),
  1151                          threadObj,          // Arg 1
  1152                          THREAD);
  1157 // NamedThread --  non-JavaThread subclasses with multiple
  1158 // uniquely named instances should derive from this.
  1159 NamedThread::NamedThread() : Thread() {
  1160   _name = NULL;
  1161   _processed_thread = NULL;
  1164 NamedThread::~NamedThread() {
  1165   if (_name != NULL) {
  1166     FREE_C_HEAP_ARRAY(char, _name, mtThread);
  1167     _name = NULL;
  1171 void NamedThread::set_name(const char* format, ...) {
  1172   guarantee(_name == NULL, "Only get to set name once.");
  1173   _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
  1174   guarantee(_name != NULL, "alloc failure");
  1175   va_list ap;
  1176   va_start(ap, format);
  1177   jio_vsnprintf(_name, max_name_len, format, ap);
  1178   va_end(ap);
  1181 // ======= WatcherThread ========
  1183 // The watcher thread exists to simulate timer interrupts.  It should
  1184 // be replaced by an abstraction over whatever native support for
  1185 // timer interrupts exists on the platform.
  1187 WatcherThread* WatcherThread::_watcher_thread   = NULL;
  1188 volatile bool  WatcherThread::_should_terminate = false;
  1190 WatcherThread::WatcherThread() : Thread() {
  1191   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
  1192   if (os::create_thread(this, os::watcher_thread)) {
  1193     _watcher_thread = this;
  1195     // Set the watcher thread to the highest OS priority which should not be
  1196     // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
  1197     // is created. The only normal thread using this priority is the reference
  1198     // handler thread, which runs for very short intervals only.
  1199     // If the VMThread's priority is not lower than the WatcherThread profiling
  1200     // will be inaccurate.
  1201     os::set_priority(this, MaxPriority);
  1202     if (!DisableStartThread) {
  1203       os::start_thread(this);
  1208 void WatcherThread::run() {
  1209   assert(this == watcher_thread(), "just checking");
  1211   this->record_stack_base_and_size();
  1212   this->initialize_thread_local_storage();
  1213   this->set_active_handles(JNIHandleBlock::allocate_block());
  1214   while(!_should_terminate) {
  1215     assert(watcher_thread() == Thread::current(),  "thread consistency check");
  1216     assert(watcher_thread() == this,  "thread consistency check");
  1218     // Calculate how long it'll be until the next PeriodicTask work
  1219     // should be done, and sleep that amount of time.
  1220     size_t time_to_wait = PeriodicTask::time_to_wait();
  1222     // we expect this to timeout - we only ever get unparked when
  1223     // we should terminate
  1225       OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
  1227       jlong prev_time = os::javaTimeNanos();
  1228       for (;;) {
  1229         int res= _SleepEvent->park(time_to_wait);
  1230         if (res == OS_TIMEOUT || _should_terminate)
  1231           break;
  1232         // spurious wakeup of some kind
  1233         jlong now = os::javaTimeNanos();
  1234         time_to_wait -= (now - prev_time) / 1000000;
  1235         if (time_to_wait <= 0)
  1236           break;
  1237         prev_time = now;
  1241     if (is_error_reported()) {
  1242       // A fatal error has happened, the error handler(VMError::report_and_die)
  1243       // should abort JVM after creating an error log file. However in some
  1244       // rare cases, the error handler itself might deadlock. Here we try to
  1245       // kill JVM if the fatal error handler fails to abort in 2 minutes.
  1246       //
  1247       // This code is in WatcherThread because WatcherThread wakes up
  1248       // periodically so the fatal error handler doesn't need to do anything;
  1249       // also because the WatcherThread is less likely to crash than other
  1250       // threads.
  1252       for (;;) {
  1253         if (!ShowMessageBoxOnError
  1254          && (OnError == NULL || OnError[0] == '\0')
  1255          && Arguments::abort_hook() == NULL) {
  1256              os::sleep(this, 2 * 60 * 1000, false);
  1257              fdStream err(defaultStream::output_fd());
  1258              err.print_raw_cr("# [ timer expired, abort... ]");
  1259              // skip atexit/vm_exit/vm_abort hooks
  1260              os::die();
  1263         // Wake up 5 seconds later, the fatal handler may reset OnError or
  1264         // ShowMessageBoxOnError when it is ready to abort.
  1265         os::sleep(this, 5 * 1000, false);
  1269     PeriodicTask::real_time_tick(time_to_wait);
  1271     // If we have no more tasks left due to dynamic disenrollment,
  1272     // shut down the thread since we don't currently support dynamic enrollment
  1273     if (PeriodicTask::num_tasks() == 0) {
  1274       _should_terminate = true;
  1278   // Signal that it is terminated
  1280     MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
  1281     _watcher_thread = NULL;
  1282     Terminator_lock->notify();
  1285   // Thread destructor usually does this..
  1286   ThreadLocalStorage::set_thread(NULL);
  1289 void WatcherThread::start() {
  1290   if (watcher_thread() == NULL) {
  1291     _should_terminate = false;
  1292     // Create the single instance of WatcherThread
  1293     new WatcherThread();
  1297 void WatcherThread::stop() {
  1298   // it is ok to take late safepoints here, if needed
  1299   MutexLocker mu(Terminator_lock);
  1300   _should_terminate = true;
  1301   OrderAccess::fence();  // ensure WatcherThread sees update in main loop
  1303   Thread* watcher = watcher_thread();
  1304   if (watcher != NULL)
  1305     watcher->_SleepEvent->unpark();
  1307   while(watcher_thread() != NULL) {
  1308     // This wait should make safepoint checks, wait without a timeout,
  1309     // and wait as a suspend-equivalent condition.
  1310     //
  1311     // Note: If the FlatProfiler is running, then this thread is waiting
  1312     // for the WatcherThread to terminate and the WatcherThread, via the
  1313     // FlatProfiler task, is waiting for the external suspend request on
  1314     // this thread to complete. wait_for_ext_suspend_completion() will
  1315     // eventually timeout, but that takes time. Making this wait a
  1316     // suspend-equivalent condition solves that timeout problem.
  1317     //
  1318     Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
  1319                           Mutex::_as_suspend_equivalent_flag);
  1323 void WatcherThread::print_on(outputStream* st) const {
  1324   st->print("\"%s\" ", name());
  1325   Thread::print_on(st);
  1326   st->cr();
  1329 // ======= JavaThread ========
  1331 // A JavaThread is a normal Java thread
  1333 void JavaThread::initialize() {
  1334   // Initialize fields
  1336   // Set the claimed par_id to -1 (ie not claiming any par_ids)
  1337   set_claimed_par_id(-1);
  1339   set_saved_exception_pc(NULL);
  1340   set_threadObj(NULL);
  1341   _anchor.clear();
  1342   set_entry_point(NULL);
  1343   set_jni_functions(jni_functions());
  1344   set_callee_target(NULL);
  1345   set_vm_result(NULL);
  1346   set_vm_result_2(NULL);
  1347   set_vframe_array_head(NULL);
  1348   set_vframe_array_last(NULL);
  1349   set_deferred_locals(NULL);
  1350   set_deopt_mark(NULL);
  1351   set_deopt_nmethod(NULL);
  1352   clear_must_deopt_id();
  1353   set_monitor_chunks(NULL);
  1354   set_next(NULL);
  1355   set_thread_state(_thread_new);
  1356   set_recorder(NULL);
  1357   _terminated = _not_terminated;
  1358   _privileged_stack_top = NULL;
  1359   _array_for_gc = NULL;
  1360   _suspend_equivalent = false;
  1361   _in_deopt_handler = 0;
  1362   _doing_unsafe_access = false;
  1363   _stack_guard_state = stack_guard_unused;
  1364   _exception_oop = NULL;
  1365   _exception_pc  = 0;
  1366   _exception_handler_pc = 0;
  1367   _is_method_handle_return = 0;
  1368   _jvmti_thread_state= NULL;
  1369   _should_post_on_exceptions_flag = JNI_FALSE;
  1370   _jvmti_get_loaded_classes_closure = NULL;
  1371   _interp_only_mode    = 0;
  1372   _special_runtime_exit_condition = _no_async_condition;
  1373   _pending_async_exception = NULL;
  1374   _is_compiling = false;
  1375   _thread_stat = NULL;
  1376   _thread_stat = new ThreadStatistics();
  1377   _blocked_on_compilation = false;
  1378   _jni_active_critical = 0;
  1379   _do_not_unlock_if_synchronized = false;
  1380   _cached_monitor_info = NULL;
  1381   _parker = Parker::Allocate(this) ;
  1383 #ifndef PRODUCT
  1384   _jmp_ring_index = 0;
  1385   for (int ji = 0 ; ji < jump_ring_buffer_size ; ji++ ) {
  1386     record_jump(NULL, NULL, NULL, 0);
  1388 #endif /* PRODUCT */
  1390   set_thread_profiler(NULL);
  1391   if (FlatProfiler::is_active()) {
  1392     // This is where we would decide to either give each thread it's own profiler
  1393     // or use one global one from FlatProfiler,
  1394     // or up to some count of the number of profiled threads, etc.
  1395     ThreadProfiler* pp = new ThreadProfiler();
  1396     pp->engage();
  1397     set_thread_profiler(pp);
  1400   // Setup safepoint state info for this thread
  1401   ThreadSafepointState::create(this);
  1403   debug_only(_java_call_counter = 0);
  1405   // JVMTI PopFrame support
  1406   _popframe_condition = popframe_inactive;
  1407   _popframe_preserved_args = NULL;
  1408   _popframe_preserved_args_size = 0;
  1410   pd_initialize();
  1413 #ifndef SERIALGC
  1414 SATBMarkQueueSet JavaThread::_satb_mark_queue_set;
  1415 DirtyCardQueueSet JavaThread::_dirty_card_queue_set;
  1416 #endif // !SERIALGC
  1418 JavaThread::JavaThread(bool is_attaching_via_jni) :
  1419   Thread()
  1420 #ifndef SERIALGC
  1421   , _satb_mark_queue(&_satb_mark_queue_set),
  1422   _dirty_card_queue(&_dirty_card_queue_set)
  1423 #endif // !SERIALGC
  1425   initialize();
  1426   if (is_attaching_via_jni) {
  1427     _jni_attach_state = _attaching_via_jni;
  1428   } else {
  1429     _jni_attach_state = _not_attaching_via_jni;
  1431   assert(_deferred_card_mark.is_empty(), "Default MemRegion ctor");
  1432   _safepoint_visible = false;
  1435 bool JavaThread::reguard_stack(address cur_sp) {
  1436   if (_stack_guard_state != stack_guard_yellow_disabled) {
  1437     return true; // Stack already guarded or guard pages not needed.
  1440   if (register_stack_overflow()) {
  1441     // For those architectures which have separate register and
  1442     // memory stacks, we must check the register stack to see if
  1443     // it has overflowed.
  1444     return false;
  1447   // Java code never executes within the yellow zone: the latter is only
  1448   // there to provoke an exception during stack banging.  If java code
  1449   // is executing there, either StackShadowPages should be larger, or
  1450   // some exception code in c1, c2 or the interpreter isn't unwinding
  1451   // when it should.
  1452   guarantee(cur_sp > stack_yellow_zone_base(), "not enough space to reguard - increase StackShadowPages");
  1454   enable_stack_yellow_zone();
  1455   return true;
  1458 bool JavaThread::reguard_stack(void) {
  1459   return reguard_stack(os::current_stack_pointer());
  1463 void JavaThread::block_if_vm_exited() {
  1464   if (_terminated == _vm_exited) {
  1465     // _vm_exited is set at safepoint, and Threads_lock is never released
  1466     // we will block here forever
  1467     Threads_lock->lock_without_safepoint_check();
  1468     ShouldNotReachHere();
  1473 // Remove this ifdef when C1 is ported to the compiler interface.
  1474 static void compiler_thread_entry(JavaThread* thread, TRAPS);
  1476 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
  1477   Thread()
  1478 #ifndef SERIALGC
  1479   , _satb_mark_queue(&_satb_mark_queue_set),
  1480   _dirty_card_queue(&_dirty_card_queue_set)
  1481 #endif // !SERIALGC
  1483   if (TraceThreadEvents) {
  1484     tty->print_cr("creating thread %p", this);
  1486   initialize();
  1487   _jni_attach_state = _not_attaching_via_jni;
  1488   set_entry_point(entry_point);
  1489   // Create the native thread itself.
  1490   // %note runtime_23
  1491   os::ThreadType thr_type = os::java_thread;
  1492   thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
  1493                                                      os::java_thread;
  1494   os::create_thread(this, thr_type, stack_sz);
  1495   _safepoint_visible = false;
  1496   // The _osthread may be NULL here because we ran out of memory (too many threads active).
  1497   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
  1498   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
  1499   // the exception consists of creating the exception object & initializing it, initialization
  1500   // will leave the VM via a JavaCall and then all locks must be unlocked).
  1501   //
  1502   // The thread is still suspended when we reach here. Thread must be explicit started
  1503   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
  1504   // by calling Threads:add. The reason why this is not done here, is because the thread
  1505   // object must be fully initialized (take a look at JVM_Start)
  1508 JavaThread::~JavaThread() {
  1509   if (TraceThreadEvents) {
  1510       tty->print_cr("terminate thread %p", this);
  1513   // Info NMT that this JavaThread is exiting, its memory
  1514   // recorder should be collected
  1515   assert(!is_safepoint_visible(), "wrong state");
  1516   MemTracker::thread_exiting(this);
  1518   // JSR166 -- return the parker to the free list
  1519   Parker::Release(_parker);
  1520   _parker = NULL ;
  1522   // Free any remaining  previous UnrollBlock
  1523   vframeArray* old_array = vframe_array_last();
  1525   if (old_array != NULL) {
  1526     Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
  1527     old_array->set_unroll_block(NULL);
  1528     delete old_info;
  1529     delete old_array;
  1532   GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
  1533   if (deferred != NULL) {
  1534     // This can only happen if thread is destroyed before deoptimization occurs.
  1535     assert(deferred->length() != 0, "empty array!");
  1536     do {
  1537       jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
  1538       deferred->remove_at(0);
  1539       // individual jvmtiDeferredLocalVariableSet are CHeapObj's
  1540       delete dlv;
  1541     } while (deferred->length() != 0);
  1542     delete deferred;
  1545   // All Java related clean up happens in exit
  1546   ThreadSafepointState::destroy(this);
  1547   if (_thread_profiler != NULL) delete _thread_profiler;
  1548   if (_thread_stat != NULL) delete _thread_stat;
  1552 // The first routine called by a new Java thread
  1553 void JavaThread::run() {
  1554   // initialize thread-local alloc buffer related fields
  1555   this->initialize_tlab();
  1557   // used to test validitity of stack trace backs
  1558   this->record_base_of_stack_pointer();
  1560   // Record real stack base and size.
  1561   this->record_stack_base_and_size();
  1563   // Initialize thread local storage; set before calling MutexLocker
  1564   this->initialize_thread_local_storage();
  1566   this->create_stack_guard_pages();
  1568   this->cache_global_variables();
  1570   // Thread is now sufficient initialized to be handled by the safepoint code as being
  1571   // in the VM. Change thread state from _thread_new to _thread_in_vm
  1572   ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
  1574   assert(JavaThread::current() == this, "sanity check");
  1575   assert(!Thread::current()->owns_locks(), "sanity check");
  1577   DTRACE_THREAD_PROBE(start, this);
  1579   // This operation might block. We call that after all safepoint checks for a new thread has
  1580   // been completed.
  1581   this->set_active_handles(JNIHandleBlock::allocate_block());
  1583   if (JvmtiExport::should_post_thread_life()) {
  1584     JvmtiExport::post_thread_start(this);
  1587   EVENT_BEGIN(TraceEventThreadStart, event);
  1588   EVENT_COMMIT(event,
  1589      EVENT_SET(event, javalangthread, java_lang_Thread::thread_id(this->threadObj())));
  1591   // We call another function to do the rest so we are sure that the stack addresses used
  1592   // from there will be lower than the stack base just computed
  1593   thread_main_inner();
  1595   // Note, thread is no longer valid at this point!
  1599 void JavaThread::thread_main_inner() {
  1600   assert(JavaThread::current() == this, "sanity check");
  1601   assert(this->threadObj() != NULL, "just checking");
  1603   // Execute thread entry point unless this thread has a pending exception
  1604   // or has been stopped before starting.
  1605   // Note: Due to JVM_StopThread we can have pending exceptions already!
  1606   if (!this->has_pending_exception() &&
  1607       !java_lang_Thread::is_stillborn(this->threadObj())) {
  1609       ResourceMark rm(this);
  1610       this->set_native_thread_name(this->get_thread_name());
  1612     HandleMark hm(this);
  1613     this->entry_point()(this, this);
  1616   DTRACE_THREAD_PROBE(stop, this);
  1618   this->exit(false);
  1619   delete this;
  1623 static void ensure_join(JavaThread* thread) {
  1624   // We do not need to grap the Threads_lock, since we are operating on ourself.
  1625   Handle threadObj(thread, thread->threadObj());
  1626   assert(threadObj.not_null(), "java thread object must exist");
  1627   ObjectLocker lock(threadObj, thread);
  1628   // Ignore pending exception (ThreadDeath), since we are exiting anyway
  1629   thread->clear_pending_exception();
  1630   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
  1631   java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
  1632   // Clear the native thread instance - this makes isAlive return false and allows the join()
  1633   // to complete once we've done the notify_all below
  1634   java_lang_Thread::set_thread(threadObj(), NULL);
  1635   lock.notify_all(thread);
  1636   // Ignore pending exception (ThreadDeath), since we are exiting anyway
  1637   thread->clear_pending_exception();
  1641 // For any new cleanup additions, please check to see if they need to be applied to
  1642 // cleanup_failed_attach_current_thread as well.
  1643 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
  1644   assert(this == JavaThread::current(),  "thread consistency check");
  1645   if (!InitializeJavaLangSystem) return;
  1647   HandleMark hm(this);
  1648   Handle uncaught_exception(this, this->pending_exception());
  1649   this->clear_pending_exception();
  1650   Handle threadObj(this, this->threadObj());
  1651   assert(threadObj.not_null(), "Java thread object should be created");
  1653   if (get_thread_profiler() != NULL) {
  1654     get_thread_profiler()->disengage();
  1655     ResourceMark rm;
  1656     get_thread_profiler()->print(get_thread_name());
  1660   // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
  1662     EXCEPTION_MARK;
  1664     CLEAR_PENDING_EXCEPTION;
  1666   // FIXIT: The is_null check is only so it works better on JDK1.2 VM's. This
  1667   // has to be fixed by a runtime query method
  1668   if (!destroy_vm || JDK_Version::is_jdk12x_version()) {
  1669     // JSR-166: change call from from ThreadGroup.uncaughtException to
  1670     // java.lang.Thread.dispatchUncaughtException
  1671     if (uncaught_exception.not_null()) {
  1672       Handle group(this, java_lang_Thread::threadGroup(threadObj()));
  1674         EXCEPTION_MARK;
  1675         // Check if the method Thread.dispatchUncaughtException() exists. If so
  1676         // call it.  Otherwise we have an older library without the JSR-166 changes,
  1677         // so call ThreadGroup.uncaughtException()
  1678         KlassHandle recvrKlass(THREAD, threadObj->klass());
  1679         CallInfo callinfo;
  1680         KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
  1681         LinkResolver::resolve_virtual_call(callinfo, threadObj, recvrKlass, thread_klass,
  1682                                            vmSymbols::dispatchUncaughtException_name(),
  1683                                            vmSymbols::throwable_void_signature(),
  1684                                            KlassHandle(), false, false, THREAD);
  1685         CLEAR_PENDING_EXCEPTION;
  1686         methodHandle method = callinfo.selected_method();
  1687         if (method.not_null()) {
  1688           JavaValue result(T_VOID);
  1689           JavaCalls::call_virtual(&result,
  1690                                   threadObj, thread_klass,
  1691                                   vmSymbols::dispatchUncaughtException_name(),
  1692                                   vmSymbols::throwable_void_signature(),
  1693                                   uncaught_exception,
  1694                                   THREAD);
  1695         } else {
  1696           KlassHandle thread_group(THREAD, SystemDictionary::ThreadGroup_klass());
  1697           JavaValue result(T_VOID);
  1698           JavaCalls::call_virtual(&result,
  1699                                   group, thread_group,
  1700                                   vmSymbols::uncaughtException_name(),
  1701                                   vmSymbols::thread_throwable_void_signature(),
  1702                                   threadObj,           // Arg 1
  1703                                   uncaught_exception,  // Arg 2
  1704                                   THREAD);
  1706         if (HAS_PENDING_EXCEPTION) {
  1707           ResourceMark rm(this);
  1708           jio_fprintf(defaultStream::error_stream(),
  1709                 "\nException: %s thrown from the UncaughtExceptionHandler"
  1710                 " in thread \"%s\"\n",
  1711                 Klass::cast(pending_exception()->klass())->external_name(),
  1712                 get_thread_name());
  1713           CLEAR_PENDING_EXCEPTION;
  1718     // Called before the java thread exit since we want to read info
  1719     // from java_lang_Thread object
  1720     EVENT_BEGIN(TraceEventThreadEnd, event);
  1721     EVENT_COMMIT(event,
  1722         EVENT_SET(event, javalangthread, java_lang_Thread::thread_id(this->threadObj())));
  1724     // Call after last event on thread
  1725     EVENT_THREAD_EXIT(this);
  1727     // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
  1728     // the execution of the method. If that is not enough, then we don't really care. Thread.stop
  1729     // is deprecated anyhow.
  1730     { int count = 3;
  1731       while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
  1732         EXCEPTION_MARK;
  1733         JavaValue result(T_VOID);
  1734         KlassHandle thread_klass(THREAD, SystemDictionary::Thread_klass());
  1735         JavaCalls::call_virtual(&result,
  1736                               threadObj, thread_klass,
  1737                               vmSymbols::exit_method_name(),
  1738                               vmSymbols::void_method_signature(),
  1739                               THREAD);
  1740         CLEAR_PENDING_EXCEPTION;
  1744     // notify JVMTI
  1745     if (JvmtiExport::should_post_thread_life()) {
  1746       JvmtiExport::post_thread_end(this);
  1749     // We have notified the agents that we are exiting, before we go on,
  1750     // we must check for a pending external suspend request and honor it
  1751     // in order to not surprise the thread that made the suspend request.
  1752     while (true) {
  1754         MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  1755         if (!is_external_suspend()) {
  1756           set_terminated(_thread_exiting);
  1757           ThreadService::current_thread_exiting(this);
  1758           break;
  1760         // Implied else:
  1761         // Things get a little tricky here. We have a pending external
  1762         // suspend request, but we are holding the SR_lock so we
  1763         // can't just self-suspend. So we temporarily drop the lock
  1764         // and then self-suspend.
  1767       ThreadBlockInVM tbivm(this);
  1768       java_suspend_self();
  1770       // We're done with this suspend request, but we have to loop around
  1771       // and check again. Eventually we will get SR_lock without a pending
  1772       // external suspend request and will be able to mark ourselves as
  1773       // exiting.
  1775     // no more external suspends are allowed at this point
  1776   } else {
  1777     // before_exit() has already posted JVMTI THREAD_END events
  1780   // Notify waiters on thread object. This has to be done after exit() is called
  1781   // on the thread (if the thread is the last thread in a daemon ThreadGroup the
  1782   // group should have the destroyed bit set before waiters are notified).
  1783   ensure_join(this);
  1784   assert(!this->has_pending_exception(), "ensure_join should have cleared");
  1786   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
  1787   // held by this thread must be released.  A detach operation must only
  1788   // get here if there are no Java frames on the stack.  Therefore, any
  1789   // owned monitors at this point MUST be JNI-acquired monitors which are
  1790   // pre-inflated and in the monitor cache.
  1791   //
  1792   // ensure_join() ignores IllegalThreadStateExceptions, and so does this.
  1793   if (exit_type == jni_detach && JNIDetachReleasesMonitors) {
  1794     assert(!this->has_last_Java_frame(), "detaching with Java frames?");
  1795     ObjectSynchronizer::release_monitors_owned_by_thread(this);
  1796     assert(!this->has_pending_exception(), "release_monitors should have cleared");
  1799   // These things needs to be done while we are still a Java Thread. Make sure that thread
  1800   // is in a consistent state, in case GC happens
  1801   assert(_privileged_stack_top == NULL, "must be NULL when we get here");
  1803   if (active_handles() != NULL) {
  1804     JNIHandleBlock* block = active_handles();
  1805     set_active_handles(NULL);
  1806     JNIHandleBlock::release_block(block);
  1809   if (free_handle_block() != NULL) {
  1810     JNIHandleBlock* block = free_handle_block();
  1811     set_free_handle_block(NULL);
  1812     JNIHandleBlock::release_block(block);
  1815   // These have to be removed while this is still a valid thread.
  1816   remove_stack_guard_pages();
  1818   if (UseTLAB) {
  1819     tlab().make_parsable(true);  // retire TLAB
  1822   if (JvmtiEnv::environments_might_exist()) {
  1823     JvmtiExport::cleanup_thread(this);
  1826 #ifndef SERIALGC
  1827   // We must flush G1-related buffers before removing a thread from
  1828   // the list of active threads.
  1829   if (UseG1GC) {
  1830     flush_barrier_queues();
  1832 #endif
  1834   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
  1835   Threads::remove(this);
  1838 #ifndef SERIALGC
  1839 // Flush G1-related queues.
  1840 void JavaThread::flush_barrier_queues() {
  1841   satb_mark_queue().flush();
  1842   dirty_card_queue().flush();
  1845 void JavaThread::initialize_queues() {
  1846   assert(!SafepointSynchronize::is_at_safepoint(),
  1847          "we should not be at a safepoint");
  1849   ObjPtrQueue& satb_queue = satb_mark_queue();
  1850   SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
  1851   // The SATB queue should have been constructed with its active
  1852   // field set to false.
  1853   assert(!satb_queue.is_active(), "SATB queue should not be active");
  1854   assert(satb_queue.is_empty(), "SATB queue should be empty");
  1855   // If we are creating the thread during a marking cycle, we should
  1856   // set the active field of the SATB queue to true.
  1857   if (satb_queue_set.is_active()) {
  1858     satb_queue.set_active(true);
  1861   DirtyCardQueue& dirty_queue = dirty_card_queue();
  1862   // The dirty card queue should have been constructed with its
  1863   // active field set to true.
  1864   assert(dirty_queue.is_active(), "dirty card queue should be active");
  1866 #endif // !SERIALGC
  1868 void JavaThread::cleanup_failed_attach_current_thread() {
  1869   if (get_thread_profiler() != NULL) {
  1870     get_thread_profiler()->disengage();
  1871     ResourceMark rm;
  1872     get_thread_profiler()->print(get_thread_name());
  1875   if (active_handles() != NULL) {
  1876     JNIHandleBlock* block = active_handles();
  1877     set_active_handles(NULL);
  1878     JNIHandleBlock::release_block(block);
  1881   if (free_handle_block() != NULL) {
  1882     JNIHandleBlock* block = free_handle_block();
  1883     set_free_handle_block(NULL);
  1884     JNIHandleBlock::release_block(block);
  1887   // These have to be removed while this is still a valid thread.
  1888   remove_stack_guard_pages();
  1890   if (UseTLAB) {
  1891     tlab().make_parsable(true);  // retire TLAB, if any
  1894 #ifndef SERIALGC
  1895   if (UseG1GC) {
  1896     flush_barrier_queues();
  1898 #endif
  1900   Threads::remove(this);
  1901   delete this;
  1907 JavaThread* JavaThread::active() {
  1908   Thread* thread = ThreadLocalStorage::thread();
  1909   assert(thread != NULL, "just checking");
  1910   if (thread->is_Java_thread()) {
  1911     return (JavaThread*) thread;
  1912   } else {
  1913     assert(thread->is_VM_thread(), "this must be a vm thread");
  1914     VM_Operation* op = ((VMThread*) thread)->vm_operation();
  1915     JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
  1916     assert(ret->is_Java_thread(), "must be a Java thread");
  1917     return ret;
  1921 bool JavaThread::is_lock_owned(address adr) const {
  1922   if (Thread::is_lock_owned(adr)) return true;
  1924   for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
  1925     if (chunk->contains(adr)) return true;
  1928   return false;
  1932 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
  1933   chunk->set_next(monitor_chunks());
  1934   set_monitor_chunks(chunk);
  1937 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
  1938   guarantee(monitor_chunks() != NULL, "must be non empty");
  1939   if (monitor_chunks() == chunk) {
  1940     set_monitor_chunks(chunk->next());
  1941   } else {
  1942     MonitorChunk* prev = monitor_chunks();
  1943     while (prev->next() != chunk) prev = prev->next();
  1944     prev->set_next(chunk->next());
  1948 // JVM support.
  1950 // Note: this function shouldn't block if it's called in
  1951 // _thread_in_native_trans state (such as from
  1952 // check_special_condition_for_native_trans()).
  1953 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
  1955   if (has_last_Java_frame() && has_async_condition()) {
  1956     // If we are at a polling page safepoint (not a poll return)
  1957     // then we must defer async exception because live registers
  1958     // will be clobbered by the exception path. Poll return is
  1959     // ok because the call we a returning from already collides
  1960     // with exception handling registers and so there is no issue.
  1961     // (The exception handling path kills call result registers but
  1962     //  this is ok since the exception kills the result anyway).
  1964     if (is_at_poll_safepoint()) {
  1965       // if the code we are returning to has deoptimized we must defer
  1966       // the exception otherwise live registers get clobbered on the
  1967       // exception path before deoptimization is able to retrieve them.
  1968       //
  1969       RegisterMap map(this, false);
  1970       frame caller_fr = last_frame().sender(&map);
  1971       assert(caller_fr.is_compiled_frame(), "what?");
  1972       if (caller_fr.is_deoptimized_frame()) {
  1973         if (TraceExceptions) {
  1974           ResourceMark rm;
  1975           tty->print_cr("deferred async exception at compiled safepoint");
  1977         return;
  1982   JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
  1983   if (condition == _no_async_condition) {
  1984     // Conditions have changed since has_special_runtime_exit_condition()
  1985     // was called:
  1986     // - if we were here only because of an external suspend request,
  1987     //   then that was taken care of above (or cancelled) so we are done
  1988     // - if we were here because of another async request, then it has
  1989     //   been cleared between the has_special_runtime_exit_condition()
  1990     //   and now so again we are done
  1991     return;
  1994   // Check for pending async. exception
  1995   if (_pending_async_exception != NULL) {
  1996     // Only overwrite an already pending exception, if it is not a threadDeath.
  1997     if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
  1999       // We cannot call Exceptions::_throw(...) here because we cannot block
  2000       set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
  2002       if (TraceExceptions) {
  2003         ResourceMark rm;
  2004         tty->print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", this);
  2005         if (has_last_Java_frame() ) {
  2006           frame f = last_frame();
  2007           tty->print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", f.pc(), f.sp());
  2009         tty->print_cr(" of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name());
  2011       _pending_async_exception = NULL;
  2012       clear_has_async_exception();
  2016   if (check_unsafe_error &&
  2017       condition == _async_unsafe_access_error && !has_pending_exception()) {
  2018     condition = _no_async_condition;  // done
  2019     switch (thread_state()) {
  2020     case _thread_in_vm:
  2022         JavaThread* THREAD = this;
  2023         THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
  2025     case _thread_in_native:
  2027         ThreadInVMfromNative tiv(this);
  2028         JavaThread* THREAD = this;
  2029         THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
  2031     case _thread_in_Java:
  2033         ThreadInVMfromJava tiv(this);
  2034         JavaThread* THREAD = this;
  2035         THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
  2037     default:
  2038       ShouldNotReachHere();
  2042   assert(condition == _no_async_condition || has_pending_exception() ||
  2043          (!check_unsafe_error && condition == _async_unsafe_access_error),
  2044          "must have handled the async condition, if no exception");
  2047 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
  2048   //
  2049   // Check for pending external suspend. Internal suspend requests do
  2050   // not use handle_special_runtime_exit_condition().
  2051   // If JNIEnv proxies are allowed, don't self-suspend if the target
  2052   // thread is not the current thread. In older versions of jdbx, jdbx
  2053   // threads could call into the VM with another thread's JNIEnv so we
  2054   // can be here operating on behalf of a suspended thread (4432884).
  2055   bool do_self_suspend = is_external_suspend_with_lock();
  2056   if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) {
  2057     //
  2058     // Because thread is external suspended the safepoint code will count
  2059     // thread as at a safepoint. This can be odd because we can be here
  2060     // as _thread_in_Java which would normally transition to _thread_blocked
  2061     // at a safepoint. We would like to mark the thread as _thread_blocked
  2062     // before calling java_suspend_self like all other callers of it but
  2063     // we must then observe proper safepoint protocol. (We can't leave
  2064     // _thread_blocked with a safepoint in progress). However we can be
  2065     // here as _thread_in_native_trans so we can't use a normal transition
  2066     // constructor/destructor pair because they assert on that type of
  2067     // transition. We could do something like:
  2068     //
  2069     // JavaThreadState state = thread_state();
  2070     // set_thread_state(_thread_in_vm);
  2071     // {
  2072     //   ThreadBlockInVM tbivm(this);
  2073     //   java_suspend_self()
  2074     // }
  2075     // set_thread_state(_thread_in_vm_trans);
  2076     // if (safepoint) block;
  2077     // set_thread_state(state);
  2078     //
  2079     // but that is pretty messy. Instead we just go with the way the
  2080     // code has worked before and note that this is the only path to
  2081     // java_suspend_self that doesn't put the thread in _thread_blocked
  2082     // mode.
  2084     frame_anchor()->make_walkable(this);
  2085     java_suspend_self();
  2087     // We might be here for reasons in addition to the self-suspend request
  2088     // so check for other async requests.
  2091   if (check_asyncs) {
  2092     check_and_handle_async_exceptions();
  2096 void JavaThread::send_thread_stop(oop java_throwable)  {
  2097   assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
  2098   assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
  2099   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
  2101   // Do not throw asynchronous exceptions against the compiler thread
  2102   // (the compiler thread should not be a Java thread -- fix in 1.4.2)
  2103   if (is_Compiler_thread()) return;
  2106     // Actually throw the Throwable against the target Thread - however
  2107     // only if there is no thread death exception installed already.
  2108     if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
  2109       // If the topmost frame is a runtime stub, then we are calling into
  2110       // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
  2111       // must deoptimize the caller before continuing, as the compiled  exception handler table
  2112       // may not be valid
  2113       if (has_last_Java_frame()) {
  2114         frame f = last_frame();
  2115         if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
  2116           // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
  2117           RegisterMap reg_map(this, UseBiasedLocking);
  2118           frame compiled_frame = f.sender(&reg_map);
  2119           if (compiled_frame.can_be_deoptimized()) {
  2120             Deoptimization::deoptimize(this, compiled_frame, &reg_map);
  2125       // Set async. pending exception in thread.
  2126       set_pending_async_exception(java_throwable);
  2128       if (TraceExceptions) {
  2129        ResourceMark rm;
  2130        tty->print_cr("Pending Async. exception installed of type: %s", InstanceKlass::cast(_pending_async_exception->klass())->external_name());
  2132       // for AbortVMOnException flag
  2133       NOT_PRODUCT(Exceptions::debug_check_abort(InstanceKlass::cast(_pending_async_exception->klass())->external_name()));
  2138   // Interrupt thread so it will wake up from a potential wait()
  2139   Thread::interrupt(this);
  2142 // External suspension mechanism.
  2143 //
  2144 // Tell the VM to suspend a thread when ever it knows that it does not hold on
  2145 // to any VM_locks and it is at a transition
  2146 // Self-suspension will happen on the transition out of the vm.
  2147 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
  2148 //
  2149 // Guarantees on return:
  2150 //   + Target thread will not execute any new bytecode (that's why we need to
  2151 //     force a safepoint)
  2152 //   + Target thread will not enter any new monitors
  2153 //
  2154 void JavaThread::java_suspend() {
  2155   { MutexLocker mu(Threads_lock);
  2156     if (!Threads::includes(this) || is_exiting() || this->threadObj() == NULL) {
  2157        return;
  2161   { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2162     if (!is_external_suspend()) {
  2163       // a racing resume has cancelled us; bail out now
  2164       return;
  2167     // suspend is done
  2168     uint32_t debug_bits = 0;
  2169     // Warning: is_ext_suspend_completed() may temporarily drop the
  2170     // SR_lock to allow the thread to reach a stable thread state if
  2171     // it is currently in a transient thread state.
  2172     if (is_ext_suspend_completed(false /* !called_by_wait */,
  2173                                  SuspendRetryDelay, &debug_bits) ) {
  2174       return;
  2178   VM_ForceSafepoint vm_suspend;
  2179   VMThread::execute(&vm_suspend);
  2182 // Part II of external suspension.
  2183 // A JavaThread self suspends when it detects a pending external suspend
  2184 // request. This is usually on transitions. It is also done in places
  2185 // where continuing to the next transition would surprise the caller,
  2186 // e.g., monitor entry.
  2187 //
  2188 // Returns the number of times that the thread self-suspended.
  2189 //
  2190 // Note: DO NOT call java_suspend_self() when you just want to block current
  2191 //       thread. java_suspend_self() is the second stage of cooperative
  2192 //       suspension for external suspend requests and should only be used
  2193 //       to complete an external suspend request.
  2194 //
  2195 int JavaThread::java_suspend_self() {
  2196   int ret = 0;
  2198   // we are in the process of exiting so don't suspend
  2199   if (is_exiting()) {
  2200      clear_external_suspend();
  2201      return ret;
  2204   assert(_anchor.walkable() ||
  2205     (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
  2206     "must have walkable stack");
  2208   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2210   assert(!this->is_ext_suspended(),
  2211     "a thread trying to self-suspend should not already be suspended");
  2213   if (this->is_suspend_equivalent()) {
  2214     // If we are self-suspending as a result of the lifting of a
  2215     // suspend equivalent condition, then the suspend_equivalent
  2216     // flag is not cleared until we set the ext_suspended flag so
  2217     // that wait_for_ext_suspend_completion() returns consistent
  2218     // results.
  2219     this->clear_suspend_equivalent();
  2222   // A racing resume may have cancelled us before we grabbed SR_lock
  2223   // above. Or another external suspend request could be waiting for us
  2224   // by the time we return from SR_lock()->wait(). The thread
  2225   // that requested the suspension may already be trying to walk our
  2226   // stack and if we return now, we can change the stack out from under
  2227   // it. This would be a "bad thing (TM)" and cause the stack walker
  2228   // to crash. We stay self-suspended until there are no more pending
  2229   // external suspend requests.
  2230   while (is_external_suspend()) {
  2231     ret++;
  2232     this->set_ext_suspended();
  2234     // _ext_suspended flag is cleared by java_resume()
  2235     while (is_ext_suspended()) {
  2236       this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
  2240   return ret;
  2243 #ifdef ASSERT
  2244 // verify the JavaThread has not yet been published in the Threads::list, and
  2245 // hence doesn't need protection from concurrent access at this stage
  2246 void JavaThread::verify_not_published() {
  2247   if (!Threads_lock->owned_by_self()) {
  2248    MutexLockerEx ml(Threads_lock,  Mutex::_no_safepoint_check_flag);
  2249    assert( !Threads::includes(this),
  2250            "java thread shouldn't have been published yet!");
  2252   else {
  2253    assert( !Threads::includes(this),
  2254            "java thread shouldn't have been published yet!");
  2257 #endif
  2259 // Slow path when the native==>VM/Java barriers detect a safepoint is in
  2260 // progress or when _suspend_flags is non-zero.
  2261 // Current thread needs to self-suspend if there is a suspend request and/or
  2262 // block if a safepoint is in progress.
  2263 // Async exception ISN'T checked.
  2264 // Note only the ThreadInVMfromNative transition can call this function
  2265 // directly and when thread state is _thread_in_native_trans
  2266 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
  2267   assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
  2269   JavaThread *curJT = JavaThread::current();
  2270   bool do_self_suspend = thread->is_external_suspend();
  2272   assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
  2274   // If JNIEnv proxies are allowed, don't self-suspend if the target
  2275   // thread is not the current thread. In older versions of jdbx, jdbx
  2276   // threads could call into the VM with another thread's JNIEnv so we
  2277   // can be here operating on behalf of a suspended thread (4432884).
  2278   if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) {
  2279     JavaThreadState state = thread->thread_state();
  2281     // We mark this thread_blocked state as a suspend-equivalent so
  2282     // that a caller to is_ext_suspend_completed() won't be confused.
  2283     // The suspend-equivalent state is cleared by java_suspend_self().
  2284     thread->set_suspend_equivalent();
  2286     // If the safepoint code sees the _thread_in_native_trans state, it will
  2287     // wait until the thread changes to other thread state. There is no
  2288     // guarantee on how soon we can obtain the SR_lock and complete the
  2289     // self-suspend request. It would be a bad idea to let safepoint wait for
  2290     // too long. Temporarily change the state to _thread_blocked to
  2291     // let the VM thread know that this thread is ready for GC. The problem
  2292     // of changing thread state is that safepoint could happen just after
  2293     // java_suspend_self() returns after being resumed, and VM thread will
  2294     // see the _thread_blocked state. We must check for safepoint
  2295     // after restoring the state and make sure we won't leave while a safepoint
  2296     // is in progress.
  2297     thread->set_thread_state(_thread_blocked);
  2298     thread->java_suspend_self();
  2299     thread->set_thread_state(state);
  2300     // Make sure new state is seen by VM thread
  2301     if (os::is_MP()) {
  2302       if (UseMembar) {
  2303         // Force a fence between the write above and read below
  2304         OrderAccess::fence();
  2305       } else {
  2306         // Must use this rather than serialization page in particular on Windows
  2307         InterfaceSupport::serialize_memory(thread);
  2312   if (SafepointSynchronize::do_call_back()) {
  2313     // If we are safepointing, then block the caller which may not be
  2314     // the same as the target thread (see above).
  2315     SafepointSynchronize::block(curJT);
  2318   if (thread->is_deopt_suspend()) {
  2319     thread->clear_deopt_suspend();
  2320     RegisterMap map(thread, false);
  2321     frame f = thread->last_frame();
  2322     while ( f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
  2323       f = f.sender(&map);
  2325     if (f.id() == thread->must_deopt_id()) {
  2326       thread->clear_must_deopt_id();
  2327       f.deoptimize(thread);
  2328     } else {
  2329       fatal("missed deoptimization!");
  2334 // Slow path when the native==>VM/Java barriers detect a safepoint is in
  2335 // progress or when _suspend_flags is non-zero.
  2336 // Current thread needs to self-suspend if there is a suspend request and/or
  2337 // block if a safepoint is in progress.
  2338 // Also check for pending async exception (not including unsafe access error).
  2339 // Note only the native==>VM/Java barriers can call this function and when
  2340 // thread state is _thread_in_native_trans.
  2341 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
  2342   check_safepoint_and_suspend_for_native_trans(thread);
  2344   if (thread->has_async_exception()) {
  2345     // We are in _thread_in_native_trans state, don't handle unsafe
  2346     // access error since that may block.
  2347     thread->check_and_handle_async_exceptions(false);
  2351 // This is a variant of the normal
  2352 // check_special_condition_for_native_trans with slightly different
  2353 // semantics for use by critical native wrappers.  It does all the
  2354 // normal checks but also performs the transition back into
  2355 // thread_in_Java state.  This is required so that critical natives
  2356 // can potentially block and perform a GC if they are the last thread
  2357 // exiting the GC_locker.
  2358 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) {
  2359   check_special_condition_for_native_trans(thread);
  2361   // Finish the transition
  2362   thread->set_thread_state(_thread_in_Java);
  2364   if (thread->do_critical_native_unlock()) {
  2365     ThreadInVMfromJavaNoAsyncException tiv(thread);
  2366     GC_locker::unlock_critical(thread);
  2367     thread->clear_critical_native_unlock();
  2371 // We need to guarantee the Threads_lock here, since resumes are not
  2372 // allowed during safepoint synchronization
  2373 // Can only resume from an external suspension
  2374 void JavaThread::java_resume() {
  2375   assert_locked_or_safepoint(Threads_lock);
  2377   // Sanity check: thread is gone, has started exiting or the thread
  2378   // was not externally suspended.
  2379   if (!Threads::includes(this) || is_exiting() || !is_external_suspend()) {
  2380     return;
  2383   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
  2385   clear_external_suspend();
  2387   if (is_ext_suspended()) {
  2388     clear_ext_suspended();
  2389     SR_lock()->notify_all();
  2393 void JavaThread::create_stack_guard_pages() {
  2394   if (! os::uses_stack_guard_pages() || _stack_guard_state != stack_guard_unused) return;
  2395   address low_addr = stack_base() - stack_size();
  2396   size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
  2398   int allocate = os::allocate_stack_guard_pages();
  2399   // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
  2401   if (allocate && !os::create_stack_guard_pages((char *) low_addr, len)) {
  2402     warning("Attempt to allocate stack guard pages failed.");
  2403     return;
  2406   if (os::guard_memory((char *) low_addr, len)) {
  2407     _stack_guard_state = stack_guard_enabled;
  2408   } else {
  2409     warning("Attempt to protect stack guard pages failed.");
  2410     if (os::uncommit_memory((char *) low_addr, len)) {
  2411       warning("Attempt to deallocate stack guard pages failed.");
  2416 void JavaThread::remove_stack_guard_pages() {
  2417   if (_stack_guard_state == stack_guard_unused) return;
  2418   address low_addr = stack_base() - stack_size();
  2419   size_t len = (StackYellowPages + StackRedPages) * os::vm_page_size();
  2421   if (os::allocate_stack_guard_pages()) {
  2422     if (os::remove_stack_guard_pages((char *) low_addr, len)) {
  2423       _stack_guard_state = stack_guard_unused;
  2424     } else {
  2425       warning("Attempt to deallocate stack guard pages failed.");
  2427   } else {
  2428     if (_stack_guard_state == stack_guard_unused) return;
  2429     if (os::unguard_memory((char *) low_addr, len)) {
  2430       _stack_guard_state = stack_guard_unused;
  2431     } else {
  2432         warning("Attempt to unprotect stack guard pages failed.");
  2437 void JavaThread::enable_stack_yellow_zone() {
  2438   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
  2439   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
  2441   // The base notation is from the stacks point of view, growing downward.
  2442   // We need to adjust it to work correctly with guard_memory()
  2443   address base = stack_yellow_zone_base() - stack_yellow_zone_size();
  2445   guarantee(base < stack_base(),"Error calculating stack yellow zone");
  2446   guarantee(base < os::current_stack_pointer(),"Error calculating stack yellow zone");
  2448   if (os::guard_memory((char *) base, stack_yellow_zone_size())) {
  2449     _stack_guard_state = stack_guard_enabled;
  2450   } else {
  2451     warning("Attempt to guard stack yellow zone failed.");
  2453   enable_register_stack_guard();
  2456 void JavaThread::disable_stack_yellow_zone() {
  2457   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
  2458   assert(_stack_guard_state != stack_guard_yellow_disabled, "already disabled");
  2460   // Simply return if called for a thread that does not use guard pages.
  2461   if (_stack_guard_state == stack_guard_unused) return;
  2463   // The base notation is from the stacks point of view, growing downward.
  2464   // We need to adjust it to work correctly with guard_memory()
  2465   address base = stack_yellow_zone_base() - stack_yellow_zone_size();
  2467   if (os::unguard_memory((char *)base, stack_yellow_zone_size())) {
  2468     _stack_guard_state = stack_guard_yellow_disabled;
  2469   } else {
  2470     warning("Attempt to unguard stack yellow zone failed.");
  2472   disable_register_stack_guard();
  2475 void JavaThread::enable_stack_red_zone() {
  2476   // The base notation is from the stacks point of view, growing downward.
  2477   // We need to adjust it to work correctly with guard_memory()
  2478   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
  2479   address base = stack_red_zone_base() - stack_red_zone_size();
  2481   guarantee(base < stack_base(),"Error calculating stack red zone");
  2482   guarantee(base < os::current_stack_pointer(),"Error calculating stack red zone");
  2484   if(!os::guard_memory((char *) base, stack_red_zone_size())) {
  2485     warning("Attempt to guard stack red zone failed.");
  2489 void JavaThread::disable_stack_red_zone() {
  2490   // The base notation is from the stacks point of view, growing downward.
  2491   // We need to adjust it to work correctly with guard_memory()
  2492   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
  2493   address base = stack_red_zone_base() - stack_red_zone_size();
  2494   if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
  2495     warning("Attempt to unguard stack red zone failed.");
  2499 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
  2500   // ignore is there is no stack
  2501   if (!has_last_Java_frame()) return;
  2502   // traverse the stack frames. Starts from top frame.
  2503   for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2504     frame* fr = fst.current();
  2505     f(fr, fst.register_map());
  2510 #ifndef PRODUCT
  2511 // Deoptimization
  2512 // Function for testing deoptimization
  2513 void JavaThread::deoptimize() {
  2514   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
  2515   StackFrameStream fst(this, UseBiasedLocking);
  2516   bool deopt = false;           // Dump stack only if a deopt actually happens.
  2517   bool only_at = strlen(DeoptimizeOnlyAt) > 0;
  2518   // Iterate over all frames in the thread and deoptimize
  2519   for(; !fst.is_done(); fst.next()) {
  2520     if(fst.current()->can_be_deoptimized()) {
  2522       if (only_at) {
  2523         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
  2524         // consists of comma or carriage return separated numbers so
  2525         // search for the current bci in that string.
  2526         address pc = fst.current()->pc();
  2527         nmethod* nm =  (nmethod*) fst.current()->cb();
  2528         ScopeDesc* sd = nm->scope_desc_at( pc);
  2529         char buffer[8];
  2530         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
  2531         size_t len = strlen(buffer);
  2532         const char * found = strstr(DeoptimizeOnlyAt, buffer);
  2533         while (found != NULL) {
  2534           if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
  2535               (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
  2536             // Check that the bci found is bracketed by terminators.
  2537             break;
  2539           found = strstr(found + 1, buffer);
  2541         if (!found) {
  2542           continue;
  2546       if (DebugDeoptimization && !deopt) {
  2547         deopt = true; // One-time only print before deopt
  2548         tty->print_cr("[BEFORE Deoptimization]");
  2549         trace_frames();
  2550         trace_stack();
  2552       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
  2556   if (DebugDeoptimization && deopt) {
  2557     tty->print_cr("[AFTER Deoptimization]");
  2558     trace_frames();
  2563 // Make zombies
  2564 void JavaThread::make_zombies() {
  2565   for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2566     if (fst.current()->can_be_deoptimized()) {
  2567       // it is a Java nmethod
  2568       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
  2569       nm->make_not_entrant();
  2573 #endif // PRODUCT
  2576 void JavaThread::deoptimized_wrt_marked_nmethods() {
  2577   if (!has_last_Java_frame()) return;
  2578   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
  2579   StackFrameStream fst(this, UseBiasedLocking);
  2580   for(; !fst.is_done(); fst.next()) {
  2581     if (fst.current()->should_be_deoptimized()) {
  2582       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
  2588 // GC support
  2589 static void frame_gc_epilogue(frame* f, const RegisterMap* map) { f->gc_epilogue(); }
  2591 void JavaThread::gc_epilogue() {
  2592   frames_do(frame_gc_epilogue);
  2596 static void frame_gc_prologue(frame* f, const RegisterMap* map) { f->gc_prologue(); }
  2598 void JavaThread::gc_prologue() {
  2599   frames_do(frame_gc_prologue);
  2602 // If the caller is a NamedThread, then remember, in the current scope,
  2603 // the given JavaThread in its _processed_thread field.
  2604 class RememberProcessedThread: public StackObj {
  2605   NamedThread* _cur_thr;
  2606 public:
  2607   RememberProcessedThread(JavaThread* jthr) {
  2608     Thread* thread = Thread::current();
  2609     if (thread->is_Named_thread()) {
  2610       _cur_thr = (NamedThread *)thread;
  2611       _cur_thr->set_processed_thread(jthr);
  2612     } else {
  2613       _cur_thr = NULL;
  2617   ~RememberProcessedThread() {
  2618     if (_cur_thr) {
  2619       _cur_thr->set_processed_thread(NULL);
  2622 };
  2624 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
  2625   // Verify that the deferred card marks have been flushed.
  2626   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
  2628   // The ThreadProfiler oops_do is done from FlatProfiler::oops_do
  2629   // since there may be more than one thread using each ThreadProfiler.
  2631   // Traverse the GCHandles
  2632   Thread::oops_do(f, cf);
  2634   assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
  2635           (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
  2637   if (has_last_Java_frame()) {
  2638     // Record JavaThread to GC thread
  2639     RememberProcessedThread rpt(this);
  2641     // Traverse the privileged stack
  2642     if (_privileged_stack_top != NULL) {
  2643       _privileged_stack_top->oops_do(f);
  2646     // traverse the registered growable array
  2647     if (_array_for_gc != NULL) {
  2648       for (int index = 0; index < _array_for_gc->length(); index++) {
  2649         f->do_oop(_array_for_gc->adr_at(index));
  2653     // Traverse the monitor chunks
  2654     for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
  2655       chunk->oops_do(f);
  2658     // Traverse the execution stack
  2659     for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2660       fst.current()->oops_do(f, cf, fst.register_map());
  2664   // callee_target is never live across a gc point so NULL it here should
  2665   // it still contain a methdOop.
  2667   set_callee_target(NULL);
  2669   assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
  2670   // If we have deferred set_locals there might be oops waiting to be
  2671   // written
  2672   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
  2673   if (list != NULL) {
  2674     for (int i = 0; i < list->length(); i++) {
  2675       list->at(i)->oops_do(f);
  2679   // Traverse instance variables at the end since the GC may be moving things
  2680   // around using this function
  2681   f->do_oop((oop*) &_threadObj);
  2682   f->do_oop((oop*) &_vm_result);
  2683   f->do_oop((oop*) &_exception_oop);
  2684   f->do_oop((oop*) &_pending_async_exception);
  2686   if (jvmti_thread_state() != NULL) {
  2687     jvmti_thread_state()->oops_do(f);
  2691 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
  2692   Thread::nmethods_do(cf);  // (super method is a no-op)
  2694   assert( (!has_last_Java_frame() && java_call_counter() == 0) ||
  2695           (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
  2697   if (has_last_Java_frame()) {
  2698     // Traverse the execution stack
  2699     for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2700       fst.current()->nmethods_do(cf);
  2705 void JavaThread::metadata_do(void f(Metadata*)) {
  2706   Thread::metadata_do(f);
  2707   if (has_last_Java_frame()) {
  2708     // Traverse the execution stack to call f() on the methods in the stack
  2709     for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  2710       fst.current()->metadata_do(f);
  2712   } else if (is_Compiler_thread()) {
  2713     // need to walk ciMetadata in current compile tasks to keep alive.
  2714     CompilerThread* ct = (CompilerThread*)this;
  2715     if (ct->env() != NULL) {
  2716       ct->env()->metadata_do(f);
  2721 // Printing
  2722 const char* _get_thread_state_name(JavaThreadState _thread_state) {
  2723   switch (_thread_state) {
  2724   case _thread_uninitialized:     return "_thread_uninitialized";
  2725   case _thread_new:               return "_thread_new";
  2726   case _thread_new_trans:         return "_thread_new_trans";
  2727   case _thread_in_native:         return "_thread_in_native";
  2728   case _thread_in_native_trans:   return "_thread_in_native_trans";
  2729   case _thread_in_vm:             return "_thread_in_vm";
  2730   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
  2731   case _thread_in_Java:           return "_thread_in_Java";
  2732   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
  2733   case _thread_blocked:           return "_thread_blocked";
  2734   case _thread_blocked_trans:     return "_thread_blocked_trans";
  2735   default:                        return "unknown thread state";
  2739 #ifndef PRODUCT
  2740 void JavaThread::print_thread_state_on(outputStream *st) const {
  2741   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
  2742 };
  2743 void JavaThread::print_thread_state() const {
  2744   print_thread_state_on(tty);
  2745 };
  2746 #endif // PRODUCT
  2748 // Called by Threads::print() for VM_PrintThreads operation
  2749 void JavaThread::print_on(outputStream *st) const {
  2750   st->print("\"%s\" ", get_thread_name());
  2751   oop thread_oop = threadObj();
  2752   if (thread_oop != NULL && java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
  2753   Thread::print_on(st);
  2754   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
  2755   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
  2756   if (thread_oop != NULL && JDK_Version::is_gte_jdk15x_version()) {
  2757     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
  2759 #ifndef PRODUCT
  2760   print_thread_state_on(st);
  2761   _safepoint_state->print_on(st);
  2762 #endif // PRODUCT
  2765 // Called by fatal error handler. The difference between this and
  2766 // JavaThread::print() is that we can't grab lock or allocate memory.
  2767 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
  2768   st->print("JavaThread \"%s\"",  get_thread_name_string(buf, buflen));
  2769   oop thread_obj = threadObj();
  2770   if (thread_obj != NULL) {
  2771      if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
  2773   st->print(" [");
  2774   st->print("%s", _get_thread_state_name(_thread_state));
  2775   if (osthread()) {
  2776     st->print(", id=%d", osthread()->thread_id());
  2778   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
  2779             _stack_base - _stack_size, _stack_base);
  2780   st->print("]");
  2781   return;
  2784 // Verification
  2786 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
  2788 void JavaThread::verify() {
  2789   // Verify oops in the thread.
  2790   oops_do(&VerifyOopClosure::verify_oop, NULL);
  2792   // Verify the stack frames.
  2793   frames_do(frame_verify);
  2796 // CR 6300358 (sub-CR 2137150)
  2797 // Most callers of this method assume that it can't return NULL but a
  2798 // thread may not have a name whilst it is in the process of attaching to
  2799 // the VM - see CR 6412693, and there are places where a JavaThread can be
  2800 // seen prior to having it's threadObj set (eg JNI attaching threads and
  2801 // if vm exit occurs during initialization). These cases can all be accounted
  2802 // for such that this method never returns NULL.
  2803 const char* JavaThread::get_thread_name() const {
  2804 #ifdef ASSERT
  2805   // early safepoints can hit while current thread does not yet have TLS
  2806   if (!SafepointSynchronize::is_at_safepoint()) {
  2807     Thread *cur = Thread::current();
  2808     if (!(cur->is_Java_thread() && cur == this)) {
  2809       // Current JavaThreads are allowed to get their own name without
  2810       // the Threads_lock.
  2811       assert_locked_or_safepoint(Threads_lock);
  2814 #endif // ASSERT
  2815     return get_thread_name_string();
  2818 // Returns a non-NULL representation of this thread's name, or a suitable
  2819 // descriptive string if there is no set name
  2820 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
  2821   const char* name_str;
  2822   oop thread_obj = threadObj();
  2823   if (thread_obj != NULL) {
  2824     typeArrayOop name = java_lang_Thread::name(thread_obj);
  2825     if (name != NULL) {
  2826       if (buf == NULL) {
  2827         name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
  2829       else {
  2830         name_str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length(), buf, buflen);
  2833     else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
  2834       name_str = "<no-name - thread is attaching>";
  2836     else {
  2837       name_str = Thread::name();
  2840   else {
  2841     name_str = Thread::name();
  2843   assert(name_str != NULL, "unexpected NULL thread name");
  2844   return name_str;
  2848 const char* JavaThread::get_threadgroup_name() const {
  2849   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
  2850   oop thread_obj = threadObj();
  2851   if (thread_obj != NULL) {
  2852     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
  2853     if (thread_group != NULL) {
  2854       typeArrayOop name = java_lang_ThreadGroup::name(thread_group);
  2855       // ThreadGroup.name can be null
  2856       if (name != NULL) {
  2857         const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
  2858         return str;
  2862   return NULL;
  2865 const char* JavaThread::get_parent_name() const {
  2866   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
  2867   oop thread_obj = threadObj();
  2868   if (thread_obj != NULL) {
  2869     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
  2870     if (thread_group != NULL) {
  2871       oop parent = java_lang_ThreadGroup::parent(thread_group);
  2872       if (parent != NULL) {
  2873         typeArrayOop name = java_lang_ThreadGroup::name(parent);
  2874         // ThreadGroup.name can be null
  2875         if (name != NULL) {
  2876           const char* str = UNICODE::as_utf8((jchar*) name->base(T_CHAR), name->length());
  2877           return str;
  2882   return NULL;
  2885 ThreadPriority JavaThread::java_priority() const {
  2886   oop thr_oop = threadObj();
  2887   if (thr_oop == NULL) return NormPriority; // Bootstrapping
  2888   ThreadPriority priority = java_lang_Thread::priority(thr_oop);
  2889   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
  2890   return priority;
  2893 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
  2895   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
  2896   // Link Java Thread object <-> C++ Thread
  2898   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
  2899   // and put it into a new Handle.  The Handle "thread_oop" can then
  2900   // be used to pass the C++ thread object to other methods.
  2902   // Set the Java level thread object (jthread) field of the
  2903   // new thread (a JavaThread *) to C++ thread object using the
  2904   // "thread_oop" handle.
  2906   // Set the thread field (a JavaThread *) of the
  2907   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
  2909   Handle thread_oop(Thread::current(),
  2910                     JNIHandles::resolve_non_null(jni_thread));
  2911   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
  2912     "must be initialized");
  2913   set_threadObj(thread_oop());
  2914   java_lang_Thread::set_thread(thread_oop(), this);
  2916   if (prio == NoPriority) {
  2917     prio = java_lang_Thread::priority(thread_oop());
  2918     assert(prio != NoPriority, "A valid priority should be present");
  2921   // Push the Java priority down to the native thread; needs Threads_lock
  2922   Thread::set_priority(this, prio);
  2924   // Add the new thread to the Threads list and set it in motion.
  2925   // We must have threads lock in order to call Threads::add.
  2926   // It is crucial that we do not block before the thread is
  2927   // added to the Threads list for if a GC happens, then the java_thread oop
  2928   // will not be visited by GC.
  2929   Threads::add(this);
  2932 oop JavaThread::current_park_blocker() {
  2933   // Support for JSR-166 locks
  2934   oop thread_oop = threadObj();
  2935   if (thread_oop != NULL &&
  2936       JDK_Version::current().supports_thread_park_blocker()) {
  2937     return java_lang_Thread::park_blocker(thread_oop);
  2939   return NULL;
  2943 void JavaThread::print_stack_on(outputStream* st) {
  2944   if (!has_last_Java_frame()) return;
  2945   ResourceMark rm;
  2946   HandleMark   hm;
  2948   RegisterMap reg_map(this);
  2949   vframe* start_vf = last_java_vframe(&reg_map);
  2950   int count = 0;
  2951   for (vframe* f = start_vf; f; f = f->sender() ) {
  2952     if (f->is_java_frame()) {
  2953       javaVFrame* jvf = javaVFrame::cast(f);
  2954       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
  2956       // Print out lock information
  2957       if (JavaMonitorsInStackTrace) {
  2958         jvf->print_lock_info_on(st, count);
  2960     } else {
  2961       // Ignore non-Java frames
  2964     // Bail-out case for too deep stacks
  2965     count++;
  2966     if (MaxJavaStackTraceDepth == count) return;
  2971 // JVMTI PopFrame support
  2972 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
  2973   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
  2974   if (in_bytes(size_in_bytes) != 0) {
  2975     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
  2976     _popframe_preserved_args_size = in_bytes(size_in_bytes);
  2977     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
  2981 void* JavaThread::popframe_preserved_args() {
  2982   return _popframe_preserved_args;
  2985 ByteSize JavaThread::popframe_preserved_args_size() {
  2986   return in_ByteSize(_popframe_preserved_args_size);
  2989 WordSize JavaThread::popframe_preserved_args_size_in_words() {
  2990   int sz = in_bytes(popframe_preserved_args_size());
  2991   assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
  2992   return in_WordSize(sz / wordSize);
  2995 void JavaThread::popframe_free_preserved_args() {
  2996   assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
  2997   FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args, mtThread);
  2998   _popframe_preserved_args = NULL;
  2999   _popframe_preserved_args_size = 0;
  3002 #ifndef PRODUCT
  3004 void JavaThread::trace_frames() {
  3005   tty->print_cr("[Describe stack]");
  3006   int frame_no = 1;
  3007   for(StackFrameStream fst(this); !fst.is_done(); fst.next()) {
  3008     tty->print("  %d. ", frame_no++);
  3009     fst.current()->print_value_on(tty,this);
  3010     tty->cr();
  3014 class PrintAndVerifyOopClosure: public OopClosure {
  3015  protected:
  3016   template <class T> inline void do_oop_work(T* p) {
  3017     oop obj = oopDesc::load_decode_heap_oop(p);
  3018     if (obj == NULL) return;
  3019     tty->print(INTPTR_FORMAT ": ", p);
  3020     if (obj->is_oop_or_null()) {
  3021       if (obj->is_objArray()) {
  3022         tty->print_cr("valid objArray: " INTPTR_FORMAT, (oopDesc*) obj);
  3023       } else {
  3024         obj->print();
  3026     } else {
  3027       tty->print_cr("invalid oop: " INTPTR_FORMAT, (oopDesc*) obj);
  3029     tty->cr();
  3031  public:
  3032   virtual void do_oop(oop* p) { do_oop_work(p); }
  3033   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
  3034 };
  3037 static void oops_print(frame* f, const RegisterMap *map) {
  3038   PrintAndVerifyOopClosure print;
  3039   f->print_value();
  3040   f->oops_do(&print, NULL, (RegisterMap*)map);
  3043 // Print our all the locations that contain oops and whether they are
  3044 // valid or not.  This useful when trying to find the oldest frame
  3045 // where an oop has gone bad since the frame walk is from youngest to
  3046 // oldest.
  3047 void JavaThread::trace_oops() {
  3048   tty->print_cr("[Trace oops]");
  3049   frames_do(oops_print);
  3053 #ifdef ASSERT
  3054 // Print or validate the layout of stack frames
  3055 void JavaThread::print_frame_layout(int depth, bool validate_only) {
  3056   ResourceMark rm;
  3057   PRESERVE_EXCEPTION_MARK;
  3058   FrameValues values;
  3059   int frame_no = 0;
  3060   for(StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
  3061     fst.current()->describe(values, ++frame_no);
  3062     if (depth == frame_no) break;
  3064   if (validate_only) {
  3065     values.validate();
  3066   } else {
  3067     tty->print_cr("[Describe stack layout]");
  3068     values.print(this);
  3071 #endif
  3073 void JavaThread::trace_stack_from(vframe* start_vf) {
  3074   ResourceMark rm;
  3075   int vframe_no = 1;
  3076   for (vframe* f = start_vf; f; f = f->sender() ) {
  3077     if (f->is_java_frame()) {
  3078       javaVFrame::cast(f)->print_activation(vframe_no++);
  3079     } else {
  3080       f->print();
  3082     if (vframe_no > StackPrintLimit) {
  3083       tty->print_cr("...<more frames>...");
  3084       return;
  3090 void JavaThread::trace_stack() {
  3091   if (!has_last_Java_frame()) return;
  3092   ResourceMark rm;
  3093   HandleMark   hm;
  3094   RegisterMap reg_map(this);
  3095   trace_stack_from(last_java_vframe(&reg_map));
  3099 #endif // PRODUCT
  3102 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
  3103   assert(reg_map != NULL, "a map must be given");
  3104   frame f = last_frame();
  3105   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender() ) {
  3106     if (vf->is_java_frame()) return javaVFrame::cast(vf);
  3108   return NULL;
  3112 Klass* JavaThread::security_get_caller_class(int depth) {
  3113   vframeStream vfst(this);
  3114   vfst.security_get_caller_frame(depth);
  3115   if (!vfst.at_end()) {
  3116     return vfst.method()->method_holder();
  3118   return NULL;
  3121 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
  3122   assert(thread->is_Compiler_thread(), "must be compiler thread");
  3123   CompileBroker::compiler_thread_loop();
  3126 // Create a CompilerThread
  3127 CompilerThread::CompilerThread(CompileQueue* queue, CompilerCounters* counters)
  3128 : JavaThread(&compiler_thread_entry) {
  3129   _env   = NULL;
  3130   _log   = NULL;
  3131   _task  = NULL;
  3132   _queue = queue;
  3133   _counters = counters;
  3134   _buffer_blob = NULL;
  3135   _scanned_nmethod = NULL;
  3137 #ifndef PRODUCT
  3138   _ideal_graph_printer = NULL;
  3139 #endif
  3142 void CompilerThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
  3143   JavaThread::oops_do(f, cf);
  3144   if (_scanned_nmethod != NULL && cf != NULL) {
  3145     // Safepoints can occur when the sweeper is scanning an nmethod so
  3146     // process it here to make sure it isn't unloaded in the middle of
  3147     // a scan.
  3148     cf->do_code_blob(_scanned_nmethod);
  3152 // ======= Threads ========
  3154 // The Threads class links together all active threads, and provides
  3155 // operations over all threads.  It is protected by its own Mutex
  3156 // lock, which is also used in other contexts to protect thread
  3157 // operations from having the thread being operated on from exiting
  3158 // and going away unexpectedly (e.g., safepoint synchronization)
  3160 JavaThread* Threads::_thread_list = NULL;
  3161 int         Threads::_number_of_threads = 0;
  3162 int         Threads::_number_of_non_daemon_threads = 0;
  3163 int         Threads::_return_code = 0;
  3164 size_t      JavaThread::_stack_size_at_create = 0;
  3165 #ifdef ASSERT
  3166 bool        Threads::_vm_complete = false;
  3167 #endif
  3169 // All JavaThreads
  3170 #define ALL_JAVA_THREADS(X) for (JavaThread* X = _thread_list; X; X = X->next())
  3172 void os_stream();
  3174 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
  3175 void Threads::threads_do(ThreadClosure* tc) {
  3176   assert_locked_or_safepoint(Threads_lock);
  3177   // ALL_JAVA_THREADS iterates through all JavaThreads
  3178   ALL_JAVA_THREADS(p) {
  3179     tc->do_thread(p);
  3181   // Someday we could have a table or list of all non-JavaThreads.
  3182   // For now, just manually iterate through them.
  3183   tc->do_thread(VMThread::vm_thread());
  3184   Universe::heap()->gc_threads_do(tc);
  3185   WatcherThread *wt = WatcherThread::watcher_thread();
  3186   // Strictly speaking, the following NULL check isn't sufficient to make sure
  3187   // the data for WatcherThread is still valid upon being examined. However,
  3188   // considering that WatchThread terminates when the VM is on the way to
  3189   // exit at safepoint, the chance of the above is extremely small. The right
  3190   // way to prevent termination of WatcherThread would be to acquire
  3191   // Terminator_lock, but we can't do that without violating the lock rank
  3192   // checking in some cases.
  3193   if (wt != NULL)
  3194     tc->do_thread(wt);
  3196   // If CompilerThreads ever become non-JavaThreads, add them here
  3199 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
  3201   extern void JDK_Version_init();
  3203   // Check version
  3204   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
  3206   // Initialize the output stream module
  3207   ostream_init();
  3209   // Process java launcher properties.
  3210   Arguments::process_sun_java_launcher_properties(args);
  3212   // Initialize the os module before using TLS
  3213   os::init();
  3215   // Initialize system properties.
  3216   Arguments::init_system_properties();
  3218   // So that JDK version can be used as a discrimintor when parsing arguments
  3219   JDK_Version_init();
  3221   // Update/Initialize System properties after JDK version number is known
  3222   Arguments::init_version_specific_system_properties();
  3224   // Parse arguments
  3225   jint parse_result = Arguments::parse(args);
  3226   if (parse_result != JNI_OK) return parse_result;
  3228   if (PauseAtStartup) {
  3229     os::pause();
  3232 #ifndef USDT2
  3233   HS_DTRACE_PROBE(hotspot, vm__init__begin);
  3234 #else /* USDT2 */
  3235   HOTSPOT_VM_INIT_BEGIN();
  3236 #endif /* USDT2 */
  3238   // Record VM creation timing statistics
  3239   TraceVmCreationTime create_vm_timer;
  3240   create_vm_timer.start();
  3242   // Timing (must come after argument parsing)
  3243   TraceTime timer("Create VM", TraceStartupTime);
  3245   // Initialize the os module after parsing the args
  3246   jint os_init_2_result = os::init_2();
  3247   if (os_init_2_result != JNI_OK) return os_init_2_result;
  3249   // intialize TLS
  3250   ThreadLocalStorage::init();
  3252   // Bootstrap native memory tracking, so it can start recording memory
  3253   // activities before worker thread is started. This is the first phase
  3254   // of bootstrapping, VM is currently running in single-thread mode.
  3255   MemTracker::bootstrap_single_thread();
  3257   // Initialize output stream logging
  3258   ostream_init_log();
  3260   // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
  3261   // Must be before create_vm_init_agents()
  3262   if (Arguments::init_libraries_at_startup()) {
  3263     convert_vm_init_libraries_to_agents();
  3266   // Launch -agentlib/-agentpath and converted -Xrun agents
  3267   if (Arguments::init_agents_at_startup()) {
  3268     create_vm_init_agents();
  3271   // Initialize Threads state
  3272   _thread_list = NULL;
  3273   _number_of_threads = 0;
  3274   _number_of_non_daemon_threads = 0;
  3276   // Initialize global data structures and create system classes in heap
  3277   vm_init_globals();
  3279   // Attach the main thread to this os thread
  3280   JavaThread* main_thread = new JavaThread();
  3281   main_thread->set_thread_state(_thread_in_vm);
  3282   // must do this before set_active_handles and initialize_thread_local_storage
  3283   // Note: on solaris initialize_thread_local_storage() will (indirectly)
  3284   // change the stack size recorded here to one based on the java thread
  3285   // stacksize. This adjusted size is what is used to figure the placement
  3286   // of the guard pages.
  3287   main_thread->record_stack_base_and_size();
  3288   main_thread->initialize_thread_local_storage();
  3290   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
  3292   if (!main_thread->set_as_starting_thread()) {
  3293     vm_shutdown_during_initialization(
  3294       "Failed necessary internal allocation. Out of swap space");
  3295     delete main_thread;
  3296     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
  3297     return JNI_ENOMEM;
  3300   // Enable guard page *after* os::create_main_thread(), otherwise it would
  3301   // crash Linux VM, see notes in os_linux.cpp.
  3302   main_thread->create_stack_guard_pages();
  3304   // Initialize Java-Level synchronization subsystem
  3305   ObjectMonitor::Initialize() ;
  3307   // Second phase of bootstrapping, VM is about entering multi-thread mode
  3308   MemTracker::bootstrap_multi_thread();
  3310   // Initialize global modules
  3311   jint status = init_globals();
  3312   if (status != JNI_OK) {
  3313     delete main_thread;
  3314     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
  3315     return status;
  3318   // Should be done after the heap is fully created
  3319   main_thread->cache_global_variables();
  3321   HandleMark hm;
  3323   { MutexLocker mu(Threads_lock);
  3324     Threads::add(main_thread);
  3327   // Any JVMTI raw monitors entered in onload will transition into
  3328   // real raw monitor. VM is setup enough here for raw monitor enter.
  3329   JvmtiExport::transition_pending_onload_raw_monitors();
  3331   if (VerifyBeforeGC &&
  3332       Universe::heap()->total_collections() >= VerifyGCStartAt) {
  3333     Universe::heap()->prepare_for_verify();
  3334     Universe::verify();   // make sure we're starting with a clean slate
  3337   // Fully start NMT
  3338   MemTracker::start();
  3340   // Create the VMThread
  3341   { TraceTime timer("Start VMThread", TraceStartupTime);
  3342     VMThread::create();
  3343     Thread* vmthread = VMThread::vm_thread();
  3345     if (!os::create_thread(vmthread, os::vm_thread))
  3346       vm_exit_during_initialization("Cannot create VM thread. Out of system resources.");
  3348     // Wait for the VM thread to become ready, and VMThread::run to initialize
  3349     // Monitors can have spurious returns, must always check another state flag
  3351       MutexLocker ml(Notify_lock);
  3352       os::start_thread(vmthread);
  3353       while (vmthread->active_handles() == NULL) {
  3354         Notify_lock->wait();
  3359   assert (Universe::is_fully_initialized(), "not initialized");
  3360   EXCEPTION_MARK;
  3362   // At this point, the Universe is initialized, but we have not executed
  3363   // any byte code.  Now is a good time (the only time) to dump out the
  3364   // internal state of the JVM for sharing.
  3365   if (DumpSharedSpaces) {
  3366     MetaspaceShared::preload_and_dump(CHECK_0);
  3367     ShouldNotReachHere();
  3370   // Always call even when there are not JVMTI environments yet, since environments
  3371   // may be attached late and JVMTI must track phases of VM execution
  3372   JvmtiExport::enter_start_phase();
  3374   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
  3375   JvmtiExport::post_vm_start();
  3378     TraceTime timer("Initialize java.lang classes", TraceStartupTime);
  3380     if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
  3381       create_vm_init_libraries();
  3384     if (InitializeJavaLangString) {
  3385       initialize_class(vmSymbols::java_lang_String(), CHECK_0);
  3386     } else {
  3387       warning("java.lang.String not initialized");
  3390     if (AggressiveOpts) {
  3392         // Forcibly initialize java/util/HashMap and mutate the private
  3393         // static final "frontCacheEnabled" field before we start creating instances
  3394 #ifdef ASSERT
  3395         Klass* tmp_k = SystemDictionary::find(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0);
  3396         assert(tmp_k == NULL, "java/util/HashMap should not be loaded yet");
  3397 #endif
  3398         Klass* k_o = SystemDictionary::resolve_or_null(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0);
  3399         KlassHandle k = KlassHandle(THREAD, k_o);
  3400         guarantee(k.not_null(), "Must find java/util/HashMap");
  3401         instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
  3402         ik->initialize(CHECK_0);
  3403         fieldDescriptor fd;
  3404         // Possible we might not find this field; if so, don't break
  3405         if (ik->find_local_field(vmSymbols::frontCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
  3406           k()->java_mirror()->bool_field_put(fd.offset(), true);
  3410       if (UseStringCache) {
  3411         // Forcibly initialize java/lang/StringValue and mutate the private
  3412         // static final "stringCacheEnabled" field before we start creating instances
  3413         Klass* k_o = SystemDictionary::resolve_or_null(vmSymbols::java_lang_StringValue(), Handle(), Handle(), CHECK_0);
  3414         // Possible that StringValue isn't present: if so, silently don't break
  3415         if (k_o != NULL) {
  3416           KlassHandle k = KlassHandle(THREAD, k_o);
  3417           instanceKlassHandle ik = instanceKlassHandle(THREAD, k());
  3418           ik->initialize(CHECK_0);
  3419           fieldDescriptor fd;
  3420           // Possible we might not find this field: if so, silently don't break
  3421           if (ik->find_local_field(vmSymbols::stringCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) {
  3422             k()->java_mirror()->bool_field_put(fd.offset(), true);
  3428     // Initialize java_lang.System (needed before creating the thread)
  3429     if (InitializeJavaLangSystem) {
  3430       initialize_class(vmSymbols::java_lang_System(), CHECK_0);
  3431       initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0);
  3432       Handle thread_group = create_initial_thread_group(CHECK_0);
  3433       Universe::set_main_thread_group(thread_group());
  3434       initialize_class(vmSymbols::java_lang_Thread(), CHECK_0);
  3435       oop thread_object = create_initial_thread(thread_group, main_thread, CHECK_0);
  3436       main_thread->set_threadObj(thread_object);
  3437       // Set thread status to running since main thread has
  3438       // been started and running.
  3439       java_lang_Thread::set_thread_status(thread_object,
  3440                                           java_lang_Thread::RUNNABLE);
  3442       // The VM preresolve methods to these classes. Make sure that get initialized
  3443       initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK_0);
  3444       initialize_class(vmSymbols::java_lang_ref_Finalizer(),  CHECK_0);
  3445       // The VM creates & returns objects of this class. Make sure it's initialized.
  3446       initialize_class(vmSymbols::java_lang_Class(), CHECK_0);
  3447       call_initializeSystemClass(CHECK_0);
  3449       // get the Java runtime name after java.lang.System is initialized
  3450       JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
  3451     } else {
  3452       warning("java.lang.System not initialized");
  3455     // an instance of OutOfMemory exception has been allocated earlier
  3456     if (InitializeJavaLangExceptionsErrors) {
  3457       initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK_0);
  3458       initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK_0);
  3459       initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK_0);
  3460       initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK_0);
  3461       initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK_0);
  3462       initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK_0);
  3463       initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK_0);
  3464       initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK_0);
  3465     } else {
  3466       warning("java.lang.OutOfMemoryError has not been initialized");
  3467       warning("java.lang.NullPointerException has not been initialized");
  3468       warning("java.lang.ClassCastException has not been initialized");
  3469       warning("java.lang.ArrayStoreException has not been initialized");
  3470       warning("java.lang.ArithmeticException has not been initialized");
  3471       warning("java.lang.StackOverflowError has not been initialized");
  3472       warning("java.lang.IllegalArgumentException has not been initialized");
  3476   // See        : bugid 4211085.
  3477   // Background : the static initializer of java.lang.Compiler tries to read
  3478   //              property"java.compiler" and read & write property "java.vm.info".
  3479   //              When a security manager is installed through the command line
  3480   //              option "-Djava.security.manager", the above properties are not
  3481   //              readable and the static initializer for java.lang.Compiler fails
  3482   //              resulting in a NoClassDefFoundError.  This can happen in any
  3483   //              user code which calls methods in java.lang.Compiler.
  3484   // Hack :       the hack is to pre-load and initialize this class, so that only
  3485   //              system domains are on the stack when the properties are read.
  3486   //              Currently even the AWT code has calls to methods in java.lang.Compiler.
  3487   //              On the classic VM, java.lang.Compiler is loaded very early to load the JIT.
  3488   // Future Fix : the best fix is to grant everyone permissions to read "java.compiler" and
  3489   //              read and write"java.vm.info" in the default policy file. See bugid 4211383
  3490   //              Once that is done, we should remove this hack.
  3491   initialize_class(vmSymbols::java_lang_Compiler(), CHECK_0);
  3493   // More hackery - the static initializer of java.lang.Compiler adds the string "nojit" to
  3494   // the java.vm.info property if no jit gets loaded through java.lang.Compiler (the hotspot
  3495   // compiler does not get loaded through java.lang.Compiler).  "java -version" with the
  3496   // hotspot vm says "nojit" all the time which is confusing.  So, we reset it here.
  3497   // This should also be taken out as soon as 4211383 gets fixed.
  3498   reset_vm_info_property(CHECK_0);
  3500   quicken_jni_functions();
  3502   // Must be run after init_ft which initializes ft_enabled
  3503   if (TRACE_INITIALIZE() != JNI_OK) {
  3504     vm_exit_during_initialization("Failed to initialize tracing backend");
  3507   // Set flag that basic initialization has completed. Used by exceptions and various
  3508   // debug stuff, that does not work until all basic classes have been initialized.
  3509   set_init_completed();
  3511 #ifndef USDT2
  3512   HS_DTRACE_PROBE(hotspot, vm__init__end);
  3513 #else /* USDT2 */
  3514   HOTSPOT_VM_INIT_END();
  3515 #endif /* USDT2 */
  3517   // record VM initialization completion time
  3518   Management::record_vm_init_completed();
  3520   // Compute system loader. Note that this has to occur after set_init_completed, since
  3521   // valid exceptions may be thrown in the process.
  3522   // Note that we do not use CHECK_0 here since we are inside an EXCEPTION_MARK and
  3523   // set_init_completed has just been called, causing exceptions not to be shortcut
  3524   // anymore. We call vm_exit_during_initialization directly instead.
  3525   SystemDictionary::compute_java_system_loader(THREAD);
  3526   if (HAS_PENDING_EXCEPTION) {
  3527     vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
  3530 #ifndef SERIALGC
  3531   // Support for ConcurrentMarkSweep. This should be cleaned up
  3532   // and better encapsulated. The ugly nested if test would go away
  3533   // once things are properly refactored. XXX YSR
  3534   if (UseConcMarkSweepGC || UseG1GC) {
  3535     if (UseConcMarkSweepGC) {
  3536       ConcurrentMarkSweepThread::makeSurrogateLockerThread(THREAD);
  3537     } else {
  3538       ConcurrentMarkThread::makeSurrogateLockerThread(THREAD);
  3540     if (HAS_PENDING_EXCEPTION) {
  3541       vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
  3544 #endif // SERIALGC
  3546   // Always call even when there are not JVMTI environments yet, since environments
  3547   // may be attached late and JVMTI must track phases of VM execution
  3548   JvmtiExport::enter_live_phase();
  3550   // Signal Dispatcher needs to be started before VMInit event is posted
  3551   os::signal_init();
  3553   // Start Attach Listener if +StartAttachListener or it can't be started lazily
  3554   if (!DisableAttachMechanism) {
  3555     if (StartAttachListener || AttachListener::init_at_startup()) {
  3556       AttachListener::init();
  3560   // Launch -Xrun agents
  3561   // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
  3562   // back-end can launch with -Xdebug -Xrunjdwp.
  3563   if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
  3564     create_vm_init_libraries();
  3567   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
  3568   JvmtiExport::post_vm_initialized();
  3570   if (!TRACE_START()) {
  3571     vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
  3574   if (CleanChunkPoolAsync) {
  3575     Chunk::start_chunk_pool_cleaner_task();
  3578   // initialize compiler(s)
  3579   CompileBroker::compilation_init();
  3581   Management::initialize(THREAD);
  3582   if (HAS_PENDING_EXCEPTION) {
  3583     // management agent fails to start possibly due to
  3584     // configuration problem and is responsible for printing
  3585     // stack trace if appropriate. Simply exit VM.
  3586     vm_exit(1);
  3589   if (Arguments::has_profile())       FlatProfiler::engage(main_thread, true);
  3590   if (Arguments::has_alloc_profile()) AllocationProfiler::engage();
  3591   if (MemProfiling)                   MemProfiler::engage();
  3592   StatSampler::engage();
  3593   if (CheckJNICalls)                  JniPeriodicChecker::engage();
  3595   BiasedLocking::init();
  3597   if (JDK_Version::current().post_vm_init_hook_enabled()) {
  3598     call_postVMInitHook(THREAD);
  3599     // The Java side of PostVMInitHook.run must deal with all
  3600     // exceptions and provide means of diagnosis.
  3601     if (HAS_PENDING_EXCEPTION) {
  3602       CLEAR_PENDING_EXCEPTION;
  3606   // Start up the WatcherThread if there are any periodic tasks
  3607   // NOTE:  All PeriodicTasks should be registered by now. If they
  3608   //   aren't, late joiners might appear to start slowly (we might
  3609   //   take a while to process their first tick).
  3610   if (PeriodicTask::num_tasks() > 0) {
  3611     WatcherThread::start();
  3614   // Give os specific code one last chance to start
  3615   os::init_3();
  3617   create_vm_timer.end();
  3618 #ifdef ASSERT
  3619   _vm_complete = true;
  3620 #endif
  3621   return JNI_OK;
  3624 // type for the Agent_OnLoad and JVM_OnLoad entry points
  3625 extern "C" {
  3626   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
  3628 // Find a command line agent library and return its entry point for
  3629 //         -agentlib:  -agentpath:   -Xrun
  3630 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
  3631 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, const char *on_load_symbols[], size_t num_symbol_entries) {
  3632   OnLoadEntry_t on_load_entry = NULL;
  3633   void *library = agent->os_lib();  // check if we have looked it up before
  3635   if (library == NULL) {
  3636     char buffer[JVM_MAXPATHLEN];
  3637     char ebuf[1024];
  3638     const char *name = agent->name();
  3639     const char *msg = "Could not find agent library ";
  3641     if (agent->is_absolute_path()) {
  3642       library = os::dll_load(name, ebuf, sizeof ebuf);
  3643       if (library == NULL) {
  3644         const char *sub_msg = " in absolute path, with error: ";
  3645         size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
  3646         char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
  3647         jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
  3648         // If we can't find the agent, exit.
  3649         vm_exit_during_initialization(buf, NULL);
  3650         FREE_C_HEAP_ARRAY(char, buf, mtThread);
  3652     } else {
  3653       // Try to load the agent from the standard dll directory
  3654       os::dll_build_name(buffer, sizeof(buffer), Arguments::get_dll_dir(), name);
  3655       library = os::dll_load(buffer, ebuf, sizeof ebuf);
  3656 #ifdef KERNEL
  3657       // Download instrument dll
  3658       if (library == NULL && strcmp(name, "instrument") == 0) {
  3659         char *props = Arguments::get_kernel_properties();
  3660         char *home  = Arguments::get_java_home();
  3661         const char *fmt   = "%s/bin/java %s -Dkernel.background.download=false"
  3662                       " sun.jkernel.DownloadManager -download client_jvm";
  3663         size_t length = strlen(props) + strlen(home) + strlen(fmt) + 1;
  3664         char *cmd = NEW_C_HEAP_ARRAY(char, length, mtThread);
  3665         jio_snprintf(cmd, length, fmt, home, props);
  3666         int status = os::fork_and_exec(cmd);
  3667         FreeHeap(props);
  3668         if (status == -1) {
  3669           warning(cmd);
  3670           vm_exit_during_initialization("fork_and_exec failed: %s",
  3671                                          strerror(errno));
  3673         FREE_C_HEAP_ARRAY(char, cmd, mtThread);
  3674         // when this comes back the instrument.dll should be where it belongs.
  3675         library = os::dll_load(buffer, ebuf, sizeof ebuf);
  3677 #endif // KERNEL
  3678       if (library == NULL) { // Try the local directory
  3679         char ns[1] = {0};
  3680         os::dll_build_name(buffer, sizeof(buffer), ns, name);
  3681         library = os::dll_load(buffer, ebuf, sizeof ebuf);
  3682         if (library == NULL) {
  3683           const char *sub_msg = " on the library path, with error: ";
  3684           size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
  3685           char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
  3686           jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
  3687           // If we can't find the agent, exit.
  3688           vm_exit_during_initialization(buf, NULL);
  3689           FREE_C_HEAP_ARRAY(char, buf, mtThread);
  3693     agent->set_os_lib(library);
  3696   // Find the OnLoad function.
  3697   for (size_t symbol_index = 0; symbol_index < num_symbol_entries; symbol_index++) {
  3698     on_load_entry = CAST_TO_FN_PTR(OnLoadEntry_t, os::dll_lookup(library, on_load_symbols[symbol_index]));
  3699     if (on_load_entry != NULL) break;
  3701   return on_load_entry;
  3704 // Find the JVM_OnLoad entry point
  3705 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
  3706   const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
  3707   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
  3710 // Find the Agent_OnLoad entry point
  3711 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
  3712   const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
  3713   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
  3716 // For backwards compatibility with -Xrun
  3717 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
  3718 // treated like -agentpath:
  3719 // Must be called before agent libraries are created
  3720 void Threads::convert_vm_init_libraries_to_agents() {
  3721   AgentLibrary* agent;
  3722   AgentLibrary* next;
  3724   for (agent = Arguments::libraries(); agent != NULL; agent = next) {
  3725     next = agent->next();  // cache the next agent now as this agent may get moved off this list
  3726     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
  3728     // If there is an JVM_OnLoad function it will get called later,
  3729     // otherwise see if there is an Agent_OnLoad
  3730     if (on_load_entry == NULL) {
  3731       on_load_entry = lookup_agent_on_load(agent);
  3732       if (on_load_entry != NULL) {
  3733         // switch it to the agent list -- so that Agent_OnLoad will be called,
  3734         // JVM_OnLoad won't be attempted and Agent_OnUnload will
  3735         Arguments::convert_library_to_agent(agent);
  3736       } else {
  3737         vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
  3743 // Create agents for -agentlib:  -agentpath:  and converted -Xrun
  3744 // Invokes Agent_OnLoad
  3745 // Called very early -- before JavaThreads exist
  3746 void Threads::create_vm_init_agents() {
  3747   extern struct JavaVM_ main_vm;
  3748   AgentLibrary* agent;
  3750   JvmtiExport::enter_onload_phase();
  3751   for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
  3752     OnLoadEntry_t  on_load_entry = lookup_agent_on_load(agent);
  3754     if (on_load_entry != NULL) {
  3755       // Invoke the Agent_OnLoad function
  3756       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
  3757       if (err != JNI_OK) {
  3758         vm_exit_during_initialization("agent library failed to init", agent->name());
  3760     } else {
  3761       vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
  3764   JvmtiExport::enter_primordial_phase();
  3767 extern "C" {
  3768   typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
  3771 void Threads::shutdown_vm_agents() {
  3772   // Send any Agent_OnUnload notifications
  3773   const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
  3774   extern struct JavaVM_ main_vm;
  3775   for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
  3777     // Find the Agent_OnUnload function.
  3778     for (uint symbol_index = 0; symbol_index < ARRAY_SIZE(on_unload_symbols); symbol_index++) {
  3779       Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
  3780                os::dll_lookup(agent->os_lib(), on_unload_symbols[symbol_index]));
  3782       // Invoke the Agent_OnUnload function
  3783       if (unload_entry != NULL) {
  3784         JavaThread* thread = JavaThread::current();
  3785         ThreadToNativeFromVM ttn(thread);
  3786         HandleMark hm(thread);
  3787         (*unload_entry)(&main_vm);
  3788         break;
  3794 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
  3795 // Invokes JVM_OnLoad
  3796 void Threads::create_vm_init_libraries() {
  3797   extern struct JavaVM_ main_vm;
  3798   AgentLibrary* agent;
  3800   for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
  3801     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
  3803     if (on_load_entry != NULL) {
  3804       // Invoke the JVM_OnLoad function
  3805       JavaThread* thread = JavaThread::current();
  3806       ThreadToNativeFromVM ttn(thread);
  3807       HandleMark hm(thread);
  3808       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
  3809       if (err != JNI_OK) {
  3810         vm_exit_during_initialization("-Xrun library failed to init", agent->name());
  3812     } else {
  3813       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
  3818 // Last thread running calls java.lang.Shutdown.shutdown()
  3819 void JavaThread::invoke_shutdown_hooks() {
  3820   HandleMark hm(this);
  3822   // We could get here with a pending exception, if so clear it now.
  3823   if (this->has_pending_exception()) {
  3824     this->clear_pending_exception();
  3827   EXCEPTION_MARK;
  3828   Klass* k =
  3829     SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
  3830                                       THREAD);
  3831   if (k != NULL) {
  3832     // SystemDictionary::resolve_or_null will return null if there was
  3833     // an exception.  If we cannot load the Shutdown class, just don't
  3834     // call Shutdown.shutdown() at all.  This will mean the shutdown hooks
  3835     // and finalizers (if runFinalizersOnExit is set) won't be run.
  3836     // Note that if a shutdown hook was registered or runFinalizersOnExit
  3837     // was called, the Shutdown class would have already been loaded
  3838     // (Runtime.addShutdownHook and runFinalizersOnExit will load it).
  3839     instanceKlassHandle shutdown_klass (THREAD, k);
  3840     JavaValue result(T_VOID);
  3841     JavaCalls::call_static(&result,
  3842                            shutdown_klass,
  3843                            vmSymbols::shutdown_method_name(),
  3844                            vmSymbols::void_method_signature(),
  3845                            THREAD);
  3847   CLEAR_PENDING_EXCEPTION;
  3850 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
  3851 // the program falls off the end of main(). Another VM exit path is through
  3852 // vm_exit() when the program calls System.exit() to return a value or when
  3853 // there is a serious error in VM. The two shutdown paths are not exactly
  3854 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
  3855 // and VM_Exit op at VM level.
  3856 //
  3857 // Shutdown sequence:
  3858 //   + Shutdown native memory tracking if it is on
  3859 //   + Wait until we are the last non-daemon thread to execute
  3860 //     <-- every thing is still working at this moment -->
  3861 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
  3862 //        shutdown hooks, run finalizers if finalization-on-exit
  3863 //   + Call before_exit(), prepare for VM exit
  3864 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
  3865 //        currently the only user of this mechanism is File.deleteOnExit())
  3866 //      > stop flat profiler, StatSampler, watcher thread, CMS threads,
  3867 //        post thread end and vm death events to JVMTI,
  3868 //        stop signal thread
  3869 //   + Call JavaThread::exit(), it will:
  3870 //      > release JNI handle blocks, remove stack guard pages
  3871 //      > remove this thread from Threads list
  3872 //     <-- no more Java code from this thread after this point -->
  3873 //   + Stop VM thread, it will bring the remaining VM to a safepoint and stop
  3874 //     the compiler threads at safepoint
  3875 //     <-- do not use anything that could get blocked by Safepoint -->
  3876 //   + Disable tracing at JNI/JVM barriers
  3877 //   + Set _vm_exited flag for threads that are still running native code
  3878 //   + Delete this thread
  3879 //   + Call exit_globals()
  3880 //      > deletes tty
  3881 //      > deletes PerfMemory resources
  3882 //   + Return to caller
  3884 bool Threads::destroy_vm() {
  3885   JavaThread* thread = JavaThread::current();
  3887 #ifdef ASSERT
  3888   _vm_complete = false;
  3889 #endif
  3890   // Wait until we are the last non-daemon thread to execute
  3891   { MutexLocker nu(Threads_lock);
  3892     while (Threads::number_of_non_daemon_threads() > 1 )
  3893       // This wait should make safepoint checks, wait without a timeout,
  3894       // and wait as a suspend-equivalent condition.
  3895       //
  3896       // Note: If the FlatProfiler is running and this thread is waiting
  3897       // for another non-daemon thread to finish, then the FlatProfiler
  3898       // is waiting for the external suspend request on this thread to
  3899       // complete. wait_for_ext_suspend_completion() will eventually
  3900       // timeout, but that takes time. Making this wait a suspend-
  3901       // equivalent condition solves that timeout problem.
  3902       //
  3903       Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
  3904                          Mutex::_as_suspend_equivalent_flag);
  3907   // Shutdown NMT before exit. Otherwise,
  3908   // it will run into trouble when system destroys static variables.
  3909   MemTracker::shutdown(MemTracker::NMT_normal);
  3911   // Hang forever on exit if we are reporting an error.
  3912   if (ShowMessageBoxOnError && is_error_reported()) {
  3913     os::infinite_sleep();
  3915   os::wait_for_keypress_at_exit();
  3917   if (JDK_Version::is_jdk12x_version()) {
  3918     // We are the last thread running, so check if finalizers should be run.
  3919     // For 1.3 or later this is done in thread->invoke_shutdown_hooks()
  3920     HandleMark rm(thread);
  3921     Universe::run_finalizers_on_exit();
  3922   } else {
  3923     // run Java level shutdown hooks
  3924     thread->invoke_shutdown_hooks();
  3927   before_exit(thread);
  3929   thread->exit(true);
  3931   // Stop VM thread.
  3933     // 4945125 The vm thread comes to a safepoint during exit.
  3934     // GC vm_operations can get caught at the safepoint, and the
  3935     // heap is unparseable if they are caught. Grab the Heap_lock
  3936     // to prevent this. The GC vm_operations will not be able to
  3937     // queue until after the vm thread is dead.
  3938     // After this point, we'll never emerge out of the safepoint before
  3939     // the VM exits, so concurrent GC threads do not need to be explicitly
  3940     // stopped; they remain inactive until the process exits.
  3941     // Note: some concurrent G1 threads may be running during a safepoint,
  3942     // but these will not be accessing the heap, just some G1-specific side
  3943     // data structures that are not accessed by any other threads but them
  3944     // after this point in a terminal safepoint.
  3946     MutexLocker ml(Heap_lock);
  3948     VMThread::wait_for_vm_thread_exit();
  3949     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
  3950     VMThread::destroy();
  3953   // clean up ideal graph printers
  3954 #if defined(COMPILER2) && !defined(PRODUCT)
  3955   IdealGraphPrinter::clean_up();
  3956 #endif
  3958   // Now, all Java threads are gone except daemon threads. Daemon threads
  3959   // running Java code or in VM are stopped by the Safepoint. However,
  3960   // daemon threads executing native code are still running.  But they
  3961   // will be stopped at native=>Java/VM barriers. Note that we can't
  3962   // simply kill or suspend them, as it is inherently deadlock-prone.
  3964 #ifndef PRODUCT
  3965   // disable function tracing at JNI/JVM barriers
  3966   TraceJNICalls = false;
  3967   TraceJVMCalls = false;
  3968   TraceRuntimeCalls = false;
  3969 #endif
  3971   VM_Exit::set_vm_exited();
  3973   notify_vm_shutdown();
  3975   delete thread;
  3977   // exit_globals() will delete tty
  3978   exit_globals();
  3980   return true;
  3984 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
  3985   if (version == JNI_VERSION_1_1) return JNI_TRUE;
  3986   return is_supported_jni_version(version);
  3990 jboolean Threads::is_supported_jni_version(jint version) {
  3991   if (version == JNI_VERSION_1_2) return JNI_TRUE;
  3992   if (version == JNI_VERSION_1_4) return JNI_TRUE;
  3993   if (version == JNI_VERSION_1_6) return JNI_TRUE;
  3994   return JNI_FALSE;
  3998 void Threads::add(JavaThread* p, bool force_daemon) {
  3999   // The threads lock must be owned at this point
  4000   assert_locked_or_safepoint(Threads_lock);
  4002   // See the comment for this method in thread.hpp for its purpose and
  4003   // why it is called here.
  4004   p->initialize_queues();
  4005   p->set_next(_thread_list);
  4006   _thread_list = p;
  4007   _number_of_threads++;
  4008   oop threadObj = p->threadObj();
  4009   bool daemon = true;
  4010   // Bootstrapping problem: threadObj can be null for initial
  4011   // JavaThread (or for threads attached via JNI)
  4012   if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
  4013     _number_of_non_daemon_threads++;
  4014     daemon = false;
  4017   p->set_safepoint_visible(true);
  4019   ThreadService::add_thread(p, daemon);
  4021   // Possible GC point.
  4022   Events::log(p, "Thread added: " INTPTR_FORMAT, p);
  4025 void Threads::remove(JavaThread* p) {
  4026   // Extra scope needed for Thread_lock, so we can check
  4027   // that we do not remove thread without safepoint code notice
  4028   { MutexLocker ml(Threads_lock);
  4030     assert(includes(p), "p must be present");
  4032     JavaThread* current = _thread_list;
  4033     JavaThread* prev    = NULL;
  4035     while (current != p) {
  4036       prev    = current;
  4037       current = current->next();
  4040     if (prev) {
  4041       prev->set_next(current->next());
  4042     } else {
  4043       _thread_list = p->next();
  4045     _number_of_threads--;
  4046     oop threadObj = p->threadObj();
  4047     bool daemon = true;
  4048     if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
  4049       _number_of_non_daemon_threads--;
  4050       daemon = false;
  4052       // Only one thread left, do a notify on the Threads_lock so a thread waiting
  4053       // on destroy_vm will wake up.
  4054       if (number_of_non_daemon_threads() == 1)
  4055         Threads_lock->notify_all();
  4057     ThreadService::remove_thread(p, daemon);
  4059     // Make sure that safepoint code disregard this thread. This is needed since
  4060     // the thread might mess around with locks after this point. This can cause it
  4061     // to do callbacks into the safepoint code. However, the safepoint code is not aware
  4062     // of this thread since it is removed from the queue.
  4063     p->set_terminated_value();
  4065     // Now, this thread is not visible to safepoint
  4066     p->set_safepoint_visible(false);
  4068   } // unlock Threads_lock
  4070   // Since Events::log uses a lock, we grab it outside the Threads_lock
  4071   Events::log(p, "Thread exited: " INTPTR_FORMAT, p);
  4074 // Threads_lock must be held when this is called (or must be called during a safepoint)
  4075 bool Threads::includes(JavaThread* p) {
  4076   assert(Threads_lock->is_locked(), "sanity check");
  4077   ALL_JAVA_THREADS(q) {
  4078     if (q == p ) {
  4079       return true;
  4082   return false;
  4085 // Operations on the Threads list for GC.  These are not explicitly locked,
  4086 // but the garbage collector must provide a safe context for them to run.
  4087 // In particular, these things should never be called when the Threads_lock
  4088 // is held by some other thread. (Note: the Safepoint abstraction also
  4089 // uses the Threads_lock to gurantee this property. It also makes sure that
  4090 // all threads gets blocked when exiting or starting).
  4092 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
  4093   ALL_JAVA_THREADS(p) {
  4094     p->oops_do(f, cf);
  4096   VMThread::vm_thread()->oops_do(f, cf);
  4099 void Threads::possibly_parallel_oops_do(OopClosure* f, CodeBlobClosure* cf) {
  4100   // Introduce a mechanism allowing parallel threads to claim threads as
  4101   // root groups.  Overhead should be small enough to use all the time,
  4102   // even in sequential code.
  4103   SharedHeap* sh = SharedHeap::heap();
  4104   // Cannot yet substitute active_workers for n_par_threads
  4105   // because of G1CollectedHeap::verify() use of
  4106   // SharedHeap::process_strong_roots().  n_par_threads == 0 will
  4107   // turn off parallelism in process_strong_roots while active_workers
  4108   // is being used for parallelism elsewhere.
  4109   bool is_par = sh->n_par_threads() > 0;
  4110   assert(!is_par ||
  4111          (SharedHeap::heap()->n_par_threads() ==
  4112           SharedHeap::heap()->workers()->active_workers()), "Mismatch");
  4113   int cp = SharedHeap::heap()->strong_roots_parity();
  4114   ALL_JAVA_THREADS(p) {
  4115     if (p->claim_oops_do(is_par, cp)) {
  4116       p->oops_do(f, cf);
  4119   VMThread* vmt = VMThread::vm_thread();
  4120   if (vmt->claim_oops_do(is_par, cp)) {
  4121     vmt->oops_do(f, cf);
  4125 #ifndef SERIALGC
  4126 // Used by ParallelScavenge
  4127 void Threads::create_thread_roots_tasks(GCTaskQueue* q) {
  4128   ALL_JAVA_THREADS(p) {
  4129     q->enqueue(new ThreadRootsTask(p));
  4131   q->enqueue(new ThreadRootsTask(VMThread::vm_thread()));
  4134 // Used by Parallel Old
  4135 void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) {
  4136   ALL_JAVA_THREADS(p) {
  4137     q->enqueue(new ThreadRootsMarkingTask(p));
  4139   q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread()));
  4141 #endif // SERIALGC
  4143 void Threads::nmethods_do(CodeBlobClosure* cf) {
  4144   ALL_JAVA_THREADS(p) {
  4145     p->nmethods_do(cf);
  4147   VMThread::vm_thread()->nmethods_do(cf);
  4150 void Threads::metadata_do(void f(Metadata*)) {
  4151   ALL_JAVA_THREADS(p) {
  4152     p->metadata_do(f);
  4156 void Threads::gc_epilogue() {
  4157   ALL_JAVA_THREADS(p) {
  4158     p->gc_epilogue();
  4162 void Threads::gc_prologue() {
  4163   ALL_JAVA_THREADS(p) {
  4164     p->gc_prologue();
  4168 void Threads::deoptimized_wrt_marked_nmethods() {
  4169   ALL_JAVA_THREADS(p) {
  4170     p->deoptimized_wrt_marked_nmethods();
  4175 // Get count Java threads that are waiting to enter the specified monitor.
  4176 GrowableArray<JavaThread*>* Threads::get_pending_threads(int count,
  4177   address monitor, bool doLock) {
  4178   assert(doLock || SafepointSynchronize::is_at_safepoint(),
  4179     "must grab Threads_lock or be at safepoint");
  4180   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
  4182   int i = 0;
  4184     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  4185     ALL_JAVA_THREADS(p) {
  4186       if (p->is_Compiler_thread()) continue;
  4188       address pending = (address)p->current_pending_monitor();
  4189       if (pending == monitor) {             // found a match
  4190         if (i < count) result->append(p);   // save the first count matches
  4191         i++;
  4195   return result;
  4199 JavaThread *Threads::owning_thread_from_monitor_owner(address owner, bool doLock) {
  4200   assert(doLock ||
  4201          Threads_lock->owned_by_self() ||
  4202          SafepointSynchronize::is_at_safepoint(),
  4203          "must grab Threads_lock or be at safepoint");
  4205   // NULL owner means not locked so we can skip the search
  4206   if (owner == NULL) return NULL;
  4209     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  4210     ALL_JAVA_THREADS(p) {
  4211       // first, see if owner is the address of a Java thread
  4212       if (owner == (address)p) return p;
  4215   assert(UseHeavyMonitors == false, "Did not find owning Java thread with UseHeavyMonitors enabled");
  4216   if (UseHeavyMonitors) return NULL;
  4218   //
  4219   // If we didn't find a matching Java thread and we didn't force use of
  4220   // heavyweight monitors, then the owner is the stack address of the
  4221   // Lock Word in the owning Java thread's stack.
  4222   //
  4223   JavaThread* the_owner = NULL;
  4225     MutexLockerEx ml(doLock ? Threads_lock : NULL);
  4226     ALL_JAVA_THREADS(q) {
  4227       if (q->is_lock_owned(owner)) {
  4228         the_owner = q;
  4229         break;
  4233   assert(the_owner != NULL, "Did not find owning Java thread for lock word address");
  4234   return the_owner;
  4237 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
  4238 void Threads::print_on(outputStream* st, bool print_stacks, bool internal_format, bool print_concurrent_locks) {
  4239   char buf[32];
  4240   st->print_cr(os::local_time_string(buf, sizeof(buf)));
  4242   st->print_cr("Full thread dump %s (%s %s):",
  4243                 Abstract_VM_Version::vm_name(),
  4244                 Abstract_VM_Version::vm_release(),
  4245                 Abstract_VM_Version::vm_info_string()
  4246                );
  4247   st->cr();
  4249 #ifndef SERIALGC
  4250   // Dump concurrent locks
  4251   ConcurrentLocksDump concurrent_locks;
  4252   if (print_concurrent_locks) {
  4253     concurrent_locks.dump_at_safepoint();
  4255 #endif // SERIALGC
  4257   ALL_JAVA_THREADS(p) {
  4258     ResourceMark rm;
  4259     p->print_on(st);
  4260     if (print_stacks) {
  4261       if (internal_format) {
  4262         p->trace_stack();
  4263       } else {
  4264         p->print_stack_on(st);
  4267     st->cr();
  4268 #ifndef SERIALGC
  4269     if (print_concurrent_locks) {
  4270       concurrent_locks.print_locks_on(p, st);
  4272 #endif // SERIALGC
  4275   VMThread::vm_thread()->print_on(st);
  4276   st->cr();
  4277   Universe::heap()->print_gc_threads_on(st);
  4278   WatcherThread* wt = WatcherThread::watcher_thread();
  4279   if (wt != NULL) wt->print_on(st);
  4280   st->cr();
  4281   CompileBroker::print_compiler_threads_on(st);
  4282   st->flush();
  4285 // Threads::print_on_error() is called by fatal error handler. It's possible
  4286 // that VM is not at safepoint and/or current thread is inside signal handler.
  4287 // Don't print stack trace, as the stack may not be walkable. Don't allocate
  4288 // memory (even in resource area), it might deadlock the error handler.
  4289 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, int buflen) {
  4290   bool found_current = false;
  4291   st->print_cr("Java Threads: ( => current thread )");
  4292   ALL_JAVA_THREADS(thread) {
  4293     bool is_current = (current == thread);
  4294     found_current = found_current || is_current;
  4296     st->print("%s", is_current ? "=>" : "  ");
  4298     st->print(PTR_FORMAT, thread);
  4299     st->print(" ");
  4300     thread->print_on_error(st, buf, buflen);
  4301     st->cr();
  4303   st->cr();
  4305   st->print_cr("Other Threads:");
  4306   if (VMThread::vm_thread()) {
  4307     bool is_current = (current == VMThread::vm_thread());
  4308     found_current = found_current || is_current;
  4309     st->print("%s", current == VMThread::vm_thread() ? "=>" : "  ");
  4311     st->print(PTR_FORMAT, VMThread::vm_thread());
  4312     st->print(" ");
  4313     VMThread::vm_thread()->print_on_error(st, buf, buflen);
  4314     st->cr();
  4316   WatcherThread* wt = WatcherThread::watcher_thread();
  4317   if (wt != NULL) {
  4318     bool is_current = (current == wt);
  4319     found_current = found_current || is_current;
  4320     st->print("%s", is_current ? "=>" : "  ");
  4322     st->print(PTR_FORMAT, wt);
  4323     st->print(" ");
  4324     wt->print_on_error(st, buf, buflen);
  4325     st->cr();
  4327   if (!found_current) {
  4328     st->cr();
  4329     st->print("=>" PTR_FORMAT " (exited) ", current);
  4330     current->print_on_error(st, buf, buflen);
  4331     st->cr();
  4335 // Internal SpinLock and Mutex
  4336 // Based on ParkEvent
  4338 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
  4339 //
  4340 // We employ SpinLocks _only for low-contention, fixed-length
  4341 // short-duration critical sections where we're concerned
  4342 // about native mutex_t or HotSpot Mutex:: latency.
  4343 // The mux construct provides a spin-then-block mutual exclusion
  4344 // mechanism.
  4345 //
  4346 // Testing has shown that contention on the ListLock guarding gFreeList
  4347 // is common.  If we implement ListLock as a simple SpinLock it's common
  4348 // for the JVM to devolve to yielding with little progress.  This is true
  4349 // despite the fact that the critical sections protected by ListLock are
  4350 // extremely short.
  4351 //
  4352 // TODO-FIXME: ListLock should be of type SpinLock.
  4353 // We should make this a 1st-class type, integrated into the lock
  4354 // hierarchy as leaf-locks.  Critically, the SpinLock structure
  4355 // should have sufficient padding to avoid false-sharing and excessive
  4356 // cache-coherency traffic.
  4359 typedef volatile int SpinLockT ;
  4361 void Thread::SpinAcquire (volatile int * adr, const char * LockName) {
  4362   if (Atomic::cmpxchg (1, adr, 0) == 0) {
  4363      return ;   // normal fast-path return
  4366   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
  4367   TEVENT (SpinAcquire - ctx) ;
  4368   int ctr = 0 ;
  4369   int Yields = 0 ;
  4370   for (;;) {
  4371      while (*adr != 0) {
  4372         ++ctr ;
  4373         if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
  4374            if (Yields > 5) {
  4375              // Consider using a simple NakedSleep() instead.
  4376              // Then SpinAcquire could be called by non-JVM threads
  4377              Thread::current()->_ParkEvent->park(1) ;
  4378            } else {
  4379              os::NakedYield() ;
  4380              ++Yields ;
  4382         } else {
  4383            SpinPause() ;
  4386      if (Atomic::cmpxchg (1, adr, 0) == 0) return ;
  4390 void Thread::SpinRelease (volatile int * adr) {
  4391   assert (*adr != 0, "invariant") ;
  4392   OrderAccess::fence() ;      // guarantee at least release consistency.
  4393   // Roach-motel semantics.
  4394   // It's safe if subsequent LDs and STs float "up" into the critical section,
  4395   // but prior LDs and STs within the critical section can't be allowed
  4396   // to reorder or float past the ST that releases the lock.
  4397   *adr = 0 ;
  4400 // muxAcquire and muxRelease:
  4401 //
  4402 // *  muxAcquire and muxRelease support a single-word lock-word construct.
  4403 //    The LSB of the word is set IFF the lock is held.
  4404 //    The remainder of the word points to the head of a singly-linked list
  4405 //    of threads blocked on the lock.
  4406 //
  4407 // *  The current implementation of muxAcquire-muxRelease uses its own
  4408 //    dedicated Thread._MuxEvent instance.  If we're interested in
  4409 //    minimizing the peak number of extant ParkEvent instances then
  4410 //    we could eliminate _MuxEvent and "borrow" _ParkEvent as long
  4411 //    as certain invariants were satisfied.  Specifically, care would need
  4412 //    to be taken with regards to consuming unpark() "permits".
  4413 //    A safe rule of thumb is that a thread would never call muxAcquire()
  4414 //    if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
  4415 //    park().  Otherwise the _ParkEvent park() operation in muxAcquire() could
  4416 //    consume an unpark() permit intended for monitorenter, for instance.
  4417 //    One way around this would be to widen the restricted-range semaphore
  4418 //    implemented in park().  Another alternative would be to provide
  4419 //    multiple instances of the PlatformEvent() for each thread.  One
  4420 //    instance would be dedicated to muxAcquire-muxRelease, for instance.
  4421 //
  4422 // *  Usage:
  4423 //    -- Only as leaf locks
  4424 //    -- for short-term locking only as muxAcquire does not perform
  4425 //       thread state transitions.
  4426 //
  4427 // Alternatives:
  4428 // *  We could implement muxAcquire and muxRelease with MCS or CLH locks
  4429 //    but with parking or spin-then-park instead of pure spinning.
  4430 // *  Use Taura-Oyama-Yonenzawa locks.
  4431 // *  It's possible to construct a 1-0 lock if we encode the lockword as
  4432 //    (List,LockByte).  Acquire will CAS the full lockword while Release
  4433 //    will STB 0 into the LockByte.  The 1-0 scheme admits stranding, so
  4434 //    acquiring threads use timers (ParkTimed) to detect and recover from
  4435 //    the stranding window.  Thread/Node structures must be aligned on 256-byte
  4436 //    boundaries by using placement-new.
  4437 // *  Augment MCS with advisory back-link fields maintained with CAS().
  4438 //    Pictorially:  LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
  4439 //    The validity of the backlinks must be ratified before we trust the value.
  4440 //    If the backlinks are invalid the exiting thread must back-track through the
  4441 //    the forward links, which are always trustworthy.
  4442 // *  Add a successor indication.  The LockWord is currently encoded as
  4443 //    (List, LOCKBIT:1).  We could also add a SUCCBIT or an explicit _succ variable
  4444 //    to provide the usual futile-wakeup optimization.
  4445 //    See RTStt for details.
  4446 // *  Consider schedctl.sc_nopreempt to cover the critical section.
  4447 //
  4450 typedef volatile intptr_t MutexT ;      // Mux Lock-word
  4451 enum MuxBits { LOCKBIT = 1 } ;
  4453 void Thread::muxAcquire (volatile intptr_t * Lock, const char * LockName) {
  4454   intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
  4455   if (w == 0) return ;
  4456   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4457      return ;
  4460   TEVENT (muxAcquire - Contention) ;
  4461   ParkEvent * const Self = Thread::current()->_MuxEvent ;
  4462   assert ((intptr_t(Self) & LOCKBIT) == 0, "invariant") ;
  4463   for (;;) {
  4464      int its = (os::is_MP() ? 100 : 0) + 1 ;
  4466      // Optional spin phase: spin-then-park strategy
  4467      while (--its >= 0) {
  4468        w = *Lock ;
  4469        if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4470           return ;
  4474      Self->reset() ;
  4475      Self->OnList = intptr_t(Lock) ;
  4476      // The following fence() isn't _strictly necessary as the subsequent
  4477      // CAS() both serializes execution and ratifies the fetched *Lock value.
  4478      OrderAccess::fence();
  4479      for (;;) {
  4480         w = *Lock ;
  4481         if ((w & LOCKBIT) == 0) {
  4482             if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4483                 Self->OnList = 0 ;   // hygiene - allows stronger asserts
  4484                 return ;
  4486             continue ;      // Interference -- *Lock changed -- Just retry
  4488         assert (w & LOCKBIT, "invariant") ;
  4489         Self->ListNext = (ParkEvent *) (w & ~LOCKBIT );
  4490         if (Atomic::cmpxchg_ptr (intptr_t(Self)|LOCKBIT, Lock, w) == w) break ;
  4493      while (Self->OnList != 0) {
  4494         Self->park() ;
  4499 void Thread::muxAcquireW (volatile intptr_t * Lock, ParkEvent * ev) {
  4500   intptr_t w = Atomic::cmpxchg_ptr (LOCKBIT, Lock, 0) ;
  4501   if (w == 0) return ;
  4502   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4503     return ;
  4506   TEVENT (muxAcquire - Contention) ;
  4507   ParkEvent * ReleaseAfter = NULL ;
  4508   if (ev == NULL) {
  4509     ev = ReleaseAfter = ParkEvent::Allocate (NULL) ;
  4511   assert ((intptr_t(ev) & LOCKBIT) == 0, "invariant") ;
  4512   for (;;) {
  4513     guarantee (ev->OnList == 0, "invariant") ;
  4514     int its = (os::is_MP() ? 100 : 0) + 1 ;
  4516     // Optional spin phase: spin-then-park strategy
  4517     while (--its >= 0) {
  4518       w = *Lock ;
  4519       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4520         if (ReleaseAfter != NULL) {
  4521           ParkEvent::Release (ReleaseAfter) ;
  4523         return ;
  4527     ev->reset() ;
  4528     ev->OnList = intptr_t(Lock) ;
  4529     // The following fence() isn't _strictly necessary as the subsequent
  4530     // CAS() both serializes execution and ratifies the fetched *Lock value.
  4531     OrderAccess::fence();
  4532     for (;;) {
  4533       w = *Lock ;
  4534       if ((w & LOCKBIT) == 0) {
  4535         if (Atomic::cmpxchg_ptr (w|LOCKBIT, Lock, w) == w) {
  4536           ev->OnList = 0 ;
  4537           // We call ::Release while holding the outer lock, thus
  4538           // artificially lengthening the critical section.
  4539           // Consider deferring the ::Release() until the subsequent unlock(),
  4540           // after we've dropped the outer lock.
  4541           if (ReleaseAfter != NULL) {
  4542             ParkEvent::Release (ReleaseAfter) ;
  4544           return ;
  4546         continue ;      // Interference -- *Lock changed -- Just retry
  4548       assert (w & LOCKBIT, "invariant") ;
  4549       ev->ListNext = (ParkEvent *) (w & ~LOCKBIT );
  4550       if (Atomic::cmpxchg_ptr (intptr_t(ev)|LOCKBIT, Lock, w) == w) break ;
  4553     while (ev->OnList != 0) {
  4554       ev->park() ;
  4559 // Release() must extract a successor from the list and then wake that thread.
  4560 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
  4561 // similar to that used by ParkEvent::Allocate() and ::Release().  DMR-based
  4562 // Release() would :
  4563 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
  4564 // (B) Extract a successor from the private list "in-hand"
  4565 // (C) attempt to CAS() the residual back into *Lock over null.
  4566 //     If there were any newly arrived threads and the CAS() would fail.
  4567 //     In that case Release() would detach the RATs, re-merge the list in-hand
  4568 //     with the RATs and repeat as needed.  Alternately, Release() might
  4569 //     detach and extract a successor, but then pass the residual list to the wakee.
  4570 //     The wakee would be responsible for reattaching and remerging before it
  4571 //     competed for the lock.
  4572 //
  4573 // Both "pop" and DMR are immune from ABA corruption -- there can be
  4574 // multiple concurrent pushers, but only one popper or detacher.
  4575 // This implementation pops from the head of the list.  This is unfair,
  4576 // but tends to provide excellent throughput as hot threads remain hot.
  4577 // (We wake recently run threads first).
  4579 void Thread::muxRelease (volatile intptr_t * Lock)  {
  4580   for (;;) {
  4581     const intptr_t w = Atomic::cmpxchg_ptr (0, Lock, LOCKBIT) ;
  4582     assert (w & LOCKBIT, "invariant") ;
  4583     if (w == LOCKBIT) return ;
  4584     ParkEvent * List = (ParkEvent *) (w & ~LOCKBIT) ;
  4585     assert (List != NULL, "invariant") ;
  4586     assert (List->OnList == intptr_t(Lock), "invariant") ;
  4587     ParkEvent * nxt = List->ListNext ;
  4589     // The following CAS() releases the lock and pops the head element.
  4590     if (Atomic::cmpxchg_ptr (intptr_t(nxt), Lock, w) != w) {
  4591       continue ;
  4593     List->OnList = 0 ;
  4594     OrderAccess::fence() ;
  4595     List->unpark () ;
  4596     return ;
  4601 void Threads::verify() {
  4602   ALL_JAVA_THREADS(p) {
  4603     p->verify();
  4605   VMThread* thread = VMThread::vm_thread();
  4606   if (thread != NULL) thread->verify();

mercurial