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