1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "classfile/moduleEntry.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/scopeDesc.hpp"
  34 #include "compiler/compileBroker.hpp"
  35 #include "compiler/compileTask.hpp"
  36 #include "gc/shared/barrierSet.hpp"
  37 #include "gc/shared/gcId.hpp"
  38 #include "gc/shared/gcLocker.inline.hpp"
  39 #include "gc/shared/workgroup.hpp"
  40 #include "interpreter/interpreter.hpp"
  41 #include "interpreter/linkResolver.hpp"
  42 #include "interpreter/oopMapCache.hpp"
  43 #include "jfr/jfrEvents.hpp"
  44 #include "jfr/support/jfrThreadId.hpp"
  45 #include "jvmtifiles/jvmtiEnv.hpp"
  46 #include "logging/log.hpp"
  47 #include "logging/logConfiguration.hpp"
  48 #include "logging/logStream.hpp"
  49 #include "memory/allocation.inline.hpp"
  50 #include "memory/metaspaceShared.hpp"
  51 #include "memory/oopFactory.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/access.inline.hpp"
  55 #include "oops/instanceKlass.hpp"
  56 #include "oops/objArrayOop.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "oops/symbol.hpp"
  59 #include "oops/typeArrayOop.inline.hpp"
  60 #include "oops/valueKlass.hpp"
  61 #include "oops/verifyOopClosure.hpp"
  62 #include "prims/jvm_misc.hpp"
  63 #include "prims/jvmtiExport.hpp"
  64 #include "prims/jvmtiThreadState.hpp"
  65 #include "prims/privilegedStack.hpp"
  66 #include "runtime/arguments.hpp"
  67 #include "runtime/atomic.hpp"
  68 #include "runtime/biasedLocking.hpp"
  69 #include "runtime/fieldDescriptor.inline.hpp"
  70 #include "runtime/flags/jvmFlagConstraintList.hpp"
  71 #include "runtime/flags/jvmFlagRangeList.hpp"
  72 #include "runtime/flags/jvmFlagWriteableList.hpp"
  73 #include "runtime/deoptimization.hpp"
  74 #include "runtime/frame.inline.hpp"
  75 #include "runtime/handshake.hpp"
  76 #include "runtime/init.hpp"
  77 #include "runtime/interfaceSupport.inline.hpp"
  78 #include "runtime/java.hpp"
  79 #include "runtime/javaCalls.hpp"
  80 #include "runtime/jniHandles.inline.hpp"
  81 #include "runtime/jniPeriodicChecker.hpp"
  82 #include "runtime/memprofiler.hpp"
  83 #include "runtime/mutexLocker.hpp"
  84 #include "runtime/objectMonitor.hpp"
  85 #include "runtime/orderAccess.hpp"
  86 #include "runtime/osThread.hpp"
  87 #include "runtime/prefetch.inline.hpp"
  88 #include "runtime/safepoint.hpp"
  89 #include "runtime/safepointMechanism.inline.hpp"
  90 #include "runtime/safepointVerifiers.hpp"
  91 #include "runtime/sharedRuntime.hpp"
  92 #include "runtime/statSampler.hpp"
  93 #include "runtime/stubRoutines.hpp"
  94 #include "runtime/sweeper.hpp"
  95 #include "runtime/task.hpp"
  96 #include "runtime/thread.inline.hpp"
  97 #include "runtime/threadCritical.hpp"
  98 #include "runtime/threadSMR.inline.hpp"
  99 #include "runtime/threadStatisticalInfo.hpp"
 100 #include "runtime/timer.hpp"
 101 #include "runtime/timerTrace.hpp"
 102 #include "runtime/vframe.inline.hpp"
 103 #include "runtime/vframeArray.hpp"
 104 #include "runtime/vframe_hp.hpp"
 105 #include "runtime/vmThread.hpp"
 106 #include "runtime/vm_operations.hpp"
 107 #include "runtime/vm_version.hpp"
 108 #include "services/attachListener.hpp"
 109 #include "services/management.hpp"
 110 #include "services/memTracker.hpp"
 111 #include "services/threadService.hpp"
 112 #include "utilities/align.hpp"
 113 #include "utilities/copy.hpp"
 114 #include "utilities/defaultStream.hpp"
 115 #include "utilities/dtrace.hpp"
 116 #include "utilities/events.hpp"
 117 #include "utilities/macros.hpp"
 118 #include "utilities/preserveException.hpp"
 119 #include "utilities/singleWriterSynchronizer.hpp"
 120 #include "utilities/vmError.hpp"
 121 #if INCLUDE_JVMCI
 122 #include "jvmci/jvmciCompiler.hpp"
 123 #include "jvmci/jvmciRuntime.hpp"
 124 #include "logging/logHandle.hpp"
 125 #endif
 126 #ifdef COMPILER1
 127 #include "c1/c1_Compiler.hpp"
 128 #endif
 129 #ifdef COMPILER2
 130 #include "opto/c2compiler.hpp"
 131 #include "opto/idealGraphPrinter.hpp"
 132 #endif
 133 #if INCLUDE_RTM_OPT
 134 #include "runtime/rtmLocking.hpp"
 135 #endif
 136 #if INCLUDE_JFR
 137 #include "jfr/jfr.hpp"
 138 #endif
 139 
 140 // Initialization after module runtime initialization
 141 void universe_post_module_init();  // must happen after call_initPhase2
 142 
 143 #ifdef DTRACE_ENABLED
 144 
 145 // Only bother with this argument setup if dtrace is available
 146 
 147   #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START
 148   #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP
 149 
 150   #define DTRACE_THREAD_PROBE(probe, javathread)                           \
 151     {                                                                      \
 152       ResourceMark rm(this);                                               \
 153       int len = 0;                                                         \
 154       const char* name = (javathread)->get_thread_name();                  \
 155       len = strlen(name);                                                  \
 156       HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */               \
 157         (char *) name, len,                                                \
 158         java_lang_Thread::thread_id((javathread)->threadObj()),            \
 159         (uintptr_t) (javathread)->osthread()->thread_id(),                 \
 160         java_lang_Thread::is_daemon((javathread)->threadObj()));           \
 161     }
 162 
 163 #else //  ndef DTRACE_ENABLED
 164 
 165   #define DTRACE_THREAD_PROBE(probe, javathread)
 166 
 167 #endif // ndef DTRACE_ENABLED
 168 
 169 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 170 // Current thread is maintained as a thread-local variable
 171 THREAD_LOCAL_DECL Thread* Thread::_thr_current = NULL;
 172 #endif
 173 
 174 // ======= Thread ========
 175 // Support for forcing alignment of thread objects for biased locking
 176 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) {
 177   if (UseBiasedLocking) {
 178     const int alignment = markOopDesc::biased_lock_alignment;
 179     size_t aligned_size = size + (alignment - sizeof(intptr_t));
 180     void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC)
 181                                           : AllocateHeap(aligned_size, flags, CURRENT_PC,
 182                                                          AllocFailStrategy::RETURN_NULL);
 183     void* aligned_addr     = align_up(real_malloc_addr, alignment);
 184     assert(((uintptr_t) aligned_addr + (uintptr_t) size) <=
 185            ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size),
 186            "JavaThread alignment code overflowed allocated storage");
 187     if (aligned_addr != real_malloc_addr) {
 188       log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT,
 189                               p2i(real_malloc_addr),
 190                               p2i(aligned_addr));
 191     }
 192     ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr;
 193     return aligned_addr;
 194   } else {
 195     return throw_excpt? AllocateHeap(size, flags, CURRENT_PC)
 196                        : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL);
 197   }
 198 }
 199 
 200 void Thread::operator delete(void* p) {
 201   if (UseBiasedLocking) {
 202     FreeHeap(((Thread*) p)->_real_malloc_address);
 203   } else {
 204     FreeHeap(p);
 205   }
 206 }
 207 
 208 void JavaThread::smr_delete() {
 209   if (_on_thread_list) {
 210     ThreadsSMRSupport::smr_delete(this);
 211   } else {
 212     delete this;
 213   }
 214 }
 215 
 216 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
 217 // JavaThread
 218 
 219 
 220 Thread::Thread() {
 221   // stack and get_thread
 222   set_stack_base(NULL);
 223   set_stack_size(0);
 224   set_self_raw_id(0);
 225   set_lgrp_id(-1);
 226   DEBUG_ONLY(clear_suspendible_thread();)
 227 
 228   // allocated data structures
 229   set_osthread(NULL);
 230   set_resource_area(new (mtThread)ResourceArea());
 231   DEBUG_ONLY(_current_resource_mark = NULL;)
 232   set_handle_area(new (mtThread) HandleArea(NULL));
 233   set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, true));
 234   set_active_handles(NULL);
 235   set_free_handle_block(NULL);
 236   set_last_handle_mark(NULL);
 237 
 238   // This initial value ==> never claimed.
 239   _oops_do_parity = 0;
 240   _threads_hazard_ptr = NULL;
 241   _threads_list_ptr = NULL;
 242   _nested_threads_hazard_ptr_cnt = 0;
 243   _rcu_counter = 0;
 244 
 245   // the handle mark links itself to last_handle_mark
 246   new HandleMark(this);
 247 
 248   // plain initialization
 249   debug_only(_owned_locks = NULL;)
 250   debug_only(_allow_allocation_count = 0;)
 251   NOT_PRODUCT(_allow_safepoint_count = 0;)
 252   NOT_PRODUCT(_skip_gcalot = false;)
 253   _jvmti_env_iteration_count = 0;
 254   set_allocated_bytes(0);
 255   _vm_operation_started_count = 0;
 256   _vm_operation_completed_count = 0;
 257   _current_pending_monitor = NULL;
 258   _current_pending_monitor_is_from_java = true;
 259   _current_waiting_monitor = NULL;
 260   _num_nested_signal = 0;
 261   omFreeList = NULL;
 262   omFreeCount = 0;
 263   omFreeProvision = 32;
 264   omInUseList = NULL;
 265   omInUseCount = 0;
 266 
 267 #ifdef ASSERT
 268   _visited_for_critical_count = false;
 269 #endif
 270 
 271   _SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true,
 272                          Monitor::_safepoint_check_sometimes);
 273   _suspend_flags = 0;
 274 
 275   // thread-specific hashCode stream generator state - Marsaglia shift-xor form
 276   _hashStateX = os::random();
 277   _hashStateY = 842502087;
 278   _hashStateZ = 0x8767;    // (int)(3579807591LL & 0xffff) ;
 279   _hashStateW = 273326509;
 280 
 281   _OnTrap   = 0;
 282   _Stalled  = 0;
 283   _TypeTag  = 0x2BAD;
 284 
 285   // Many of the following fields are effectively final - immutable
 286   // Note that nascent threads can't use the Native Monitor-Mutex
 287   // construct until the _MutexEvent is initialized ...
 288   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
 289   // we might instead use a stack of ParkEvents that we could provision on-demand.
 290   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
 291   // and ::Release()
 292   _ParkEvent   = ParkEvent::Allocate(this);
 293   _SleepEvent  = ParkEvent::Allocate(this);
 294   _MutexEvent  = ParkEvent::Allocate(this);
 295   _MuxEvent    = ParkEvent::Allocate(this);
 296 
 297   _buffered_values_dealiaser = NULL;
 298 
 299 #ifdef CHECK_UNHANDLED_OOPS
 300   if (CheckUnhandledOops) {
 301     _unhandled_oops = new UnhandledOops(this);
 302   }
 303 #endif // CHECK_UNHANDLED_OOPS
 304 #ifdef ASSERT
 305   if (UseBiasedLocking) {
 306     assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
 307     assert(this == _real_malloc_address ||
 308            this == align_up(_real_malloc_address, (int)markOopDesc::biased_lock_alignment),
 309            "bug in forced alignment of thread objects");
 310   }
 311 #endif // ASSERT
 312 
 313   // Notify the barrier set that a thread is being created. Note that some
 314   // threads are created before a barrier set is available. The call to
 315   // BarrierSet::on_thread_create() for these threads is therefore deferred
 316   // to BarrierSet::set_barrier_set().
 317   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 318   if (barrier_set != NULL) {
 319     barrier_set->on_thread_create(this);
 320   } else {
 321     DEBUG_ONLY(Threads::inc_threads_before_barrier_set();)
 322   }
 323 }
 324 
 325 void Thread::initialize_thread_current() {
 326 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 327   assert(_thr_current == NULL, "Thread::current already initialized");
 328   _thr_current = this;
 329 #endif
 330   assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized");
 331   ThreadLocalStorage::set_thread(this);
 332   assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
 333 }
 334 
 335 void Thread::clear_thread_current() {
 336   assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!");
 337 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 338   _thr_current = NULL;
 339 #endif
 340   ThreadLocalStorage::set_thread(NULL);
 341 }
 342 
 343 void Thread::record_stack_base_and_size() {
 344   set_stack_base(os::current_stack_base());
 345   set_stack_size(os::current_stack_size());
 346   // CR 7190089: on Solaris, primordial thread's stack is adjusted
 347   // in initialize_thread(). Without the adjustment, stack size is
 348   // incorrect if stack is set to unlimited (ulimit -s unlimited).
 349   // So far, only Solaris has real implementation of initialize_thread().
 350   //
 351   // set up any platform-specific state.
 352   os::initialize_thread(this);
 353 
 354   // Set stack limits after thread is initialized.
 355   if (is_Java_thread()) {
 356     ((JavaThread*) this)->set_stack_overflow_limit();
 357     ((JavaThread*) this)->set_reserved_stack_activation(stack_base());
 358   }
 359 #if INCLUDE_NMT
 360   // record thread's native stack, stack grows downward
 361   MemTracker::record_thread_stack(stack_end(), stack_size());
 362 #endif // INCLUDE_NMT
 363   log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: "
 364     PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).",
 365     os::current_thread_id(), p2i(stack_base() - stack_size()),
 366     p2i(stack_base()), stack_size()/1024);
 367 }
 368 
 369 
 370 Thread::~Thread() {
 371   JFR_ONLY(Jfr::on_thread_destruct(this);)
 372 
 373   // Notify the barrier set that a thread is being destroyed. Note that a barrier
 374   // set might not be available if we encountered errors during bootstrapping.
 375   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 376   if (barrier_set != NULL) {
 377     barrier_set->on_thread_destroy(this);
 378   }
 379 
 380 
 381   // stack_base can be NULL if the thread is never started or exited before
 382   // record_stack_base_and_size called. Although, we would like to ensure
 383   // that all started threads do call record_stack_base_and_size(), there is
 384   // not proper way to enforce that.
 385 #if INCLUDE_NMT
 386   if (_stack_base != NULL) {
 387     MemTracker::release_thread_stack(stack_end(), stack_size());
 388 #ifdef ASSERT
 389     set_stack_base(NULL);
 390 #endif
 391   }
 392 #endif // INCLUDE_NMT
 393 
 394   // deallocate data structures
 395   delete resource_area();
 396   // since the handle marks are using the handle area, we have to deallocated the root
 397   // handle mark before deallocating the thread's handle area,
 398   assert(last_handle_mark() != NULL, "check we have an element");
 399   delete last_handle_mark();
 400   assert(last_handle_mark() == NULL, "check we have reached the end");
 401 
 402   // It's possible we can encounter a null _ParkEvent, etc., in stillborn threads.
 403   // We NULL out the fields for good hygiene.
 404   ParkEvent::Release(_ParkEvent); _ParkEvent   = NULL;
 405   ParkEvent::Release(_SleepEvent); _SleepEvent  = NULL;
 406   ParkEvent::Release(_MutexEvent); _MutexEvent  = NULL;
 407   ParkEvent::Release(_MuxEvent); _MuxEvent    = NULL;
 408 
 409   delete handle_area();
 410   delete metadata_handles();
 411 
 412   // SR_handler uses this as a termination indicator -
 413   // needs to happen before os::free_thread()
 414   delete _SR_lock;
 415   _SR_lock = NULL;
 416 
 417   // osthread() can be NULL, if creation of thread failed.
 418   if (osthread() != NULL) os::free_thread(osthread());
 419 
 420   // clear Thread::current if thread is deleting itself.
 421   // Needed to ensure JNI correctly detects non-attached threads.
 422   if (this == Thread::current()) {
 423     clear_thread_current();
 424   }
 425 
 426   CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();)
 427 }
 428 
 429 // NOTE: dummy function for assertion purpose.
 430 void Thread::run() {
 431   ShouldNotReachHere();
 432 }
 433 
 434 #ifdef ASSERT
 435 // A JavaThread is considered "dangling" if it is not the current
 436 // thread, has been added the Threads list, the system is not at a
 437 // safepoint and the Thread is not "protected".
 438 //
 439 void Thread::check_for_dangling_thread_pointer(Thread *thread) {
 440   assert(!thread->is_Java_thread() || Thread::current() == thread ||
 441          !((JavaThread *) thread)->on_thread_list() ||
 442          SafepointSynchronize::is_at_safepoint() ||
 443          ThreadsSMRSupport::is_a_protected_JavaThread_with_lock((JavaThread *) thread),
 444          "possibility of dangling Thread pointer");
 445 }
 446 #endif
 447 
 448 ThreadPriority Thread::get_priority(const Thread* const thread) {
 449   ThreadPriority priority;
 450   // Can return an error!
 451   (void)os::get_priority(thread, priority);
 452   assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found");
 453   return priority;
 454 }
 455 
 456 void Thread::set_priority(Thread* thread, ThreadPriority priority) {
 457   debug_only(check_for_dangling_thread_pointer(thread);)
 458   // Can return an error!
 459   (void)os::set_priority(thread, priority);
 460 }
 461 
 462 
 463 void Thread::start(Thread* thread) {
 464   // Start is different from resume in that its safety is guaranteed by context or
 465   // being called from a Java method synchronized on the Thread object.
 466   if (!DisableStartThread) {
 467     if (thread->is_Java_thread()) {
 468       // Initialize the thread state to RUNNABLE before starting this thread.
 469       // Can not set it after the thread started because we do not know the
 470       // exact thread state at that time. It could be in MONITOR_WAIT or
 471       // in SLEEPING or some other state.
 472       java_lang_Thread::set_thread_status(((JavaThread*)thread)->threadObj(),
 473                                           java_lang_Thread::RUNNABLE);
 474     }
 475     os::start_thread(thread);
 476   }
 477 }
 478 
 479 // Enqueue a VM_Operation to do the job for us - sometime later
 480 void Thread::send_async_exception(oop java_thread, oop java_throwable) {
 481   VM_ThreadStop* vm_stop = new VM_ThreadStop(java_thread, java_throwable);
 482   VMThread::execute(vm_stop);
 483 }
 484 
 485 
 486 // Check if an external suspend request has completed (or has been
 487 // cancelled). Returns true if the thread is externally suspended and
 488 // false otherwise.
 489 //
 490 // The bits parameter returns information about the code path through
 491 // the routine. Useful for debugging:
 492 //
 493 // set in is_ext_suspend_completed():
 494 // 0x00000001 - routine was entered
 495 // 0x00000010 - routine return false at end
 496 // 0x00000100 - thread exited (return false)
 497 // 0x00000200 - suspend request cancelled (return false)
 498 // 0x00000400 - thread suspended (return true)
 499 // 0x00001000 - thread is in a suspend equivalent state (return true)
 500 // 0x00002000 - thread is native and walkable (return true)
 501 // 0x00004000 - thread is native_trans and walkable (needed retry)
 502 //
 503 // set in wait_for_ext_suspend_completion():
 504 // 0x00010000 - routine was entered
 505 // 0x00020000 - suspend request cancelled before loop (return false)
 506 // 0x00040000 - thread suspended before loop (return true)
 507 // 0x00080000 - suspend request cancelled in loop (return false)
 508 // 0x00100000 - thread suspended in loop (return true)
 509 // 0x00200000 - suspend not completed during retry loop (return false)
 510 
 511 // Helper class for tracing suspend wait debug bits.
 512 //
 513 // 0x00000100 indicates that the target thread exited before it could
 514 // self-suspend which is not a wait failure. 0x00000200, 0x00020000 and
 515 // 0x00080000 each indicate a cancelled suspend request so they don't
 516 // count as wait failures either.
 517 #define DEBUG_FALSE_BITS (0x00000010 | 0x00200000)
 518 
 519 class TraceSuspendDebugBits : public StackObj {
 520  private:
 521   JavaThread * jt;
 522   bool         is_wait;
 523   bool         called_by_wait;  // meaningful when !is_wait
 524   uint32_t *   bits;
 525 
 526  public:
 527   TraceSuspendDebugBits(JavaThread *_jt, bool _is_wait, bool _called_by_wait,
 528                         uint32_t *_bits) {
 529     jt             = _jt;
 530     is_wait        = _is_wait;
 531     called_by_wait = _called_by_wait;
 532     bits           = _bits;
 533   }
 534 
 535   ~TraceSuspendDebugBits() {
 536     if (!is_wait) {
 537 #if 1
 538       // By default, don't trace bits for is_ext_suspend_completed() calls.
 539       // That trace is very chatty.
 540       return;
 541 #else
 542       if (!called_by_wait) {
 543         // If tracing for is_ext_suspend_completed() is enabled, then only
 544         // trace calls to it from wait_for_ext_suspend_completion()
 545         return;
 546       }
 547 #endif
 548     }
 549 
 550     if (AssertOnSuspendWaitFailure || TraceSuspendWaitFailures) {
 551       if (bits != NULL && (*bits & DEBUG_FALSE_BITS) != 0) {
 552         MutexLocker ml(Threads_lock);  // needed for get_thread_name()
 553         ResourceMark rm;
 554 
 555         tty->print_cr(
 556                       "Failed wait_for_ext_suspend_completion(thread=%s, debug_bits=%x)",
 557                       jt->get_thread_name(), *bits);
 558 
 559         guarantee(!AssertOnSuspendWaitFailure, "external suspend wait failed");
 560       }
 561     }
 562   }
 563 };
 564 #undef DEBUG_FALSE_BITS
 565 
 566 
 567 bool JavaThread::is_ext_suspend_completed(bool called_by_wait, int delay,
 568                                           uint32_t *bits) {
 569   TraceSuspendDebugBits tsdb(this, false /* !is_wait */, called_by_wait, bits);
 570 
 571   bool did_trans_retry = false;  // only do thread_in_native_trans retry once
 572   bool do_trans_retry;           // flag to force the retry
 573 
 574   *bits |= 0x00000001;
 575 
 576   do {
 577     do_trans_retry = false;
 578 
 579     if (is_exiting()) {
 580       // Thread is in the process of exiting. This is always checked
 581       // first to reduce the risk of dereferencing a freed JavaThread.
 582       *bits |= 0x00000100;
 583       return false;
 584     }
 585 
 586     if (!is_external_suspend()) {
 587       // Suspend request is cancelled. This is always checked before
 588       // is_ext_suspended() to reduce the risk of a rogue resume
 589       // confusing the thread that made the suspend request.
 590       *bits |= 0x00000200;
 591       return false;
 592     }
 593 
 594     if (is_ext_suspended()) {
 595       // thread is suspended
 596       *bits |= 0x00000400;
 597       return true;
 598     }
 599 
 600     // Now that we no longer do hard suspends of threads running
 601     // native code, the target thread can be changing thread state
 602     // while we are in this routine:
 603     //
 604     //   _thread_in_native -> _thread_in_native_trans -> _thread_blocked
 605     //
 606     // We save a copy of the thread state as observed at this moment
 607     // and make our decision about suspend completeness based on the
 608     // copy. This closes the race where the thread state is seen as
 609     // _thread_in_native_trans in the if-thread_blocked check, but is
 610     // seen as _thread_blocked in if-thread_in_native_trans check.
 611     JavaThreadState save_state = thread_state();
 612 
 613     if (save_state == _thread_blocked && is_suspend_equivalent()) {
 614       // If the thread's state is _thread_blocked and this blocking
 615       // condition is known to be equivalent to a suspend, then we can
 616       // consider the thread to be externally suspended. This means that
 617       // the code that sets _thread_blocked has been modified to do
 618       // self-suspension if the blocking condition releases. We also
 619       // used to check for CONDVAR_WAIT here, but that is now covered by
 620       // the _thread_blocked with self-suspension check.
 621       //
 622       // Return true since we wouldn't be here unless there was still an
 623       // external suspend request.
 624       *bits |= 0x00001000;
 625       return true;
 626     } else if (save_state == _thread_in_native && frame_anchor()->walkable()) {
 627       // Threads running native code will self-suspend on native==>VM/Java
 628       // transitions. If its stack is walkable (should always be the case
 629       // unless this function is called before the actual java_suspend()
 630       // call), then the wait is done.
 631       *bits |= 0x00002000;
 632       return true;
 633     } else if (!called_by_wait && !did_trans_retry &&
 634                save_state == _thread_in_native_trans &&
 635                frame_anchor()->walkable()) {
 636       // The thread is transitioning from thread_in_native to another
 637       // thread state. check_safepoint_and_suspend_for_native_trans()
 638       // will force the thread to self-suspend. If it hasn't gotten
 639       // there yet we may have caught the thread in-between the native
 640       // code check above and the self-suspend. Lucky us. If we were
 641       // called by wait_for_ext_suspend_completion(), then it
 642       // will be doing the retries so we don't have to.
 643       //
 644       // Since we use the saved thread state in the if-statement above,
 645       // there is a chance that the thread has already transitioned to
 646       // _thread_blocked by the time we get here. In that case, we will
 647       // make a single unnecessary pass through the logic below. This
 648       // doesn't hurt anything since we still do the trans retry.
 649 
 650       *bits |= 0x00004000;
 651 
 652       // Once the thread leaves thread_in_native_trans for another
 653       // thread state, we break out of this retry loop. We shouldn't
 654       // need this flag to prevent us from getting back here, but
 655       // sometimes paranoia is good.
 656       did_trans_retry = true;
 657 
 658       // We wait for the thread to transition to a more usable state.
 659       for (int i = 1; i <= SuspendRetryCount; i++) {
 660         // We used to do an "os::yield_all(i)" call here with the intention
 661         // that yielding would increase on each retry. However, the parameter
 662         // is ignored on Linux which means the yield didn't scale up. Waiting
 663         // on the SR_lock below provides a much more predictable scale up for
 664         // the delay. It also provides a simple/direct point to check for any
 665         // safepoint requests from the VMThread
 666 
 667         // temporarily drops SR_lock while doing wait with safepoint check
 668         // (if we're a JavaThread - the WatcherThread can also call this)
 669         // and increase delay with each retry
 670         SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
 671 
 672         // check the actual thread state instead of what we saved above
 673         if (thread_state() != _thread_in_native_trans) {
 674           // the thread has transitioned to another thread state so
 675           // try all the checks (except this one) one more time.
 676           do_trans_retry = true;
 677           break;
 678         }
 679       } // end retry loop
 680 
 681 
 682     }
 683   } while (do_trans_retry);
 684 
 685   *bits |= 0x00000010;
 686   return false;
 687 }
 688 
 689 // Wait for an external suspend request to complete (or be cancelled).
 690 // Returns true if the thread is externally suspended and false otherwise.
 691 //
 692 bool JavaThread::wait_for_ext_suspend_completion(int retries, int delay,
 693                                                  uint32_t *bits) {
 694   TraceSuspendDebugBits tsdb(this, true /* is_wait */,
 695                              false /* !called_by_wait */, bits);
 696 
 697   // local flag copies to minimize SR_lock hold time
 698   bool is_suspended;
 699   bool pending;
 700   uint32_t reset_bits;
 701 
 702   // set a marker so is_ext_suspend_completed() knows we are the caller
 703   *bits |= 0x00010000;
 704 
 705   // We use reset_bits to reinitialize the bits value at the top of
 706   // each retry loop. This allows the caller to make use of any
 707   // unused bits for their own marking purposes.
 708   reset_bits = *bits;
 709 
 710   {
 711     MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
 712     is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
 713                                             delay, bits);
 714     pending = is_external_suspend();
 715   }
 716   // must release SR_lock to allow suspension to complete
 717 
 718   if (!pending) {
 719     // A cancelled suspend request is the only false return from
 720     // is_ext_suspend_completed() that keeps us from entering the
 721     // retry loop.
 722     *bits |= 0x00020000;
 723     return false;
 724   }
 725 
 726   if (is_suspended) {
 727     *bits |= 0x00040000;
 728     return true;
 729   }
 730 
 731   for (int i = 1; i <= retries; i++) {
 732     *bits = reset_bits;  // reinit to only track last retry
 733 
 734     // We used to do an "os::yield_all(i)" call here with the intention
 735     // that yielding would increase on each retry. However, the parameter
 736     // is ignored on Linux which means the yield didn't scale up. Waiting
 737     // on the SR_lock below provides a much more predictable scale up for
 738     // the delay. It also provides a simple/direct point to check for any
 739     // safepoint requests from the VMThread
 740 
 741     {
 742       MutexLocker ml(SR_lock());
 743       // wait with safepoint check (if we're a JavaThread - the WatcherThread
 744       // can also call this)  and increase delay with each retry
 745       SR_lock()->wait(!Thread::current()->is_Java_thread(), i * delay);
 746 
 747       is_suspended = is_ext_suspend_completed(true /* called_by_wait */,
 748                                               delay, bits);
 749 
 750       // It is possible for the external suspend request to be cancelled
 751       // (by a resume) before the actual suspend operation is completed.
 752       // Refresh our local copy to see if we still need to wait.
 753       pending = is_external_suspend();
 754     }
 755 
 756     if (!pending) {
 757       // A cancelled suspend request is the only false return from
 758       // is_ext_suspend_completed() that keeps us from staying in the
 759       // retry loop.
 760       *bits |= 0x00080000;
 761       return false;
 762     }
 763 
 764     if (is_suspended) {
 765       *bits |= 0x00100000;
 766       return true;
 767     }
 768   } // end retry loop
 769 
 770   // thread did not suspend after all our retries
 771   *bits |= 0x00200000;
 772   return false;
 773 }
 774 
 775 // Called from API entry points which perform stack walking. If the
 776 // associated JavaThread is the current thread, then wait_for_suspend
 777 // is not used. Otherwise, it determines if we should wait for the
 778 // "other" thread to complete external suspension. (NOTE: in future
 779 // releases the suspension mechanism should be reimplemented so this
 780 // is not necessary.)
 781 //
 782 bool
 783 JavaThread::is_thread_fully_suspended(bool wait_for_suspend, uint32_t *bits) {
 784   if (this != JavaThread::current()) {
 785     // "other" threads require special handling.
 786     if (wait_for_suspend) {
 787       // We are allowed to wait for the external suspend to complete
 788       // so give the other thread a chance to get suspended.
 789       if (!wait_for_ext_suspend_completion(SuspendRetryCount,
 790                                            SuspendRetryDelay, bits)) {
 791         // Didn't make it so let the caller know.
 792         return false;
 793       }
 794     }
 795     // We aren't allowed to wait for the external suspend to complete
 796     // so if the other thread isn't externally suspended we need to
 797     // let the caller know.
 798     else if (!is_ext_suspend_completed_with_lock(bits)) {
 799       return false;
 800     }
 801   }
 802 
 803   return true;
 804 }
 805 
 806 #ifndef PRODUCT
 807 void JavaThread::record_jump(address target, address instr, const char* file,
 808                              int line) {
 809 
 810   // This should not need to be atomic as the only way for simultaneous
 811   // updates is via interrupts. Even then this should be rare or non-existent
 812   // and we don't care that much anyway.
 813 
 814   int index = _jmp_ring_index;
 815   _jmp_ring_index = (index + 1) & (jump_ring_buffer_size - 1);
 816   _jmp_ring[index]._target = (intptr_t) target;
 817   _jmp_ring[index]._instruction = (intptr_t) instr;
 818   _jmp_ring[index]._file = file;
 819   _jmp_ring[index]._line = line;
 820 }
 821 #endif // PRODUCT
 822 
 823 void Thread::interrupt(Thread* thread) {
 824   debug_only(check_for_dangling_thread_pointer(thread);)
 825   os::interrupt(thread);
 826 }
 827 
 828 bool Thread::is_interrupted(Thread* thread, bool clear_interrupted) {
 829   debug_only(check_for_dangling_thread_pointer(thread);)
 830   // Note:  If clear_interrupted==false, this simply fetches and
 831   // returns the value of the field osthread()->interrupted().
 832   return os::is_interrupted(thread, clear_interrupted);
 833 }
 834 
 835 
 836 // GC Support
 837 bool Thread::claim_oops_do_par_case(int strong_roots_parity) {
 838   int thread_parity = _oops_do_parity;
 839   if (thread_parity != strong_roots_parity) {
 840     jint res = Atomic::cmpxchg(strong_roots_parity, &_oops_do_parity, thread_parity);
 841     if (res == thread_parity) {
 842       return true;
 843     } else {
 844       guarantee(res == strong_roots_parity, "Or else what?");
 845       return false;
 846     }
 847   }
 848   return false;
 849 }
 850 
 851 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
 852   active_handles()->oops_do(f);
 853   // Do oop for ThreadShadow
 854   f->do_oop((oop*)&_pending_exception);
 855   handle_area()->oops_do(f);
 856 
 857   if (MonitorInUseLists) {
 858     // When using thread local monitor lists, we scan them here,
 859     // and the remaining global monitors in ObjectSynchronizer::oops_do().
 860     ObjectSynchronizer::thread_local_used_oops_do(this, f);
 861   }
 862 }
 863 
 864 void Thread::metadata_handles_do(void f(Metadata*)) {
 865   // Only walk the Handles in Thread.
 866   if (metadata_handles() != NULL) {
 867     for (int i = 0; i< metadata_handles()->length(); i++) {
 868       f(metadata_handles()->at(i));
 869     }
 870   }
 871 }
 872 
 873 void Thread::print_on(outputStream* st, bool print_extended_info) const {
 874   // get_priority assumes osthread initialized
 875   if (osthread() != NULL) {
 876     int os_prio;
 877     if (os::get_native_priority(this, &os_prio) == OS_OK) {
 878       st->print("os_prio=%d ", os_prio);
 879     }
 880 
 881     st->print("cpu=%.2fms ",
 882               os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0
 883               );
 884     st->print("elapsed=%.2fs ",
 885               _statistical_info.getElapsedTime() / 1000.0
 886               );
 887     if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) {
 888       size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes();
 889       st->print("allocated=" SIZE_FORMAT "%s ",
 890                 byte_size_in_proper_unit(allocated_bytes),
 891                 proper_unit_for_byte_size(allocated_bytes)
 892                 );
 893       st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount());
 894     }
 895 
 896     st->print("tid=" INTPTR_FORMAT " ", p2i(this));
 897     osthread()->print_on(st);
 898   }
 899   ThreadsSMRSupport::print_info_on(this, st);
 900   st->print(" ");
 901   debug_only(if (WizardMode) print_owned_locks_on(st);)
 902 }
 903 
 904 // Thread::print_on_error() is called by fatal error handler. Don't use
 905 // any lock or allocate memory.
 906 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const {
 907   assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates");
 908 
 909   if (is_VM_thread())                 { st->print("VMThread"); }
 910   else if (is_GC_task_thread())       { st->print("GCTaskThread"); }
 911   else if (is_Watcher_thread())       { st->print("WatcherThread"); }
 912   else if (is_ConcurrentGC_thread())  { st->print("ConcurrentGCThread"); }
 913   else                                { st->print("Thread"); }
 914 
 915   if (is_Named_thread()) {
 916     st->print(" \"%s\"", name());
 917   }
 918 
 919   st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]",
 920             p2i(stack_end()), p2i(stack_base()));
 921 
 922   if (osthread()) {
 923     st->print(" [id=%d]", osthread()->thread_id());
 924   }
 925 
 926   ThreadsSMRSupport::print_info_on(this, st);
 927 }
 928 
 929 void Thread::print_value_on(outputStream* st) const {
 930   if (is_Named_thread()) {
 931     st->print(" \"%s\" ", name());
 932   }
 933   st->print(INTPTR_FORMAT, p2i(this));   // print address
 934 }
 935 
 936 void JavaThread::print_vt_buffer_stats_on(outputStream* st) const {
 937   st->print_cr("%s:", this->name());
 938   st->print_cr("\tChunks in use       : %d", vtchunk_in_use());
 939   st->print_cr("\tCached chunk        : %d", local_free_chunk() == NULL ? 0 : 1);
 940   st->print_cr("\tMax chunks          : %d", vtchunk_max());
 941   st->print_cr("\tReturned chunks     : %d", vtchunk_total_returned());
 942   st->print_cr("\tFailed chunk allocs : %d", vtchunk_total_failed());
 943   st->print_cr("\tMemory buffered     : " JLONG_FORMAT, vtchunk_total_memory_buffered());
 944   st->print_cr("");
 945 }
 946 
 947 #ifdef ASSERT
 948 void Thread::print_owned_locks_on(outputStream* st) const {
 949   Monitor *cur = _owned_locks;
 950   if (cur == NULL) {
 951     st->print(" (no locks) ");
 952   } else {
 953     st->print_cr(" Locks owned:");
 954     while (cur) {
 955       cur->print_on(st);
 956       cur = cur->next();
 957     }
 958   }
 959 }
 960 
 961 static int ref_use_count  = 0;
 962 
 963 bool Thread::owns_locks_but_compiled_lock() const {
 964   for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
 965     if (cur != Compile_lock) return true;
 966   }
 967   return false;
 968 }
 969 
 970 
 971 #endif
 972 
 973 #ifndef PRODUCT
 974 
 975 // The flag: potential_vm_operation notifies if this particular safepoint state could potentially
 976 // invoke the vm-thread (e.g., an oop allocation). In that case, we also have to make sure that
 977 // no locks which allow_vm_block's are held
 978 void Thread::check_for_valid_safepoint_state(bool potential_vm_operation) {
 979   // Check if current thread is allowed to block at a safepoint
 980   if (!(_allow_safepoint_count == 0)) {
 981     fatal("Possible safepoint reached by thread that does not allow it");
 982   }
 983   if (is_Java_thread() && ((JavaThread*)this)->thread_state() != _thread_in_vm) {
 984     fatal("LEAF method calling lock?");
 985   }
 986 
 987 #ifdef ASSERT
 988   if (potential_vm_operation && is_Java_thread()
 989       && !Universe::is_bootstrapping()) {
 990     // Make sure we do not hold any locks that the VM thread also uses.
 991     // This could potentially lead to deadlocks
 992     for (Monitor *cur = _owned_locks; cur; cur = cur->next()) {
 993       // Threads_lock is special, since the safepoint synchronization will not start before this is
 994       // acquired. Hence, a JavaThread cannot be holding it at a safepoint. So is VMOperationRequest_lock,
 995       // since it is used to transfer control between JavaThreads and the VMThread
 996       // Do not *exclude* any locks unless you are absolutely sure it is correct. Ask someone else first!
 997       if ((cur->allow_vm_block() &&
 998            cur != Threads_lock &&
 999            cur != Compile_lock &&               // Temporary: should not be necessary when we get separate compilation
1000            cur != VMOperationRequest_lock &&
1001            cur != VMOperationQueue_lock) ||
1002            cur->rank() == Mutex::special) {
1003         fatal("Thread holding lock at safepoint that vm can block on: %s", cur->name());
1004       }
1005     }
1006   }
1007 
1008   if (GCALotAtAllSafepoints) {
1009     // We could enter a safepoint here and thus have a gc
1010     InterfaceSupport::check_gc_alot();
1011   }
1012 #endif
1013 }
1014 #endif
1015 
1016 bool Thread::is_in_stack(address adr) const {
1017   assert(Thread::current() == this, "is_in_stack can only be called from current thread");
1018   address end = os::current_stack_pointer();
1019   // Allow non Java threads to call this without stack_base
1020   if (_stack_base == NULL) return true;
1021   if (stack_base() >= adr && adr >= end) return true;
1022 
1023   return false;
1024 }
1025 
1026 bool Thread::is_in_usable_stack(address adr) const {
1027   size_t stack_guard_size = os::uses_stack_guard_pages() ? JavaThread::stack_guard_zone_size() : 0;
1028   size_t usable_stack_size = _stack_size - stack_guard_size;
1029 
1030   return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size));
1031 }
1032 
1033 
1034 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter
1035 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being
1036 // used for compilation in the future. If that change is made, the need for these methods
1037 // should be revisited, and they should be removed if possible.
1038 
1039 bool Thread::is_lock_owned(address adr) const {
1040   return on_local_stack(adr);
1041 }
1042 
1043 bool Thread::set_as_starting_thread() {
1044   // NOTE: this must be called inside the main thread.
1045   return os::create_main_thread((JavaThread*)this);
1046 }
1047 
1048 static void initialize_class(Symbol* class_name, TRAPS) {
1049   Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK);
1050   InstanceKlass::cast(klass)->initialize(CHECK);
1051 }
1052 
1053 
1054 // Creates the initial ThreadGroup
1055 static Handle create_initial_thread_group(TRAPS) {
1056   Handle system_instance = JavaCalls::construct_new_instance(
1057                             SystemDictionary::ThreadGroup_klass(),
1058                             vmSymbols::void_method_signature(),
1059                             CHECK_NH);
1060   Universe::set_system_thread_group(system_instance());
1061 
1062   Handle string = java_lang_String::create_from_str("main", CHECK_NH);
1063   Handle main_instance = JavaCalls::construct_new_instance(
1064                             SystemDictionary::ThreadGroup_klass(),
1065                             vmSymbols::threadgroup_string_void_signature(),
1066                             system_instance,
1067                             string,
1068                             CHECK_NH);
1069   return main_instance;
1070 }
1071 
1072 // Creates the initial Thread
1073 static oop create_initial_thread(Handle thread_group, JavaThread* thread,
1074                                  TRAPS) {
1075   InstanceKlass* ik = SystemDictionary::Thread_klass();
1076   assert(ik->is_initialized(), "must be");
1077   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK_NULL);
1078 
1079   // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
1080   // constructor calls Thread.current(), which must be set here for the
1081   // initial thread.
1082   java_lang_Thread::set_thread(thread_oop(), thread);
1083   java_lang_Thread::set_priority(thread_oop(), NormPriority);
1084   thread->set_threadObj(thread_oop());
1085 
1086   Handle string = java_lang_String::create_from_str("main", CHECK_NULL);
1087 
1088   JavaValue result(T_VOID);
1089   JavaCalls::call_special(&result, thread_oop,
1090                           ik,
1091                           vmSymbols::object_initializer_name(),
1092                           vmSymbols::threadgroup_string_void_signature(),
1093                           thread_group,
1094                           string,
1095                           CHECK_NULL);
1096   return thread_oop();
1097 }
1098 
1099 char java_runtime_name[128] = "";
1100 char java_runtime_version[128] = "";
1101 
1102 // extract the JRE name from java.lang.VersionProps.java_runtime_name
1103 static const char* get_java_runtime_name(TRAPS) {
1104   Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(),
1105                                     Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1106   fieldDescriptor fd;
1107   bool found = k != NULL &&
1108                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_name_name(),
1109                                                         vmSymbols::string_signature(), &fd);
1110   if (found) {
1111     oop name_oop = k->java_mirror()->obj_field(fd.offset());
1112     if (name_oop == NULL) {
1113       return NULL;
1114     }
1115     const char* name = java_lang_String::as_utf8_string(name_oop,
1116                                                         java_runtime_name,
1117                                                         sizeof(java_runtime_name));
1118     return name;
1119   } else {
1120     return NULL;
1121   }
1122 }
1123 
1124 // extract the JRE version from java.lang.VersionProps.java_runtime_version
1125 static const char* get_java_runtime_version(TRAPS) {
1126   Klass* k = SystemDictionary::find(vmSymbols::java_lang_VersionProps(),
1127                                     Handle(), Handle(), CHECK_AND_CLEAR_NULL);
1128   fieldDescriptor fd;
1129   bool found = k != NULL &&
1130                InstanceKlass::cast(k)->find_local_field(vmSymbols::java_runtime_version_name(),
1131                                                         vmSymbols::string_signature(), &fd);
1132   if (found) {
1133     oop name_oop = k->java_mirror()->obj_field(fd.offset());
1134     if (name_oop == NULL) {
1135       return NULL;
1136     }
1137     const char* name = java_lang_String::as_utf8_string(name_oop,
1138                                                         java_runtime_version,
1139                                                         sizeof(java_runtime_version));
1140     return name;
1141   } else {
1142     return NULL;
1143   }
1144 }
1145 
1146 // General purpose hook into Java code, run once when the VM is initialized.
1147 // The Java library method itself may be changed independently from the VM.
1148 static void call_postVMInitHook(TRAPS) {
1149   Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
1150   if (klass != NULL) {
1151     JavaValue result(T_VOID);
1152     JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
1153                            vmSymbols::void_method_signature(),
1154                            CHECK);
1155   }
1156 }
1157 
1158 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
1159                                     bool daemon, TRAPS) {
1160   assert(thread_group.not_null(), "thread group should be specified");
1161   assert(threadObj() == NULL, "should only create Java thread object once");
1162 
1163   InstanceKlass* ik = SystemDictionary::Thread_klass();
1164   assert(ik->is_initialized(), "must be");
1165   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
1166 
1167   // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
1168   // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
1169   // constructor calls Thread.current(), which must be set here.
1170   java_lang_Thread::set_thread(thread_oop(), this);
1171   java_lang_Thread::set_priority(thread_oop(), NormPriority);
1172   set_threadObj(thread_oop());
1173 
1174   JavaValue result(T_VOID);
1175   if (thread_name != NULL) {
1176     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
1177     // Thread gets assigned specified name and null target
1178     JavaCalls::call_special(&result,
1179                             thread_oop,
1180                             ik,
1181                             vmSymbols::object_initializer_name(),
1182                             vmSymbols::threadgroup_string_void_signature(),
1183                             thread_group,
1184                             name,
1185                             THREAD);
1186   } else {
1187     // Thread gets assigned name "Thread-nnn" and null target
1188     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
1189     JavaCalls::call_special(&result,
1190                             thread_oop,
1191                             ik,
1192                             vmSymbols::object_initializer_name(),
1193                             vmSymbols::threadgroup_runnable_void_signature(),
1194                             thread_group,
1195                             Handle(),
1196                             THREAD);
1197   }
1198 
1199 
1200   if (daemon) {
1201     java_lang_Thread::set_daemon(thread_oop());
1202   }
1203 
1204   if (HAS_PENDING_EXCEPTION) {
1205     return;
1206   }
1207 
1208   Klass* group =  SystemDictionary::ThreadGroup_klass();
1209   Handle threadObj(THREAD, this->threadObj());
1210 
1211   JavaCalls::call_special(&result,
1212                           thread_group,
1213                           group,
1214                           vmSymbols::add_method_name(),
1215                           vmSymbols::thread_void_signature(),
1216                           threadObj,          // Arg 1
1217                           THREAD);
1218 }
1219 
1220 // List of all NonJavaThreads and safe iteration over that list.
1221 
1222 class NonJavaThread::List {
1223 public:
1224   NonJavaThread* volatile _head;
1225   SingleWriterSynchronizer _protect;
1226 
1227   List() : _head(NULL), _protect() {}
1228 };
1229 
1230 NonJavaThread::List NonJavaThread::_the_list;
1231 
1232 NonJavaThread::Iterator::Iterator() :
1233   _protect_enter(_the_list._protect.enter()),
1234   _current(OrderAccess::load_acquire(&_the_list._head))
1235 {}
1236 
1237 NonJavaThread::Iterator::~Iterator() {
1238   _the_list._protect.exit(_protect_enter);
1239 }
1240 
1241 void NonJavaThread::Iterator::step() {
1242   assert(!end(), "precondition");
1243   _current = OrderAccess::load_acquire(&_current->_next);
1244 }
1245 
1246 NonJavaThread::NonJavaThread() : Thread(), _next(NULL) {
1247   // Add this thread to _the_list.
1248   MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1249   _next = _the_list._head;
1250   OrderAccess::release_store(&_the_list._head, this);
1251 }
1252 
1253 NonJavaThread::~NonJavaThread() {
1254   // Remove this thread from _the_list.
1255   MutexLockerEx lock(NonJavaThreadsList_lock, Mutex::_no_safepoint_check_flag);
1256   NonJavaThread* volatile* p = &_the_list._head;
1257   for (NonJavaThread* t = *p; t != NULL; p = &t->_next, t = *p) {
1258     if (t == this) {
1259       *p = this->_next;
1260       // Wait for any in-progress iterators.
1261       _the_list._protect.synchronize();
1262       break;
1263     }
1264   }
1265 }
1266 
1267 // NamedThread --  non-JavaThread subclasses with multiple
1268 // uniquely named instances should derive from this.
1269 NamedThread::NamedThread() :
1270   NonJavaThread(),
1271   _name(NULL),
1272   _processed_thread(NULL),
1273   _gc_id(GCId::undefined())
1274 {}
1275 
1276 NamedThread::~NamedThread() {
1277   if (_name != NULL) {
1278     FREE_C_HEAP_ARRAY(char, _name);
1279     _name = NULL;
1280   }
1281 }
1282 
1283 void NamedThread::set_name(const char* format, ...) {
1284   guarantee(_name == NULL, "Only get to set name once.");
1285   _name = NEW_C_HEAP_ARRAY(char, max_name_len, mtThread);
1286   guarantee(_name != NULL, "alloc failure");
1287   va_list ap;
1288   va_start(ap, format);
1289   jio_vsnprintf(_name, max_name_len, format, ap);
1290   va_end(ap);
1291 }
1292 
1293 void NamedThread::initialize_named_thread() {
1294   set_native_thread_name(name());
1295 }
1296 
1297 void NamedThread::print_on(outputStream* st) const {
1298   st->print("\"%s\" ", name());
1299   Thread::print_on(st);
1300   st->cr();
1301 }
1302 
1303 
1304 // ======= WatcherThread ========
1305 
1306 // The watcher thread exists to simulate timer interrupts.  It should
1307 // be replaced by an abstraction over whatever native support for
1308 // timer interrupts exists on the platform.
1309 
1310 WatcherThread* WatcherThread::_watcher_thread   = NULL;
1311 bool WatcherThread::_startable = false;
1312 volatile bool  WatcherThread::_should_terminate = false;
1313 
1314 WatcherThread::WatcherThread() : NonJavaThread() {
1315   assert(watcher_thread() == NULL, "we can only allocate one WatcherThread");
1316   if (os::create_thread(this, os::watcher_thread)) {
1317     _watcher_thread = this;
1318 
1319     // Set the watcher thread to the highest OS priority which should not be
1320     // used, unless a Java thread with priority java.lang.Thread.MAX_PRIORITY
1321     // is created. The only normal thread using this priority is the reference
1322     // handler thread, which runs for very short intervals only.
1323     // If the VMThread's priority is not lower than the WatcherThread profiling
1324     // will be inaccurate.
1325     os::set_priority(this, MaxPriority);
1326     if (!DisableStartThread) {
1327       os::start_thread(this);
1328     }
1329   }
1330 }
1331 
1332 int WatcherThread::sleep() const {
1333   // The WatcherThread does not participate in the safepoint protocol
1334   // for the PeriodicTask_lock because it is not a JavaThread.
1335   MutexLockerEx ml(PeriodicTask_lock, Mutex::_no_safepoint_check_flag);
1336 
1337   if (_should_terminate) {
1338     // check for termination before we do any housekeeping or wait
1339     return 0;  // we did not sleep.
1340   }
1341 
1342   // remaining will be zero if there are no tasks,
1343   // causing the WatcherThread to sleep until a task is
1344   // enrolled
1345   int remaining = PeriodicTask::time_to_wait();
1346   int time_slept = 0;
1347 
1348   // we expect this to timeout - we only ever get unparked when
1349   // we should terminate or when a new task has been enrolled
1350   OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */);
1351 
1352   jlong time_before_loop = os::javaTimeNanos();
1353 
1354   while (true) {
1355     bool timedout = PeriodicTask_lock->wait(Mutex::_no_safepoint_check_flag,
1356                                             remaining);
1357     jlong now = os::javaTimeNanos();
1358 
1359     if (remaining == 0) {
1360       // if we didn't have any tasks we could have waited for a long time
1361       // consider the time_slept zero and reset time_before_loop
1362       time_slept = 0;
1363       time_before_loop = now;
1364     } else {
1365       // need to recalculate since we might have new tasks in _tasks
1366       time_slept = (int) ((now - time_before_loop) / 1000000);
1367     }
1368 
1369     // Change to task list or spurious wakeup of some kind
1370     if (timedout || _should_terminate) {
1371       break;
1372     }
1373 
1374     remaining = PeriodicTask::time_to_wait();
1375     if (remaining == 0) {
1376       // Last task was just disenrolled so loop around and wait until
1377       // another task gets enrolled
1378       continue;
1379     }
1380 
1381     remaining -= time_slept;
1382     if (remaining <= 0) {
1383       break;
1384     }
1385   }
1386 
1387   return time_slept;
1388 }
1389 
1390 void WatcherThread::run() {
1391   assert(this == watcher_thread(), "just checking");
1392 
1393   this->record_stack_base_and_size();
1394   this->set_native_thread_name(this->name());
1395   this->set_active_handles(JNIHandleBlock::allocate_block());
1396   while (true) {
1397     assert(watcher_thread() == Thread::current(), "thread consistency check");
1398     assert(watcher_thread() == this, "thread consistency check");
1399 
1400     // Calculate how long it'll be until the next PeriodicTask work
1401     // should be done, and sleep that amount of time.
1402     int time_waited = sleep();
1403 
1404     if (VMError::is_error_reported()) {
1405       // A fatal error has happened, the error handler(VMError::report_and_die)
1406       // should abort JVM after creating an error log file. However in some
1407       // rare cases, the error handler itself might deadlock. Here periodically
1408       // check for error reporting timeouts, and if it happens, just proceed to
1409       // abort the VM.
1410 
1411       // This code is in WatcherThread because WatcherThread wakes up
1412       // periodically so the fatal error handler doesn't need to do anything;
1413       // also because the WatcherThread is less likely to crash than other
1414       // threads.
1415 
1416       for (;;) {
1417         // Note: we use naked sleep in this loop because we want to avoid using
1418         // any kind of VM infrastructure which may be broken at this point.
1419         if (VMError::check_timeout()) {
1420           // We hit error reporting timeout. Error reporting was interrupted and
1421           // will be wrapping things up now (closing files etc). Give it some more
1422           // time, then quit the VM.
1423           os::naked_short_sleep(200);
1424           // Print a message to stderr.
1425           fdStream err(defaultStream::output_fd());
1426           err.print_raw_cr("# [ timer expired, abort... ]");
1427           // skip atexit/vm_exit/vm_abort hooks
1428           os::die();
1429         }
1430 
1431         // Wait a second, then recheck for timeout.
1432         os::naked_short_sleep(999);
1433       }
1434     }
1435 
1436     if (_should_terminate) {
1437       // check for termination before posting the next tick
1438       break;
1439     }
1440 
1441     PeriodicTask::real_time_tick(time_waited);
1442   }
1443 
1444   // Signal that it is terminated
1445   {
1446     MutexLockerEx mu(Terminator_lock, Mutex::_no_safepoint_check_flag);
1447     _watcher_thread = NULL;
1448     Terminator_lock->notify();
1449   }
1450 }
1451 
1452 void WatcherThread::start() {
1453   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1454 
1455   if (watcher_thread() == NULL && _startable) {
1456     _should_terminate = false;
1457     // Create the single instance of WatcherThread
1458     new WatcherThread();
1459   }
1460 }
1461 
1462 void WatcherThread::make_startable() {
1463   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1464   _startable = true;
1465 }
1466 
1467 void WatcherThread::stop() {
1468   {
1469     // Follow normal safepoint aware lock enter protocol since the
1470     // WatcherThread is stopped by another JavaThread.
1471     MutexLocker ml(PeriodicTask_lock);
1472     _should_terminate = true;
1473 
1474     WatcherThread* watcher = watcher_thread();
1475     if (watcher != NULL) {
1476       // unpark the WatcherThread so it can see that it should terminate
1477       watcher->unpark();
1478     }
1479   }
1480 
1481   MutexLocker mu(Terminator_lock);
1482 
1483   while (watcher_thread() != NULL) {
1484     // This wait should make safepoint checks, wait without a timeout,
1485     // and wait as a suspend-equivalent condition.
1486     Terminator_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
1487                           Mutex::_as_suspend_equivalent_flag);
1488   }
1489 }
1490 
1491 void WatcherThread::unpark() {
1492   assert(PeriodicTask_lock->owned_by_self(), "PeriodicTask_lock required");
1493   PeriodicTask_lock->notify();
1494 }
1495 
1496 void WatcherThread::print_on(outputStream* st) const {
1497   st->print("\"%s\" ", name());
1498   Thread::print_on(st);
1499   st->cr();
1500 }
1501 
1502 // ======= JavaThread ========
1503 
1504 #if INCLUDE_JVMCI
1505 
1506 jlong* JavaThread::_jvmci_old_thread_counters;
1507 
1508 bool jvmci_counters_include(JavaThread* thread) {
1509   return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
1510 }
1511 
1512 void JavaThread::collect_counters(typeArrayOop array) {
1513   if (JVMCICounterSize > 0) {
1514     JavaThreadIteratorWithHandle jtiwh;
1515     for (int i = 0; i < array->length(); i++) {
1516       array->long_at_put(i, _jvmci_old_thread_counters[i]);
1517     }
1518     for (; JavaThread *tp = jtiwh.next(); ) {
1519       if (jvmci_counters_include(tp)) {
1520         for (int i = 0; i < array->length(); i++) {
1521           array->long_at_put(i, array->long_at(i) + tp->_jvmci_counters[i]);
1522         }
1523       }
1524     }
1525   }
1526 }
1527 
1528 #endif // INCLUDE_JVMCI
1529 
1530 // A JavaThread is a normal Java thread
1531 
1532 void JavaThread::initialize() {
1533   // Initialize fields
1534 
1535   set_saved_exception_pc(NULL);
1536   set_threadObj(NULL);
1537   _anchor.clear();
1538   set_entry_point(NULL);
1539   set_jni_functions(jni_functions());
1540   set_callee_target(NULL);
1541   set_vm_result(NULL);
1542   set_vm_result_2(NULL);
1543   set_return_buffered_value(NULL);
1544   set_vframe_array_head(NULL);
1545   set_vframe_array_last(NULL);
1546   set_deferred_locals(NULL);
1547   set_deopt_mark(NULL);
1548   set_deopt_compiled_method(NULL);
1549   clear_must_deopt_id();
1550   set_monitor_chunks(NULL);
1551   set_next(NULL);
1552   _on_thread_list = false;
1553   set_thread_state(_thread_new);
1554   _terminated = _not_terminated;
1555   _privileged_stack_top = NULL;
1556   _array_for_gc = NULL;
1557   _suspend_equivalent = false;
1558   _in_deopt_handler = 0;
1559   _doing_unsafe_access = false;
1560   _stack_guard_state = stack_guard_unused;
1561 #if INCLUDE_JVMCI
1562   _pending_monitorenter = false;
1563   _pending_deoptimization = -1;
1564   _pending_failed_speculation = 0;
1565   _pending_transfer_to_interpreter = false;
1566   _adjusting_comp_level = false;
1567   _jvmci._alternate_call_target = NULL;
1568   assert(_jvmci._implicit_exception_pc == NULL, "must be");
1569   if (JVMCICounterSize > 0) {
1570     _jvmci_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
1571     memset(_jvmci_counters, 0, sizeof(jlong) * JVMCICounterSize);
1572   } else {
1573     _jvmci_counters = NULL;
1574   }
1575 #endif // INCLUDE_JVMCI
1576   _reserved_stack_activation = NULL;  // stack base not known yet
1577   (void)const_cast<oop&>(_exception_oop = oop(NULL));
1578   _exception_pc  = 0;
1579   _exception_handler_pc = 0;
1580   _is_method_handle_return = 0;
1581   _jvmti_thread_state= NULL;
1582   _should_post_on_exceptions_flag = JNI_FALSE;
1583   _interp_only_mode    = 0;
1584   _special_runtime_exit_condition = _no_async_condition;
1585   _pending_async_exception = NULL;
1586   _thread_stat = NULL;
1587   _thread_stat = new ThreadStatistics();
1588   _blocked_on_compilation = false;
1589   _jni_active_critical = 0;
1590   _pending_jni_exception_check_fn = NULL;
1591   _do_not_unlock_if_synchronized = false;
1592   _cached_monitor_info = NULL;
1593   _parker = Parker::Allocate(this);
1594 
1595 #ifndef PRODUCT
1596   _jmp_ring_index = 0;
1597   for (int ji = 0; ji < jump_ring_buffer_size; ji++) {
1598     record_jump(NULL, NULL, NULL, 0);
1599   }
1600 #endif // PRODUCT
1601 
1602   // Setup safepoint state info for this thread
1603   ThreadSafepointState::create(this);
1604 
1605   debug_only(_java_call_counter = 0);
1606 
1607   // JVMTI PopFrame support
1608   _popframe_condition = popframe_inactive;
1609   _popframe_preserved_args = NULL;
1610   _popframe_preserved_args_size = 0;
1611   _frames_to_pop_failed_realloc = 0;
1612 
1613   // Buffered value types support
1614   _vt_alloc_ptr = NULL;
1615   _vt_alloc_limit = NULL;
1616   _local_free_chunk = NULL;
1617   _current_vtbuffer_mark = VTBuffer::mark_A;
1618   // Buffered value types instrumentation support
1619   _vtchunk_in_use = 0;
1620   _vtchunk_max = 0;
1621   _vtchunk_total_returned = 0;
1622   _vtchunk_total_failed = 0;
1623   _vtchunk_total_memory_buffered = 0;
1624 
1625   if (SafepointMechanism::uses_thread_local_poll()) {
1626     SafepointMechanism::initialize_header(this);
1627   }
1628 
1629   pd_initialize();
1630 }
1631 
1632 JavaThread::JavaThread(bool is_attaching_via_jni) :
1633                        Thread() {
1634   initialize();
1635   if (is_attaching_via_jni) {
1636     _jni_attach_state = _attaching_via_jni;
1637   } else {
1638     _jni_attach_state = _not_attaching_via_jni;
1639   }
1640   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1641 }
1642 
1643 bool JavaThread::reguard_stack(address cur_sp) {
1644   if (_stack_guard_state != stack_guard_yellow_reserved_disabled
1645       && _stack_guard_state != stack_guard_reserved_disabled) {
1646     return true; // Stack already guarded or guard pages not needed.
1647   }
1648 
1649   if (register_stack_overflow()) {
1650     // For those architectures which have separate register and
1651     // memory stacks, we must check the register stack to see if
1652     // it has overflowed.
1653     return false;
1654   }
1655 
1656   // Java code never executes within the yellow zone: the latter is only
1657   // there to provoke an exception during stack banging.  If java code
1658   // is executing there, either StackShadowPages should be larger, or
1659   // some exception code in c1, c2 or the interpreter isn't unwinding
1660   // when it should.
1661   guarantee(cur_sp > stack_reserved_zone_base(),
1662             "not enough space to reguard - increase StackShadowPages");
1663   if (_stack_guard_state == stack_guard_yellow_reserved_disabled) {
1664     enable_stack_yellow_reserved_zone();
1665     if (reserved_stack_activation() != stack_base()) {
1666       set_reserved_stack_activation(stack_base());
1667     }
1668   } else if (_stack_guard_state == stack_guard_reserved_disabled) {
1669     set_reserved_stack_activation(stack_base());
1670     enable_stack_reserved_zone();
1671   }
1672   return true;
1673 }
1674 
1675 bool JavaThread::reguard_stack(void) {
1676   return reguard_stack(os::current_stack_pointer());
1677 }
1678 
1679 
1680 void JavaThread::block_if_vm_exited() {
1681   if (_terminated == _vm_exited) {
1682     // _vm_exited is set at safepoint, and Threads_lock is never released
1683     // we will block here forever
1684     Threads_lock->lock_without_safepoint_check();
1685     ShouldNotReachHere();
1686   }
1687 }
1688 
1689 
1690 // Remove this ifdef when C1 is ported to the compiler interface.
1691 static void compiler_thread_entry(JavaThread* thread, TRAPS);
1692 static void sweeper_thread_entry(JavaThread* thread, TRAPS);
1693 
1694 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
1695                        Thread() {
1696   initialize();
1697   _jni_attach_state = _not_attaching_via_jni;
1698   set_entry_point(entry_point);
1699   // Create the native thread itself.
1700   // %note runtime_23
1701   os::ThreadType thr_type = os::java_thread;
1702   thr_type = entry_point == &compiler_thread_entry ? os::compiler_thread :
1703                                                      os::java_thread;
1704   os::create_thread(this, thr_type, stack_sz);
1705   // The _osthread may be NULL here because we ran out of memory (too many threads active).
1706   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1707   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1708   // the exception consists of creating the exception object & initializing it, initialization
1709   // will leave the VM via a JavaCall and then all locks must be unlocked).
1710   //
1711   // The thread is still suspended when we reach here. Thread must be explicit started
1712   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1713   // by calling Threads:add. The reason why this is not done here, is because the thread
1714   // object must be fully initialized (take a look at JVM_Start)
1715 }
1716 
1717 JavaThread::~JavaThread() {
1718 
1719   // JSR166 -- return the parker to the free list
1720   Parker::Release(_parker);
1721   _parker = NULL;
1722 
1723   // Free any remaining  previous UnrollBlock
1724   vframeArray* old_array = vframe_array_last();
1725 
1726   if (old_array != NULL) {
1727     Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
1728     old_array->set_unroll_block(NULL);
1729     delete old_info;
1730     delete old_array;
1731   }
1732 
1733   GrowableArray<jvmtiDeferredLocalVariableSet*>* deferred = deferred_locals();
1734   if (deferred != NULL) {
1735     // This can only happen if thread is destroyed before deoptimization occurs.
1736     assert(deferred->length() != 0, "empty array!");
1737     do {
1738       jvmtiDeferredLocalVariableSet* dlv = deferred->at(0);
1739       deferred->remove_at(0);
1740       // individual jvmtiDeferredLocalVariableSet are CHeapObj's
1741       delete dlv;
1742     } while (deferred->length() != 0);
1743     delete deferred;
1744   }
1745 
1746   // All Java related clean up happens in exit
1747   ThreadSafepointState::destroy(this);
1748   if (_thread_stat != NULL) delete _thread_stat;
1749 
1750   if (_vt_alloc_ptr != NULL) {
1751     VTBufferChunk* chunk = VTBufferChunk::chunk(_vt_alloc_ptr);
1752     while (chunk != NULL) {
1753       VTBufferChunk* temp = chunk->prev();
1754       VTBuffer::recycle_chunk(this, chunk);
1755       chunk = temp;
1756     }
1757     _vt_alloc_ptr = NULL;
1758     _vt_alloc_limit = NULL;
1759   }
1760 
1761 #if INCLUDE_JVMCI
1762   if (JVMCICounterSize > 0) {
1763     if (jvmci_counters_include(this)) {
1764       for (int i = 0; i < JVMCICounterSize; i++) {
1765         _jvmci_old_thread_counters[i] += _jvmci_counters[i];
1766       }
1767     }
1768     FREE_C_HEAP_ARRAY(jlong, _jvmci_counters);
1769   }
1770 #endif // INCLUDE_JVMCI
1771 }
1772 
1773 
1774 // The first routine called by a new Java thread
1775 void JavaThread::run() {
1776   // initialize thread-local alloc buffer related fields
1777   this->initialize_tlab();
1778 
1779   // used to test validity of stack trace backs
1780   this->record_base_of_stack_pointer();
1781 
1782   // Record real stack base and size.
1783   this->record_stack_base_and_size();
1784 
1785   this->create_stack_guard_pages();
1786 
1787   this->cache_global_variables();
1788 
1789   // Thread is now sufficient initialized to be handled by the safepoint code as being
1790   // in the VM. Change thread state from _thread_new to _thread_in_vm
1791   ThreadStateTransition::transition_and_fence(this, _thread_new, _thread_in_vm);
1792 
1793   assert(JavaThread::current() == this, "sanity check");
1794   assert(!Thread::current()->owns_locks(), "sanity check");
1795 
1796   DTRACE_THREAD_PROBE(start, this);
1797 
1798   // This operation might block. We call that after all safepoint checks for a new thread has
1799   // been completed.
1800   this->set_active_handles(JNIHandleBlock::allocate_block());
1801 
1802   if (JvmtiExport::should_post_thread_life()) {
1803     JvmtiExport::post_thread_start(this);
1804   }
1805 
1806   EventThreadStart event;
1807   if (event.should_commit()) {
1808     event.set_thread(JFR_THREAD_ID(this));
1809     event.commit();
1810   }
1811 
1812   // We call another function to do the rest so we are sure that the stack addresses used
1813   // from there will be lower than the stack base just computed
1814   thread_main_inner();
1815 
1816   // Note, thread is no longer valid at this point!
1817 }
1818 
1819 
1820 void JavaThread::thread_main_inner() {
1821   assert(JavaThread::current() == this, "sanity check");
1822   assert(this->threadObj() != NULL, "just checking");
1823 
1824   // Execute thread entry point unless this thread has a pending exception
1825   // or has been stopped before starting.
1826   // Note: Due to JVM_StopThread we can have pending exceptions already!
1827   if (!this->has_pending_exception() &&
1828       !java_lang_Thread::is_stillborn(this->threadObj())) {
1829     {
1830       ResourceMark rm(this);
1831       this->set_native_thread_name(this->get_thread_name());
1832     }
1833     HandleMark hm(this);
1834     this->entry_point()(this, this);
1835   }
1836 
1837   DTRACE_THREAD_PROBE(stop, this);
1838 
1839   this->exit(false);
1840   this->smr_delete();
1841 }
1842 
1843 
1844 static void ensure_join(JavaThread* thread) {
1845   // We do not need to grab the Threads_lock, since we are operating on ourself.
1846   Handle threadObj(thread, thread->threadObj());
1847   assert(threadObj.not_null(), "java thread object must exist");
1848   ObjectLocker lock(threadObj, thread);
1849   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1850   thread->clear_pending_exception();
1851   // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
1852   java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
1853   // Clear the native thread instance - this makes isAlive return false and allows the join()
1854   // to complete once we've done the notify_all below
1855   java_lang_Thread::set_thread(threadObj(), NULL);
1856   lock.notify_all(thread);
1857   // Ignore pending exception (ThreadDeath), since we are exiting anyway
1858   thread->clear_pending_exception();
1859 }
1860 
1861 
1862 // For any new cleanup additions, please check to see if they need to be applied to
1863 // cleanup_failed_attach_current_thread as well.
1864 void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
1865   assert(this == JavaThread::current(), "thread consistency check");
1866 
1867   elapsedTimer _timer_exit_phase1;
1868   elapsedTimer _timer_exit_phase2;
1869   elapsedTimer _timer_exit_phase3;
1870   elapsedTimer _timer_exit_phase4;
1871 
1872   if (log_is_enabled(Debug, os, thread, timer)) {
1873     _timer_exit_phase1.start();
1874   }
1875 
1876   HandleMark hm(this);
1877   Handle uncaught_exception(this, this->pending_exception());
1878   this->clear_pending_exception();
1879   Handle threadObj(this, this->threadObj());
1880   assert(threadObj.not_null(), "Java thread object should be created");
1881 
1882   // FIXIT: This code should be moved into else part, when reliable 1.2/1.3 check is in place
1883   {
1884     EXCEPTION_MARK;
1885 
1886     CLEAR_PENDING_EXCEPTION;
1887   }
1888   if (!destroy_vm) {
1889     if (uncaught_exception.not_null()) {
1890       EXCEPTION_MARK;
1891       // Call method Thread.dispatchUncaughtException().
1892       Klass* thread_klass = SystemDictionary::Thread_klass();
1893       JavaValue result(T_VOID);
1894       JavaCalls::call_virtual(&result,
1895                               threadObj, thread_klass,
1896                               vmSymbols::dispatchUncaughtException_name(),
1897                               vmSymbols::throwable_void_signature(),
1898                               uncaught_exception,
1899                               THREAD);
1900       if (HAS_PENDING_EXCEPTION) {
1901         ResourceMark rm(this);
1902         jio_fprintf(defaultStream::error_stream(),
1903                     "\nException: %s thrown from the UncaughtExceptionHandler"
1904                     " in thread \"%s\"\n",
1905                     pending_exception()->klass()->external_name(),
1906                     get_thread_name());
1907         CLEAR_PENDING_EXCEPTION;
1908       }
1909     }
1910 
1911     // Called before the java thread exit since we want to read info
1912     // from java_lang_Thread object
1913     EventThreadEnd event;
1914     if (event.should_commit()) {
1915       event.set_thread(JFR_THREAD_ID(this));
1916       event.commit();
1917     }
1918 
1919     // Call after last event on thread
1920     JFR_ONLY(Jfr::on_thread_exit(this);)
1921 
1922     // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
1923     // the execution of the method. If that is not enough, then we don't really care. Thread.stop
1924     // is deprecated anyhow.
1925     if (!is_Compiler_thread()) {
1926       int count = 3;
1927       while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
1928         EXCEPTION_MARK;
1929         JavaValue result(T_VOID);
1930         Klass* thread_klass = SystemDictionary::Thread_klass();
1931         JavaCalls::call_virtual(&result,
1932                                 threadObj, thread_klass,
1933                                 vmSymbols::exit_method_name(),
1934                                 vmSymbols::void_method_signature(),
1935                                 THREAD);
1936         CLEAR_PENDING_EXCEPTION;
1937       }
1938     }
1939     // notify JVMTI
1940     if (JvmtiExport::should_post_thread_life()) {
1941       JvmtiExport::post_thread_end(this);
1942     }
1943 
1944     // We have notified the agents that we are exiting, before we go on,
1945     // we must check for a pending external suspend request and honor it
1946     // in order to not surprise the thread that made the suspend request.
1947     while (true) {
1948       {
1949         MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
1950         if (!is_external_suspend()) {
1951           set_terminated(_thread_exiting);
1952           ThreadService::current_thread_exiting(this);
1953           break;
1954         }
1955         // Implied else:
1956         // Things get a little tricky here. We have a pending external
1957         // suspend request, but we are holding the SR_lock so we
1958         // can't just self-suspend. So we temporarily drop the lock
1959         // and then self-suspend.
1960       }
1961 
1962       ThreadBlockInVM tbivm(this);
1963       java_suspend_self();
1964 
1965       // We're done with this suspend request, but we have to loop around
1966       // and check again. Eventually we will get SR_lock without a pending
1967       // external suspend request and will be able to mark ourselves as
1968       // exiting.
1969     }
1970     // no more external suspends are allowed at this point
1971   } else {
1972     // before_exit() has already posted JVMTI THREAD_END events
1973   }
1974 
1975   if (log_is_enabled(Debug, os, thread, timer)) {
1976     _timer_exit_phase1.stop();
1977     _timer_exit_phase2.start();
1978   }
1979   // Notify waiters on thread object. This has to be done after exit() is called
1980   // on the thread (if the thread is the last thread in a daemon ThreadGroup the
1981   // group should have the destroyed bit set before waiters are notified).
1982   ensure_join(this);
1983   assert(!this->has_pending_exception(), "ensure_join should have cleared");
1984 
1985   if (log_is_enabled(Debug, os, thread, timer)) {
1986     _timer_exit_phase2.stop();
1987     _timer_exit_phase3.start();
1988   }
1989   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1990   // held by this thread must be released. The spec does not distinguish
1991   // between JNI-acquired and regular Java monitors. We can only see
1992   // regular Java monitors here if monitor enter-exit matching is broken.
1993   //
1994   // Optionally release any monitors for regular JavaThread exits. This
1995   // is provided as a work around for any bugs in monitor enter-exit
1996   // matching. This can be expensive so it is not enabled by default.
1997   //
1998   // ensure_join() ignores IllegalThreadStateExceptions, and so does
1999   // ObjectSynchronizer::release_monitors_owned_by_thread().
2000   if (exit_type == jni_detach || ObjectMonitor::Knob_ExitRelease) {
2001     // Sanity check even though JNI DetachCurrentThread() would have
2002     // returned JNI_ERR if there was a Java frame. JavaThread exit
2003     // should be done executing Java code by the time we get here.
2004     assert(!this->has_last_Java_frame(),
2005            "should not have a Java frame when detaching or exiting");
2006     ObjectSynchronizer::release_monitors_owned_by_thread(this);
2007     assert(!this->has_pending_exception(), "release_monitors should have cleared");
2008   }
2009 
2010   // These things needs to be done while we are still a Java Thread. Make sure that thread
2011   // is in a consistent state, in case GC happens
2012   assert(_privileged_stack_top == NULL, "must be NULL when we get here");
2013 
2014   if (active_handles() != NULL) {
2015     JNIHandleBlock* block = active_handles();
2016     set_active_handles(NULL);
2017     JNIHandleBlock::release_block(block);
2018   }
2019 
2020   if (free_handle_block() != NULL) {
2021     JNIHandleBlock* block = free_handle_block();
2022     set_free_handle_block(NULL);
2023     JNIHandleBlock::release_block(block);
2024   }
2025 
2026   // These have to be removed while this is still a valid thread.
2027   remove_stack_guard_pages();
2028 
2029   if (UseTLAB) {
2030     tlab().make_parsable(true);  // retire TLAB
2031   }
2032 
2033   if (JvmtiEnv::environments_might_exist()) {
2034     JvmtiExport::cleanup_thread(this);
2035   }
2036 
2037   // We must flush any deferred card marks and other various GC barrier
2038   // related buffers (e.g. G1 SATB buffer and G1 dirty card queue buffer)
2039   // before removing a thread from the list of active threads.
2040   BarrierSet::barrier_set()->on_thread_detach(this);
2041 
2042   log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
2043     exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
2044     os::current_thread_id());
2045 
2046   if (log_is_enabled(Debug, os, thread, timer)) {
2047     _timer_exit_phase3.stop();
2048     _timer_exit_phase4.start();
2049   }
2050   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
2051   Threads::remove(this);
2052 
2053   if (log_is_enabled(Debug, os, thread, timer)) {
2054     _timer_exit_phase4.stop();
2055     ResourceMark rm(this);
2056     log_debug(os, thread, timer)("name='%s'"
2057                                  ", exit-phase1=" JLONG_FORMAT
2058                                  ", exit-phase2=" JLONG_FORMAT
2059                                  ", exit-phase3=" JLONG_FORMAT
2060                                  ", exit-phase4=" JLONG_FORMAT,
2061                                  get_thread_name(),
2062                                  _timer_exit_phase1.milliseconds(),
2063                                  _timer_exit_phase2.milliseconds(),
2064                                  _timer_exit_phase3.milliseconds(),
2065                                  _timer_exit_phase4.milliseconds());
2066   }
2067 }
2068 
2069 void JavaThread::cleanup_failed_attach_current_thread() {
2070   if (active_handles() != NULL) {
2071     JNIHandleBlock* block = active_handles();
2072     set_active_handles(NULL);
2073     JNIHandleBlock::release_block(block);
2074   }
2075 
2076   if (free_handle_block() != NULL) {
2077     JNIHandleBlock* block = free_handle_block();
2078     set_free_handle_block(NULL);
2079     JNIHandleBlock::release_block(block);
2080   }
2081 
2082   // These have to be removed while this is still a valid thread.
2083   remove_stack_guard_pages();
2084 
2085   if (UseTLAB) {
2086     tlab().make_parsable(true);  // retire TLAB, if any
2087   }
2088 
2089   BarrierSet::barrier_set()->on_thread_detach(this);
2090 
2091   Threads::remove(this);
2092   this->smr_delete();
2093 }
2094 
2095 JavaThread* JavaThread::active() {
2096   Thread* thread = Thread::current();
2097   if (thread->is_Java_thread()) {
2098     return (JavaThread*) thread;
2099   } else {
2100     assert(thread->is_VM_thread(), "this must be a vm thread");
2101     VM_Operation* op = ((VMThread*) thread)->vm_operation();
2102     JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
2103     assert(ret->is_Java_thread(), "must be a Java thread");
2104     return ret;
2105   }
2106 }
2107 
2108 bool JavaThread::is_lock_owned(address adr) const {
2109   if (Thread::is_lock_owned(adr)) return true;
2110 
2111   for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2112     if (chunk->contains(adr)) return true;
2113   }
2114 
2115   return false;
2116 }
2117 
2118 
2119 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
2120   chunk->set_next(monitor_chunks());
2121   set_monitor_chunks(chunk);
2122 }
2123 
2124 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
2125   guarantee(monitor_chunks() != NULL, "must be non empty");
2126   if (monitor_chunks() == chunk) {
2127     set_monitor_chunks(chunk->next());
2128   } else {
2129     MonitorChunk* prev = monitor_chunks();
2130     while (prev->next() != chunk) prev = prev->next();
2131     prev->set_next(chunk->next());
2132   }
2133 }
2134 
2135 // JVM support.
2136 
2137 // Note: this function shouldn't block if it's called in
2138 // _thread_in_native_trans state (such as from
2139 // check_special_condition_for_native_trans()).
2140 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
2141 
2142   if (has_last_Java_frame() && has_async_condition()) {
2143     // If we are at a polling page safepoint (not a poll return)
2144     // then we must defer async exception because live registers
2145     // will be clobbered by the exception path. Poll return is
2146     // ok because the call we a returning from already collides
2147     // with exception handling registers and so there is no issue.
2148     // (The exception handling path kills call result registers but
2149     //  this is ok since the exception kills the result anyway).
2150 
2151     if (is_at_poll_safepoint()) {
2152       // if the code we are returning to has deoptimized we must defer
2153       // the exception otherwise live registers get clobbered on the
2154       // exception path before deoptimization is able to retrieve them.
2155       //
2156       RegisterMap map(this, false);
2157       frame caller_fr = last_frame().sender(&map);
2158       assert(caller_fr.is_compiled_frame(), "what?");
2159       if (caller_fr.is_deoptimized_frame()) {
2160         log_info(exceptions)("deferred async exception at compiled safepoint");
2161         return;
2162       }
2163     }
2164   }
2165 
2166   JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
2167   if (condition == _no_async_condition) {
2168     // Conditions have changed since has_special_runtime_exit_condition()
2169     // was called:
2170     // - if we were here only because of an external suspend request,
2171     //   then that was taken care of above (or cancelled) so we are done
2172     // - if we were here because of another async request, then it has
2173     //   been cleared between the has_special_runtime_exit_condition()
2174     //   and now so again we are done
2175     return;
2176   }
2177 
2178   // Check for pending async. exception
2179   if (_pending_async_exception != NULL) {
2180     // Only overwrite an already pending exception, if it is not a threadDeath.
2181     if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
2182 
2183       // We cannot call Exceptions::_throw(...) here because we cannot block
2184       set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
2185 
2186       LogTarget(Info, exceptions) lt;
2187       if (lt.is_enabled()) {
2188         ResourceMark rm;
2189         LogStream ls(lt);
2190         ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this));
2191           if (has_last_Java_frame()) {
2192             frame f = last_frame();
2193            ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp()));
2194           }
2195         ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name());
2196       }
2197       _pending_async_exception = NULL;
2198       clear_has_async_exception();
2199     }
2200   }
2201 
2202   if (check_unsafe_error &&
2203       condition == _async_unsafe_access_error && !has_pending_exception()) {
2204     condition = _no_async_condition;  // done
2205     switch (thread_state()) {
2206     case _thread_in_vm: {
2207       JavaThread* THREAD = this;
2208       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2209     }
2210     case _thread_in_native: {
2211       ThreadInVMfromNative tiv(this);
2212       JavaThread* THREAD = this;
2213       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2214     }
2215     case _thread_in_Java: {
2216       ThreadInVMfromJava tiv(this);
2217       JavaThread* THREAD = this;
2218       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
2219     }
2220     default:
2221       ShouldNotReachHere();
2222     }
2223   }
2224 
2225   assert(condition == _no_async_condition || has_pending_exception() ||
2226          (!check_unsafe_error && condition == _async_unsafe_access_error),
2227          "must have handled the async condition, if no exception");
2228 }
2229 
2230 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
2231   //
2232   // Check for pending external suspend. Internal suspend requests do
2233   // not use handle_special_runtime_exit_condition().
2234   // If JNIEnv proxies are allowed, don't self-suspend if the target
2235   // thread is not the current thread. In older versions of jdbx, jdbx
2236   // threads could call into the VM with another thread's JNIEnv so we
2237   // can be here operating on behalf of a suspended thread (4432884).
2238   bool do_self_suspend = is_external_suspend_with_lock();
2239   if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) {
2240     //
2241     // Because thread is external suspended the safepoint code will count
2242     // thread as at a safepoint. This can be odd because we can be here
2243     // as _thread_in_Java which would normally transition to _thread_blocked
2244     // at a safepoint. We would like to mark the thread as _thread_blocked
2245     // before calling java_suspend_self like all other callers of it but
2246     // we must then observe proper safepoint protocol. (We can't leave
2247     // _thread_blocked with a safepoint in progress). However we can be
2248     // here as _thread_in_native_trans so we can't use a normal transition
2249     // constructor/destructor pair because they assert on that type of
2250     // transition. We could do something like:
2251     //
2252     // JavaThreadState state = thread_state();
2253     // set_thread_state(_thread_in_vm);
2254     // {
2255     //   ThreadBlockInVM tbivm(this);
2256     //   java_suspend_self()
2257     // }
2258     // set_thread_state(_thread_in_vm_trans);
2259     // if (safepoint) block;
2260     // set_thread_state(state);
2261     //
2262     // but that is pretty messy. Instead we just go with the way the
2263     // code has worked before and note that this is the only path to
2264     // java_suspend_self that doesn't put the thread in _thread_blocked
2265     // mode.
2266 
2267     frame_anchor()->make_walkable(this);
2268     java_suspend_self();
2269 
2270     // We might be here for reasons in addition to the self-suspend request
2271     // so check for other async requests.
2272   }
2273 
2274   if (check_asyncs) {
2275     check_and_handle_async_exceptions();
2276   }
2277 
2278   JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)
2279 }
2280 
2281 void JavaThread::send_thread_stop(oop java_throwable)  {
2282   assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
2283   assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
2284   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
2285 
2286   // Do not throw asynchronous exceptions against the compiler thread
2287   // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2288   if (!can_call_java()) return;
2289 
2290   {
2291     // Actually throw the Throwable against the target Thread - however
2292     // only if there is no thread death exception installed already.
2293     if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2294       // If the topmost frame is a runtime stub, then we are calling into
2295       // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2296       // must deoptimize the caller before continuing, as the compiled  exception handler table
2297       // may not be valid
2298       if (has_last_Java_frame()) {
2299         frame f = last_frame();
2300         if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
2301           // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2302           RegisterMap reg_map(this, UseBiasedLocking);
2303           frame compiled_frame = f.sender(&reg_map);
2304           if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
2305             Deoptimization::deoptimize(this, compiled_frame, &reg_map);
2306           }
2307         }
2308       }
2309 
2310       // Set async. pending exception in thread.
2311       set_pending_async_exception(java_throwable);
2312 
2313       if (log_is_enabled(Info, exceptions)) {
2314          ResourceMark rm;
2315         log_info(exceptions)("Pending Async. exception installed of type: %s",
2316                              InstanceKlass::cast(_pending_async_exception->klass())->external_name());
2317       }
2318       // for AbortVMOnException flag
2319       Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name());
2320     }
2321   }
2322 
2323 
2324   // Interrupt thread so it will wake up from a potential wait()
2325   Thread::interrupt(this);
2326 }
2327 
2328 // External suspension mechanism.
2329 //
2330 // Tell the VM to suspend a thread when ever it knows that it does not hold on
2331 // to any VM_locks and it is at a transition
2332 // Self-suspension will happen on the transition out of the vm.
2333 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
2334 //
2335 // Guarantees on return:
2336 //   + Target thread will not execute any new bytecode (that's why we need to
2337 //     force a safepoint)
2338 //   + Target thread will not enter any new monitors
2339 //
2340 void JavaThread::java_suspend() {
2341   ThreadsListHandle tlh;
2342   if (!tlh.includes(this) || threadObj() == NULL || is_exiting()) {
2343     return;
2344   }
2345 
2346   { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2347     if (!is_external_suspend()) {
2348       // a racing resume has cancelled us; bail out now
2349       return;
2350     }
2351 
2352     // suspend is done
2353     uint32_t debug_bits = 0;
2354     // Warning: is_ext_suspend_completed() may temporarily drop the
2355     // SR_lock to allow the thread to reach a stable thread state if
2356     // it is currently in a transient thread state.
2357     if (is_ext_suspend_completed(false /* !called_by_wait */,
2358                                  SuspendRetryDelay, &debug_bits)) {
2359       return;
2360     }
2361   }
2362 
2363   VM_ThreadSuspend vm_suspend;
2364   VMThread::execute(&vm_suspend);
2365 }
2366 
2367 // Part II of external suspension.
2368 // A JavaThread self suspends when it detects a pending external suspend
2369 // request. This is usually on transitions. It is also done in places
2370 // where continuing to the next transition would surprise the caller,
2371 // e.g., monitor entry.
2372 //
2373 // Returns the number of times that the thread self-suspended.
2374 //
2375 // Note: DO NOT call java_suspend_self() when you just want to block current
2376 //       thread. java_suspend_self() is the second stage of cooperative
2377 //       suspension for external suspend requests and should only be used
2378 //       to complete an external suspend request.
2379 //
2380 int JavaThread::java_suspend_self() {
2381   int ret = 0;
2382 
2383   // we are in the process of exiting so don't suspend
2384   if (is_exiting()) {
2385     clear_external_suspend();
2386     return ret;
2387   }
2388 
2389   assert(_anchor.walkable() ||
2390          (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
2391          "must have walkable stack");
2392 
2393   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2394 
2395   assert(!this->is_ext_suspended(),
2396          "a thread trying to self-suspend should not already be suspended");
2397 
2398   if (this->is_suspend_equivalent()) {
2399     // If we are self-suspending as a result of the lifting of a
2400     // suspend equivalent condition, then the suspend_equivalent
2401     // flag is not cleared until we set the ext_suspended flag so
2402     // that wait_for_ext_suspend_completion() returns consistent
2403     // results.
2404     this->clear_suspend_equivalent();
2405   }
2406 
2407   // A racing resume may have cancelled us before we grabbed SR_lock
2408   // above. Or another external suspend request could be waiting for us
2409   // by the time we return from SR_lock()->wait(). The thread
2410   // that requested the suspension may already be trying to walk our
2411   // stack and if we return now, we can change the stack out from under
2412   // it. This would be a "bad thing (TM)" and cause the stack walker
2413   // to crash. We stay self-suspended until there are no more pending
2414   // external suspend requests.
2415   while (is_external_suspend()) {
2416     ret++;
2417     this->set_ext_suspended();
2418 
2419     // _ext_suspended flag is cleared by java_resume()
2420     while (is_ext_suspended()) {
2421       this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
2422     }
2423   }
2424 
2425   return ret;
2426 }
2427 
2428 #ifdef ASSERT
2429 // Verify the JavaThread has not yet been published in the Threads::list, and
2430 // hence doesn't need protection from concurrent access at this stage.
2431 void JavaThread::verify_not_published() {
2432   // Cannot create a ThreadsListHandle here and check !tlh.includes(this)
2433   // since an unpublished JavaThread doesn't participate in the
2434   // Thread-SMR protocol for keeping a ThreadsList alive.
2435   assert(!on_thread_list(), "JavaThread shouldn't have been published yet!");
2436 }
2437 #endif
2438 
2439 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2440 // progress or when _suspend_flags is non-zero.
2441 // Current thread needs to self-suspend if there is a suspend request and/or
2442 // block if a safepoint is in progress.
2443 // Async exception ISN'T checked.
2444 // Note only the ThreadInVMfromNative transition can call this function
2445 // directly and when thread state is _thread_in_native_trans
2446 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
2447   assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
2448 
2449   JavaThread *curJT = JavaThread::current();
2450   bool do_self_suspend = thread->is_external_suspend();
2451 
2452   assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
2453 
2454   // If JNIEnv proxies are allowed, don't self-suspend if the target
2455   // thread is not the current thread. In older versions of jdbx, jdbx
2456   // threads could call into the VM with another thread's JNIEnv so we
2457   // can be here operating on behalf of a suspended thread (4432884).
2458   if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) {
2459     JavaThreadState state = thread->thread_state();
2460 
2461     // We mark this thread_blocked state as a suspend-equivalent so
2462     // that a caller to is_ext_suspend_completed() won't be confused.
2463     // The suspend-equivalent state is cleared by java_suspend_self().
2464     thread->set_suspend_equivalent();
2465 
2466     // If the safepoint code sees the _thread_in_native_trans state, it will
2467     // wait until the thread changes to other thread state. There is no
2468     // guarantee on how soon we can obtain the SR_lock and complete the
2469     // self-suspend request. It would be a bad idea to let safepoint wait for
2470     // too long. Temporarily change the state to _thread_blocked to
2471     // let the VM thread know that this thread is ready for GC. The problem
2472     // of changing thread state is that safepoint could happen just after
2473     // java_suspend_self() returns after being resumed, and VM thread will
2474     // see the _thread_blocked state. We must check for safepoint
2475     // after restoring the state and make sure we won't leave while a safepoint
2476     // is in progress.
2477     thread->set_thread_state(_thread_blocked);
2478     thread->java_suspend_self();
2479     thread->set_thread_state(state);
2480 
2481     InterfaceSupport::serialize_thread_state_with_handler(thread);
2482   }
2483 
2484   SafepointMechanism::block_if_requested(curJT);
2485 
2486   if (thread->is_deopt_suspend()) {
2487     thread->clear_deopt_suspend();
2488     RegisterMap map(thread, false);
2489     frame f = thread->last_frame();
2490     while (f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
2491       f = f.sender(&map);
2492     }
2493     if (f.id() == thread->must_deopt_id()) {
2494       thread->clear_must_deopt_id();
2495       f.deoptimize(thread);
2496     } else {
2497       fatal("missed deoptimization!");
2498     }
2499   }
2500 
2501   JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(thread);)
2502 }
2503 
2504 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2505 // progress or when _suspend_flags is non-zero.
2506 // Current thread needs to self-suspend if there is a suspend request and/or
2507 // block if a safepoint is in progress.
2508 // Also check for pending async exception (not including unsafe access error).
2509 // Note only the native==>VM/Java barriers can call this function and when
2510 // thread state is _thread_in_native_trans.
2511 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
2512   check_safepoint_and_suspend_for_native_trans(thread);
2513 
2514   if (thread->has_async_exception()) {
2515     // We are in _thread_in_native_trans state, don't handle unsafe
2516     // access error since that may block.
2517     thread->check_and_handle_async_exceptions(false);
2518   }
2519 }
2520 
2521 // This is a variant of the normal
2522 // check_special_condition_for_native_trans with slightly different
2523 // semantics for use by critical native wrappers.  It does all the
2524 // normal checks but also performs the transition back into
2525 // thread_in_Java state.  This is required so that critical natives
2526 // can potentially block and perform a GC if they are the last thread
2527 // exiting the GCLocker.
2528 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) {
2529   check_special_condition_for_native_trans(thread);
2530 
2531   // Finish the transition
2532   thread->set_thread_state(_thread_in_Java);
2533 
2534   if (thread->do_critical_native_unlock()) {
2535     ThreadInVMfromJavaNoAsyncException tiv(thread);
2536     GCLocker::unlock_critical(thread);
2537     thread->clear_critical_native_unlock();
2538   }
2539 }
2540 
2541 // We need to guarantee the Threads_lock here, since resumes are not
2542 // allowed during safepoint synchronization
2543 // Can only resume from an external suspension
2544 void JavaThread::java_resume() {
2545   assert_locked_or_safepoint(Threads_lock);
2546 
2547   // Sanity check: thread is gone, has started exiting or the thread
2548   // was not externally suspended.
2549   ThreadsListHandle tlh;
2550   if (!tlh.includes(this) || is_exiting() || !is_external_suspend()) {
2551     return;
2552   }
2553 
2554   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2555 
2556   clear_external_suspend();
2557 
2558   if (is_ext_suspended()) {
2559     clear_ext_suspended();
2560     SR_lock()->notify_all();
2561   }
2562 }
2563 
2564 size_t JavaThread::_stack_red_zone_size = 0;
2565 size_t JavaThread::_stack_yellow_zone_size = 0;
2566 size_t JavaThread::_stack_reserved_zone_size = 0;
2567 size_t JavaThread::_stack_shadow_zone_size = 0;
2568 
2569 void JavaThread::create_stack_guard_pages() {
2570   if (!os::uses_stack_guard_pages() ||
2571       _stack_guard_state != stack_guard_unused ||
2572       (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) {
2573       log_info(os, thread)("Stack guard page creation for thread "
2574                            UINTX_FORMAT " disabled", os::current_thread_id());
2575     return;
2576   }
2577   address low_addr = stack_end();
2578   size_t len = stack_guard_zone_size();
2579 
2580   assert(is_aligned(low_addr, os::vm_page_size()), "Stack base should be the start of a page");
2581   assert(is_aligned(len, os::vm_page_size()), "Stack size should be a multiple of page size");
2582 
2583   int must_commit = os::must_commit_stack_guard_pages();
2584   // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
2585 
2586   if (must_commit && !os::create_stack_guard_pages((char *) low_addr, len)) {
2587     log_warning(os, thread)("Attempt to allocate stack guard pages failed.");
2588     return;
2589   }
2590 
2591   if (os::guard_memory((char *) low_addr, len)) {
2592     _stack_guard_state = stack_guard_enabled;
2593   } else {
2594     log_warning(os, thread)("Attempt to protect stack guard pages failed ("
2595       PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2596     if (os::uncommit_memory((char *) low_addr, len)) {
2597       log_warning(os, thread)("Attempt to deallocate stack guard pages failed.");
2598     }
2599     return;
2600   }
2601 
2602   log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages activated: "
2603     PTR_FORMAT "-" PTR_FORMAT ".",
2604     os::current_thread_id(), p2i(low_addr), p2i(low_addr + len));
2605 }
2606 
2607 void JavaThread::remove_stack_guard_pages() {
2608   assert(Thread::current() == this, "from different thread");
2609   if (_stack_guard_state == stack_guard_unused) return;
2610   address low_addr = stack_end();
2611   size_t len = stack_guard_zone_size();
2612 
2613   if (os::must_commit_stack_guard_pages()) {
2614     if (os::remove_stack_guard_pages((char *) low_addr, len)) {
2615       _stack_guard_state = stack_guard_unused;
2616     } else {
2617       log_warning(os, thread)("Attempt to deallocate stack guard pages failed ("
2618         PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2619       return;
2620     }
2621   } else {
2622     if (_stack_guard_state == stack_guard_unused) return;
2623     if (os::unguard_memory((char *) low_addr, len)) {
2624       _stack_guard_state = stack_guard_unused;
2625     } else {
2626       log_warning(os, thread)("Attempt to unprotect stack guard pages failed ("
2627         PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2628       return;
2629     }
2630   }
2631 
2632   log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages removed: "
2633     PTR_FORMAT "-" PTR_FORMAT ".",
2634     os::current_thread_id(), p2i(low_addr), p2i(low_addr + len));
2635 }
2636 
2637 void JavaThread::enable_stack_reserved_zone() {
2638   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2639   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2640 
2641   // The base notation is from the stack's point of view, growing downward.
2642   // We need to adjust it to work correctly with guard_memory()
2643   address base = stack_reserved_zone_base() - stack_reserved_zone_size();
2644 
2645   guarantee(base < stack_base(),"Error calculating stack reserved zone");
2646   guarantee(base < os::current_stack_pointer(),"Error calculating stack reserved zone");
2647 
2648   if (os::guard_memory((char *) base, stack_reserved_zone_size())) {
2649     _stack_guard_state = stack_guard_enabled;
2650   } else {
2651     warning("Attempt to guard stack reserved zone failed.");
2652   }
2653   enable_register_stack_guard();
2654 }
2655 
2656 void JavaThread::disable_stack_reserved_zone() {
2657   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2658   assert(_stack_guard_state != stack_guard_reserved_disabled, "already disabled");
2659 
2660   // Simply return if called for a thread that does not use guard pages.
2661   if (_stack_guard_state == stack_guard_unused) return;
2662 
2663   // The base notation is from the stack's point of view, growing downward.
2664   // We need to adjust it to work correctly with guard_memory()
2665   address base = stack_reserved_zone_base() - stack_reserved_zone_size();
2666 
2667   if (os::unguard_memory((char *)base, stack_reserved_zone_size())) {
2668     _stack_guard_state = stack_guard_reserved_disabled;
2669   } else {
2670     warning("Attempt to unguard stack reserved zone failed.");
2671   }
2672   disable_register_stack_guard();
2673 }
2674 
2675 void JavaThread::enable_stack_yellow_reserved_zone() {
2676   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2677   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2678 
2679   // The base notation is from the stacks point of view, growing downward.
2680   // We need to adjust it to work correctly with guard_memory()
2681   address base = stack_red_zone_base();
2682 
2683   guarantee(base < stack_base(), "Error calculating stack yellow zone");
2684   guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone");
2685 
2686   if (os::guard_memory((char *) base, stack_yellow_reserved_zone_size())) {
2687     _stack_guard_state = stack_guard_enabled;
2688   } else {
2689     warning("Attempt to guard stack yellow zone failed.");
2690   }
2691   enable_register_stack_guard();
2692 }
2693 
2694 void JavaThread::disable_stack_yellow_reserved_zone() {
2695   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2696   assert(_stack_guard_state != stack_guard_yellow_reserved_disabled, "already disabled");
2697 
2698   // Simply return if called for a thread that does not use guard pages.
2699   if (_stack_guard_state == stack_guard_unused) return;
2700 
2701   // The base notation is from the stacks point of view, growing downward.
2702   // We need to adjust it to work correctly with guard_memory()
2703   address base = stack_red_zone_base();
2704 
2705   if (os::unguard_memory((char *)base, stack_yellow_reserved_zone_size())) {
2706     _stack_guard_state = stack_guard_yellow_reserved_disabled;
2707   } else {
2708     warning("Attempt to unguard stack yellow zone failed.");
2709   }
2710   disable_register_stack_guard();
2711 }
2712 
2713 void JavaThread::enable_stack_red_zone() {
2714   // The base notation is from the stacks point of view, growing downward.
2715   // We need to adjust it to work correctly with guard_memory()
2716   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2717   address base = stack_red_zone_base() - stack_red_zone_size();
2718 
2719   guarantee(base < stack_base(), "Error calculating stack red zone");
2720   guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone");
2721 
2722   if (!os::guard_memory((char *) base, stack_red_zone_size())) {
2723     warning("Attempt to guard stack red zone failed.");
2724   }
2725 }
2726 
2727 void JavaThread::disable_stack_red_zone() {
2728   // The base notation is from the stacks point of view, growing downward.
2729   // We need to adjust it to work correctly with guard_memory()
2730   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2731   address base = stack_red_zone_base() - stack_red_zone_size();
2732   if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
2733     warning("Attempt to unguard stack red zone failed.");
2734   }
2735 }
2736 
2737 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2738   // ignore is there is no stack
2739   if (!has_last_Java_frame()) return;
2740   // Because this method is used to verify oops, it must support
2741   // oops in buffered values
2742   BufferedValuesDealiaser dealiaser(this);
2743 
2744   // traverse the stack frames. Starts from top frame.
2745   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2746     frame* fr = fst.current();
2747     f(fr, fst.register_map());
2748   }
2749 }
2750 
2751 
2752 #ifndef PRODUCT
2753 // Deoptimization
2754 // Function for testing deoptimization
2755 void JavaThread::deoptimize() {
2756   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2757   StackFrameStream fst(this, UseBiasedLocking);
2758   bool deopt = false;           // Dump stack only if a deopt actually happens.
2759   bool only_at = strlen(DeoptimizeOnlyAt) > 0;
2760   // Iterate over all frames in the thread and deoptimize
2761   for (; !fst.is_done(); fst.next()) {
2762     if (fst.current()->can_be_deoptimized()) {
2763 
2764       if (only_at) {
2765         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
2766         // consists of comma or carriage return separated numbers so
2767         // search for the current bci in that string.
2768         address pc = fst.current()->pc();
2769         nmethod* nm =  (nmethod*) fst.current()->cb();
2770         ScopeDesc* sd = nm->scope_desc_at(pc);
2771         char buffer[8];
2772         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
2773         size_t len = strlen(buffer);
2774         const char * found = strstr(DeoptimizeOnlyAt, buffer);
2775         while (found != NULL) {
2776           if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
2777               (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
2778             // Check that the bci found is bracketed by terminators.
2779             break;
2780           }
2781           found = strstr(found + 1, buffer);
2782         }
2783         if (!found) {
2784           continue;
2785         }
2786       }
2787 
2788       if (DebugDeoptimization && !deopt) {
2789         deopt = true; // One-time only print before deopt
2790         tty->print_cr("[BEFORE Deoptimization]");
2791         trace_frames();
2792         trace_stack();
2793       }
2794       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2795     }
2796   }
2797 
2798   if (DebugDeoptimization && deopt) {
2799     tty->print_cr("[AFTER Deoptimization]");
2800     trace_frames();
2801   }
2802 }
2803 
2804 
2805 // Make zombies
2806 void JavaThread::make_zombies() {
2807   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2808     if (fst.current()->can_be_deoptimized()) {
2809       // it is a Java nmethod
2810       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
2811       nm->make_not_entrant();
2812     }
2813   }
2814 }
2815 #endif // PRODUCT
2816 
2817 
2818 void JavaThread::deoptimized_wrt_marked_nmethods() {
2819   if (!has_last_Java_frame()) return;
2820   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2821   StackFrameStream fst(this, UseBiasedLocking);
2822   for (; !fst.is_done(); fst.next()) {
2823     if (fst.current()->should_be_deoptimized()) {
2824       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2825     }
2826   }
2827 }
2828 
2829 
2830 // If the caller is a NamedThread, then remember, in the current scope,
2831 // the given JavaThread in its _processed_thread field.
2832 class RememberProcessedThread: public StackObj {
2833   NamedThread* _cur_thr;
2834  public:
2835   RememberProcessedThread(JavaThread* jthr) {
2836     Thread* thread = Thread::current();
2837     if (thread->is_Named_thread()) {
2838       _cur_thr = (NamedThread *)thread;
2839       _cur_thr->set_processed_thread(jthr);
2840     } else {
2841       _cur_thr = NULL;
2842     }
2843   }
2844 
2845   ~RememberProcessedThread() {
2846     if (_cur_thr) {
2847       _cur_thr->set_processed_thread(NULL);
2848     }
2849   }
2850 };
2851 
2852 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
2853   // Verify that the deferred card marks have been flushed.
2854   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2855 
2856   BufferedValuesDealiaser dealiaser(this);
2857 
2858   // Traverse the GCHandles
2859   Thread::oops_do(f, cf);
2860 
2861   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2862          (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2863 
2864   if (has_last_Java_frame()) {
2865     // Record JavaThread to GC thread
2866     RememberProcessedThread rpt(this);
2867 
2868     // Traverse the privileged stack
2869     if (_privileged_stack_top != NULL) {
2870       _privileged_stack_top->oops_do(f);
2871     }
2872 
2873     // traverse the registered growable array
2874     if (_array_for_gc != NULL) {
2875       for (int index = 0; index < _array_for_gc->length(); index++) {
2876         if (!VTBuffer::is_in_vt_buffer(_array_for_gc->at(index))) {
2877          f->do_oop(_array_for_gc->adr_at(index));
2878         } else {
2879           oop value = _array_for_gc->at(index);
2880           assert(value->is_value(), "Sanity check");
2881           dealiaser.oops_do(f, value);
2882         }
2883       }
2884     }
2885 
2886     // Traverse the monitor chunks
2887     for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2888       chunk->oops_do(f);
2889     }
2890 
2891     // Traverse the execution stack
2892     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2893       fst.current()->oops_do(f, cf, fst.register_map());
2894     }
2895   }
2896 
2897   // callee_target is never live across a gc point so NULL it here should
2898   // it still contain a methdOop.
2899 
2900   set_callee_target(NULL);
2901 
2902   assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
2903   // If we have deferred set_locals there might be oops waiting to be
2904   // written
2905   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
2906   if (list != NULL) {
2907     for (int i = 0; i < list->length(); i++) {
2908       list->at(i)->oops_do(f);
2909     }
2910   }
2911 
2912   // Traverse instance variables at the end since the GC may be moving things
2913   // around using this function
2914   f->do_oop((oop*) &_threadObj);
2915   if (!VTBuffer::is_in_vt_buffer(_vm_result)) {
2916     f->do_oop((oop*) &_vm_result);
2917   } else {
2918     assert(_vm_result->is_value(), "Must be a value");
2919     dealiaser.oops_do(f, _vm_result);
2920   }
2921   f->do_oop((oop*) &_exception_oop);
2922   f->do_oop((oop*) &_pending_async_exception);
2923 
2924   if (jvmti_thread_state() != NULL) {
2925     jvmti_thread_state()->oops_do(f);
2926   }
2927 }
2928 
2929 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
2930   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2931          (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2932 
2933   if (has_last_Java_frame()) {
2934     // Traverse the execution stack
2935     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2936       fst.current()->nmethods_do(cf);
2937     }
2938   }
2939 }
2940 
2941 void JavaThread::metadata_do(void f(Metadata*)) {
2942   if (has_last_Java_frame()) {
2943     // Traverse the execution stack to call f() on the methods in the stack
2944     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2945       fst.current()->metadata_do(f);
2946     }
2947   } else if (is_Compiler_thread()) {
2948     // need to walk ciMetadata in current compile tasks to keep alive.
2949     CompilerThread* ct = (CompilerThread*)this;
2950     if (ct->env() != NULL) {
2951       ct->env()->metadata_do(f);
2952     }
2953     CompileTask* task = ct->task();
2954     if (task != NULL) {
2955       task->metadata_do(f);
2956     }
2957   }
2958 }
2959 
2960 // Printing
2961 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2962   switch (_thread_state) {
2963   case _thread_uninitialized:     return "_thread_uninitialized";
2964   case _thread_new:               return "_thread_new";
2965   case _thread_new_trans:         return "_thread_new_trans";
2966   case _thread_in_native:         return "_thread_in_native";
2967   case _thread_in_native_trans:   return "_thread_in_native_trans";
2968   case _thread_in_vm:             return "_thread_in_vm";
2969   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
2970   case _thread_in_Java:           return "_thread_in_Java";
2971   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
2972   case _thread_blocked:           return "_thread_blocked";
2973   case _thread_blocked_trans:     return "_thread_blocked_trans";
2974   default:                        return "unknown thread state";
2975   }
2976 }
2977 
2978 #ifndef PRODUCT
2979 void JavaThread::print_thread_state_on(outputStream *st) const {
2980   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
2981 };
2982 void JavaThread::print_thread_state() const {
2983   print_thread_state_on(tty);
2984 }
2985 #endif // PRODUCT
2986 
2987 // Called by Threads::print() for VM_PrintThreads operation
2988 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
2989   st->print_raw("\"");
2990   st->print_raw(get_thread_name());
2991   st->print_raw("\" ");
2992   oop thread_oop = threadObj();
2993   if (thread_oop != NULL) {
2994     st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop));
2995     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
2996     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2997   }
2998   Thread::print_on(st, print_extended_info);
2999   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
3000   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
3001   if (thread_oop != NULL) {
3002     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
3003   }
3004 #ifndef PRODUCT
3005   print_thread_state_on(st);
3006   _safepoint_state->print_on(st);
3007 #endif // PRODUCT
3008   if (is_Compiler_thread()) {
3009     CompileTask *task = ((CompilerThread*)this)->task();
3010     if (task != NULL) {
3011       st->print("   Compiling: ");
3012       task->print(st, NULL, true, false);
3013     } else {
3014       st->print("   No compile task");
3015     }
3016     st->cr();
3017   }
3018 }
3019 
3020 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
3021   st->print("%s", get_thread_name_string(buf, buflen));
3022 }
3023 
3024 // Called by fatal error handler. The difference between this and
3025 // JavaThread::print() is that we can't grab lock or allocate memory.
3026 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
3027   st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
3028   oop thread_obj = threadObj();
3029   if (thread_obj != NULL) {
3030     if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
3031   }
3032   st->print(" [");
3033   st->print("%s", _get_thread_state_name(_thread_state));
3034   if (osthread()) {
3035     st->print(", id=%d", osthread()->thread_id());
3036   }
3037   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
3038             p2i(stack_end()), p2i(stack_base()));
3039   st->print("]");
3040 
3041   ThreadsSMRSupport::print_info_on(this, st);
3042   return;
3043 }
3044 
3045 // Verification
3046 
3047 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
3048 
3049 void JavaThread::verify() {
3050   // Verify oops in the thread.
3051   oops_do(&VerifyOopClosure::verify_oop, NULL);
3052 
3053   // Verify the stack frames.
3054   frames_do(frame_verify);
3055 }
3056 
3057 // CR 6300358 (sub-CR 2137150)
3058 // Most callers of this method assume that it can't return NULL but a
3059 // thread may not have a name whilst it is in the process of attaching to
3060 // the VM - see CR 6412693, and there are places where a JavaThread can be
3061 // seen prior to having it's threadObj set (eg JNI attaching threads and
3062 // if vm exit occurs during initialization). These cases can all be accounted
3063 // for such that this method never returns NULL.
3064 const char* JavaThread::get_thread_name() const {
3065 #ifdef ASSERT
3066   // early safepoints can hit while current thread does not yet have TLS
3067   if (!SafepointSynchronize::is_at_safepoint()) {
3068     Thread *cur = Thread::current();
3069     if (!(cur->is_Java_thread() && cur == this)) {
3070       // Current JavaThreads are allowed to get their own name without
3071       // the Threads_lock.
3072       assert_locked_or_safepoint(Threads_lock);
3073     }
3074   }
3075 #endif // ASSERT
3076   return get_thread_name_string();
3077 }
3078 
3079 // Returns a non-NULL representation of this thread's name, or a suitable
3080 // descriptive string if there is no set name
3081 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
3082   const char* name_str;
3083   oop thread_obj = threadObj();
3084   if (thread_obj != NULL) {
3085     oop name = java_lang_Thread::name(thread_obj);
3086     if (name != NULL) {
3087       if (buf == NULL) {
3088         name_str = java_lang_String::as_utf8_string(name);
3089       } else {
3090         name_str = java_lang_String::as_utf8_string(name, buf, buflen);
3091       }
3092     } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
3093       name_str = "<no-name - thread is attaching>";
3094     } else {
3095       name_str = Thread::name();
3096     }
3097   } else {
3098     name_str = Thread::name();
3099   }
3100   assert(name_str != NULL, "unexpected NULL thread name");
3101   return name_str;
3102 }
3103 
3104 
3105 const char* JavaThread::get_threadgroup_name() const {
3106   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
3107   oop thread_obj = threadObj();
3108   if (thread_obj != NULL) {
3109     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
3110     if (thread_group != NULL) {
3111       // ThreadGroup.name can be null
3112       return java_lang_ThreadGroup::name(thread_group);
3113     }
3114   }
3115   return NULL;
3116 }
3117 
3118 const char* JavaThread::get_parent_name() const {
3119   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
3120   oop thread_obj = threadObj();
3121   if (thread_obj != NULL) {
3122     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
3123     if (thread_group != NULL) {
3124       oop parent = java_lang_ThreadGroup::parent(thread_group);
3125       if (parent != NULL) {
3126         // ThreadGroup.name can be null
3127         return java_lang_ThreadGroup::name(parent);
3128       }
3129     }
3130   }
3131   return NULL;
3132 }
3133 
3134 ThreadPriority JavaThread::java_priority() const {
3135   oop thr_oop = threadObj();
3136   if (thr_oop == NULL) return NormPriority; // Bootstrapping
3137   ThreadPriority priority = java_lang_Thread::priority(thr_oop);
3138   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
3139   return priority;
3140 }
3141 
3142 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
3143 
3144   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
3145   // Link Java Thread object <-> C++ Thread
3146 
3147   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
3148   // and put it into a new Handle.  The Handle "thread_oop" can then
3149   // be used to pass the C++ thread object to other methods.
3150 
3151   // Set the Java level thread object (jthread) field of the
3152   // new thread (a JavaThread *) to C++ thread object using the
3153   // "thread_oop" handle.
3154 
3155   // Set the thread field (a JavaThread *) of the
3156   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
3157 
3158   Handle thread_oop(Thread::current(),
3159                     JNIHandles::resolve_non_null(jni_thread));
3160   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
3161          "must be initialized");
3162   set_threadObj(thread_oop());
3163   java_lang_Thread::set_thread(thread_oop(), this);
3164 
3165   if (prio == NoPriority) {
3166     prio = java_lang_Thread::priority(thread_oop());
3167     assert(prio != NoPriority, "A valid priority should be present");
3168   }
3169 
3170   // Push the Java priority down to the native thread; needs Threads_lock
3171   Thread::set_priority(this, prio);
3172 
3173   // Add the new thread to the Threads list and set it in motion.
3174   // We must have threads lock in order to call Threads::add.
3175   // It is crucial that we do not block before the thread is
3176   // added to the Threads list for if a GC happens, then the java_thread oop
3177   // will not be visited by GC.
3178   Threads::add(this);
3179 }
3180 
3181 oop JavaThread::current_park_blocker() {
3182   // Support for JSR-166 locks
3183   oop thread_oop = threadObj();
3184   if (thread_oop != NULL &&
3185       JDK_Version::current().supports_thread_park_blocker()) {
3186     return java_lang_Thread::park_blocker(thread_oop);
3187   }
3188   return NULL;
3189 }
3190 
3191 
3192 void JavaThread::print_stack_on(outputStream* st) {
3193   if (!has_last_Java_frame()) return;
3194   ResourceMark rm;
3195   HandleMark   hm;
3196 
3197   RegisterMap reg_map(this);
3198   vframe* start_vf = last_java_vframe(&reg_map);
3199   int count = 0;
3200   for (vframe* f = start_vf; f != NULL; f = f->sender()) {
3201     if (f->is_java_frame()) {
3202       javaVFrame* jvf = javaVFrame::cast(f);
3203       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
3204 
3205       // Print out lock information
3206       if (JavaMonitorsInStackTrace) {
3207         jvf->print_lock_info_on(st, count);
3208       }
3209     } else {
3210       // Ignore non-Java frames
3211     }
3212 
3213     // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0
3214     count++;
3215     if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return;
3216   }
3217 }
3218 
3219 
3220 // JVMTI PopFrame support
3221 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
3222   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
3223   if (in_bytes(size_in_bytes) != 0) {
3224     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
3225     _popframe_preserved_args_size = in_bytes(size_in_bytes);
3226     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
3227   }
3228 }
3229 
3230 void* JavaThread::popframe_preserved_args() {
3231   return _popframe_preserved_args;
3232 }
3233 
3234 ByteSize JavaThread::popframe_preserved_args_size() {
3235   return in_ByteSize(_popframe_preserved_args_size);
3236 }
3237 
3238 WordSize JavaThread::popframe_preserved_args_size_in_words() {
3239   int sz = in_bytes(popframe_preserved_args_size());
3240   assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
3241   return in_WordSize(sz / wordSize);
3242 }
3243 
3244 void JavaThread::popframe_free_preserved_args() {
3245   assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
3246   FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args);
3247   _popframe_preserved_args = NULL;
3248   _popframe_preserved_args_size = 0;
3249 }
3250 
3251 #ifndef PRODUCT
3252 
3253 void JavaThread::trace_frames() {
3254   tty->print_cr("[Describe stack]");
3255   int frame_no = 1;
3256   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
3257     tty->print("  %d. ", frame_no++);
3258     fst.current()->print_value_on(tty, this);
3259     tty->cr();
3260   }
3261 }
3262 
3263 class PrintAndVerifyOopClosure: public OopClosure {
3264  protected:
3265   template <class T> inline void do_oop_work(T* p) {
3266     oop obj = RawAccess<>::oop_load(p);
3267     if (obj == NULL) return;
3268     tty->print(INTPTR_FORMAT ": ", p2i(p));
3269     if (oopDesc::is_oop_or_null(obj)) {
3270       if (obj->is_objArray()) {
3271         tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj));
3272       } else {
3273         obj->print();
3274       }
3275     } else {
3276       tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
3277     }
3278     tty->cr();
3279   }
3280  public:
3281   virtual void do_oop(oop* p) { do_oop_work(p); }
3282   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
3283 };
3284 
3285 
3286 static void oops_print(frame* f, const RegisterMap *map) {
3287   PrintAndVerifyOopClosure print;
3288   f->print_value();
3289   f->oops_do(&print, NULL, (RegisterMap*)map);
3290 }
3291 
3292 // Print our all the locations that contain oops and whether they are
3293 // valid or not.  This useful when trying to find the oldest frame
3294 // where an oop has gone bad since the frame walk is from youngest to
3295 // oldest.
3296 void JavaThread::trace_oops() {
3297   tty->print_cr("[Trace oops]");
3298   frames_do(oops_print);
3299 }
3300 
3301 
3302 #ifdef ASSERT
3303 // Print or validate the layout of stack frames
3304 void JavaThread::print_frame_layout(int depth, bool validate_only) {
3305   ResourceMark rm;
3306   PRESERVE_EXCEPTION_MARK;
3307   FrameValues values;
3308   int frame_no = 0;
3309   for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
3310     fst.current()->describe(values, ++frame_no);
3311     if (depth == frame_no) break;
3312   }
3313   if (validate_only) {
3314     values.validate();
3315   } else {
3316     tty->print_cr("[Describe stack layout]");
3317     values.print(this);
3318   }
3319 }
3320 #endif
3321 
3322 void JavaThread::trace_stack_from(vframe* start_vf) {
3323   ResourceMark rm;
3324   int vframe_no = 1;
3325   for (vframe* f = start_vf; f; f = f->sender()) {
3326     if (f->is_java_frame()) {
3327       javaVFrame::cast(f)->print_activation(vframe_no++);
3328     } else {
3329       f->print();
3330     }
3331     if (vframe_no > StackPrintLimit) {
3332       tty->print_cr("...<more frames>...");
3333       return;
3334     }
3335   }
3336 }
3337 
3338 
3339 void JavaThread::trace_stack() {
3340   if (!has_last_Java_frame()) return;
3341   ResourceMark rm;
3342   HandleMark   hm;
3343   RegisterMap reg_map(this);
3344   trace_stack_from(last_java_vframe(&reg_map));
3345 }
3346 
3347 
3348 #endif // PRODUCT
3349 
3350 
3351 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
3352   assert(reg_map != NULL, "a map must be given");
3353   frame f = last_frame();
3354   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
3355     if (vf->is_java_frame()) return javaVFrame::cast(vf);
3356   }
3357   return NULL;
3358 }
3359 
3360 
3361 Klass* JavaThread::security_get_caller_class(int depth) {
3362   vframeStream vfst(this);
3363   vfst.security_get_caller_frame(depth);
3364   if (!vfst.at_end()) {
3365     return vfst.method()->method_holder();
3366   }
3367   return NULL;
3368 }
3369 
3370 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
3371   assert(thread->is_Compiler_thread(), "must be compiler thread");
3372   CompileBroker::compiler_thread_loop();
3373 }
3374 
3375 static void sweeper_thread_entry(JavaThread* thread, TRAPS) {
3376   NMethodSweeper::sweeper_loop();
3377 }
3378 
3379 // Create a CompilerThread
3380 CompilerThread::CompilerThread(CompileQueue* queue,
3381                                CompilerCounters* counters)
3382                                : JavaThread(&compiler_thread_entry) {
3383   _env   = NULL;
3384   _log   = NULL;
3385   _task  = NULL;
3386   _queue = queue;
3387   _counters = counters;
3388   _buffer_blob = NULL;
3389   _compiler = NULL;
3390 
3391   // Compiler uses resource area for compilation, let's bias it to mtCompiler
3392   resource_area()->bias_to(mtCompiler);
3393 
3394 #ifndef PRODUCT
3395   _ideal_graph_printer = NULL;
3396 #endif
3397 }
3398 
3399 CompilerThread::~CompilerThread() {
3400   // Delete objects which were allocated on heap.
3401   delete _counters;
3402 }
3403 
3404 bool CompilerThread::can_call_java() const {
3405   return _compiler != NULL && _compiler->is_jvmci();
3406 }
3407 
3408 // Create sweeper thread
3409 CodeCacheSweeperThread::CodeCacheSweeperThread()
3410 : JavaThread(&sweeper_thread_entry) {
3411   _scanned_compiled_method = NULL;
3412 }
3413 
3414 void CodeCacheSweeperThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
3415   JavaThread::oops_do(f, cf);
3416   if (_scanned_compiled_method != NULL && cf != NULL) {
3417     // Safepoints can occur when the sweeper is scanning an nmethod so
3418     // process it here to make sure it isn't unloaded in the middle of
3419     // a scan.
3420     cf->do_code_blob(_scanned_compiled_method);
3421   }
3422 }
3423 
3424 void CodeCacheSweeperThread::nmethods_do(CodeBlobClosure* cf) {
3425   JavaThread::nmethods_do(cf);
3426   if (_scanned_compiled_method != NULL && cf != NULL) {
3427     // Safepoints can occur when the sweeper is scanning an nmethod so
3428     // process it here to make sure it isn't unloaded in the middle of
3429     // a scan.
3430     cf->do_code_blob(_scanned_compiled_method);
3431   }
3432 }
3433 
3434 
3435 // ======= Threads ========
3436 
3437 // The Threads class links together all active threads, and provides
3438 // operations over all threads. It is protected by the Threads_lock,
3439 // which is also used in other global contexts like safepointing.
3440 // ThreadsListHandles are used to safely perform operations on one
3441 // or more threads without the risk of the thread exiting during the
3442 // operation.
3443 //
3444 // Note: The Threads_lock is currently more widely used than we
3445 // would like. We are actively migrating Threads_lock uses to other
3446 // mechanisms in order to reduce Threads_lock contention.
3447 
3448 JavaThread* Threads::_thread_list = NULL;
3449 int         Threads::_number_of_threads = 0;
3450 int         Threads::_number_of_non_daemon_threads = 0;
3451 int         Threads::_return_code = 0;
3452 int         Threads::_thread_claim_parity = 0;
3453 size_t      JavaThread::_stack_size_at_create = 0;
3454 
3455 #ifdef ASSERT
3456 bool        Threads::_vm_complete = false;
3457 size_t      Threads::_threads_before_barrier_set = 0;
3458 #endif
3459 
3460 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) {
3461   Prefetch::read((void*)addr, prefetch_interval);
3462   return *addr;
3463 }
3464 
3465 // Possibly the ugliest for loop the world has seen. C++ does not allow
3466 // multiple types in the declaration section of the for loop. In this case
3467 // we are only dealing with pointers and hence can cast them. It looks ugly
3468 // but macros are ugly and therefore it's fine to make things absurdly ugly.
3469 #define DO_JAVA_THREADS(LIST, X)                                                                                          \
3470     for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes,                           \
3471              *MACRO_list = (JavaThread*)(LIST),                                                                           \
3472              **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(),  \
3473              **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(),                                     \
3474              *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval);                 \
3475          MACRO_current_p != MACRO_end;                                                                                    \
3476          MACRO_current_p++,                                                                                               \
3477              X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval))
3478 
3479 // All JavaThreads
3480 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(ThreadsSMRSupport::get_java_thread_list(), X)
3481 
3482 // All NonJavaThreads (i.e., every non-JavaThread in the system).
3483 void Threads::non_java_threads_do(ThreadClosure* tc) {
3484   NoSafepointVerifier nsv(!SafepointSynchronize::is_at_safepoint(), false);
3485   for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) {
3486     tc->do_thread(njti.current());
3487   }
3488 }
3489 
3490 // All JavaThreads
3491 void Threads::java_threads_do(ThreadClosure* tc) {
3492   assert_locked_or_safepoint(Threads_lock);
3493   // ALL_JAVA_THREADS iterates through all JavaThreads.
3494   ALL_JAVA_THREADS(p) {
3495     tc->do_thread(p);
3496   }
3497 }
3498 
3499 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) {
3500   assert_locked_or_safepoint(Threads_lock);
3501   java_threads_do(tc);
3502   tc->do_thread(VMThread::vm_thread());
3503 }
3504 
3505 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system).
3506 void Threads::threads_do(ThreadClosure* tc) {
3507   assert_locked_or_safepoint(Threads_lock);
3508   java_threads_do(tc);
3509   non_java_threads_do(tc);
3510 }
3511 
3512 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) {
3513   int cp = Threads::thread_claim_parity();
3514   ALL_JAVA_THREADS(p) {
3515     if (p->claim_oops_do(is_par, cp)) {
3516       tc->do_thread(p);
3517     }
3518   }
3519   VMThread* vmt = VMThread::vm_thread();
3520   if (vmt->claim_oops_do(is_par, cp)) {
3521     tc->do_thread(vmt);
3522   }
3523 }
3524 
3525 // The system initialization in the library has three phases.
3526 //
3527 // Phase 1: java.lang.System class initialization
3528 //     java.lang.System is a primordial class loaded and initialized
3529 //     by the VM early during startup.  java.lang.System.<clinit>
3530 //     only does registerNatives and keeps the rest of the class
3531 //     initialization work later until thread initialization completes.
3532 //
3533 //     System.initPhase1 initializes the system properties, the static
3534 //     fields in, out, and err. Set up java signal handlers, OS-specific
3535 //     system settings, and thread group of the main thread.
3536 static void call_initPhase1(TRAPS) {
3537   Klass* klass =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3538   JavaValue result(T_VOID);
3539   JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(),
3540                                          vmSymbols::void_method_signature(), CHECK);
3541 }
3542 
3543 // Phase 2. Module system initialization
3544 //     This will initialize the module system.  Only java.base classes
3545 //     can be loaded until phase 2 completes.
3546 //
3547 //     Call System.initPhase2 after the compiler initialization and jsr292
3548 //     classes get initialized because module initialization runs a lot of java
3549 //     code, that for performance reasons, should be compiled.  Also, this will
3550 //     enable the startup code to use lambda and other language features in this
3551 //     phase and onward.
3552 //
3553 //     After phase 2, The VM will begin search classes from -Xbootclasspath/a.
3554 static void call_initPhase2(TRAPS) {
3555   TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
3556 
3557   Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3558 
3559   JavaValue result(T_INT);
3560   JavaCallArguments args;
3561   args.push_int(DisplayVMOutputToStderr);
3562   args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
3563   JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
3564                                          vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
3565   if (result.get_jint() != JNI_OK) {
3566     vm_exit_during_initialization(); // no message or exception
3567   }
3568 
3569   universe_post_module_init();
3570 }
3571 
3572 // Phase 3. final setup - set security manager, system class loader and TCCL
3573 //
3574 //     This will instantiate and set the security manager, set the system class
3575 //     loader as well as the thread context class loader.  The security manager
3576 //     and system class loader may be a custom class loaded from -Xbootclasspath/a,
3577 //     other modules or the application's classpath.
3578 static void call_initPhase3(TRAPS) {
3579   Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3580   JavaValue result(T_VOID);
3581   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
3582                                          vmSymbols::void_method_signature(), CHECK);
3583 }
3584 
3585 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
3586   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
3587 
3588   if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
3589     create_vm_init_libraries();
3590   }
3591 
3592   initialize_class(vmSymbols::java_lang_String(), CHECK);
3593 
3594   // Inject CompactStrings value after the static initializers for String ran.
3595   java_lang_String::set_compact_strings(CompactStrings);
3596 
3597   // Initialize java_lang.System (needed before creating the thread)
3598   initialize_class(vmSymbols::java_lang_System(), CHECK);
3599   // The VM creates & returns objects of this class. Make sure it's initialized.
3600   initialize_class(vmSymbols::java_lang_Class(), CHECK);
3601   initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
3602   Handle thread_group = create_initial_thread_group(CHECK);
3603   Universe::set_main_thread_group(thread_group());
3604   initialize_class(vmSymbols::java_lang_Thread(), CHECK);
3605   oop thread_object = create_initial_thread(thread_group, main_thread, CHECK);
3606   main_thread->set_threadObj(thread_object);
3607   // Set thread status to running since main thread has
3608   // been started and running.
3609   java_lang_Thread::set_thread_status(thread_object,
3610                                       java_lang_Thread::RUNNABLE);
3611 
3612   // The VM creates objects of this class.
3613   initialize_class(vmSymbols::java_lang_Module(), CHECK);
3614 
3615   // The VM preresolves methods to these classes. Make sure that they get initialized
3616   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
3617   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
3618 
3619   // Phase 1 of the system initialization in the library, java.lang.System class initialization
3620   call_initPhase1(CHECK);
3621 
3622   // get the Java runtime name after java.lang.System is initialized
3623   JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
3624   JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
3625 
3626   // an instance of OutOfMemory exception has been allocated earlier
3627   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
3628   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
3629   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
3630   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
3631   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
3632   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
3633   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
3634   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
3635 }
3636 
3637 void Threads::initialize_jsr292_core_classes(TRAPS) {
3638   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
3639 
3640   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
3641   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
3642   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
3643   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
3644 }
3645 
3646 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
3647   extern void JDK_Version_init();
3648 
3649   // Preinitialize version info.
3650   VM_Version::early_initialize();
3651 
3652   // Check version
3653   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
3654 
3655   // Initialize library-based TLS
3656   ThreadLocalStorage::init();
3657 
3658   // Initialize the output stream module
3659   ostream_init();
3660 
3661   // Process java launcher properties.
3662   Arguments::process_sun_java_launcher_properties(args);
3663 
3664   // Initialize the os module
3665   os::init();
3666 
3667   // Record VM creation timing statistics
3668   TraceVmCreationTime create_vm_timer;
3669   create_vm_timer.start();
3670 
3671   // Initialize system properties.
3672   Arguments::init_system_properties();
3673 
3674   // So that JDK version can be used as a discriminator when parsing arguments
3675   JDK_Version_init();
3676 
3677   // Update/Initialize System properties after JDK version number is known
3678   Arguments::init_version_specific_system_properties();
3679 
3680   // Make sure to initialize log configuration *before* parsing arguments
3681   LogConfiguration::initialize(create_vm_timer.begin_time());
3682 
3683   // Parse arguments
3684   // Note: this internally calls os::init_container_support()
3685   jint parse_result = Arguments::parse(args);
3686   if (parse_result != JNI_OK) return parse_result;
3687 
3688   os::init_before_ergo();
3689 
3690   jint ergo_result = Arguments::apply_ergo();
3691   if (ergo_result != JNI_OK) return ergo_result;
3692 
3693   // Final check of all ranges after ergonomics which may change values.
3694   if (!JVMFlagRangeList::check_ranges()) {
3695     return JNI_EINVAL;
3696   }
3697 
3698   // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
3699   bool constraint_result = JVMFlagConstraintList::check_constraints(JVMFlagConstraint::AfterErgo);
3700   if (!constraint_result) {
3701     return JNI_EINVAL;
3702   }
3703 
3704   JVMFlagWriteableList::mark_startup();
3705 
3706   if (PauseAtStartup) {
3707     os::pause();
3708   }
3709 
3710   HOTSPOT_VM_INIT_BEGIN();
3711 
3712   // Timing (must come after argument parsing)
3713   TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime));
3714 
3715 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT
3716   // Initialize assert poison page mechanism.
3717   if (ShowRegistersOnAssert) {
3718     initialize_assert_poison();
3719   }
3720 #endif // CAN_SHOW_REGISTERS_ON_ASSERT
3721 
3722   // Initialize the os module after parsing the args
3723   jint os_init_2_result = os::init_2();
3724   if (os_init_2_result != JNI_OK) return os_init_2_result;
3725 
3726   SafepointMechanism::initialize();
3727 
3728   jint adjust_after_os_result = Arguments::adjust_after_os();
3729   if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
3730 
3731   // Initialize output stream logging
3732   ostream_init_log();
3733 
3734   // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
3735   // Must be before create_vm_init_agents()
3736   if (Arguments::init_libraries_at_startup()) {
3737     convert_vm_init_libraries_to_agents();
3738   }
3739 
3740   // Launch -agentlib/-agentpath and converted -Xrun agents
3741   if (Arguments::init_agents_at_startup()) {
3742     create_vm_init_agents();
3743   }
3744 
3745   // Initialize Threads state
3746   _thread_list = NULL;
3747   _number_of_threads = 0;
3748   _number_of_non_daemon_threads = 0;
3749 
3750   // Initialize global data structures and create system classes in heap
3751   vm_init_globals();
3752 
3753 #if INCLUDE_JVMCI
3754   if (JVMCICounterSize > 0) {
3755     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
3756     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
3757   } else {
3758     JavaThread::_jvmci_old_thread_counters = NULL;
3759   }
3760 #endif // INCLUDE_JVMCI
3761 
3762   // Attach the main thread to this os thread
3763   JavaThread* main_thread = new JavaThread();
3764   main_thread->set_thread_state(_thread_in_vm);
3765   main_thread->initialize_thread_current();
3766   // must do this before set_active_handles
3767   main_thread->record_stack_base_and_size();
3768   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3769 
3770   if (!main_thread->set_as_starting_thread()) {
3771     vm_shutdown_during_initialization(
3772                                       "Failed necessary internal allocation. Out of swap space");
3773     main_thread->smr_delete();
3774     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3775     return JNI_ENOMEM;
3776   }
3777 
3778   // Enable guard page *after* os::create_main_thread(), otherwise it would
3779   // crash Linux VM, see notes in os_linux.cpp.
3780   main_thread->create_stack_guard_pages();
3781 
3782   // Initialize Java-Level synchronization subsystem
3783   ObjectMonitor::Initialize();
3784 
3785   // Initialize global modules
3786   jint status = init_globals();
3787   if (status != JNI_OK) {
3788     main_thread->smr_delete();
3789     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3790     return status;
3791   }
3792 
3793   JFR_ONLY(Jfr::on_vm_init();)
3794 
3795   // Should be done after the heap is fully created
3796   main_thread->cache_global_variables();
3797 
3798   HandleMark hm;
3799 
3800   { MutexLocker mu(Threads_lock);
3801     Threads::add(main_thread);
3802   }
3803 
3804   // Any JVMTI raw monitors entered in onload will transition into
3805   // real raw monitor. VM is setup enough here for raw monitor enter.
3806   JvmtiExport::transition_pending_onload_raw_monitors();
3807 
3808   // Create the VMThread
3809   { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime));
3810 
3811   VMThread::create();
3812     Thread* vmthread = VMThread::vm_thread();
3813 
3814     if (!os::create_thread(vmthread, os::vm_thread)) {
3815       vm_exit_during_initialization("Cannot create VM thread. "
3816                                     "Out of system resources.");
3817     }
3818 
3819     // Wait for the VM thread to become ready, and VMThread::run to initialize
3820     // Monitors can have spurious returns, must always check another state flag
3821     {
3822       MutexLocker ml(Notify_lock);
3823       os::start_thread(vmthread);
3824       while (vmthread->active_handles() == NULL) {
3825         Notify_lock->wait();
3826       }
3827     }
3828   }
3829 
3830   assert(Universe::is_fully_initialized(), "not initialized");
3831   if (VerifyDuringStartup) {
3832     // Make sure we're starting with a clean slate.
3833     VM_Verify verify_op;
3834     VMThread::execute(&verify_op);
3835   }
3836 
3837   // We need this to update the java.vm.info property in case any flags used
3838   // to initially define it have been changed. This is needed for both CDS and
3839   // AOT, since UseSharedSpaces and UseAOT may be changed after java.vm.info
3840   // is initially computed. See Abstract_VM_Version::vm_info_string().
3841   // This update must happen before we initialize the java classes, but
3842   // after any initialization logic that might modify the flags.
3843   Arguments::update_vm_info_property(VM_Version::vm_info_string());
3844 
3845   Thread* THREAD = Thread::current();
3846 
3847   // Always call even when there are not JVMTI environments yet, since environments
3848   // may be attached late and JVMTI must track phases of VM execution
3849   JvmtiExport::enter_early_start_phase();
3850 
3851   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3852   JvmtiExport::post_early_vm_start();
3853 
3854   initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
3855 
3856   quicken_jni_functions();
3857 
3858   // No more stub generation allowed after that point.
3859   StubCodeDesc::freeze();
3860 
3861   // Set flag that basic initialization has completed. Used by exceptions and various
3862   // debug stuff, that does not work until all basic classes have been initialized.
3863   set_init_completed();
3864 
3865   LogConfiguration::post_initialize();
3866   Metaspace::post_initialize();
3867 
3868   HOTSPOT_VM_INIT_END();
3869 
3870   // record VM initialization completion time
3871 #if INCLUDE_MANAGEMENT
3872   Management::record_vm_init_completed();
3873 #endif // INCLUDE_MANAGEMENT
3874 
3875   // Signal Dispatcher needs to be started before VMInit event is posted
3876   os::initialize_jdk_signal_support(CHECK_JNI_ERR);
3877 
3878   // Start Attach Listener if +StartAttachListener or it can't be started lazily
3879   if (!DisableAttachMechanism) {
3880     AttachListener::vm_start();
3881     if (StartAttachListener || AttachListener::init_at_startup()) {
3882       AttachListener::init();
3883     }
3884   }
3885 
3886   // Launch -Xrun agents
3887   // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3888   // back-end can launch with -Xdebug -Xrunjdwp.
3889   if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3890     create_vm_init_libraries();
3891   }
3892 
3893   if (CleanChunkPoolAsync) {
3894     Chunk::start_chunk_pool_cleaner_task();
3895   }
3896 
3897   // initialize compiler(s)
3898 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
3899 #if INCLUDE_JVMCI
3900   bool force_JVMCI_intialization = false;
3901   if (EnableJVMCI) {
3902     // Initialize JVMCI eagerly when it is explicitly requested.
3903     // Or when JVMCIPrintProperties is enabled.
3904     // The JVMCI Java initialization code will read this flag and
3905     // do the printing if it's set.
3906     force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties;
3907 
3908     if (!force_JVMCI_intialization) {
3909       // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking
3910       // compilations via JVMCI will not actually block until JVMCI is initialized.
3911       force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation);
3912     }
3913   }
3914 #endif
3915   CompileBroker::compilation_init_phase1(CHECK_JNI_ERR);
3916   // Postpone completion of compiler initialization to after JVMCI
3917   // is initialized to avoid timeouts of blocking compilations.
3918   if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) {
3919     CompileBroker::compilation_init_phase2();
3920   }
3921 #endif
3922 
3923   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3924   // It is done after compilers are initialized, because otherwise compilations of
3925   // signature polymorphic MH intrinsics can be missed
3926   // (see SystemDictionary::find_method_handle_intrinsic).
3927   initialize_jsr292_core_classes(CHECK_JNI_ERR);
3928 
3929   // This will initialize the module system.  Only java.base classes can be
3930   // loaded until phase 2 completes
3931   call_initPhase2(CHECK_JNI_ERR);
3932 
3933   // Always call even when there are not JVMTI environments yet, since environments
3934   // may be attached late and JVMTI must track phases of VM execution
3935   JvmtiExport::enter_start_phase();
3936 
3937   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3938   JvmtiExport::post_vm_start();
3939 
3940   // Final system initialization including security manager and system class loader
3941   call_initPhase3(CHECK_JNI_ERR);
3942 
3943   // cache the system and platform class loaders
3944   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
3945 
3946 #if INCLUDE_CDS
3947   if (DumpSharedSpaces) {
3948     // capture the module path info from the ModuleEntryTable
3949     ClassLoader::initialize_module_path(THREAD);
3950   }
3951 #endif
3952 
3953 #if INCLUDE_JVMCI
3954   if (force_JVMCI_intialization) {
3955     JVMCIRuntime::force_initialization(CHECK_JNI_ERR);
3956     CompileBroker::compilation_init_phase2();
3957   }
3958 #endif
3959 
3960   // Always call even when there are not JVMTI environments yet, since environments
3961   // may be attached late and JVMTI must track phases of VM execution
3962   JvmtiExport::enter_live_phase();
3963 
3964   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3965   JvmtiExport::post_vm_initialized();
3966 
3967   JFR_ONLY(Jfr::on_vm_start();)
3968 
3969 #if INCLUDE_MANAGEMENT
3970   Management::initialize(THREAD);
3971 
3972   if (HAS_PENDING_EXCEPTION) {
3973     // management agent fails to start possibly due to
3974     // configuration problem and is responsible for printing
3975     // stack trace if appropriate. Simply exit VM.
3976     vm_exit(1);
3977   }
3978 #endif // INCLUDE_MANAGEMENT
3979 
3980   if (MemProfiling)                   MemProfiler::engage();
3981   StatSampler::engage();
3982   if (CheckJNICalls)                  JniPeriodicChecker::engage();
3983 
3984   BiasedLocking::init();
3985 
3986 #if INCLUDE_RTM_OPT
3987   RTMLockingCounters::init();
3988 #endif
3989 
3990   if (JDK_Version::current().post_vm_init_hook_enabled()) {
3991     call_postVMInitHook(THREAD);
3992     // The Java side of PostVMInitHook.run must deal with all
3993     // exceptions and provide means of diagnosis.
3994     if (HAS_PENDING_EXCEPTION) {
3995       CLEAR_PENDING_EXCEPTION;
3996     }
3997   }
3998 
3999   {
4000     MutexLocker ml(PeriodicTask_lock);
4001     // Make sure the WatcherThread can be started by WatcherThread::start()
4002     // or by dynamic enrollment.
4003     WatcherThread::make_startable();
4004     // Start up the WatcherThread if there are any periodic tasks
4005     // NOTE:  All PeriodicTasks should be registered by now. If they
4006     //   aren't, late joiners might appear to start slowly (we might
4007     //   take a while to process their first tick).
4008     if (PeriodicTask::num_tasks() > 0) {
4009       WatcherThread::start();
4010     }
4011   }
4012 
4013   create_vm_timer.end();
4014 #ifdef ASSERT
4015   _vm_complete = true;
4016 #endif
4017 
4018   if (DumpSharedSpaces) {
4019     MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
4020     ShouldNotReachHere();
4021   }
4022 
4023   return JNI_OK;
4024 }
4025 
4026 // type for the Agent_OnLoad and JVM_OnLoad entry points
4027 extern "C" {
4028   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
4029 }
4030 // Find a command line agent library and return its entry point for
4031 //         -agentlib:  -agentpath:   -Xrun
4032 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
4033 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent,
4034                                     const char *on_load_symbols[],
4035                                     size_t num_symbol_entries) {
4036   OnLoadEntry_t on_load_entry = NULL;
4037   void *library = NULL;
4038 
4039   if (!agent->valid()) {
4040     char buffer[JVM_MAXPATHLEN];
4041     char ebuf[1024] = "";
4042     const char *name = agent->name();
4043     const char *msg = "Could not find agent library ";
4044 
4045     // First check to see if agent is statically linked into executable
4046     if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
4047       library = agent->os_lib();
4048     } else if (agent->is_absolute_path()) {
4049       library = os::dll_load(name, ebuf, sizeof ebuf);
4050       if (library == NULL) {
4051         const char *sub_msg = " in absolute path, with error: ";
4052         size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
4053         char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
4054         jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
4055         // If we can't find the agent, exit.
4056         vm_exit_during_initialization(buf, NULL);
4057         FREE_C_HEAP_ARRAY(char, buf);
4058       }
4059     } else {
4060       // Try to load the agent from the standard dll directory
4061       if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
4062                              name)) {
4063         library = os::dll_load(buffer, ebuf, sizeof ebuf);
4064       }
4065       if (library == NULL) { // Try the library path directory.
4066         if (os::dll_build_name(buffer, sizeof(buffer), name)) {
4067           library = os::dll_load(buffer, ebuf, sizeof ebuf);
4068         }
4069         if (library == NULL) {
4070           const char *sub_msg = " on the library path, with error: ";
4071           const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image.";
4072 
4073           size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) +
4074                        strlen(ebuf) + strlen(sub_msg2) + 1;
4075           char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
4076           if (!agent->is_instrument_lib()) {
4077             jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
4078           } else {
4079             jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2);
4080           }
4081           // If we can't find the agent, exit.
4082           vm_exit_during_initialization(buf, NULL);
4083           FREE_C_HEAP_ARRAY(char, buf);
4084         }
4085       }
4086     }
4087     agent->set_os_lib(library);
4088     agent->set_valid();
4089   }
4090 
4091   // Find the OnLoad function.
4092   on_load_entry =
4093     CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
4094                                                           false,
4095                                                           on_load_symbols,
4096                                                           num_symbol_entries));
4097   return on_load_entry;
4098 }
4099 
4100 // Find the JVM_OnLoad entry point
4101 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
4102   const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
4103   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
4104 }
4105 
4106 // Find the Agent_OnLoad entry point
4107 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
4108   const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
4109   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
4110 }
4111 
4112 // For backwards compatibility with -Xrun
4113 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
4114 // treated like -agentpath:
4115 // Must be called before agent libraries are created
4116 void Threads::convert_vm_init_libraries_to_agents() {
4117   AgentLibrary* agent;
4118   AgentLibrary* next;
4119 
4120   for (agent = Arguments::libraries(); agent != NULL; agent = next) {
4121     next = agent->next();  // cache the next agent now as this agent may get moved off this list
4122     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4123 
4124     // If there is an JVM_OnLoad function it will get called later,
4125     // otherwise see if there is an Agent_OnLoad
4126     if (on_load_entry == NULL) {
4127       on_load_entry = lookup_agent_on_load(agent);
4128       if (on_load_entry != NULL) {
4129         // switch it to the agent list -- so that Agent_OnLoad will be called,
4130         // JVM_OnLoad won't be attempted and Agent_OnUnload will
4131         Arguments::convert_library_to_agent(agent);
4132       } else {
4133         vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
4134       }
4135     }
4136   }
4137 }
4138 
4139 // Create agents for -agentlib:  -agentpath:  and converted -Xrun
4140 // Invokes Agent_OnLoad
4141 // Called very early -- before JavaThreads exist
4142 void Threads::create_vm_init_agents() {
4143   extern struct JavaVM_ main_vm;
4144   AgentLibrary* agent;
4145 
4146   JvmtiExport::enter_onload_phase();
4147 
4148   for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
4149     OnLoadEntry_t  on_load_entry = lookup_agent_on_load(agent);
4150 
4151     if (on_load_entry != NULL) {
4152       // Invoke the Agent_OnLoad function
4153       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4154       if (err != JNI_OK) {
4155         vm_exit_during_initialization("agent library failed to init", agent->name());
4156       }
4157     } else {
4158       vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
4159     }
4160   }
4161   JvmtiExport::enter_primordial_phase();
4162 }
4163 
4164 extern "C" {
4165   typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
4166 }
4167 
4168 void Threads::shutdown_vm_agents() {
4169   // Send any Agent_OnUnload notifications
4170   const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
4171   size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
4172   extern struct JavaVM_ main_vm;
4173   for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
4174 
4175     // Find the Agent_OnUnload function.
4176     Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
4177                                                    os::find_agent_function(agent,
4178                                                    false,
4179                                                    on_unload_symbols,
4180                                                    num_symbol_entries));
4181 
4182     // Invoke the Agent_OnUnload function
4183     if (unload_entry != NULL) {
4184       JavaThread* thread = JavaThread::current();
4185       ThreadToNativeFromVM ttn(thread);
4186       HandleMark hm(thread);
4187       (*unload_entry)(&main_vm);
4188     }
4189   }
4190 }
4191 
4192 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
4193 // Invokes JVM_OnLoad
4194 void Threads::create_vm_init_libraries() {
4195   extern struct JavaVM_ main_vm;
4196   AgentLibrary* agent;
4197 
4198   for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
4199     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4200 
4201     if (on_load_entry != NULL) {
4202       // Invoke the JVM_OnLoad function
4203       JavaThread* thread = JavaThread::current();
4204       ThreadToNativeFromVM ttn(thread);
4205       HandleMark hm(thread);
4206       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4207       if (err != JNI_OK) {
4208         vm_exit_during_initialization("-Xrun library failed to init", agent->name());
4209       }
4210     } else {
4211       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
4212     }
4213   }
4214 }
4215 
4216 
4217 // Last thread running calls java.lang.Shutdown.shutdown()
4218 void JavaThread::invoke_shutdown_hooks() {
4219   HandleMark hm(this);
4220 
4221   // We could get here with a pending exception, if so clear it now.
4222   if (this->has_pending_exception()) {
4223     this->clear_pending_exception();
4224   }
4225 
4226   EXCEPTION_MARK;
4227   Klass* shutdown_klass =
4228     SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
4229                                       THREAD);
4230   if (shutdown_klass != NULL) {
4231     // SystemDictionary::resolve_or_null will return null if there was
4232     // an exception.  If we cannot load the Shutdown class, just don't
4233     // call Shutdown.shutdown() at all.  This will mean the shutdown hooks
4234     // won't be run.  Note that if a shutdown hook was registered,
4235     // the Shutdown class would have already been loaded
4236     // (Runtime.addShutdownHook will load it).
4237     JavaValue result(T_VOID);
4238     JavaCalls::call_static(&result,
4239                            shutdown_klass,
4240                            vmSymbols::shutdown_method_name(),
4241                            vmSymbols::void_method_signature(),
4242                            THREAD);
4243   }
4244   CLEAR_PENDING_EXCEPTION;
4245 }
4246 
4247 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
4248 // the program falls off the end of main(). Another VM exit path is through
4249 // vm_exit() when the program calls System.exit() to return a value or when
4250 // there is a serious error in VM. The two shutdown paths are not exactly
4251 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
4252 // and VM_Exit op at VM level.
4253 //
4254 // Shutdown sequence:
4255 //   + Shutdown native memory tracking if it is on
4256 //   + Wait until we are the last non-daemon thread to execute
4257 //     <-- every thing is still working at this moment -->
4258 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
4259 //        shutdown hooks
4260 //   + Call before_exit(), prepare for VM exit
4261 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
4262 //        currently the only user of this mechanism is File.deleteOnExit())
4263 //      > stop StatSampler, watcher thread, CMS threads,
4264 //        post thread end and vm death events to JVMTI,
4265 //        stop signal thread
4266 //   + Call JavaThread::exit(), it will:
4267 //      > release JNI handle blocks, remove stack guard pages
4268 //      > remove this thread from Threads list
4269 //     <-- no more Java code from this thread after this point -->
4270 //   + Stop VM thread, it will bring the remaining VM to a safepoint and stop
4271 //     the compiler threads at safepoint
4272 //     <-- do not use anything that could get blocked by Safepoint -->
4273 //   + Disable tracing at JNI/JVM barriers
4274 //   + Set _vm_exited flag for threads that are still running native code
4275 //   + Delete this thread
4276 //   + Call exit_globals()
4277 //      > deletes tty
4278 //      > deletes PerfMemory resources
4279 //   + Return to caller
4280 
4281 bool Threads::destroy_vm() {
4282   JavaThread* thread = JavaThread::current();
4283 
4284 #ifdef ASSERT
4285   _vm_complete = false;
4286 #endif
4287   // Wait until we are the last non-daemon thread to execute
4288   { MutexLocker nu(Threads_lock);
4289     while (Threads::number_of_non_daemon_threads() > 1)
4290       // This wait should make safepoint checks, wait without a timeout,
4291       // and wait as a suspend-equivalent condition.
4292       Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
4293                          Mutex::_as_suspend_equivalent_flag);
4294   }
4295 
4296   EventShutdown e;
4297   if (e.should_commit()) {
4298     e.set_reason("No remaining non-daemon Java threads");
4299     e.commit();
4300   }
4301 
4302   // Hang forever on exit if we are reporting an error.
4303   if (ShowMessageBoxOnError && VMError::is_error_reported()) {
4304     os::infinite_sleep();
4305   }
4306   os::wait_for_keypress_at_exit();
4307 
4308   // run Java level shutdown hooks
4309   thread->invoke_shutdown_hooks();
4310 
4311   before_exit(thread);
4312 
4313   thread->exit(true);
4314   // thread will never call smr_delete, instead of implicit cancel
4315   // in wait_for_vm_thread_exit we do it explicit.
4316   thread->cancel_handshake();
4317 
4318   // Stop VM thread.
4319   {
4320     // 4945125 The vm thread comes to a safepoint during exit.
4321     // GC vm_operations can get caught at the safepoint, and the
4322     // heap is unparseable if they are caught. Grab the Heap_lock
4323     // to prevent this. The GC vm_operations will not be able to
4324     // queue until after the vm thread is dead. After this point,
4325     // we'll never emerge out of the safepoint before the VM exits.
4326 
4327     MutexLocker ml(Heap_lock);
4328 
4329     VMThread::wait_for_vm_thread_exit();
4330     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
4331     VMThread::destroy();
4332   }
4333 
4334   // Now, all Java threads are gone except daemon threads. Daemon threads
4335   // running Java code or in VM are stopped by the Safepoint. However,
4336   // daemon threads executing native code are still running.  But they
4337   // will be stopped at native=>Java/VM barriers. Note that we can't
4338   // simply kill or suspend them, as it is inherently deadlock-prone.
4339 
4340   VM_Exit::set_vm_exited();
4341 
4342   // Clean up ideal graph printers after the VMThread has started
4343   // the final safepoint which will block all the Compiler threads.
4344   // Note that this Thread has already logically exited so the
4345   // clean_up() function's use of a JavaThreadIteratorWithHandle
4346   // would be a problem except set_vm_exited() has remembered the
4347   // shutdown thread which is granted a policy exception.
4348 #if defined(COMPILER2) && !defined(PRODUCT)
4349   IdealGraphPrinter::clean_up();
4350 #endif
4351 
4352   notify_vm_shutdown();
4353 
4354   // We are after VM_Exit::set_vm_exited() so we can't call
4355   // thread->smr_delete() or we will block on the Threads_lock.
4356   // Deleting the shutdown thread here is safe because another
4357   // JavaThread cannot have an active ThreadsListHandle for
4358   // this JavaThread.
4359   delete thread;
4360 
4361 #if INCLUDE_JVMCI
4362   if (JVMCICounterSize > 0) {
4363     FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
4364   }
4365 #endif
4366 
4367   // exit_globals() will delete tty
4368   exit_globals();
4369 
4370   LogConfiguration::finalize();
4371 
4372   return true;
4373 }
4374 
4375 
4376 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
4377   if (version == JNI_VERSION_1_1) return JNI_TRUE;
4378   return is_supported_jni_version(version);
4379 }
4380 
4381 
4382 jboolean Threads::is_supported_jni_version(jint version) {
4383   if (version == JNI_VERSION_1_2) return JNI_TRUE;
4384   if (version == JNI_VERSION_1_4) return JNI_TRUE;
4385   if (version == JNI_VERSION_1_6) return JNI_TRUE;
4386   if (version == JNI_VERSION_1_8) return JNI_TRUE;
4387   if (version == JNI_VERSION_9) return JNI_TRUE;
4388   if (version == JNI_VERSION_10) return JNI_TRUE;
4389   return JNI_FALSE;
4390 }
4391 
4392 
4393 void Threads::add(JavaThread* p, bool force_daemon) {
4394   // The threads lock must be owned at this point
4395   assert_locked_or_safepoint(Threads_lock);
4396 
4397   BarrierSet::barrier_set()->on_thread_attach(p);
4398 
4399   p->set_next(_thread_list);
4400   _thread_list = p;
4401 
4402   // Once a JavaThread is added to the Threads list, smr_delete() has
4403   // to be used to delete it. Otherwise we can just delete it directly.
4404   p->set_on_thread_list();
4405 
4406   _number_of_threads++;
4407   oop threadObj = p->threadObj();
4408   bool daemon = true;
4409   // Bootstrapping problem: threadObj can be null for initial
4410   // JavaThread (or for threads attached via JNI)
4411   if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
4412     _number_of_non_daemon_threads++;
4413     daemon = false;
4414   }
4415 
4416   ThreadService::add_thread(p, daemon);
4417 
4418   // Maintain fast thread list
4419   ThreadsSMRSupport::add_thread(p);
4420 
4421   // Possible GC point.
4422   Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
4423 }
4424 
4425 void Threads::remove(JavaThread* p) {
4426 
4427   // Reclaim the objectmonitors from the omInUseList and omFreeList of the moribund thread.
4428   ObjectSynchronizer::omFlush(p);
4429 
4430   // Extra scope needed for Thread_lock, so we can check
4431   // that we do not remove thread without safepoint code notice
4432   { MutexLocker ml(Threads_lock);
4433 
4434     assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present");
4435 
4436     // Maintain fast thread list
4437     ThreadsSMRSupport::remove_thread(p);
4438 
4439     JavaThread* current = _thread_list;
4440     JavaThread* prev    = NULL;
4441 
4442     while (current != p) {
4443       prev    = current;
4444       current = current->next();
4445     }
4446 
4447     if (prev) {
4448       prev->set_next(current->next());
4449     } else {
4450       _thread_list = p->next();
4451     }
4452 
4453     _number_of_threads--;
4454     oop threadObj = p->threadObj();
4455     bool daemon = true;
4456     if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
4457       _number_of_non_daemon_threads--;
4458       daemon = false;
4459 
4460       // Only one thread left, do a notify on the Threads_lock so a thread waiting
4461       // on destroy_vm will wake up.
4462       if (number_of_non_daemon_threads() == 1) {
4463         Threads_lock->notify_all();
4464       }
4465     }
4466     ThreadService::remove_thread(p, daemon);
4467 
4468     // Make sure that safepoint code disregard this thread. This is needed since
4469     // the thread might mess around with locks after this point. This can cause it
4470     // to do callbacks into the safepoint code. However, the safepoint code is not aware
4471     // of this thread since it is removed from the queue.
4472     p->set_terminated_value();
4473   } // unlock Threads_lock
4474 
4475   // Since Events::log uses a lock, we grab it outside the Threads_lock
4476   Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
4477 }
4478 
4479 // Operations on the Threads list for GC.  These are not explicitly locked,
4480 // but the garbage collector must provide a safe context for them to run.
4481 // In particular, these things should never be called when the Threads_lock
4482 // is held by some other thread. (Note: the Safepoint abstraction also
4483 // uses the Threads_lock to guarantee this property. It also makes sure that
4484 // all threads gets blocked when exiting or starting).
4485 
4486 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
4487   ALL_JAVA_THREADS(p) {
4488     p->oops_do(f, cf);
4489   }
4490   VMThread::vm_thread()->oops_do(f, cf);
4491 }
4492 
4493 void Threads::change_thread_claim_parity() {
4494   // Set the new claim parity.
4495   assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2,
4496          "Not in range.");
4497   _thread_claim_parity++;
4498   if (_thread_claim_parity == 3) _thread_claim_parity = 1;
4499   assert(_thread_claim_parity >= 1 && _thread_claim_parity <= 2,
4500          "Not in range.");
4501 }
4502 
4503 #ifdef ASSERT
4504 void Threads::assert_all_threads_claimed() {
4505   ALL_JAVA_THREADS(p) {
4506     const int thread_parity = p->oops_do_parity();
4507     assert((thread_parity == _thread_claim_parity),
4508            "Thread " PTR_FORMAT " has incorrect parity %d != %d", p2i(p), thread_parity, _thread_claim_parity);
4509   }
4510   VMThread* vmt = VMThread::vm_thread();
4511   const int thread_parity = vmt->oops_do_parity();
4512   assert((thread_parity == _thread_claim_parity),
4513          "VMThread " PTR_FORMAT " has incorrect parity %d != %d", p2i(vmt), thread_parity, _thread_claim_parity);
4514 }
4515 #endif // ASSERT
4516 
4517 class ParallelOopsDoThreadClosure : public ThreadClosure {
4518 private:
4519   OopClosure* _f;
4520   CodeBlobClosure* _cf;
4521 public:
4522   ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {}
4523   void do_thread(Thread* t) {
4524     t->oops_do(_f, _cf);
4525   }
4526 };
4527 
4528 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) {
4529   ParallelOopsDoThreadClosure tc(f, cf);
4530   possibly_parallel_threads_do(is_par, &tc);
4531 }
4532 
4533 void Threads::nmethods_do(CodeBlobClosure* cf) {
4534   ALL_JAVA_THREADS(p) {
4535     // This is used by the code cache sweeper to mark nmethods that are active
4536     // on the stack of a Java thread. Ignore the sweeper thread itself to avoid
4537     // marking CodeCacheSweeperThread::_scanned_compiled_method as active.
4538     if(!p->is_Code_cache_sweeper_thread()) {
4539       p->nmethods_do(cf);
4540     }
4541   }
4542 }
4543 
4544 void Threads::metadata_do(void f(Metadata*)) {
4545   ALL_JAVA_THREADS(p) {
4546     p->metadata_do(f);
4547   }
4548 }
4549 
4550 class ThreadHandlesClosure : public ThreadClosure {
4551   void (*_f)(Metadata*);
4552  public:
4553   ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
4554   virtual void do_thread(Thread* thread) {
4555     thread->metadata_handles_do(_f);
4556   }
4557 };
4558 
4559 void Threads::metadata_handles_do(void f(Metadata*)) {
4560   // Only walk the Handles in Thread.
4561   ThreadHandlesClosure handles_closure(f);
4562   threads_do(&handles_closure);
4563 }
4564 
4565 void Threads::deoptimized_wrt_marked_nmethods() {
4566   ALL_JAVA_THREADS(p) {
4567     p->deoptimized_wrt_marked_nmethods();
4568   }
4569 }
4570 
4571 
4572 // Get count Java threads that are waiting to enter the specified monitor.
4573 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
4574                                                          int count,
4575                                                          address monitor) {
4576   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4577 
4578   int i = 0;
4579   DO_JAVA_THREADS(t_list, p) {
4580     if (!p->can_call_java()) continue;
4581 
4582     address pending = (address)p->current_pending_monitor();
4583     if (pending == monitor) {             // found a match
4584       if (i < count) result->append(p);   // save the first count matches
4585       i++;
4586     }
4587   }
4588 
4589   return result;
4590 }
4591 
4592 
4593 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list,
4594                                                       address owner) {
4595   // NULL owner means not locked so we can skip the search
4596   if (owner == NULL) return NULL;
4597 
4598   DO_JAVA_THREADS(t_list, p) {
4599     // first, see if owner is the address of a Java thread
4600     if (owner == (address)p) return p;
4601   }
4602 
4603   // Cannot assert on lack of success here since this function may be
4604   // used by code that is trying to report useful problem information
4605   // like deadlock detection.
4606   if (UseHeavyMonitors) return NULL;
4607 
4608   // If we didn't find a matching Java thread and we didn't force use of
4609   // heavyweight monitors, then the owner is the stack address of the
4610   // Lock Word in the owning Java thread's stack.
4611   //
4612   JavaThread* the_owner = NULL;
4613   DO_JAVA_THREADS(t_list, q) {
4614     if (q->is_lock_owned(owner)) {
4615       the_owner = q;
4616       break;
4617     }
4618   }
4619 
4620   // cannot assert on lack of success here; see above comment
4621   return the_owner;
4622 }
4623 
4624 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4625 void Threads::print_on(outputStream* st, bool print_stacks,
4626                        bool internal_format, bool print_concurrent_locks,
4627                        bool print_extended_info) {
4628   char buf[32];
4629   st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
4630 
4631   st->print_cr("Full thread dump %s (%s %s):",
4632                Abstract_VM_Version::vm_name(),
4633                Abstract_VM_Version::vm_release(),
4634                Abstract_VM_Version::vm_info_string());
4635   st->cr();
4636 
4637 #if INCLUDE_SERVICES
4638   // Dump concurrent locks
4639   ConcurrentLocksDump concurrent_locks;
4640   if (print_concurrent_locks) {
4641     concurrent_locks.dump_at_safepoint();
4642   }
4643 #endif // INCLUDE_SERVICES
4644 
4645   ThreadsSMRSupport::print_info_on(st);
4646   st->cr();
4647 
4648   ALL_JAVA_THREADS(p) {
4649     ResourceMark rm;
4650     p->print_on(st, print_extended_info);
4651     if (print_stacks) {
4652       if (internal_format) {
4653         p->trace_stack();
4654       } else {
4655         p->print_stack_on(st);
4656       }
4657     }
4658     st->cr();
4659 #if INCLUDE_SERVICES
4660     if (print_concurrent_locks) {
4661       concurrent_locks.print_locks_on(p, st);
4662     }
4663 #endif // INCLUDE_SERVICES
4664   }
4665 
4666   VMThread::vm_thread()->print_on(st);
4667   st->cr();
4668   Universe::heap()->print_gc_threads_on(st);
4669   WatcherThread* wt = WatcherThread::watcher_thread();
4670   if (wt != NULL) {
4671     wt->print_on(st);
4672     st->cr();
4673   }
4674 
4675   st->flush();
4676 }
4677 
4678 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
4679                              int buflen, bool* found_current) {
4680   if (this_thread != NULL) {
4681     bool is_current = (current == this_thread);
4682     *found_current = *found_current || is_current;
4683     st->print("%s", is_current ? "=>" : "  ");
4684 
4685     st->print(PTR_FORMAT, p2i(this_thread));
4686     st->print(" ");
4687     this_thread->print_on_error(st, buf, buflen);
4688     st->cr();
4689   }
4690 }
4691 
4692 class PrintOnErrorClosure : public ThreadClosure {
4693   outputStream* _st;
4694   Thread* _current;
4695   char* _buf;
4696   int _buflen;
4697   bool* _found_current;
4698  public:
4699   PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
4700                       int buflen, bool* found_current) :
4701    _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
4702 
4703   virtual void do_thread(Thread* thread) {
4704     Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
4705   }
4706 };
4707 
4708 // Threads::print_on_error() is called by fatal error handler. It's possible
4709 // that VM is not at safepoint and/or current thread is inside signal handler.
4710 // Don't print stack trace, as the stack may not be walkable. Don't allocate
4711 // memory (even in resource area), it might deadlock the error handler.
4712 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
4713                              int buflen) {
4714   ThreadsSMRSupport::print_info_on(st);
4715   st->cr();
4716 
4717   bool found_current = false;
4718   st->print_cr("Java Threads: ( => current thread )");
4719   ALL_JAVA_THREADS(thread) {
4720     print_on_error(thread, st, current, buf, buflen, &found_current);
4721   }
4722   st->cr();
4723 
4724   st->print_cr("Other Threads:");
4725   print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
4726   print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
4727 
4728   PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
4729   Universe::heap()->gc_threads_do(&print_closure);
4730 
4731   if (!found_current) {
4732     st->cr();
4733     st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
4734     current->print_on_error(st, buf, buflen);
4735     st->cr();
4736   }
4737   st->cr();
4738 
4739   st->print_cr("Threads with active compile tasks:");
4740   print_threads_compiling(st, buf, buflen);
4741 }
4742 
4743 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) {
4744   ALL_JAVA_THREADS(thread) {
4745     if (thread->is_Compiler_thread()) {
4746       CompilerThread* ct = (CompilerThread*) thread;
4747 
4748       // Keep task in local variable for NULL check.
4749       // ct->_task might be set to NULL by concurring compiler thread
4750       // because it completed the compilation. The task is never freed,
4751       // though, just returned to a free list.
4752       CompileTask* task = ct->task();
4753       if (task != NULL) {
4754         thread->print_name_on_error(st, buf, buflen);
4755         task->print(st, NULL, true, true);
4756       }
4757     }
4758   }
4759 }
4760 
4761 
4762 // Internal SpinLock and Mutex
4763 // Based on ParkEvent
4764 
4765 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
4766 //
4767 // We employ SpinLocks _only for low-contention, fixed-length
4768 // short-duration critical sections where we're concerned
4769 // about native mutex_t or HotSpot Mutex:: latency.
4770 // The mux construct provides a spin-then-block mutual exclusion
4771 // mechanism.
4772 //
4773 // Testing has shown that contention on the ListLock guarding gFreeList
4774 // is common.  If we implement ListLock as a simple SpinLock it's common
4775 // for the JVM to devolve to yielding with little progress.  This is true
4776 // despite the fact that the critical sections protected by ListLock are
4777 // extremely short.
4778 //
4779 // TODO-FIXME: ListLock should be of type SpinLock.
4780 // We should make this a 1st-class type, integrated into the lock
4781 // hierarchy as leaf-locks.  Critically, the SpinLock structure
4782 // should have sufficient padding to avoid false-sharing and excessive
4783 // cache-coherency traffic.
4784 
4785 
4786 typedef volatile int SpinLockT;
4787 
4788 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
4789   if (Atomic::cmpxchg (1, adr, 0) == 0) {
4790     return;   // normal fast-path return
4791   }
4792 
4793   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
4794   TEVENT(SpinAcquire - ctx);
4795   int ctr = 0;
4796   int Yields = 0;
4797   for (;;) {
4798     while (*adr != 0) {
4799       ++ctr;
4800       if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
4801         if (Yields > 5) {
4802           os::naked_short_sleep(1);
4803         } else {
4804           os::naked_yield();
4805           ++Yields;
4806         }
4807       } else {
4808         SpinPause();
4809       }
4810     }
4811     if (Atomic::cmpxchg(1, adr, 0) == 0) return;
4812   }
4813 }
4814 
4815 void Thread::SpinRelease(volatile int * adr) {
4816   assert(*adr != 0, "invariant");
4817   OrderAccess::fence();      // guarantee at least release consistency.
4818   // Roach-motel semantics.
4819   // It's safe if subsequent LDs and STs float "up" into the critical section,
4820   // but prior LDs and STs within the critical section can't be allowed
4821   // to reorder or float past the ST that releases the lock.
4822   // Loads and stores in the critical section - which appear in program
4823   // order before the store that releases the lock - must also appear
4824   // before the store that releases the lock in memory visibility order.
4825   // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
4826   // the ST of 0 into the lock-word which releases the lock, so fence
4827   // more than covers this on all platforms.
4828   *adr = 0;
4829 }
4830 
4831 // muxAcquire and muxRelease:
4832 //
4833 // *  muxAcquire and muxRelease support a single-word lock-word construct.
4834 //    The LSB of the word is set IFF the lock is held.
4835 //    The remainder of the word points to the head of a singly-linked list
4836 //    of threads blocked on the lock.
4837 //
4838 // *  The current implementation of muxAcquire-muxRelease uses its own
4839 //    dedicated Thread._MuxEvent instance.  If we're interested in
4840 //    minimizing the peak number of extant ParkEvent instances then
4841 //    we could eliminate _MuxEvent and "borrow" _ParkEvent as long
4842 //    as certain invariants were satisfied.  Specifically, care would need
4843 //    to be taken with regards to consuming unpark() "permits".
4844 //    A safe rule of thumb is that a thread would never call muxAcquire()
4845 //    if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
4846 //    park().  Otherwise the _ParkEvent park() operation in muxAcquire() could
4847 //    consume an unpark() permit intended for monitorenter, for instance.
4848 //    One way around this would be to widen the restricted-range semaphore
4849 //    implemented in park().  Another alternative would be to provide
4850 //    multiple instances of the PlatformEvent() for each thread.  One
4851 //    instance would be dedicated to muxAcquire-muxRelease, for instance.
4852 //
4853 // *  Usage:
4854 //    -- Only as leaf locks
4855 //    -- for short-term locking only as muxAcquire does not perform
4856 //       thread state transitions.
4857 //
4858 // Alternatives:
4859 // *  We could implement muxAcquire and muxRelease with MCS or CLH locks
4860 //    but with parking or spin-then-park instead of pure spinning.
4861 // *  Use Taura-Oyama-Yonenzawa locks.
4862 // *  It's possible to construct a 1-0 lock if we encode the lockword as
4863 //    (List,LockByte).  Acquire will CAS the full lockword while Release
4864 //    will STB 0 into the LockByte.  The 1-0 scheme admits stranding, so
4865 //    acquiring threads use timers (ParkTimed) to detect and recover from
4866 //    the stranding window.  Thread/Node structures must be aligned on 256-byte
4867 //    boundaries by using placement-new.
4868 // *  Augment MCS with advisory back-link fields maintained with CAS().
4869 //    Pictorially:  LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
4870 //    The validity of the backlinks must be ratified before we trust the value.
4871 //    If the backlinks are invalid the exiting thread must back-track through the
4872 //    the forward links, which are always trustworthy.
4873 // *  Add a successor indication.  The LockWord is currently encoded as
4874 //    (List, LOCKBIT:1).  We could also add a SUCCBIT or an explicit _succ variable
4875 //    to provide the usual futile-wakeup optimization.
4876 //    See RTStt for details.
4877 //
4878 
4879 
4880 const intptr_t LOCKBIT = 1;
4881 
4882 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) {
4883   intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0);
4884   if (w == 0) return;
4885   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4886     return;
4887   }
4888 
4889   TEVENT(muxAcquire - Contention);
4890   ParkEvent * const Self = Thread::current()->_MuxEvent;
4891   assert((intptr_t(Self) & LOCKBIT) == 0, "invariant");
4892   for (;;) {
4893     int its = (os::is_MP() ? 100 : 0) + 1;
4894 
4895     // Optional spin phase: spin-then-park strategy
4896     while (--its >= 0) {
4897       w = *Lock;
4898       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4899         return;
4900       }
4901     }
4902 
4903     Self->reset();
4904     Self->OnList = intptr_t(Lock);
4905     // The following fence() isn't _strictly necessary as the subsequent
4906     // CAS() both serializes execution and ratifies the fetched *Lock value.
4907     OrderAccess::fence();
4908     for (;;) {
4909       w = *Lock;
4910       if ((w & LOCKBIT) == 0) {
4911         if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4912           Self->OnList = 0;   // hygiene - allows stronger asserts
4913           return;
4914         }
4915         continue;      // Interference -- *Lock changed -- Just retry
4916       }
4917       assert(w & LOCKBIT, "invariant");
4918       Self->ListNext = (ParkEvent *) (w & ~LOCKBIT);
4919       if (Atomic::cmpxchg(intptr_t(Self)|LOCKBIT, Lock, w) == w) break;
4920     }
4921 
4922     while (Self->OnList != 0) {
4923       Self->park();
4924     }
4925   }
4926 }
4927 
4928 void Thread::muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev) {
4929   intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0);
4930   if (w == 0) return;
4931   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4932     return;
4933   }
4934 
4935   TEVENT(muxAcquire - Contention);
4936   ParkEvent * ReleaseAfter = NULL;
4937   if (ev == NULL) {
4938     ev = ReleaseAfter = ParkEvent::Allocate(NULL);
4939   }
4940   assert((intptr_t(ev) & LOCKBIT) == 0, "invariant");
4941   for (;;) {
4942     guarantee(ev->OnList == 0, "invariant");
4943     int its = (os::is_MP() ? 100 : 0) + 1;
4944 
4945     // Optional spin phase: spin-then-park strategy
4946     while (--its >= 0) {
4947       w = *Lock;
4948       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4949         if (ReleaseAfter != NULL) {
4950           ParkEvent::Release(ReleaseAfter);
4951         }
4952         return;
4953       }
4954     }
4955 
4956     ev->reset();
4957     ev->OnList = intptr_t(Lock);
4958     // The following fence() isn't _strictly necessary as the subsequent
4959     // CAS() both serializes execution and ratifies the fetched *Lock value.
4960     OrderAccess::fence();
4961     for (;;) {
4962       w = *Lock;
4963       if ((w & LOCKBIT) == 0) {
4964         if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4965           ev->OnList = 0;
4966           // We call ::Release while holding the outer lock, thus
4967           // artificially lengthening the critical section.
4968           // Consider deferring the ::Release() until the subsequent unlock(),
4969           // after we've dropped the outer lock.
4970           if (ReleaseAfter != NULL) {
4971             ParkEvent::Release(ReleaseAfter);
4972           }
4973           return;
4974         }
4975         continue;      // Interference -- *Lock changed -- Just retry
4976       }
4977       assert(w & LOCKBIT, "invariant");
4978       ev->ListNext = (ParkEvent *) (w & ~LOCKBIT);
4979       if (Atomic::cmpxchg(intptr_t(ev)|LOCKBIT, Lock, w) == w) break;
4980     }
4981 
4982     while (ev->OnList != 0) {
4983       ev->park();
4984     }
4985   }
4986 }
4987 
4988 // Release() must extract a successor from the list and then wake that thread.
4989 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
4990 // similar to that used by ParkEvent::Allocate() and ::Release().  DMR-based
4991 // Release() would :
4992 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
4993 // (B) Extract a successor from the private list "in-hand"
4994 // (C) attempt to CAS() the residual back into *Lock over null.
4995 //     If there were any newly arrived threads and the CAS() would fail.
4996 //     In that case Release() would detach the RATs, re-merge the list in-hand
4997 //     with the RATs and repeat as needed.  Alternately, Release() might
4998 //     detach and extract a successor, but then pass the residual list to the wakee.
4999 //     The wakee would be responsible for reattaching and remerging before it
5000 //     competed for the lock.
5001 //
5002 // Both "pop" and DMR are immune from ABA corruption -- there can be
5003 // multiple concurrent pushers, but only one popper or detacher.
5004 // This implementation pops from the head of the list.  This is unfair,
5005 // but tends to provide excellent throughput as hot threads remain hot.
5006 // (We wake recently run threads first).
5007 //
5008 // All paths through muxRelease() will execute a CAS.
5009 // Release consistency -- We depend on the CAS in muxRelease() to provide full
5010 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations
5011 // executed within the critical section are complete and globally visible before the
5012 // store (CAS) to the lock-word that releases the lock becomes globally visible.
5013 void Thread::muxRelease(volatile intptr_t * Lock)  {
5014   for (;;) {
5015     const intptr_t w = Atomic::cmpxchg((intptr_t)0, Lock, LOCKBIT);
5016     assert(w & LOCKBIT, "invariant");
5017     if (w == LOCKBIT) return;
5018     ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT);
5019     assert(List != NULL, "invariant");
5020     assert(List->OnList == intptr_t(Lock), "invariant");
5021     ParkEvent * const nxt = List->ListNext;
5022     guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant");
5023 
5024     // The following CAS() releases the lock and pops the head element.
5025     // The CAS() also ratifies the previously fetched lock-word value.
5026     if (Atomic::cmpxchg(intptr_t(nxt), Lock, w) != w) {
5027       continue;
5028     }
5029     List->OnList = 0;
5030     OrderAccess::fence();
5031     List->unpark();
5032     return;
5033   }
5034 }
5035 
5036 
5037 void Threads::verify() {
5038   ALL_JAVA_THREADS(p) {
5039     p->verify();
5040   }
5041   VMThread* thread = VMThread::vm_thread();
5042   if (thread != NULL) thread->verify();
5043 }
5044 
5045 void Threads::print_vt_buffer_stats_on(outputStream* st) {
5046   ALL_JAVA_THREADS(p) {
5047     p->print_vt_buffer_stats_on(st);
5048   }
5049 }