1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #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 before removing a thread from
1998   // the list of active threads.
1999   Universe::heap()->flush_deferred_store_barrier(this);
2000   assert(deferred_card_mark().is_empty(), "Should have been flushed");
2001 
2002 #if INCLUDE_ALL_GCS
2003   // We must flush the G1-related buffers before removing a thread
2004   // from the list of active threads. We must do this after any deferred
2005   // card marks have been flushed (above) so that any entries that are
2006   // added to the thread's dirty card queue as a result are not lost.
2007   if (UseG1GC) {
2008     flush_barrier_queues();
2009   }
2010 #endif // INCLUDE_ALL_GCS
2011 
2012   log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").",
2013     exit_type == JavaThread::normal_exit ? "exiting" : "detaching",
2014     os::current_thread_id());
2015 
2016   if (log_is_enabled(Debug, os, thread, timer)) {
2017     _timer_exit_phase3.stop();
2018     _timer_exit_phase4.start();
2019   }
2020   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
2021   Threads::remove(this);
2022 
2023   if (log_is_enabled(Debug, os, thread, timer)) {
2024     _timer_exit_phase4.stop();
2025     ResourceMark rm(this);
2026     log_debug(os, thread, timer)("name='%s'"
2027                                  ", exit-phase1=" JLONG_FORMAT
2028                                  ", exit-phase2=" JLONG_FORMAT
2029                                  ", exit-phase3=" JLONG_FORMAT
2030                                  ", exit-phase4=" JLONG_FORMAT,
2031                                  get_thread_name(),
2032                                  _timer_exit_phase1.milliseconds(),
2033                                  _timer_exit_phase2.milliseconds(),
2034                                  _timer_exit_phase3.milliseconds(),
2035                                  _timer_exit_phase4.milliseconds());
2036   }
2037 }
2038 
2039 #if INCLUDE_ALL_GCS
2040 // Flush G1-related queues.
2041 void JavaThread::flush_barrier_queues() {
2042   satb_mark_queue().flush();
2043   dirty_card_queue().flush();
2044 }
2045 
2046 void JavaThread::initialize_queues() {
2047   assert(!SafepointSynchronize::is_at_safepoint(),
2048          "we should not be at a safepoint");
2049 
2050   SATBMarkQueue& satb_queue = satb_mark_queue();
2051   SATBMarkQueueSet& satb_queue_set = satb_mark_queue_set();
2052   // The SATB queue should have been constructed with its active
2053   // field set to false.
2054   assert(!satb_queue.is_active(), "SATB queue should not be active");
2055   assert(satb_queue.is_empty(), "SATB queue should be empty");
2056   // If we are creating the thread during a marking cycle, we should
2057   // set the active field of the SATB queue to true.
2058   if (satb_queue_set.is_active()) {
2059     satb_queue.set_active(true);
2060   }
2061 
2062   DirtyCardQueue& dirty_queue = dirty_card_queue();
2063   // The dirty card queue should have been constructed with its
2064   // active field set to true.
2065   assert(dirty_queue.is_active(), "dirty card queue should be active");
2066 }
2067 #endif // INCLUDE_ALL_GCS
2068 
2069 void JavaThread::cleanup_failed_attach_current_thread() {
2070   if (active_handles() != NULL) {
2071     JNIHandleBlock* block = active_handles();
2072     set_active_handles(NULL);
2073     JNIHandleBlock::release_block(block);
2074   }
2075 
2076   if (free_handle_block() != NULL) {
2077     JNIHandleBlock* block = free_handle_block();
2078     set_free_handle_block(NULL);
2079     JNIHandleBlock::release_block(block);
2080   }
2081 
2082   // These have to be removed while this is still a valid thread.
2083   remove_stack_guard_pages();
2084 
2085   if (UseTLAB) {
2086     tlab().make_parsable(true);  // retire TLAB, if any
2087   }
2088 
2089 #if INCLUDE_ALL_GCS
2090   if (UseG1GC) {
2091     flush_barrier_queues();
2092   }
2093 #endif // INCLUDE_ALL_GCS
2094 
2095   Threads::remove(this);
2096   this->smr_delete();
2097 }
2098 
2099 
2100 
2101 
2102 JavaThread* JavaThread::active() {
2103   Thread* thread = Thread::current();
2104   if (thread->is_Java_thread()) {
2105     return (JavaThread*) thread;
2106   } else {
2107     assert(thread->is_VM_thread(), "this must be a vm thread");
2108     VM_Operation* op = ((VMThread*) thread)->vm_operation();
2109     JavaThread *ret=op == NULL ? NULL : (JavaThread *)op->calling_thread();
2110     assert(ret->is_Java_thread(), "must be a Java thread");
2111     return ret;
2112   }
2113 }
2114 
2115 bool JavaThread::is_lock_owned(address adr) const {
2116   if (Thread::is_lock_owned(adr)) return true;
2117 
2118   for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2119     if (chunk->contains(adr)) return true;
2120   }
2121 
2122   return false;
2123 }
2124 
2125 
2126 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) {
2127   chunk->set_next(monitor_chunks());
2128   set_monitor_chunks(chunk);
2129 }
2130 
2131 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) {
2132   guarantee(monitor_chunks() != NULL, "must be non empty");
2133   if (monitor_chunks() == chunk) {
2134     set_monitor_chunks(chunk->next());
2135   } else {
2136     MonitorChunk* prev = monitor_chunks();
2137     while (prev->next() != chunk) prev = prev->next();
2138     prev->set_next(chunk->next());
2139   }
2140 }
2141 
2142 // JVM support.
2143 
2144 // Note: this function shouldn't block if it's called in
2145 // _thread_in_native_trans state (such as from
2146 // check_special_condition_for_native_trans()).
2147 void JavaThread::check_and_handle_async_exceptions(bool check_unsafe_error) {
2148 
2149   if (has_last_Java_frame() && has_async_condition()) {
2150     // If we are at a polling page safepoint (not a poll return)
2151     // then we must defer async exception because live registers
2152     // will be clobbered by the exception path. Poll return is
2153     // ok because the call we a returning from already collides
2154     // with exception handling registers and so there is no issue.
2155     // (The exception handling path kills call result registers but
2156     //  this is ok since the exception kills the result anyway).
2157 
2158     if (is_at_poll_safepoint()) {
2159       // if the code we are returning to has deoptimized we must defer
2160       // the exception otherwise live registers get clobbered on the
2161       // exception path before deoptimization is able to retrieve them.
2162       //
2163       RegisterMap map(this, false);
2164       frame caller_fr = last_frame().sender(&map);
2165       assert(caller_fr.is_compiled_frame(), "what?");
2166       if (caller_fr.is_deoptimized_frame()) {
2167         log_info(exceptions)("deferred async exception at compiled safepoint");
2168         return;
2169       }
2170     }
2171   }
2172 
2173   JavaThread::AsyncRequests condition = clear_special_runtime_exit_condition();
2174   if (condition == _no_async_condition) {
2175     // Conditions have changed since has_special_runtime_exit_condition()
2176     // was called:
2177     // - if we were here only because of an external suspend request,
2178     //   then that was taken care of above (or cancelled) so we are done
2179     // - if we were here because of another async request, then it has
2180     //   been cleared between the has_special_runtime_exit_condition()
2181     //   and now so again we are done
2182     return;
2183   }
2184 
2185   // Check for pending async. exception
2186   if (_pending_async_exception != NULL) {
2187     // Only overwrite an already pending exception, if it is not a threadDeath.
2188     if (!has_pending_exception() || !pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())) {
2189 
2190       // We cannot call Exceptions::_throw(...) here because we cannot block
2191       set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
2192 
2193       LogTarget(Info, exceptions) lt;
2194       if (lt.is_enabled()) {
2195         ResourceMark rm;
2196         LogStream ls(lt);
2197         ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this));
2198           if (has_last_Java_frame()) {
2199             frame f = last_frame();
2200            ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp()));
2201           }
2202         ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name());
2203       }
2204       _pending_async_exception = NULL;
2205       clear_has_async_exception();
2206     }
2207   }
2208 
2209   if (check_unsafe_error &&
2210       condition == _async_unsafe_access_error && !has_pending_exception()) {
2211     condition = _no_async_condition;  // done
2212     switch (thread_state()) {
2213     case _thread_in_vm: {
2214       JavaThread* THREAD = this;
2215       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2216     }
2217     case _thread_in_native: {
2218       ThreadInVMfromNative tiv(this);
2219       JavaThread* THREAD = this;
2220       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in an unsafe memory access operation");
2221     }
2222     case _thread_in_Java: {
2223       ThreadInVMfromJava tiv(this);
2224       JavaThread* THREAD = this;
2225       THROW_MSG(vmSymbols::java_lang_InternalError(), "a fault occurred in a recent unsafe memory access operation in compiled Java code");
2226     }
2227     default:
2228       ShouldNotReachHere();
2229     }
2230   }
2231 
2232   assert(condition == _no_async_condition || has_pending_exception() ||
2233          (!check_unsafe_error && condition == _async_unsafe_access_error),
2234          "must have handled the async condition, if no exception");
2235 }
2236 
2237 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
2238   //
2239   // Check for pending external suspend. Internal suspend requests do
2240   // not use handle_special_runtime_exit_condition().
2241   // If JNIEnv proxies are allowed, don't self-suspend if the target
2242   // thread is not the current thread. In older versions of jdbx, jdbx
2243   // threads could call into the VM with another thread's JNIEnv so we
2244   // can be here operating on behalf of a suspended thread (4432884).
2245   bool do_self_suspend = is_external_suspend_with_lock();
2246   if (do_self_suspend && (!AllowJNIEnvProxy || this == JavaThread::current())) {
2247     //
2248     // Because thread is external suspended the safepoint code will count
2249     // thread as at a safepoint. This can be odd because we can be here
2250     // as _thread_in_Java which would normally transition to _thread_blocked
2251     // at a safepoint. We would like to mark the thread as _thread_blocked
2252     // before calling java_suspend_self like all other callers of it but
2253     // we must then observe proper safepoint protocol. (We can't leave
2254     // _thread_blocked with a safepoint in progress). However we can be
2255     // here as _thread_in_native_trans so we can't use a normal transition
2256     // constructor/destructor pair because they assert on that type of
2257     // transition. We could do something like:
2258     //
2259     // JavaThreadState state = thread_state();
2260     // set_thread_state(_thread_in_vm);
2261     // {
2262     //   ThreadBlockInVM tbivm(this);
2263     //   java_suspend_self()
2264     // }
2265     // set_thread_state(_thread_in_vm_trans);
2266     // if (safepoint) block;
2267     // set_thread_state(state);
2268     //
2269     // but that is pretty messy. Instead we just go with the way the
2270     // code has worked before and note that this is the only path to
2271     // java_suspend_self that doesn't put the thread in _thread_blocked
2272     // mode.
2273 
2274     frame_anchor()->make_walkable(this);
2275     java_suspend_self();
2276 
2277     // We might be here for reasons in addition to the self-suspend request
2278     // so check for other async requests.
2279   }
2280 
2281   if (check_asyncs) {
2282     check_and_handle_async_exceptions();
2283   }
2284 #if INCLUDE_TRACE
2285   if (is_trace_suspend()) {
2286     TRACE_SUSPEND_THREAD(this);
2287   }
2288 #endif
2289 }
2290 
2291 void JavaThread::send_thread_stop(oop java_throwable)  {
2292   assert(Thread::current()->is_VM_thread(), "should be in the vm thread");
2293   assert(Threads_lock->is_locked(), "Threads_lock should be locked by safepoint code");
2294   assert(SafepointSynchronize::is_at_safepoint(), "all threads are stopped");
2295 
2296   // Do not throw asynchronous exceptions against the compiler thread
2297   // (the compiler thread should not be a Java thread -- fix in 1.4.2)
2298   if (!can_call_java()) return;
2299 
2300   {
2301     // Actually throw the Throwable against the target Thread - however
2302     // only if there is no thread death exception installed already.
2303     if (_pending_async_exception == NULL || !_pending_async_exception->is_a(SystemDictionary::ThreadDeath_klass())) {
2304       // If the topmost frame is a runtime stub, then we are calling into
2305       // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..)
2306       // must deoptimize the caller before continuing, as the compiled  exception handler table
2307       // may not be valid
2308       if (has_last_Java_frame()) {
2309         frame f = last_frame();
2310         if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) {
2311           // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2312           RegisterMap reg_map(this, UseBiasedLocking);
2313           frame compiled_frame = f.sender(&reg_map);
2314           if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) {
2315             Deoptimization::deoptimize(this, compiled_frame, &reg_map);
2316           }
2317         }
2318       }
2319 
2320       // Set async. pending exception in thread.
2321       set_pending_async_exception(java_throwable);
2322 
2323       if (log_is_enabled(Info, exceptions)) {
2324          ResourceMark rm;
2325         log_info(exceptions)("Pending Async. exception installed of type: %s",
2326                              InstanceKlass::cast(_pending_async_exception->klass())->external_name());
2327       }
2328       // for AbortVMOnException flag
2329       Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name());
2330     }
2331   }
2332 
2333 
2334   // Interrupt thread so it will wake up from a potential wait()
2335   Thread::interrupt(this);
2336 }
2337 
2338 // External suspension mechanism.
2339 //
2340 // Tell the VM to suspend a thread when ever it knows that it does not hold on
2341 // to any VM_locks and it is at a transition
2342 // Self-suspension will happen on the transition out of the vm.
2343 // Catch "this" coming in from JNIEnv pointers when the thread has been freed
2344 //
2345 // Guarantees on return:
2346 //   + Target thread will not execute any new bytecode (that's why we need to
2347 //     force a safepoint)
2348 //   + Target thread will not enter any new monitors
2349 //
2350 void JavaThread::java_suspend() {
2351   ThreadsListHandle tlh;
2352   if (!tlh.includes(this) || threadObj() == NULL || is_exiting()) {
2353     return;
2354   }
2355 
2356   { MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2357     if (!is_external_suspend()) {
2358       // a racing resume has cancelled us; bail out now
2359       return;
2360     }
2361 
2362     // suspend is done
2363     uint32_t debug_bits = 0;
2364     // Warning: is_ext_suspend_completed() may temporarily drop the
2365     // SR_lock to allow the thread to reach a stable thread state if
2366     // it is currently in a transient thread state.
2367     if (is_ext_suspend_completed(false /* !called_by_wait */,
2368                                  SuspendRetryDelay, &debug_bits)) {
2369       return;
2370     }
2371   }
2372 
2373   VM_ThreadSuspend vm_suspend;
2374   VMThread::execute(&vm_suspend);
2375 }
2376 
2377 // Part II of external suspension.
2378 // A JavaThread self suspends when it detects a pending external suspend
2379 // request. This is usually on transitions. It is also done in places
2380 // where continuing to the next transition would surprise the caller,
2381 // e.g., monitor entry.
2382 //
2383 // Returns the number of times that the thread self-suspended.
2384 //
2385 // Note: DO NOT call java_suspend_self() when you just want to block current
2386 //       thread. java_suspend_self() is the second stage of cooperative
2387 //       suspension for external suspend requests and should only be used
2388 //       to complete an external suspend request.
2389 //
2390 int JavaThread::java_suspend_self() {
2391   int ret = 0;
2392 
2393   // we are in the process of exiting so don't suspend
2394   if (is_exiting()) {
2395     clear_external_suspend();
2396     return ret;
2397   }
2398 
2399   assert(_anchor.walkable() ||
2400          (is_Java_thread() && !((JavaThread*)this)->has_last_Java_frame()),
2401          "must have walkable stack");
2402 
2403   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2404 
2405   assert(!this->is_ext_suspended(),
2406          "a thread trying to self-suspend should not already be suspended");
2407 
2408   if (this->is_suspend_equivalent()) {
2409     // If we are self-suspending as a result of the lifting of a
2410     // suspend equivalent condition, then the suspend_equivalent
2411     // flag is not cleared until we set the ext_suspended flag so
2412     // that wait_for_ext_suspend_completion() returns consistent
2413     // results.
2414     this->clear_suspend_equivalent();
2415   }
2416 
2417   // A racing resume may have cancelled us before we grabbed SR_lock
2418   // above. Or another external suspend request could be waiting for us
2419   // by the time we return from SR_lock()->wait(). The thread
2420   // that requested the suspension may already be trying to walk our
2421   // stack and if we return now, we can change the stack out from under
2422   // it. This would be a "bad thing (TM)" and cause the stack walker
2423   // to crash. We stay self-suspended until there are no more pending
2424   // external suspend requests.
2425   while (is_external_suspend()) {
2426     ret++;
2427     this->set_ext_suspended();
2428 
2429     // _ext_suspended flag is cleared by java_resume()
2430     while (is_ext_suspended()) {
2431       this->SR_lock()->wait(Mutex::_no_safepoint_check_flag);
2432     }
2433   }
2434 
2435   return ret;
2436 }
2437 
2438 #ifdef ASSERT
2439 // verify the JavaThread has not yet been published in the Threads::list, and
2440 // hence doesn't need protection from concurrent access at this stage
2441 void JavaThread::verify_not_published() {
2442   ThreadsListHandle tlh;
2443   assert(!tlh.includes(this), "JavaThread shouldn't have been published yet!");
2444 }
2445 #endif
2446 
2447 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2448 // progress or when _suspend_flags is non-zero.
2449 // Current thread needs to self-suspend if there is a suspend request and/or
2450 // block if a safepoint is in progress.
2451 // Async exception ISN'T checked.
2452 // Note only the ThreadInVMfromNative transition can call this function
2453 // directly and when thread state is _thread_in_native_trans
2454 void JavaThread::check_safepoint_and_suspend_for_native_trans(JavaThread *thread) {
2455   assert(thread->thread_state() == _thread_in_native_trans, "wrong state");
2456 
2457   JavaThread *curJT = JavaThread::current();
2458   bool do_self_suspend = thread->is_external_suspend();
2459 
2460   assert(!curJT->has_last_Java_frame() || curJT->frame_anchor()->walkable(), "Unwalkable stack in native->vm transition");
2461 
2462   // If JNIEnv proxies are allowed, don't self-suspend if the target
2463   // thread is not the current thread. In older versions of jdbx, jdbx
2464   // threads could call into the VM with another thread's JNIEnv so we
2465   // can be here operating on behalf of a suspended thread (4432884).
2466   if (do_self_suspend && (!AllowJNIEnvProxy || curJT == thread)) {
2467     JavaThreadState state = thread->thread_state();
2468 
2469     // We mark this thread_blocked state as a suspend-equivalent so
2470     // that a caller to is_ext_suspend_completed() won't be confused.
2471     // The suspend-equivalent state is cleared by java_suspend_self().
2472     thread->set_suspend_equivalent();
2473 
2474     // If the safepoint code sees the _thread_in_native_trans state, it will
2475     // wait until the thread changes to other thread state. There is no
2476     // guarantee on how soon we can obtain the SR_lock and complete the
2477     // self-suspend request. It would be a bad idea to let safepoint wait for
2478     // too long. Temporarily change the state to _thread_blocked to
2479     // let the VM thread know that this thread is ready for GC. The problem
2480     // of changing thread state is that safepoint could happen just after
2481     // java_suspend_self() returns after being resumed, and VM thread will
2482     // see the _thread_blocked state. We must check for safepoint
2483     // after restoring the state and make sure we won't leave while a safepoint
2484     // is in progress.
2485     thread->set_thread_state(_thread_blocked);
2486     thread->java_suspend_self();
2487     thread->set_thread_state(state);
2488 
2489     InterfaceSupport::serialize_thread_state_with_handler(thread);
2490   }
2491 
2492   SafepointMechanism::block_if_requested(curJT);
2493 
2494   if (thread->is_deopt_suspend()) {
2495     thread->clear_deopt_suspend();
2496     RegisterMap map(thread, false);
2497     frame f = thread->last_frame();
2498     while (f.id() != thread->must_deopt_id() && ! f.is_first_frame()) {
2499       f = f.sender(&map);
2500     }
2501     if (f.id() == thread->must_deopt_id()) {
2502       thread->clear_must_deopt_id();
2503       f.deoptimize(thread);
2504     } else {
2505       fatal("missed deoptimization!");
2506     }
2507   }
2508 #if INCLUDE_TRACE
2509   if (thread->is_trace_suspend()) {
2510     TRACE_SUSPEND_THREAD(thread);
2511   }
2512 #endif
2513 }
2514 
2515 // Slow path when the native==>VM/Java barriers detect a safepoint is in
2516 // progress or when _suspend_flags is non-zero.
2517 // Current thread needs to self-suspend if there is a suspend request and/or
2518 // block if a safepoint is in progress.
2519 // Also check for pending async exception (not including unsafe access error).
2520 // Note only the native==>VM/Java barriers can call this function and when
2521 // thread state is _thread_in_native_trans.
2522 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) {
2523   check_safepoint_and_suspend_for_native_trans(thread);
2524 
2525   if (thread->has_async_exception()) {
2526     // We are in _thread_in_native_trans state, don't handle unsafe
2527     // access error since that may block.
2528     thread->check_and_handle_async_exceptions(false);
2529   }
2530 }
2531 
2532 // This is a variant of the normal
2533 // check_special_condition_for_native_trans with slightly different
2534 // semantics for use by critical native wrappers.  It does all the
2535 // normal checks but also performs the transition back into
2536 // thread_in_Java state.  This is required so that critical natives
2537 // can potentially block and perform a GC if they are the last thread
2538 // exiting the GCLocker.
2539 void JavaThread::check_special_condition_for_native_trans_and_transition(JavaThread *thread) {
2540   check_special_condition_for_native_trans(thread);
2541 
2542   // Finish the transition
2543   thread->set_thread_state(_thread_in_Java);
2544 
2545   if (thread->do_critical_native_unlock()) {
2546     ThreadInVMfromJavaNoAsyncException tiv(thread);
2547     GCLocker::unlock_critical(thread);
2548     thread->clear_critical_native_unlock();
2549   }
2550 }
2551 
2552 // We need to guarantee the Threads_lock here, since resumes are not
2553 // allowed during safepoint synchronization
2554 // Can only resume from an external suspension
2555 void JavaThread::java_resume() {
2556   assert_locked_or_safepoint(Threads_lock);
2557 
2558   // Sanity check: thread is gone, has started exiting or the thread
2559   // was not externally suspended.
2560   ThreadsListHandle tlh;
2561   if (!tlh.includes(this) || is_exiting() || !is_external_suspend()) {
2562     return;
2563   }
2564 
2565   MutexLockerEx ml(SR_lock(), Mutex::_no_safepoint_check_flag);
2566 
2567   clear_external_suspend();
2568 
2569   if (is_ext_suspended()) {
2570     clear_ext_suspended();
2571     SR_lock()->notify_all();
2572   }
2573 }
2574 
2575 size_t JavaThread::_stack_red_zone_size = 0;
2576 size_t JavaThread::_stack_yellow_zone_size = 0;
2577 size_t JavaThread::_stack_reserved_zone_size = 0;
2578 size_t JavaThread::_stack_shadow_zone_size = 0;
2579 
2580 void JavaThread::create_stack_guard_pages() {
2581   if (!os::uses_stack_guard_pages() ||
2582       _stack_guard_state != stack_guard_unused ||
2583       (DisablePrimordialThreadGuardPages && os::is_primordial_thread())) {
2584       log_info(os, thread)("Stack guard page creation for thread "
2585                            UINTX_FORMAT " disabled", os::current_thread_id());
2586     return;
2587   }
2588   address low_addr = stack_end();
2589   size_t len = stack_guard_zone_size();
2590 
2591   assert(is_aligned(low_addr, os::vm_page_size()), "Stack base should be the start of a page");
2592   assert(is_aligned(len, os::vm_page_size()), "Stack size should be a multiple of page size");
2593 
2594   int must_commit = os::must_commit_stack_guard_pages();
2595   // warning("Guarding at " PTR_FORMAT " for len " SIZE_FORMAT "\n", low_addr, len);
2596 
2597   if (must_commit && !os::create_stack_guard_pages((char *) low_addr, len)) {
2598     log_warning(os, thread)("Attempt to allocate stack guard pages failed.");
2599     return;
2600   }
2601 
2602   if (os::guard_memory((char *) low_addr, len)) {
2603     _stack_guard_state = stack_guard_enabled;
2604   } else {
2605     log_warning(os, thread)("Attempt to protect stack guard pages failed ("
2606       PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2607     if (os::uncommit_memory((char *) low_addr, len)) {
2608       log_warning(os, thread)("Attempt to deallocate stack guard pages failed.");
2609     }
2610     return;
2611   }
2612 
2613   log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages activated: "
2614     PTR_FORMAT "-" PTR_FORMAT ".",
2615     os::current_thread_id(), p2i(low_addr), p2i(low_addr + len));
2616 }
2617 
2618 void JavaThread::remove_stack_guard_pages() {
2619   assert(Thread::current() == this, "from different thread");
2620   if (_stack_guard_state == stack_guard_unused) return;
2621   address low_addr = stack_end();
2622   size_t len = stack_guard_zone_size();
2623 
2624   if (os::must_commit_stack_guard_pages()) {
2625     if (os::remove_stack_guard_pages((char *) low_addr, len)) {
2626       _stack_guard_state = stack_guard_unused;
2627     } else {
2628       log_warning(os, thread)("Attempt to deallocate stack guard pages failed ("
2629         PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2630       return;
2631     }
2632   } else {
2633     if (_stack_guard_state == stack_guard_unused) return;
2634     if (os::unguard_memory((char *) low_addr, len)) {
2635       _stack_guard_state = stack_guard_unused;
2636     } else {
2637       log_warning(os, thread)("Attempt to unprotect stack guard pages failed ("
2638         PTR_FORMAT "-" PTR_FORMAT ").", p2i(low_addr), p2i(low_addr + len));
2639       return;
2640     }
2641   }
2642 
2643   log_debug(os, thread)("Thread " UINTX_FORMAT " stack guard pages removed: "
2644     PTR_FORMAT "-" PTR_FORMAT ".",
2645     os::current_thread_id(), p2i(low_addr), p2i(low_addr + len));
2646 }
2647 
2648 void JavaThread::enable_stack_reserved_zone() {
2649   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2650   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2651 
2652   // The base notation is from the stack's point of view, growing downward.
2653   // We need to adjust it to work correctly with guard_memory()
2654   address base = stack_reserved_zone_base() - stack_reserved_zone_size();
2655 
2656   guarantee(base < stack_base(),"Error calculating stack reserved zone");
2657   guarantee(base < os::current_stack_pointer(),"Error calculating stack reserved zone");
2658 
2659   if (os::guard_memory((char *) base, stack_reserved_zone_size())) {
2660     _stack_guard_state = stack_guard_enabled;
2661   } else {
2662     warning("Attempt to guard stack reserved zone failed.");
2663   }
2664   enable_register_stack_guard();
2665 }
2666 
2667 void JavaThread::disable_stack_reserved_zone() {
2668   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2669   assert(_stack_guard_state != stack_guard_reserved_disabled, "already disabled");
2670 
2671   // Simply return if called for a thread that does not use guard pages.
2672   if (_stack_guard_state == stack_guard_unused) return;
2673 
2674   // The base notation is from the stack's point of view, growing downward.
2675   // We need to adjust it to work correctly with guard_memory()
2676   address base = stack_reserved_zone_base() - stack_reserved_zone_size();
2677 
2678   if (os::unguard_memory((char *)base, stack_reserved_zone_size())) {
2679     _stack_guard_state = stack_guard_reserved_disabled;
2680   } else {
2681     warning("Attempt to unguard stack reserved zone failed.");
2682   }
2683   disable_register_stack_guard();
2684 }
2685 
2686 void JavaThread::enable_stack_yellow_reserved_zone() {
2687   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2688   assert(_stack_guard_state != stack_guard_enabled, "already enabled");
2689 
2690   // The base notation is from the stacks point of view, growing downward.
2691   // We need to adjust it to work correctly with guard_memory()
2692   address base = stack_red_zone_base();
2693 
2694   guarantee(base < stack_base(), "Error calculating stack yellow zone");
2695   guarantee(base < os::current_stack_pointer(), "Error calculating stack yellow zone");
2696 
2697   if (os::guard_memory((char *) base, stack_yellow_reserved_zone_size())) {
2698     _stack_guard_state = stack_guard_enabled;
2699   } else {
2700     warning("Attempt to guard stack yellow zone failed.");
2701   }
2702   enable_register_stack_guard();
2703 }
2704 
2705 void JavaThread::disable_stack_yellow_reserved_zone() {
2706   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2707   assert(_stack_guard_state != stack_guard_yellow_reserved_disabled, "already disabled");
2708 
2709   // Simply return if called for a thread that does not use guard pages.
2710   if (_stack_guard_state == stack_guard_unused) return;
2711 
2712   // The base notation is from the stacks point of view, growing downward.
2713   // We need to adjust it to work correctly with guard_memory()
2714   address base = stack_red_zone_base();
2715 
2716   if (os::unguard_memory((char *)base, stack_yellow_reserved_zone_size())) {
2717     _stack_guard_state = stack_guard_yellow_reserved_disabled;
2718   } else {
2719     warning("Attempt to unguard stack yellow zone failed.");
2720   }
2721   disable_register_stack_guard();
2722 }
2723 
2724 void JavaThread::enable_stack_red_zone() {
2725   // The base notation is from the stacks point of view, growing downward.
2726   // We need to adjust it to work correctly with guard_memory()
2727   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2728   address base = stack_red_zone_base() - stack_red_zone_size();
2729 
2730   guarantee(base < stack_base(), "Error calculating stack red zone");
2731   guarantee(base < os::current_stack_pointer(), "Error calculating stack red zone");
2732 
2733   if (!os::guard_memory((char *) base, stack_red_zone_size())) {
2734     warning("Attempt to guard stack red zone failed.");
2735   }
2736 }
2737 
2738 void JavaThread::disable_stack_red_zone() {
2739   // The base notation is from the stacks point of view, growing downward.
2740   // We need to adjust it to work correctly with guard_memory()
2741   assert(_stack_guard_state != stack_guard_unused, "must be using guard pages.");
2742   address base = stack_red_zone_base() - stack_red_zone_size();
2743   if (!os::unguard_memory((char *)base, stack_red_zone_size())) {
2744     warning("Attempt to unguard stack red zone failed.");
2745   }
2746 }
2747 
2748 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2749   // ignore is there is no stack
2750   if (!has_last_Java_frame()) return;
2751   // traverse the stack frames. Starts from top frame.
2752   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2753     frame* fr = fst.current();
2754     f(fr, fst.register_map());
2755   }
2756 }
2757 
2758 
2759 #ifndef PRODUCT
2760 // Deoptimization
2761 // Function for testing deoptimization
2762 void JavaThread::deoptimize() {
2763   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2764   StackFrameStream fst(this, UseBiasedLocking);
2765   bool deopt = false;           // Dump stack only if a deopt actually happens.
2766   bool only_at = strlen(DeoptimizeOnlyAt) > 0;
2767   // Iterate over all frames in the thread and deoptimize
2768   for (; !fst.is_done(); fst.next()) {
2769     if (fst.current()->can_be_deoptimized()) {
2770 
2771       if (only_at) {
2772         // Deoptimize only at particular bcis.  DeoptimizeOnlyAt
2773         // consists of comma or carriage return separated numbers so
2774         // search for the current bci in that string.
2775         address pc = fst.current()->pc();
2776         nmethod* nm =  (nmethod*) fst.current()->cb();
2777         ScopeDesc* sd = nm->scope_desc_at(pc);
2778         char buffer[8];
2779         jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci());
2780         size_t len = strlen(buffer);
2781         const char * found = strstr(DeoptimizeOnlyAt, buffer);
2782         while (found != NULL) {
2783           if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') &&
2784               (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) {
2785             // Check that the bci found is bracketed by terminators.
2786             break;
2787           }
2788           found = strstr(found + 1, buffer);
2789         }
2790         if (!found) {
2791           continue;
2792         }
2793       }
2794 
2795       if (DebugDeoptimization && !deopt) {
2796         deopt = true; // One-time only print before deopt
2797         tty->print_cr("[BEFORE Deoptimization]");
2798         trace_frames();
2799         trace_stack();
2800       }
2801       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2802     }
2803   }
2804 
2805   if (DebugDeoptimization && deopt) {
2806     tty->print_cr("[AFTER Deoptimization]");
2807     trace_frames();
2808   }
2809 }
2810 
2811 
2812 // Make zombies
2813 void JavaThread::make_zombies() {
2814   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2815     if (fst.current()->can_be_deoptimized()) {
2816       // it is a Java nmethod
2817       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
2818       nm->make_not_entrant();
2819     }
2820   }
2821 }
2822 #endif // PRODUCT
2823 
2824 
2825 void JavaThread::deoptimized_wrt_marked_nmethods() {
2826   if (!has_last_Java_frame()) return;
2827   // BiasedLocking needs an updated RegisterMap for the revoke monitors pass
2828   StackFrameStream fst(this, UseBiasedLocking);
2829   for (; !fst.is_done(); fst.next()) {
2830     if (fst.current()->should_be_deoptimized()) {
2831       Deoptimization::deoptimize(this, *fst.current(), fst.register_map());
2832     }
2833   }
2834 }
2835 
2836 
2837 // If the caller is a NamedThread, then remember, in the current scope,
2838 // the given JavaThread in its _processed_thread field.
2839 class RememberProcessedThread: public StackObj {
2840   NamedThread* _cur_thr;
2841  public:
2842   RememberProcessedThread(JavaThread* jthr) {
2843     Thread* thread = Thread::current();
2844     if (thread->is_Named_thread()) {
2845       _cur_thr = (NamedThread *)thread;
2846       _cur_thr->set_processed_thread(jthr);
2847     } else {
2848       _cur_thr = NULL;
2849     }
2850   }
2851 
2852   ~RememberProcessedThread() {
2853     if (_cur_thr) {
2854       _cur_thr->set_processed_thread(NULL);
2855     }
2856   }
2857 };
2858 
2859 void JavaThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
2860   // Verify that the deferred card marks have been flushed.
2861   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2862 
2863   // Traverse the GCHandles
2864   Thread::oops_do(f, cf);
2865 
2866   JVMCI_ONLY(f->do_oop((oop*)&_pending_failed_speculation);)
2867 
2868   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2869          (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2870 
2871   if (has_last_Java_frame()) {
2872     // Record JavaThread to GC thread
2873     RememberProcessedThread rpt(this);
2874 
2875     // Traverse the privileged stack
2876     if (_privileged_stack_top != NULL) {
2877       _privileged_stack_top->oops_do(f);
2878     }
2879 
2880     // traverse the registered growable array
2881     if (_array_for_gc != NULL) {
2882       for (int index = 0; index < _array_for_gc->length(); index++) {
2883         f->do_oop(_array_for_gc->adr_at(index));
2884       }
2885     }
2886 
2887     // Traverse the monitor chunks
2888     for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) {
2889       chunk->oops_do(f);
2890     }
2891 
2892     // Traverse the execution stack
2893     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2894       fst.current()->oops_do(f, cf, fst.register_map());
2895     }
2896   }
2897 
2898   // callee_target is never live across a gc point so NULL it here should
2899   // it still contain a methdOop.
2900 
2901   set_callee_target(NULL);
2902 
2903   assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!");
2904   // If we have deferred set_locals there might be oops waiting to be
2905   // written
2906   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = deferred_locals();
2907   if (list != NULL) {
2908     for (int i = 0; i < list->length(); i++) {
2909       list->at(i)->oops_do(f);
2910     }
2911   }
2912 
2913   // Traverse instance variables at the end since the GC may be moving things
2914   // around using this function
2915   f->do_oop((oop*) &_threadObj);
2916   f->do_oop((oop*) &_vm_result);
2917   f->do_oop((oop*) &_exception_oop);
2918   f->do_oop((oop*) &_pending_async_exception);
2919 
2920   if (jvmti_thread_state() != NULL) {
2921     jvmti_thread_state()->oops_do(f);
2922   }
2923 }
2924 
2925 void JavaThread::nmethods_do(CodeBlobClosure* cf) {
2926   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2927          (has_last_Java_frame() && java_call_counter() > 0), "wrong java_sp info!");
2928 
2929   if (has_last_Java_frame()) {
2930     // Traverse the execution stack
2931     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2932       fst.current()->nmethods_do(cf);
2933     }
2934   }
2935 }
2936 
2937 void JavaThread::metadata_do(void f(Metadata*)) {
2938   if (has_last_Java_frame()) {
2939     // Traverse the execution stack to call f() on the methods in the stack
2940     for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
2941       fst.current()->metadata_do(f);
2942     }
2943   } else if (is_Compiler_thread()) {
2944     // need to walk ciMetadata in current compile tasks to keep alive.
2945     CompilerThread* ct = (CompilerThread*)this;
2946     if (ct->env() != NULL) {
2947       ct->env()->metadata_do(f);
2948     }
2949     if (ct->task() != NULL) {
2950       ct->task()->metadata_do(f);
2951     }
2952   }
2953 }
2954 
2955 // Printing
2956 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2957   switch (_thread_state) {
2958   case _thread_uninitialized:     return "_thread_uninitialized";
2959   case _thread_new:               return "_thread_new";
2960   case _thread_new_trans:         return "_thread_new_trans";
2961   case _thread_in_native:         return "_thread_in_native";
2962   case _thread_in_native_trans:   return "_thread_in_native_trans";
2963   case _thread_in_vm:             return "_thread_in_vm";
2964   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
2965   case _thread_in_Java:           return "_thread_in_Java";
2966   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
2967   case _thread_blocked:           return "_thread_blocked";
2968   case _thread_blocked_trans:     return "_thread_blocked_trans";
2969   default:                        return "unknown thread state";
2970   }
2971 }
2972 
2973 #ifndef PRODUCT
2974 void JavaThread::print_thread_state_on(outputStream *st) const {
2975   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
2976 };
2977 void JavaThread::print_thread_state() const {
2978   print_thread_state_on(tty);
2979 }
2980 #endif // PRODUCT
2981 
2982 // Called by Threads::print() for VM_PrintThreads operation
2983 void JavaThread::print_on(outputStream *st) const {
2984   st->print_raw("\"");
2985   st->print_raw(get_thread_name());
2986   st->print_raw("\" ");
2987   oop thread_oop = threadObj();
2988   if (thread_oop != NULL) {
2989     st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop));
2990     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
2991     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2992   }
2993   Thread::print_on(st);
2994   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
2995   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
2996   if (thread_oop != NULL) {
2997     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
2998   }
2999 #ifndef PRODUCT
3000   print_thread_state_on(st);
3001   _safepoint_state->print_on(st);
3002 #endif // PRODUCT
3003   if (is_Compiler_thread()) {
3004     CompilerThread* ct = (CompilerThread*)this;
3005     if (ct->task() != NULL) {
3006       st->print("   Compiling: ");
3007       ct->task()->print(st, NULL, true, false);
3008     } else {
3009       st->print("   No compile task");
3010     }
3011     st->cr();
3012   }
3013 }
3014 
3015 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
3016   st->print("%s", get_thread_name_string(buf, buflen));
3017 }
3018 
3019 // Called by fatal error handler. The difference between this and
3020 // JavaThread::print() is that we can't grab lock or allocate memory.
3021 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
3022   st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen));
3023   oop thread_obj = threadObj();
3024   if (thread_obj != NULL) {
3025     if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
3026   }
3027   st->print(" [");
3028   st->print("%s", _get_thread_state_name(_thread_state));
3029   if (osthread()) {
3030     st->print(", id=%d", osthread()->thread_id());
3031   }
3032   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
3033             p2i(stack_end()), p2i(stack_base()));
3034   st->print("]");
3035 
3036   if (_threads_hazard_ptr != NULL) {
3037     st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(_threads_hazard_ptr));
3038   }
3039   if (_nested_threads_hazard_ptr != NULL) {
3040     print_nested_threads_hazard_ptrs_on(st);
3041   }
3042   return;
3043 }
3044 
3045 // Verification
3046 
3047 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
3048 
3049 void JavaThread::verify() {
3050   // Verify oops in the thread.
3051   oops_do(&VerifyOopClosure::verify_oop, NULL);
3052 
3053   // Verify the stack frames.
3054   frames_do(frame_verify);
3055 }
3056 
3057 // CR 6300358 (sub-CR 2137150)
3058 // Most callers of this method assume that it can't return NULL but a
3059 // thread may not have a name whilst it is in the process of attaching to
3060 // the VM - see CR 6412693, and there are places where a JavaThread can be
3061 // seen prior to having it's threadObj set (eg JNI attaching threads and
3062 // if vm exit occurs during initialization). These cases can all be accounted
3063 // for such that this method never returns NULL.
3064 const char* JavaThread::get_thread_name() const {
3065 #ifdef ASSERT
3066   // early safepoints can hit while current thread does not yet have TLS
3067   if (!SafepointSynchronize::is_at_safepoint()) {
3068     Thread *cur = Thread::current();
3069     if (!(cur->is_Java_thread() && cur == this)) {
3070       // Current JavaThreads are allowed to get their own name without
3071       // the Threads_lock.
3072       assert_locked_or_safepoint(Threads_lock);
3073     }
3074   }
3075 #endif // ASSERT
3076   return get_thread_name_string();
3077 }
3078 
3079 // Returns a non-NULL representation of this thread's name, or a suitable
3080 // descriptive string if there is no set name
3081 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const {
3082   const char* name_str;
3083   oop thread_obj = threadObj();
3084   if (thread_obj != NULL) {
3085     oop name = java_lang_Thread::name(thread_obj);
3086     if (name != NULL) {
3087       if (buf == NULL) {
3088         name_str = java_lang_String::as_utf8_string(name);
3089       } else {
3090         name_str = java_lang_String::as_utf8_string(name, buf, buflen);
3091       }
3092     } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306
3093       name_str = "<no-name - thread is attaching>";
3094     } else {
3095       name_str = Thread::name();
3096     }
3097   } else {
3098     name_str = Thread::name();
3099   }
3100   assert(name_str != NULL, "unexpected NULL thread name");
3101   return name_str;
3102 }
3103 
3104 
3105 const char* JavaThread::get_threadgroup_name() const {
3106   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
3107   oop thread_obj = threadObj();
3108   if (thread_obj != NULL) {
3109     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
3110     if (thread_group != NULL) {
3111       // ThreadGroup.name can be null
3112       return java_lang_ThreadGroup::name(thread_group);
3113     }
3114   }
3115   return NULL;
3116 }
3117 
3118 const char* JavaThread::get_parent_name() const {
3119   debug_only(if (JavaThread::current() != this) assert_locked_or_safepoint(Threads_lock);)
3120   oop thread_obj = threadObj();
3121   if (thread_obj != NULL) {
3122     oop thread_group = java_lang_Thread::threadGroup(thread_obj);
3123     if (thread_group != NULL) {
3124       oop parent = java_lang_ThreadGroup::parent(thread_group);
3125       if (parent != NULL) {
3126         // ThreadGroup.name can be null
3127         return java_lang_ThreadGroup::name(parent);
3128       }
3129     }
3130   }
3131   return NULL;
3132 }
3133 
3134 ThreadPriority JavaThread::java_priority() const {
3135   oop thr_oop = threadObj();
3136   if (thr_oop == NULL) return NormPriority; // Bootstrapping
3137   ThreadPriority priority = java_lang_Thread::priority(thr_oop);
3138   assert(MinPriority <= priority && priority <= MaxPriority, "sanity check");
3139   return priority;
3140 }
3141 
3142 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) {
3143 
3144   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
3145   // Link Java Thread object <-> C++ Thread
3146 
3147   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
3148   // and put it into a new Handle.  The Handle "thread_oop" can then
3149   // be used to pass the C++ thread object to other methods.
3150 
3151   // Set the Java level thread object (jthread) field of the
3152   // new thread (a JavaThread *) to C++ thread object using the
3153   // "thread_oop" handle.
3154 
3155   // Set the thread field (a JavaThread *) of the
3156   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
3157 
3158   Handle thread_oop(Thread::current(),
3159                     JNIHandles::resolve_non_null(jni_thread));
3160   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
3161          "must be initialized");
3162   set_threadObj(thread_oop());
3163   java_lang_Thread::set_thread(thread_oop(), this);
3164 
3165   if (prio == NoPriority) {
3166     prio = java_lang_Thread::priority(thread_oop());
3167     assert(prio != NoPriority, "A valid priority should be present");
3168   }
3169 
3170   // Push the Java priority down to the native thread; needs Threads_lock
3171   Thread::set_priority(this, prio);
3172 
3173   prepare_ext();
3174 
3175   // Add the new thread to the Threads list and set it in motion.
3176   // We must have threads lock in order to call Threads::add.
3177   // It is crucial that we do not block before the thread is
3178   // added to the Threads list for if a GC happens, then the java_thread oop
3179   // will not be visited by GC.
3180   Threads::add(this);
3181 }
3182 
3183 oop JavaThread::current_park_blocker() {
3184   // Support for JSR-166 locks
3185   oop thread_oop = threadObj();
3186   if (thread_oop != NULL &&
3187       JDK_Version::current().supports_thread_park_blocker()) {
3188     return java_lang_Thread::park_blocker(thread_oop);
3189   }
3190   return NULL;
3191 }
3192 
3193 
3194 void JavaThread::print_stack_on(outputStream* st) {
3195   if (!has_last_Java_frame()) return;
3196   ResourceMark rm;
3197   HandleMark   hm;
3198 
3199   RegisterMap reg_map(this);
3200   vframe* start_vf = last_java_vframe(&reg_map);
3201   int count = 0;
3202   for (vframe* f = start_vf; f; f = f->sender()) {
3203     if (f->is_java_frame()) {
3204       javaVFrame* jvf = javaVFrame::cast(f);
3205       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
3206 
3207       // Print out lock information
3208       if (JavaMonitorsInStackTrace) {
3209         jvf->print_lock_info_on(st, count);
3210       }
3211     } else {
3212       // Ignore non-Java frames
3213     }
3214 
3215     // Bail-out case for too deep stacks
3216     count++;
3217     if (MaxJavaStackTraceDepth == count) return;
3218   }
3219 }
3220 
3221 
3222 // JVMTI PopFrame support
3223 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
3224   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
3225   if (in_bytes(size_in_bytes) != 0) {
3226     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
3227     _popframe_preserved_args_size = in_bytes(size_in_bytes);
3228     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
3229   }
3230 }
3231 
3232 void* JavaThread::popframe_preserved_args() {
3233   return _popframe_preserved_args;
3234 }
3235 
3236 ByteSize JavaThread::popframe_preserved_args_size() {
3237   return in_ByteSize(_popframe_preserved_args_size);
3238 }
3239 
3240 WordSize JavaThread::popframe_preserved_args_size_in_words() {
3241   int sz = in_bytes(popframe_preserved_args_size());
3242   assert(sz % wordSize == 0, "argument size must be multiple of wordSize");
3243   return in_WordSize(sz / wordSize);
3244 }
3245 
3246 void JavaThread::popframe_free_preserved_args() {
3247   assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice");
3248   FREE_C_HEAP_ARRAY(char, (char*) _popframe_preserved_args);
3249   _popframe_preserved_args = NULL;
3250   _popframe_preserved_args_size = 0;
3251 }
3252 
3253 #ifndef PRODUCT
3254 
3255 void JavaThread::trace_frames() {
3256   tty->print_cr("[Describe stack]");
3257   int frame_no = 1;
3258   for (StackFrameStream fst(this); !fst.is_done(); fst.next()) {
3259     tty->print("  %d. ", frame_no++);
3260     fst.current()->print_value_on(tty, this);
3261     tty->cr();
3262   }
3263 }
3264 
3265 class PrintAndVerifyOopClosure: public OopClosure {
3266  protected:
3267   template <class T> inline void do_oop_work(T* p) {
3268     oop obj = oopDesc::load_decode_heap_oop(p);
3269     if (obj == NULL) return;
3270     tty->print(INTPTR_FORMAT ": ", p2i(p));
3271     if (oopDesc::is_oop_or_null(obj)) {
3272       if (obj->is_objArray()) {
3273         tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj));
3274       } else {
3275         obj->print();
3276       }
3277     } else {
3278       tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
3279     }
3280     tty->cr();
3281   }
3282  public:
3283   virtual void do_oop(oop* p) { do_oop_work(p); }
3284   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
3285 };
3286 
3287 
3288 static void oops_print(frame* f, const RegisterMap *map) {
3289   PrintAndVerifyOopClosure print;
3290   f->print_value();
3291   f->oops_do(&print, NULL, (RegisterMap*)map);
3292 }
3293 
3294 // Print our all the locations that contain oops and whether they are
3295 // valid or not.  This useful when trying to find the oldest frame
3296 // where an oop has gone bad since the frame walk is from youngest to
3297 // oldest.
3298 void JavaThread::trace_oops() {
3299   tty->print_cr("[Trace oops]");
3300   frames_do(oops_print);
3301 }
3302 
3303 
3304 #ifdef ASSERT
3305 // Print or validate the layout of stack frames
3306 void JavaThread::print_frame_layout(int depth, bool validate_only) {
3307   ResourceMark rm;
3308   PRESERVE_EXCEPTION_MARK;
3309   FrameValues values;
3310   int frame_no = 0;
3311   for (StackFrameStream fst(this, false); !fst.is_done(); fst.next()) {
3312     fst.current()->describe(values, ++frame_no);
3313     if (depth == frame_no) break;
3314   }
3315   if (validate_only) {
3316     values.validate();
3317   } else {
3318     tty->print_cr("[Describe stack layout]");
3319     values.print(this);
3320   }
3321 }
3322 #endif
3323 
3324 void JavaThread::trace_stack_from(vframe* start_vf) {
3325   ResourceMark rm;
3326   int vframe_no = 1;
3327   for (vframe* f = start_vf; f; f = f->sender()) {
3328     if (f->is_java_frame()) {
3329       javaVFrame::cast(f)->print_activation(vframe_no++);
3330     } else {
3331       f->print();
3332     }
3333     if (vframe_no > StackPrintLimit) {
3334       tty->print_cr("...<more frames>...");
3335       return;
3336     }
3337   }
3338 }
3339 
3340 
3341 void JavaThread::trace_stack() {
3342   if (!has_last_Java_frame()) return;
3343   ResourceMark rm;
3344   HandleMark   hm;
3345   RegisterMap reg_map(this);
3346   trace_stack_from(last_java_vframe(&reg_map));
3347 }
3348 
3349 
3350 #endif // PRODUCT
3351 
3352 
3353 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {
3354   assert(reg_map != NULL, "a map must be given");
3355   frame f = last_frame();
3356   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
3357     if (vf->is_java_frame()) return javaVFrame::cast(vf);
3358   }
3359   return NULL;
3360 }
3361 
3362 
3363 Klass* JavaThread::security_get_caller_class(int depth) {
3364   vframeStream vfst(this);
3365   vfst.security_get_caller_frame(depth);
3366   if (!vfst.at_end()) {
3367     return vfst.method()->method_holder();
3368   }
3369   return NULL;
3370 }
3371 
3372 static void compiler_thread_entry(JavaThread* thread, TRAPS) {
3373   assert(thread->is_Compiler_thread(), "must be compiler thread");
3374   CompileBroker::compiler_thread_loop();
3375 }
3376 
3377 static void sweeper_thread_entry(JavaThread* thread, TRAPS) {
3378   NMethodSweeper::sweeper_loop();
3379 }
3380 
3381 // Create a CompilerThread
3382 CompilerThread::CompilerThread(CompileQueue* queue,
3383                                CompilerCounters* counters)
3384                                : JavaThread(&compiler_thread_entry) {
3385   _env   = NULL;
3386   _log   = NULL;
3387   _task  = NULL;
3388   _queue = queue;
3389   _counters = counters;
3390   _buffer_blob = NULL;
3391   _compiler = NULL;
3392 
3393   // Compiler uses resource area for compilation, let's bias it to mtCompiler
3394   resource_area()->bias_to(mtCompiler);
3395 
3396 #ifndef PRODUCT
3397   _ideal_graph_printer = NULL;
3398 #endif
3399 }
3400 
3401 bool CompilerThread::can_call_java() const {
3402   return _compiler != NULL && _compiler->is_jvmci();
3403 }
3404 
3405 // Create sweeper thread
3406 CodeCacheSweeperThread::CodeCacheSweeperThread()
3407 : JavaThread(&sweeper_thread_entry) {
3408   _scanned_compiled_method = NULL;
3409 }
3410 
3411 void CodeCacheSweeperThread::oops_do(OopClosure* f, CodeBlobClosure* cf) {
3412   JavaThread::oops_do(f, cf);
3413   if (_scanned_compiled_method != NULL && cf != NULL) {
3414     // Safepoints can occur when the sweeper is scanning an nmethod so
3415     // process it here to make sure it isn't unloaded in the middle of
3416     // a scan.
3417     cf->do_code_blob(_scanned_compiled_method);
3418   }
3419 }
3420 
3421 void CodeCacheSweeperThread::nmethods_do(CodeBlobClosure* cf) {
3422   JavaThread::nmethods_do(cf);
3423   if (_scanned_compiled_method != NULL && cf != NULL) {
3424     // Safepoints can occur when the sweeper is scanning an nmethod so
3425     // process it here to make sure it isn't unloaded in the middle of
3426     // a scan.
3427     cf->do_code_blob(_scanned_compiled_method);
3428   }
3429 }
3430 
3431 
3432 // ======= Threads ========
3433 
3434 // The Threads class links together all active threads, and provides
3435 // operations over all threads. It is protected by the Threads_lock,
3436 // which is also used in other global contexts like safepointing.
3437 // ThreadsListHandles are used to safely perform operations on one
3438 // or more threads without the risk of the thread exiting during the
3439 // operation.
3440 //
3441 // Note: The Threads_lock is currently more widely used than we
3442 // would like. We are actively migrating Threads_lock uses to other
3443 // mechanisms in order to reduce Threads_lock contention.
3444 
3445 JavaThread* Threads::_thread_list = NULL;
3446 int         Threads::_number_of_threads = 0;
3447 int         Threads::_number_of_non_daemon_threads = 0;
3448 int         Threads::_return_code = 0;
3449 int         Threads::_thread_claim_parity = 0;
3450 size_t      JavaThread::_stack_size_at_create = 0;
3451 
3452 #ifdef ASSERT
3453 bool        Threads::_vm_complete = false;
3454 #endif
3455 
3456 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) {
3457   Prefetch::read((void*)addr, prefetch_interval);
3458   return *addr;
3459 }
3460 
3461 // Possibly the ugliest for loop the world has seen. C++ does not allow
3462 // multiple types in the declaration section of the for loop. In this case
3463 // we are only dealing with pointers and hence can cast them. It looks ugly
3464 // but macros are ugly and therefore it's fine to make things absurdly ugly.
3465 #define DO_JAVA_THREADS(LIST, X)                                                                                          \
3466     for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes,                           \
3467              *MACRO_list = (JavaThread*)(LIST),                                                                           \
3468              **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(),  \
3469              **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(),                                     \
3470              *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval);                 \
3471          MACRO_current_p != MACRO_end;                                                                                    \
3472          MACRO_current_p++,                                                                                               \
3473              X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval))
3474 
3475 // All JavaThreads
3476 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(ThreadsSMRSupport::get_smr_java_thread_list(), X)
3477 
3478 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system)
3479 void Threads::threads_do(ThreadClosure* tc) {
3480   assert_locked_or_safepoint(Threads_lock);
3481   // ALL_JAVA_THREADS iterates through all JavaThreads
3482   ALL_JAVA_THREADS(p) {
3483     tc->do_thread(p);
3484   }
3485   // Someday we could have a table or list of all non-JavaThreads.
3486   // For now, just manually iterate through them.
3487   tc->do_thread(VMThread::vm_thread());
3488   Universe::heap()->gc_threads_do(tc);
3489   WatcherThread *wt = WatcherThread::watcher_thread();
3490   // Strictly speaking, the following NULL check isn't sufficient to make sure
3491   // the data for WatcherThread is still valid upon being examined. However,
3492   // considering that WatchThread terminates when the VM is on the way to
3493   // exit at safepoint, the chance of the above is extremely small. The right
3494   // way to prevent termination of WatcherThread would be to acquire
3495   // Terminator_lock, but we can't do that without violating the lock rank
3496   // checking in some cases.
3497   if (wt != NULL) {
3498     tc->do_thread(wt);
3499   }
3500 
3501   // If CompilerThreads ever become non-JavaThreads, add them here
3502 }
3503 
3504 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) {
3505   int cp = Threads::thread_claim_parity();
3506   ALL_JAVA_THREADS(p) {
3507     if (p->claim_oops_do(is_par, cp)) {
3508       tc->do_thread(p);
3509     }
3510   }
3511   VMThread* vmt = VMThread::vm_thread();
3512   if (vmt->claim_oops_do(is_par, cp)) {
3513     tc->do_thread(vmt);
3514   }
3515 }
3516 
3517 // The system initialization in the library has three phases.
3518 //
3519 // Phase 1: java.lang.System class initialization
3520 //     java.lang.System is a primordial class loaded and initialized
3521 //     by the VM early during startup.  java.lang.System.<clinit>
3522 //     only does registerNatives and keeps the rest of the class
3523 //     initialization work later until thread initialization completes.
3524 //
3525 //     System.initPhase1 initializes the system properties, the static
3526 //     fields in, out, and err. Set up java signal handlers, OS-specific
3527 //     system settings, and thread group of the main thread.
3528 static void call_initPhase1(TRAPS) {
3529   Klass* klass =  SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3530   JavaValue result(T_VOID);
3531   JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(),
3532                                          vmSymbols::void_method_signature(), CHECK);
3533 }
3534 
3535 // Phase 2. Module system initialization
3536 //     This will initialize the module system.  Only java.base classes
3537 //     can be loaded until phase 2 completes.
3538 //
3539 //     Call System.initPhase2 after the compiler initialization and jsr292
3540 //     classes get initialized because module initialization runs a lot of java
3541 //     code, that for performance reasons, should be compiled.  Also, this will
3542 //     enable the startup code to use lambda and other language features in this
3543 //     phase and onward.
3544 //
3545 //     After phase 2, The VM will begin search classes from -Xbootclasspath/a.
3546 static void call_initPhase2(TRAPS) {
3547   TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime));
3548 
3549   Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3550 
3551   JavaValue result(T_INT);
3552   JavaCallArguments args;
3553   args.push_int(DisplayVMOutputToStderr);
3554   args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown
3555   JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(),
3556                                          vmSymbols::boolean_boolean_int_signature(), &args, CHECK);
3557   if (result.get_jint() != JNI_OK) {
3558     vm_exit_during_initialization(); // no message or exception
3559   }
3560 
3561   universe_post_module_init();
3562 }
3563 
3564 // Phase 3. final setup - set security manager, system class loader and TCCL
3565 //
3566 //     This will instantiate and set the security manager, set the system class
3567 //     loader as well as the thread context class loader.  The security manager
3568 //     and system class loader may be a custom class loaded from -Xbootclasspath/a,
3569 //     other modules or the application's classpath.
3570 static void call_initPhase3(TRAPS) {
3571   Klass* klass = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_System(), true, CHECK);
3572   JavaValue result(T_VOID);
3573   JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(),
3574                                          vmSymbols::void_method_signature(), CHECK);
3575 }
3576 
3577 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) {
3578   TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime));
3579 
3580   if (EagerXrunInit && Arguments::init_libraries_at_startup()) {
3581     create_vm_init_libraries();
3582   }
3583 
3584   initialize_class(vmSymbols::java_lang_String(), CHECK);
3585 
3586   // Inject CompactStrings value after the static initializers for String ran.
3587   java_lang_String::set_compact_strings(CompactStrings);
3588 
3589   // Initialize java_lang.System (needed before creating the thread)
3590   initialize_class(vmSymbols::java_lang_System(), CHECK);
3591   // The VM creates & returns objects of this class. Make sure it's initialized.
3592   initialize_class(vmSymbols::java_lang_Class(), CHECK);
3593   initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK);
3594   Handle thread_group = create_initial_thread_group(CHECK);
3595   Universe::set_main_thread_group(thread_group());
3596   initialize_class(vmSymbols::java_lang_Thread(), CHECK);
3597   oop thread_object = create_initial_thread(thread_group, main_thread, CHECK);
3598   main_thread->set_threadObj(thread_object);
3599   // Set thread status to running since main thread has
3600   // been started and running.
3601   java_lang_Thread::set_thread_status(thread_object,
3602                                       java_lang_Thread::RUNNABLE);
3603 
3604   // The VM creates objects of this class.
3605   initialize_class(vmSymbols::java_lang_Module(), CHECK);
3606 
3607   // The VM preresolves methods to these classes. Make sure that they get initialized
3608   initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK);
3609   initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK);
3610 
3611   // Phase 1 of the system initialization in the library, java.lang.System class initialization
3612   call_initPhase1(CHECK);
3613 
3614   // get the Java runtime name after java.lang.System is initialized
3615   JDK_Version::set_runtime_name(get_java_runtime_name(THREAD));
3616   JDK_Version::set_runtime_version(get_java_runtime_version(THREAD));
3617 
3618   // an instance of OutOfMemory exception has been allocated earlier
3619   initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK);
3620   initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK);
3621   initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK);
3622   initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK);
3623   initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK);
3624   initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK);
3625   initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK);
3626   initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK);
3627 }
3628 
3629 void Threads::initialize_jsr292_core_classes(TRAPS) {
3630   TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime));
3631 
3632   initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK);
3633   initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK);
3634   initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK);
3635   initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK);
3636 }
3637 
3638 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) {
3639   extern void JDK_Version_init();
3640 
3641   // Preinitialize version info.
3642   VM_Version::early_initialize();
3643 
3644   // Check version
3645   if (!is_supported_jni_version(args->version)) return JNI_EVERSION;
3646 
3647   // Initialize library-based TLS
3648   ThreadLocalStorage::init();
3649 
3650   // Initialize the output stream module
3651   ostream_init();
3652 
3653   // Process java launcher properties.
3654   Arguments::process_sun_java_launcher_properties(args);
3655 
3656   // Initialize the os module
3657   os::init();
3658 
3659   // Record VM creation timing statistics
3660   TraceVmCreationTime create_vm_timer;
3661   create_vm_timer.start();
3662 
3663   // Initialize system properties.
3664   Arguments::init_system_properties();
3665 
3666   // So that JDK version can be used as a discriminator when parsing arguments
3667   JDK_Version_init();
3668 
3669   // Update/Initialize System properties after JDK version number is known
3670   Arguments::init_version_specific_system_properties();
3671 
3672   // Make sure to initialize log configuration *before* parsing arguments
3673   LogConfiguration::initialize(create_vm_timer.begin_time());
3674 
3675   // Parse arguments
3676   // Note: this internally calls os::init_container_support()
3677   jint parse_result = Arguments::parse(args);
3678   if (parse_result != JNI_OK) return parse_result;
3679 
3680   os::init_before_ergo();
3681 
3682   jint ergo_result = Arguments::apply_ergo();
3683   if (ergo_result != JNI_OK) return ergo_result;
3684 
3685   // Final check of all ranges after ergonomics which may change values.
3686   if (!CommandLineFlagRangeList::check_ranges()) {
3687     return JNI_EINVAL;
3688   }
3689 
3690   // Final check of all 'AfterErgo' constraints after ergonomics which may change values.
3691   bool constraint_result = CommandLineFlagConstraintList::check_constraints(CommandLineFlagConstraint::AfterErgo);
3692   if (!constraint_result) {
3693     return JNI_EINVAL;
3694   }
3695 
3696   CommandLineFlagWriteableList::mark_startup();
3697 
3698   if (PauseAtStartup) {
3699     os::pause();
3700   }
3701 
3702   HOTSPOT_VM_INIT_BEGIN();
3703 
3704   // Timing (must come after argument parsing)
3705   TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime));
3706 
3707   // Initialize the os module after parsing the args
3708   jint os_init_2_result = os::init_2();
3709   if (os_init_2_result != JNI_OK) return os_init_2_result;
3710 
3711   SafepointMechanism::initialize();
3712 
3713   jint adjust_after_os_result = Arguments::adjust_after_os();
3714   if (adjust_after_os_result != JNI_OK) return adjust_after_os_result;
3715 
3716   // Initialize output stream logging
3717   ostream_init_log();
3718 
3719   // Convert -Xrun to -agentlib: if there is no JVM_OnLoad
3720   // Must be before create_vm_init_agents()
3721   if (Arguments::init_libraries_at_startup()) {
3722     convert_vm_init_libraries_to_agents();
3723   }
3724 
3725   // Launch -agentlib/-agentpath and converted -Xrun agents
3726   if (Arguments::init_agents_at_startup()) {
3727     create_vm_init_agents();
3728   }
3729 
3730   // Initialize Threads state
3731   _thread_list = NULL;
3732   _number_of_threads = 0;
3733   _number_of_non_daemon_threads = 0;
3734 
3735   // Initialize global data structures and create system classes in heap
3736   vm_init_globals();
3737 
3738 #if INCLUDE_JVMCI
3739   if (JVMCICounterSize > 0) {
3740     JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtInternal);
3741     memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize);
3742   } else {
3743     JavaThread::_jvmci_old_thread_counters = NULL;
3744   }
3745 #endif // INCLUDE_JVMCI
3746 
3747   // Attach the main thread to this os thread
3748   JavaThread* main_thread = new JavaThread();
3749   main_thread->set_thread_state(_thread_in_vm);
3750   main_thread->initialize_thread_current();
3751   // must do this before set_active_handles
3752   main_thread->record_stack_base_and_size();
3753   main_thread->set_active_handles(JNIHandleBlock::allocate_block());
3754 
3755   if (!main_thread->set_as_starting_thread()) {
3756     vm_shutdown_during_initialization(
3757                                       "Failed necessary internal allocation. Out of swap space");
3758     main_thread->smr_delete();
3759     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3760     return JNI_ENOMEM;
3761   }
3762 
3763   // Enable guard page *after* os::create_main_thread(), otherwise it would
3764   // crash Linux VM, see notes in os_linux.cpp.
3765   main_thread->create_stack_guard_pages();
3766 
3767   // Initialize Java-Level synchronization subsystem
3768   ObjectMonitor::Initialize();
3769 
3770   // Initialize global modules
3771   jint status = init_globals();
3772   if (status != JNI_OK) {
3773     main_thread->smr_delete();
3774     *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again
3775     return status;
3776   }
3777 
3778   if (TRACE_INITIALIZE() != JNI_OK) {
3779     vm_exit_during_initialization("Failed to initialize tracing backend");
3780   }
3781 
3782   // Should be done after the heap is fully created
3783   main_thread->cache_global_variables();
3784 
3785   HandleMark hm;
3786 
3787   { MutexLocker mu(Threads_lock);
3788     Threads::add(main_thread);
3789   }
3790 
3791   // Any JVMTI raw monitors entered in onload will transition into
3792   // real raw monitor. VM is setup enough here for raw monitor enter.
3793   JvmtiExport::transition_pending_onload_raw_monitors();
3794 
3795   // Create the VMThread
3796   { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime));
3797 
3798   VMThread::create();
3799     Thread* vmthread = VMThread::vm_thread();
3800 
3801     if (!os::create_thread(vmthread, os::vm_thread)) {
3802       vm_exit_during_initialization("Cannot create VM thread. "
3803                                     "Out of system resources.");
3804     }
3805 
3806     // Wait for the VM thread to become ready, and VMThread::run to initialize
3807     // Monitors can have spurious returns, must always check another state flag
3808     {
3809       MutexLocker ml(Notify_lock);
3810       os::start_thread(vmthread);
3811       while (vmthread->active_handles() == NULL) {
3812         Notify_lock->wait();
3813       }
3814     }
3815   }
3816 
3817   assert(Universe::is_fully_initialized(), "not initialized");
3818   if (VerifyDuringStartup) {
3819     // Make sure we're starting with a clean slate.
3820     VM_Verify verify_op;
3821     VMThread::execute(&verify_op);
3822   }
3823 
3824   Thread* THREAD = Thread::current();
3825 
3826   // Always call even when there are not JVMTI environments yet, since environments
3827   // may be attached late and JVMTI must track phases of VM execution
3828   JvmtiExport::enter_early_start_phase();
3829 
3830   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3831   JvmtiExport::post_early_vm_start();
3832 
3833   initialize_java_lang_classes(main_thread, CHECK_JNI_ERR);
3834 
3835   // We need this for ClassDataSharing - the initial vm.info property is set
3836   // with the default value of CDS "sharing" which may be reset through
3837   // command line options.
3838   reset_vm_info_property(CHECK_JNI_ERR);
3839 
3840   quicken_jni_functions();
3841 
3842   // No more stub generation allowed after that point.
3843   StubCodeDesc::freeze();
3844 
3845   // Set flag that basic initialization has completed. Used by exceptions and various
3846   // debug stuff, that does not work until all basic classes have been initialized.
3847   set_init_completed();
3848 
3849   LogConfiguration::post_initialize();
3850   Metaspace::post_initialize();
3851 
3852   HOTSPOT_VM_INIT_END();
3853 
3854   // record VM initialization completion time
3855 #if INCLUDE_MANAGEMENT
3856   Management::record_vm_init_completed();
3857 #endif // INCLUDE_MANAGEMENT
3858 
3859   // Signal Dispatcher needs to be started before VMInit event is posted
3860   os::signal_init(CHECK_JNI_ERR);
3861 
3862   // Start Attach Listener if +StartAttachListener or it can't be started lazily
3863   if (!DisableAttachMechanism) {
3864     AttachListener::vm_start();
3865     if (StartAttachListener || AttachListener::init_at_startup()) {
3866       AttachListener::init();
3867     }
3868   }
3869 
3870   // Launch -Xrun agents
3871   // Must be done in the JVMTI live phase so that for backward compatibility the JDWP
3872   // back-end can launch with -Xdebug -Xrunjdwp.
3873   if (!EagerXrunInit && Arguments::init_libraries_at_startup()) {
3874     create_vm_init_libraries();
3875   }
3876 
3877   if (CleanChunkPoolAsync) {
3878     Chunk::start_chunk_pool_cleaner_task();
3879   }
3880 
3881   // initialize compiler(s)
3882 #if defined(COMPILER1) || COMPILER2_OR_JVMCI
3883   CompileBroker::compilation_init(CHECK_JNI_ERR);
3884 #endif
3885 
3886   // Pre-initialize some JSR292 core classes to avoid deadlock during class loading.
3887   // It is done after compilers are initialized, because otherwise compilations of
3888   // signature polymorphic MH intrinsics can be missed
3889   // (see SystemDictionary::find_method_handle_intrinsic).
3890   initialize_jsr292_core_classes(CHECK_JNI_ERR);
3891 
3892   // This will initialize the module system.  Only java.base classes can be
3893   // loaded until phase 2 completes
3894   call_initPhase2(CHECK_JNI_ERR);
3895 
3896   // Always call even when there are not JVMTI environments yet, since environments
3897   // may be attached late and JVMTI must track phases of VM execution
3898   JvmtiExport::enter_start_phase();
3899 
3900   // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents.
3901   JvmtiExport::post_vm_start();
3902 
3903   // Final system initialization including security manager and system class loader
3904   call_initPhase3(CHECK_JNI_ERR);
3905 
3906   // cache the system and platform class loaders
3907   SystemDictionary::compute_java_loaders(CHECK_JNI_ERR);
3908 
3909 #if INCLUDE_JVMCI
3910   if (EnableJVMCI) {
3911     // Initialize JVMCI eagerly if JVMCIPrintProperties is enabled.
3912     // The JVMCI Java initialization code will read this flag and
3913     // do the printing if it's set.
3914     bool init = JVMCIPrintProperties;
3915 
3916     if (!init) {
3917       // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking
3918       // compilations via JVMCI will not actually block until JVMCI is initialized.
3919       init = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation);
3920     }
3921 
3922     if (init) {
3923       JVMCIRuntime::force_initialization(CHECK_JNI_ERR);
3924     }
3925   }
3926 #endif
3927 
3928   // Always call even when there are not JVMTI environments yet, since environments
3929   // may be attached late and JVMTI must track phases of VM execution
3930   JvmtiExport::enter_live_phase();
3931 
3932   // Notify JVMTI agents that VM initialization is complete - nop if no agents.
3933   JvmtiExport::post_vm_initialized();
3934 
3935   if (TRACE_START() != JNI_OK) {
3936     vm_exit_during_initialization("Failed to start tracing backend.");
3937   }
3938 
3939 #if INCLUDE_MANAGEMENT
3940   Management::initialize(THREAD);
3941 
3942   if (HAS_PENDING_EXCEPTION) {
3943     // management agent fails to start possibly due to
3944     // configuration problem and is responsible for printing
3945     // stack trace if appropriate. Simply exit VM.
3946     vm_exit(1);
3947   }
3948 #endif // INCLUDE_MANAGEMENT
3949 
3950   if (MemProfiling)                   MemProfiler::engage();
3951   StatSampler::engage();
3952   if (CheckJNICalls)                  JniPeriodicChecker::engage();
3953 
3954   BiasedLocking::init();
3955 
3956 #if INCLUDE_RTM_OPT
3957   RTMLockingCounters::init();
3958 #endif
3959 
3960   if (JDK_Version::current().post_vm_init_hook_enabled()) {
3961     call_postVMInitHook(THREAD);
3962     // The Java side of PostVMInitHook.run must deal with all
3963     // exceptions and provide means of diagnosis.
3964     if (HAS_PENDING_EXCEPTION) {
3965       CLEAR_PENDING_EXCEPTION;
3966     }
3967   }
3968 
3969   {
3970     MutexLocker ml(PeriodicTask_lock);
3971     // Make sure the WatcherThread can be started by WatcherThread::start()
3972     // or by dynamic enrollment.
3973     WatcherThread::make_startable();
3974     // Start up the WatcherThread if there are any periodic tasks
3975     // NOTE:  All PeriodicTasks should be registered by now. If they
3976     //   aren't, late joiners might appear to start slowly (we might
3977     //   take a while to process their first tick).
3978     if (PeriodicTask::num_tasks() > 0) {
3979       WatcherThread::start();
3980     }
3981   }
3982 
3983   create_vm_timer.end();
3984 #ifdef ASSERT
3985   _vm_complete = true;
3986 #endif
3987 
3988   if (DumpSharedSpaces) {
3989     MetaspaceShared::preload_and_dump(CHECK_JNI_ERR);
3990     ShouldNotReachHere();
3991   }
3992 
3993   return JNI_OK;
3994 }
3995 
3996 // type for the Agent_OnLoad and JVM_OnLoad entry points
3997 extern "C" {
3998   typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *);
3999 }
4000 // Find a command line agent library and return its entry point for
4001 //         -agentlib:  -agentpath:   -Xrun
4002 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array.
4003 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent,
4004                                     const char *on_load_symbols[],
4005                                     size_t num_symbol_entries) {
4006   OnLoadEntry_t on_load_entry = NULL;
4007   void *library = NULL;
4008 
4009   if (!agent->valid()) {
4010     char buffer[JVM_MAXPATHLEN];
4011     char ebuf[1024] = "";
4012     const char *name = agent->name();
4013     const char *msg = "Could not find agent library ";
4014 
4015     // First check to see if agent is statically linked into executable
4016     if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) {
4017       library = agent->os_lib();
4018     } else if (agent->is_absolute_path()) {
4019       library = os::dll_load(name, ebuf, sizeof ebuf);
4020       if (library == NULL) {
4021         const char *sub_msg = " in absolute path, with error: ";
4022         size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
4023         char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
4024         jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
4025         // If we can't find the agent, exit.
4026         vm_exit_during_initialization(buf, NULL);
4027         FREE_C_HEAP_ARRAY(char, buf);
4028       }
4029     } else {
4030       // Try to load the agent from the standard dll directory
4031       if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(),
4032                              name)) {
4033         library = os::dll_load(buffer, ebuf, sizeof ebuf);
4034       }
4035       if (library == NULL) { // Try the library path directory.
4036         if (os::dll_build_name(buffer, sizeof(buffer), name)) {
4037           library = os::dll_load(buffer, ebuf, sizeof ebuf);
4038         }
4039         if (library == NULL) {
4040           const char *sub_msg = " on the library path, with error: ";
4041           size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1;
4042           char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread);
4043           jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf);
4044           // If we can't find the agent, exit.
4045           vm_exit_during_initialization(buf, NULL);
4046           FREE_C_HEAP_ARRAY(char, buf);
4047         }
4048       }
4049     }
4050     agent->set_os_lib(library);
4051     agent->set_valid();
4052   }
4053 
4054   // Find the OnLoad function.
4055   on_load_entry =
4056     CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent,
4057                                                           false,
4058                                                           on_load_symbols,
4059                                                           num_symbol_entries));
4060   return on_load_entry;
4061 }
4062 
4063 // Find the JVM_OnLoad entry point
4064 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) {
4065   const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS;
4066   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
4067 }
4068 
4069 // Find the Agent_OnLoad entry point
4070 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) {
4071   const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS;
4072   return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*));
4073 }
4074 
4075 // For backwards compatibility with -Xrun
4076 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be
4077 // treated like -agentpath:
4078 // Must be called before agent libraries are created
4079 void Threads::convert_vm_init_libraries_to_agents() {
4080   AgentLibrary* agent;
4081   AgentLibrary* next;
4082 
4083   for (agent = Arguments::libraries(); agent != NULL; agent = next) {
4084     next = agent->next();  // cache the next agent now as this agent may get moved off this list
4085     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4086 
4087     // If there is an JVM_OnLoad function it will get called later,
4088     // otherwise see if there is an Agent_OnLoad
4089     if (on_load_entry == NULL) {
4090       on_load_entry = lookup_agent_on_load(agent);
4091       if (on_load_entry != NULL) {
4092         // switch it to the agent list -- so that Agent_OnLoad will be called,
4093         // JVM_OnLoad won't be attempted and Agent_OnUnload will
4094         Arguments::convert_library_to_agent(agent);
4095       } else {
4096         vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name());
4097       }
4098     }
4099   }
4100 }
4101 
4102 // Create agents for -agentlib:  -agentpath:  and converted -Xrun
4103 // Invokes Agent_OnLoad
4104 // Called very early -- before JavaThreads exist
4105 void Threads::create_vm_init_agents() {
4106   extern struct JavaVM_ main_vm;
4107   AgentLibrary* agent;
4108 
4109   JvmtiExport::enter_onload_phase();
4110 
4111   for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
4112     OnLoadEntry_t  on_load_entry = lookup_agent_on_load(agent);
4113 
4114     if (on_load_entry != NULL) {
4115       // Invoke the Agent_OnLoad function
4116       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4117       if (err != JNI_OK) {
4118         vm_exit_during_initialization("agent library failed to init", agent->name());
4119       }
4120     } else {
4121       vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name());
4122     }
4123   }
4124   JvmtiExport::enter_primordial_phase();
4125 }
4126 
4127 extern "C" {
4128   typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *);
4129 }
4130 
4131 void Threads::shutdown_vm_agents() {
4132   // Send any Agent_OnUnload notifications
4133   const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS;
4134   size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols);
4135   extern struct JavaVM_ main_vm;
4136   for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) {
4137 
4138     // Find the Agent_OnUnload function.
4139     Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t,
4140                                                    os::find_agent_function(agent,
4141                                                    false,
4142                                                    on_unload_symbols,
4143                                                    num_symbol_entries));
4144 
4145     // Invoke the Agent_OnUnload function
4146     if (unload_entry != NULL) {
4147       JavaThread* thread = JavaThread::current();
4148       ThreadToNativeFromVM ttn(thread);
4149       HandleMark hm(thread);
4150       (*unload_entry)(&main_vm);
4151     }
4152   }
4153 }
4154 
4155 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries
4156 // Invokes JVM_OnLoad
4157 void Threads::create_vm_init_libraries() {
4158   extern struct JavaVM_ main_vm;
4159   AgentLibrary* agent;
4160 
4161   for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) {
4162     OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent);
4163 
4164     if (on_load_entry != NULL) {
4165       // Invoke the JVM_OnLoad function
4166       JavaThread* thread = JavaThread::current();
4167       ThreadToNativeFromVM ttn(thread);
4168       HandleMark hm(thread);
4169       jint err = (*on_load_entry)(&main_vm, agent->options(), NULL);
4170       if (err != JNI_OK) {
4171         vm_exit_during_initialization("-Xrun library failed to init", agent->name());
4172       }
4173     } else {
4174       vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name());
4175     }
4176   }
4177 }
4178 
4179 
4180 // Last thread running calls java.lang.Shutdown.shutdown()
4181 void JavaThread::invoke_shutdown_hooks() {
4182   HandleMark hm(this);
4183 
4184   // We could get here with a pending exception, if so clear it now.
4185   if (this->has_pending_exception()) {
4186     this->clear_pending_exception();
4187   }
4188 
4189   EXCEPTION_MARK;
4190   Klass* shutdown_klass =
4191     SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(),
4192                                       THREAD);
4193   if (shutdown_klass != NULL) {
4194     // SystemDictionary::resolve_or_null will return null if there was
4195     // an exception.  If we cannot load the Shutdown class, just don't
4196     // call Shutdown.shutdown() at all.  This will mean the shutdown hooks
4197     // and finalizers (if runFinalizersOnExit is set) won't be run.
4198     // Note that if a shutdown hook was registered or runFinalizersOnExit
4199     // was called, the Shutdown class would have already been loaded
4200     // (Runtime.addShutdownHook and runFinalizersOnExit will load it).
4201     JavaValue result(T_VOID);
4202     JavaCalls::call_static(&result,
4203                            shutdown_klass,
4204                            vmSymbols::shutdown_method_name(),
4205                            vmSymbols::void_method_signature(),
4206                            THREAD);
4207   }
4208   CLEAR_PENDING_EXCEPTION;
4209 }
4210 
4211 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when
4212 // the program falls off the end of main(). Another VM exit path is through
4213 // vm_exit() when the program calls System.exit() to return a value or when
4214 // there is a serious error in VM. The two shutdown paths are not exactly
4215 // the same, but they share Shutdown.shutdown() at Java level and before_exit()
4216 // and VM_Exit op at VM level.
4217 //
4218 // Shutdown sequence:
4219 //   + Shutdown native memory tracking if it is on
4220 //   + Wait until we are the last non-daemon thread to execute
4221 //     <-- every thing is still working at this moment -->
4222 //   + Call java.lang.Shutdown.shutdown(), which will invoke Java level
4223 //        shutdown hooks, run finalizers if finalization-on-exit
4224 //   + Call before_exit(), prepare for VM exit
4225 //      > run VM level shutdown hooks (they are registered through JVM_OnExit(),
4226 //        currently the only user of this mechanism is File.deleteOnExit())
4227 //      > stop StatSampler, watcher thread, CMS threads,
4228 //        post thread end and vm death events to JVMTI,
4229 //        stop signal thread
4230 //   + Call JavaThread::exit(), it will:
4231 //      > release JNI handle blocks, remove stack guard pages
4232 //      > remove this thread from Threads list
4233 //     <-- no more Java code from this thread after this point -->
4234 //   + Stop VM thread, it will bring the remaining VM to a safepoint and stop
4235 //     the compiler threads at safepoint
4236 //     <-- do not use anything that could get blocked by Safepoint -->
4237 //   + Disable tracing at JNI/JVM barriers
4238 //   + Set _vm_exited flag for threads that are still running native code
4239 //   + Delete this thread
4240 //   + Call exit_globals()
4241 //      > deletes tty
4242 //      > deletes PerfMemory resources
4243 //   + Return to caller
4244 
4245 bool Threads::destroy_vm() {
4246   JavaThread* thread = JavaThread::current();
4247 
4248 #ifdef ASSERT
4249   _vm_complete = false;
4250 #endif
4251   // Wait until we are the last non-daemon thread to execute
4252   { MutexLocker nu(Threads_lock);
4253     while (Threads::number_of_non_daemon_threads() > 1)
4254       // This wait should make safepoint checks, wait without a timeout,
4255       // and wait as a suspend-equivalent condition.
4256       Threads_lock->wait(!Mutex::_no_safepoint_check_flag, 0,
4257                          Mutex::_as_suspend_equivalent_flag);
4258   }
4259 
4260   // Hang forever on exit if we are reporting an error.
4261   if (ShowMessageBoxOnError && VMError::is_error_reported()) {
4262     os::infinite_sleep();
4263   }
4264   os::wait_for_keypress_at_exit();
4265 
4266   // run Java level shutdown hooks
4267   thread->invoke_shutdown_hooks();
4268 
4269   before_exit(thread);
4270 
4271   thread->exit(true);
4272 
4273   // Stop VM thread.
4274   {
4275     // 4945125 The vm thread comes to a safepoint during exit.
4276     // GC vm_operations can get caught at the safepoint, and the
4277     // heap is unparseable if they are caught. Grab the Heap_lock
4278     // to prevent this. The GC vm_operations will not be able to
4279     // queue until after the vm thread is dead. After this point,
4280     // we'll never emerge out of the safepoint before the VM exits.
4281 
4282     MutexLocker ml(Heap_lock);
4283 
4284     VMThread::wait_for_vm_thread_exit();
4285     assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint");
4286     VMThread::destroy();
4287   }
4288 
4289   // clean up ideal graph printers
4290 #if defined(COMPILER2) && !defined(PRODUCT)
4291   IdealGraphPrinter::clean_up();
4292 #endif
4293 
4294   // Now, all Java threads are gone except daemon threads. Daemon threads
4295   // running Java code or in VM are stopped by the Safepoint. However,
4296   // daemon threads executing native code are still running.  But they
4297   // will be stopped at native=>Java/VM barriers. Note that we can't
4298   // simply kill or suspend them, as it is inherently deadlock-prone.
4299 
4300   VM_Exit::set_vm_exited();
4301 
4302   notify_vm_shutdown();
4303 
4304   // We are after VM_Exit::set_vm_exited() so we can't call
4305   // thread->smr_delete() or we will block on the Threads_lock.
4306   // Deleting the shutdown thread here is safe because another
4307   // JavaThread cannot have an active ThreadsListHandle for
4308   // this JavaThread.
4309   delete thread;
4310 
4311 #if INCLUDE_JVMCI
4312   if (JVMCICounterSize > 0) {
4313     FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters);
4314   }
4315 #endif
4316 
4317   // exit_globals() will delete tty
4318   exit_globals();
4319 
4320   LogConfiguration::finalize();
4321 
4322   return true;
4323 }
4324 
4325 
4326 jboolean Threads::is_supported_jni_version_including_1_1(jint version) {
4327   if (version == JNI_VERSION_1_1) return JNI_TRUE;
4328   return is_supported_jni_version(version);
4329 }
4330 
4331 
4332 jboolean Threads::is_supported_jni_version(jint version) {
4333   if (version == JNI_VERSION_1_2) return JNI_TRUE;
4334   if (version == JNI_VERSION_1_4) return JNI_TRUE;
4335   if (version == JNI_VERSION_1_6) return JNI_TRUE;
4336   if (version == JNI_VERSION_1_8) return JNI_TRUE;
4337   if (version == JNI_VERSION_9) return JNI_TRUE;
4338   if (version == JNI_VERSION_10) return JNI_TRUE;
4339   return JNI_FALSE;
4340 }
4341 
4342 
4343 void Threads::add(JavaThread* p, bool force_daemon) {
4344   // The threads lock must be owned at this point
4345   assert_locked_or_safepoint(Threads_lock);
4346 
4347   // See the comment for this method in thread.hpp for its purpose and
4348   // why it is called here.
4349   p->initialize_queues();
4350   p->set_next(_thread_list);
4351   _thread_list = p;
4352 
4353   // Once a JavaThread is added to the Threads list, smr_delete() has
4354   // to be used to delete it. Otherwise we can just delete it directly.
4355   p->set_on_thread_list();
4356 
4357   _number_of_threads++;
4358   oop threadObj = p->threadObj();
4359   bool daemon = true;
4360   // Bootstrapping problem: threadObj can be null for initial
4361   // JavaThread (or for threads attached via JNI)
4362   if ((!force_daemon) && (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj))) {
4363     _number_of_non_daemon_threads++;
4364     daemon = false;
4365   }
4366 
4367   ThreadService::add_thread(p, daemon);
4368 
4369   // Maintain fast thread list
4370   ThreadsList *new_list = ThreadsList::add_thread(ThreadsSMRSupport::get_smr_java_thread_list(), p);
4371   if (EnableThreadSMRStatistics) {
4372     ThreadsSMRSupport::inc_smr_java_thread_list_alloc_cnt();
4373     ThreadsSMRSupport::update_smr_java_thread_list_max(new_list->length());
4374   }
4375   // Initial _smr_java_thread_list will not generate a "Threads::add" mesg.
4376   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::add: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
4377 
4378   ThreadsList *old_list = ThreadsSMRSupport::xchg_smr_java_thread_list(new_list);
4379   ThreadsSMRSupport::smr_free_list(old_list);
4380 
4381   // Possible GC point.
4382   Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p));
4383 }
4384 
4385 void Threads::remove(JavaThread* p) {
4386 
4387   // Reclaim the objectmonitors from the omInUseList and omFreeList of the moribund thread.
4388   ObjectSynchronizer::omFlush(p);
4389 
4390   // Extra scope needed for Thread_lock, so we can check
4391   // that we do not remove thread without safepoint code notice
4392   { MutexLocker ml(Threads_lock);
4393 
4394     assert(ThreadsSMRSupport::get_smr_java_thread_list()->includes(p), "p must be present");
4395 
4396     // Maintain fast thread list
4397     ThreadsList *new_list = ThreadsList::remove_thread(ThreadsSMRSupport::get_smr_java_thread_list(), p);
4398     if (EnableThreadSMRStatistics) {
4399       ThreadsSMRSupport::inc_smr_java_thread_list_alloc_cnt();
4400       // This list is smaller so no need to check for a "longest" update.
4401     }
4402 
4403     // Final _smr_java_thread_list will not generate a "Threads::remove" mesg.
4404     log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::remove: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
4405 
4406     ThreadsList *old_list = ThreadsSMRSupport::xchg_smr_java_thread_list(new_list);
4407     ThreadsSMRSupport::smr_free_list(old_list);
4408 
4409     JavaThread* current = _thread_list;
4410     JavaThread* prev    = NULL;
4411 
4412     while (current != p) {
4413       prev    = current;
4414       current = current->next();
4415     }
4416 
4417     if (prev) {
4418       prev->set_next(current->next());
4419     } else {
4420       _thread_list = p->next();
4421     }
4422 
4423     _number_of_threads--;
4424     oop threadObj = p->threadObj();
4425     bool daemon = true;
4426     if (threadObj == NULL || !java_lang_Thread::is_daemon(threadObj)) {
4427       _number_of_non_daemon_threads--;
4428       daemon = false;
4429 
4430       // Only one thread left, do a notify on the Threads_lock so a thread waiting
4431       // on destroy_vm will wake up.
4432       if (number_of_non_daemon_threads() == 1) {
4433         Threads_lock->notify_all();
4434       }
4435     }
4436     ThreadService::remove_thread(p, daemon);
4437 
4438     // Make sure that safepoint code disregard this thread. This is needed since
4439     // the thread might mess around with locks after this point. This can cause it
4440     // to do callbacks into the safepoint code. However, the safepoint code is not aware
4441     // of this thread since it is removed from the queue.
4442     p->set_terminated_value();
4443   } // unlock Threads_lock
4444 
4445   // Since Events::log uses a lock, we grab it outside the Threads_lock
4446   Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p));
4447 }
4448 
4449 // Operations on the Threads list for GC.  These are not explicitly locked,
4450 // but the garbage collector must provide a safe context for them to run.
4451 // In particular, these things should never be called when the Threads_lock
4452 // is held by some other thread. (Note: the Safepoint abstraction also
4453 // uses the Threads_lock to guarantee this property. It also makes sure that
4454 // all threads gets blocked when exiting or starting).
4455 
4456 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) {
4457   ALL_JAVA_THREADS(p) {
4458     p->oops_do(f, cf);
4459   }
4460   VMThread::vm_thread()->oops_do(f, cf);
4461 }
4462 
4463 void Threads::change_thread_claim_parity() {
4464   // Set the new claim parity.
4465   assert(_thread_claim_parity >= 0 && _thread_claim_parity <= 2,
4466          "Not in range.");
4467   _thread_claim_parity++;
4468   if (_thread_claim_parity == 3) _thread_claim_parity = 1;
4469   assert(_thread_claim_parity >= 1 && _thread_claim_parity <= 2,
4470          "Not in range.");
4471 }
4472 
4473 #ifdef ASSERT
4474 void Threads::assert_all_threads_claimed() {
4475   ALL_JAVA_THREADS(p) {
4476     const int thread_parity = p->oops_do_parity();
4477     assert((thread_parity == _thread_claim_parity),
4478            "Thread " PTR_FORMAT " has incorrect parity %d != %d", p2i(p), thread_parity, _thread_claim_parity);
4479   }
4480   VMThread* vmt = VMThread::vm_thread();
4481   const int thread_parity = vmt->oops_do_parity();
4482   assert((thread_parity == _thread_claim_parity),
4483          "VMThread " PTR_FORMAT " has incorrect parity %d != %d", p2i(vmt), thread_parity, _thread_claim_parity);
4484 }
4485 #endif // ASSERT
4486 
4487 class ParallelOopsDoThreadClosure : public ThreadClosure {
4488 private:
4489   OopClosure* _f;
4490   CodeBlobClosure* _cf;
4491 public:
4492   ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {}
4493   void do_thread(Thread* t) {
4494     t->oops_do(_f, _cf);
4495   }
4496 };
4497 
4498 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) {
4499   ParallelOopsDoThreadClosure tc(f, cf);
4500   possibly_parallel_threads_do(is_par, &tc);
4501 }
4502 
4503 #if INCLUDE_ALL_GCS
4504 // Used by ParallelScavenge
4505 void Threads::create_thread_roots_tasks(GCTaskQueue* q) {
4506   ALL_JAVA_THREADS(p) {
4507     q->enqueue(new ThreadRootsTask(p));
4508   }
4509   q->enqueue(new ThreadRootsTask(VMThread::vm_thread()));
4510 }
4511 
4512 // Used by Parallel Old
4513 void Threads::create_thread_roots_marking_tasks(GCTaskQueue* q) {
4514   ALL_JAVA_THREADS(p) {
4515     q->enqueue(new ThreadRootsMarkingTask(p));
4516   }
4517   q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread()));
4518 }
4519 #endif // INCLUDE_ALL_GCS
4520 
4521 void Threads::nmethods_do(CodeBlobClosure* cf) {
4522   ALL_JAVA_THREADS(p) {
4523     // This is used by the code cache sweeper to mark nmethods that are active
4524     // on the stack of a Java thread. Ignore the sweeper thread itself to avoid
4525     // marking CodeCacheSweeperThread::_scanned_compiled_method as active.
4526     if(!p->is_Code_cache_sweeper_thread()) {
4527       p->nmethods_do(cf);
4528     }
4529   }
4530 }
4531 
4532 void Threads::metadata_do(void f(Metadata*)) {
4533   ALL_JAVA_THREADS(p) {
4534     p->metadata_do(f);
4535   }
4536 }
4537 
4538 class ThreadHandlesClosure : public ThreadClosure {
4539   void (*_f)(Metadata*);
4540  public:
4541   ThreadHandlesClosure(void f(Metadata*)) : _f(f) {}
4542   virtual void do_thread(Thread* thread) {
4543     thread->metadata_handles_do(_f);
4544   }
4545 };
4546 
4547 void Threads::metadata_handles_do(void f(Metadata*)) {
4548   // Only walk the Handles in Thread.
4549   ThreadHandlesClosure handles_closure(f);
4550   threads_do(&handles_closure);
4551 }
4552 
4553 void Threads::deoptimized_wrt_marked_nmethods() {
4554   ALL_JAVA_THREADS(p) {
4555     p->deoptimized_wrt_marked_nmethods();
4556   }
4557 }
4558 
4559 
4560 // Get count Java threads that are waiting to enter the specified monitor.
4561 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list,
4562                                                          int count,
4563                                                          address monitor) {
4564   GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count);
4565 
4566   int i = 0;
4567   DO_JAVA_THREADS(t_list, p) {
4568     if (!p->can_call_java()) continue;
4569 
4570     address pending = (address)p->current_pending_monitor();
4571     if (pending == monitor) {             // found a match
4572       if (i < count) result->append(p);   // save the first count matches
4573       i++;
4574     }
4575   }
4576 
4577   return result;
4578 }
4579 
4580 
4581 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list,
4582                                                       address owner) {
4583   // NULL owner means not locked so we can skip the search
4584   if (owner == NULL) return NULL;
4585 
4586   DO_JAVA_THREADS(t_list, p) {
4587     // first, see if owner is the address of a Java thread
4588     if (owner == (address)p) return p;
4589   }
4590 
4591   // Cannot assert on lack of success here since this function may be
4592   // used by code that is trying to report useful problem information
4593   // like deadlock detection.
4594   if (UseHeavyMonitors) return NULL;
4595 
4596   // If we didn't find a matching Java thread and we didn't force use of
4597   // heavyweight monitors, then the owner is the stack address of the
4598   // Lock Word in the owning Java thread's stack.
4599   //
4600   JavaThread* the_owner = NULL;
4601   DO_JAVA_THREADS(t_list, q) {
4602     if (q->is_lock_owned(owner)) {
4603       the_owner = q;
4604       break;
4605     }
4606   }
4607 
4608   // cannot assert on lack of success here; see above comment
4609   return the_owner;
4610 }
4611 
4612 // Threads::print_on() is called at safepoint by VM_PrintThreads operation.
4613 void Threads::print_on(outputStream* st, bool print_stacks,
4614                        bool internal_format, bool print_concurrent_locks) {
4615   char buf[32];
4616   st->print_raw_cr(os::local_time_string(buf, sizeof(buf)));
4617 
4618   st->print_cr("Full thread dump %s (%s %s):",
4619                Abstract_VM_Version::vm_name(),
4620                Abstract_VM_Version::vm_release(),
4621                Abstract_VM_Version::vm_info_string());
4622   st->cr();
4623 
4624 #if INCLUDE_SERVICES
4625   // Dump concurrent locks
4626   ConcurrentLocksDump concurrent_locks;
4627   if (print_concurrent_locks) {
4628     concurrent_locks.dump_at_safepoint();
4629   }
4630 #endif // INCLUDE_SERVICES
4631 
4632   ThreadsSMRSupport::print_smr_info_on(st);
4633   st->cr();
4634 
4635   ALL_JAVA_THREADS(p) {
4636     ResourceMark rm;
4637     p->print_on(st);
4638     if (print_stacks) {
4639       if (internal_format) {
4640         p->trace_stack();
4641       } else {
4642         p->print_stack_on(st);
4643       }
4644     }
4645     st->cr();
4646 #if INCLUDE_SERVICES
4647     if (print_concurrent_locks) {
4648       concurrent_locks.print_locks_on(p, st);
4649     }
4650 #endif // INCLUDE_SERVICES
4651   }
4652 
4653   VMThread::vm_thread()->print_on(st);
4654   st->cr();
4655   Universe::heap()->print_gc_threads_on(st);
4656   WatcherThread* wt = WatcherThread::watcher_thread();
4657   if (wt != NULL) {
4658     wt->print_on(st);
4659     st->cr();
4660   }
4661 
4662   st->flush();
4663 }
4664 
4665 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf,
4666                              int buflen, bool* found_current) {
4667   if (this_thread != NULL) {
4668     bool is_current = (current == this_thread);
4669     *found_current = *found_current || is_current;
4670     st->print("%s", is_current ? "=>" : "  ");
4671 
4672     st->print(PTR_FORMAT, p2i(this_thread));
4673     st->print(" ");
4674     this_thread->print_on_error(st, buf, buflen);
4675     st->cr();
4676   }
4677 }
4678 
4679 class PrintOnErrorClosure : public ThreadClosure {
4680   outputStream* _st;
4681   Thread* _current;
4682   char* _buf;
4683   int _buflen;
4684   bool* _found_current;
4685  public:
4686   PrintOnErrorClosure(outputStream* st, Thread* current, char* buf,
4687                       int buflen, bool* found_current) :
4688    _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {}
4689 
4690   virtual void do_thread(Thread* thread) {
4691     Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current);
4692   }
4693 };
4694 
4695 // Threads::print_on_error() is called by fatal error handler. It's possible
4696 // that VM is not at safepoint and/or current thread is inside signal handler.
4697 // Don't print stack trace, as the stack may not be walkable. Don't allocate
4698 // memory (even in resource area), it might deadlock the error handler.
4699 void Threads::print_on_error(outputStream* st, Thread* current, char* buf,
4700                              int buflen) {
4701   ThreadsSMRSupport::print_smr_info_on(st);
4702   st->cr();
4703 
4704   bool found_current = false;
4705   st->print_cr("Java Threads: ( => current thread )");
4706   ALL_JAVA_THREADS(thread) {
4707     print_on_error(thread, st, current, buf, buflen, &found_current);
4708   }
4709   st->cr();
4710 
4711   st->print_cr("Other Threads:");
4712   print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current);
4713   print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current);
4714 
4715   PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current);
4716   Universe::heap()->gc_threads_do(&print_closure);
4717 
4718   if (!found_current) {
4719     st->cr();
4720     st->print("=>" PTR_FORMAT " (exited) ", p2i(current));
4721     current->print_on_error(st, buf, buflen);
4722     st->cr();
4723   }
4724   st->cr();
4725 
4726   st->print_cr("Threads with active compile tasks:");
4727   print_threads_compiling(st, buf, buflen);
4728 }
4729 
4730 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen) {
4731   ALL_JAVA_THREADS(thread) {
4732     if (thread->is_Compiler_thread()) {
4733       CompilerThread* ct = (CompilerThread*) thread;
4734       if (ct->task() != NULL) {
4735         thread->print_name_on_error(st, buf, buflen);
4736         ct->task()->print(st, NULL, true, true);
4737       }
4738     }
4739   }
4740 }
4741 
4742 
4743 // Internal SpinLock and Mutex
4744 // Based on ParkEvent
4745 
4746 // Ad-hoc mutual exclusion primitives: SpinLock and Mux
4747 //
4748 // We employ SpinLocks _only for low-contention, fixed-length
4749 // short-duration critical sections where we're concerned
4750 // about native mutex_t or HotSpot Mutex:: latency.
4751 // The mux construct provides a spin-then-block mutual exclusion
4752 // mechanism.
4753 //
4754 // Testing has shown that contention on the ListLock guarding gFreeList
4755 // is common.  If we implement ListLock as a simple SpinLock it's common
4756 // for the JVM to devolve to yielding with little progress.  This is true
4757 // despite the fact that the critical sections protected by ListLock are
4758 // extremely short.
4759 //
4760 // TODO-FIXME: ListLock should be of type SpinLock.
4761 // We should make this a 1st-class type, integrated into the lock
4762 // hierarchy as leaf-locks.  Critically, the SpinLock structure
4763 // should have sufficient padding to avoid false-sharing and excessive
4764 // cache-coherency traffic.
4765 
4766 
4767 typedef volatile int SpinLockT;
4768 
4769 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
4770   if (Atomic::cmpxchg (1, adr, 0) == 0) {
4771     return;   // normal fast-path return
4772   }
4773 
4774   // Slow-path : We've encountered contention -- Spin/Yield/Block strategy.
4775   TEVENT(SpinAcquire - ctx);
4776   int ctr = 0;
4777   int Yields = 0;
4778   for (;;) {
4779     while (*adr != 0) {
4780       ++ctr;
4781       if ((ctr & 0xFFF) == 0 || !os::is_MP()) {
4782         if (Yields > 5) {
4783           os::naked_short_sleep(1);
4784         } else {
4785           os::naked_yield();
4786           ++Yields;
4787         }
4788       } else {
4789         SpinPause();
4790       }
4791     }
4792     if (Atomic::cmpxchg(1, adr, 0) == 0) return;
4793   }
4794 }
4795 
4796 void Thread::SpinRelease(volatile int * adr) {
4797   assert(*adr != 0, "invariant");
4798   OrderAccess::fence();      // guarantee at least release consistency.
4799   // Roach-motel semantics.
4800   // It's safe if subsequent LDs and STs float "up" into the critical section,
4801   // but prior LDs and STs within the critical section can't be allowed
4802   // to reorder or float past the ST that releases the lock.
4803   // Loads and stores in the critical section - which appear in program
4804   // order before the store that releases the lock - must also appear
4805   // before the store that releases the lock in memory visibility order.
4806   // Conceptually we need a #loadstore|#storestore "release" MEMBAR before
4807   // the ST of 0 into the lock-word which releases the lock, so fence
4808   // more than covers this on all platforms.
4809   *adr = 0;
4810 }
4811 
4812 // muxAcquire and muxRelease:
4813 //
4814 // *  muxAcquire and muxRelease support a single-word lock-word construct.
4815 //    The LSB of the word is set IFF the lock is held.
4816 //    The remainder of the word points to the head of a singly-linked list
4817 //    of threads blocked on the lock.
4818 //
4819 // *  The current implementation of muxAcquire-muxRelease uses its own
4820 //    dedicated Thread._MuxEvent instance.  If we're interested in
4821 //    minimizing the peak number of extant ParkEvent instances then
4822 //    we could eliminate _MuxEvent and "borrow" _ParkEvent as long
4823 //    as certain invariants were satisfied.  Specifically, care would need
4824 //    to be taken with regards to consuming unpark() "permits".
4825 //    A safe rule of thumb is that a thread would never call muxAcquire()
4826 //    if it's enqueued (cxq, EntryList, WaitList, etc) and will subsequently
4827 //    park().  Otherwise the _ParkEvent park() operation in muxAcquire() could
4828 //    consume an unpark() permit intended for monitorenter, for instance.
4829 //    One way around this would be to widen the restricted-range semaphore
4830 //    implemented in park().  Another alternative would be to provide
4831 //    multiple instances of the PlatformEvent() for each thread.  One
4832 //    instance would be dedicated to muxAcquire-muxRelease, for instance.
4833 //
4834 // *  Usage:
4835 //    -- Only as leaf locks
4836 //    -- for short-term locking only as muxAcquire does not perform
4837 //       thread state transitions.
4838 //
4839 // Alternatives:
4840 // *  We could implement muxAcquire and muxRelease with MCS or CLH locks
4841 //    but with parking or spin-then-park instead of pure spinning.
4842 // *  Use Taura-Oyama-Yonenzawa locks.
4843 // *  It's possible to construct a 1-0 lock if we encode the lockword as
4844 //    (List,LockByte).  Acquire will CAS the full lockword while Release
4845 //    will STB 0 into the LockByte.  The 1-0 scheme admits stranding, so
4846 //    acquiring threads use timers (ParkTimed) to detect and recover from
4847 //    the stranding window.  Thread/Node structures must be aligned on 256-byte
4848 //    boundaries by using placement-new.
4849 // *  Augment MCS with advisory back-link fields maintained with CAS().
4850 //    Pictorially:  LockWord -> T1 <-> T2 <-> T3 <-> ... <-> Tn <-> Owner.
4851 //    The validity of the backlinks must be ratified before we trust the value.
4852 //    If the backlinks are invalid the exiting thread must back-track through the
4853 //    the forward links, which are always trustworthy.
4854 // *  Add a successor indication.  The LockWord is currently encoded as
4855 //    (List, LOCKBIT:1).  We could also add a SUCCBIT or an explicit _succ variable
4856 //    to provide the usual futile-wakeup optimization.
4857 //    See RTStt for details.
4858 // *  Consider schedctl.sc_nopreempt to cover the critical section.
4859 //
4860 
4861 
4862 const intptr_t LOCKBIT = 1;
4863 
4864 void Thread::muxAcquire(volatile intptr_t * Lock, const char * LockName) {
4865   intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0);
4866   if (w == 0) return;
4867   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4868     return;
4869   }
4870 
4871   TEVENT(muxAcquire - Contention);
4872   ParkEvent * const Self = Thread::current()->_MuxEvent;
4873   assert((intptr_t(Self) & LOCKBIT) == 0, "invariant");
4874   for (;;) {
4875     int its = (os::is_MP() ? 100 : 0) + 1;
4876 
4877     // Optional spin phase: spin-then-park strategy
4878     while (--its >= 0) {
4879       w = *Lock;
4880       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4881         return;
4882       }
4883     }
4884 
4885     Self->reset();
4886     Self->OnList = intptr_t(Lock);
4887     // The following fence() isn't _strictly necessary as the subsequent
4888     // CAS() both serializes execution and ratifies the fetched *Lock value.
4889     OrderAccess::fence();
4890     for (;;) {
4891       w = *Lock;
4892       if ((w & LOCKBIT) == 0) {
4893         if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4894           Self->OnList = 0;   // hygiene - allows stronger asserts
4895           return;
4896         }
4897         continue;      // Interference -- *Lock changed -- Just retry
4898       }
4899       assert(w & LOCKBIT, "invariant");
4900       Self->ListNext = (ParkEvent *) (w & ~LOCKBIT);
4901       if (Atomic::cmpxchg(intptr_t(Self)|LOCKBIT, Lock, w) == w) break;
4902     }
4903 
4904     while (Self->OnList != 0) {
4905       Self->park();
4906     }
4907   }
4908 }
4909 
4910 void Thread::muxAcquireW(volatile intptr_t * Lock, ParkEvent * ev) {
4911   intptr_t w = Atomic::cmpxchg(LOCKBIT, Lock, (intptr_t)0);
4912   if (w == 0) return;
4913   if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4914     return;
4915   }
4916 
4917   TEVENT(muxAcquire - Contention);
4918   ParkEvent * ReleaseAfter = NULL;
4919   if (ev == NULL) {
4920     ev = ReleaseAfter = ParkEvent::Allocate(NULL);
4921   }
4922   assert((intptr_t(ev) & LOCKBIT) == 0, "invariant");
4923   for (;;) {
4924     guarantee(ev->OnList == 0, "invariant");
4925     int its = (os::is_MP() ? 100 : 0) + 1;
4926 
4927     // Optional spin phase: spin-then-park strategy
4928     while (--its >= 0) {
4929       w = *Lock;
4930       if ((w & LOCKBIT) == 0 && Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4931         if (ReleaseAfter != NULL) {
4932           ParkEvent::Release(ReleaseAfter);
4933         }
4934         return;
4935       }
4936     }
4937 
4938     ev->reset();
4939     ev->OnList = intptr_t(Lock);
4940     // The following fence() isn't _strictly necessary as the subsequent
4941     // CAS() both serializes execution and ratifies the fetched *Lock value.
4942     OrderAccess::fence();
4943     for (;;) {
4944       w = *Lock;
4945       if ((w & LOCKBIT) == 0) {
4946         if (Atomic::cmpxchg(w|LOCKBIT, Lock, w) == w) {
4947           ev->OnList = 0;
4948           // We call ::Release while holding the outer lock, thus
4949           // artificially lengthening the critical section.
4950           // Consider deferring the ::Release() until the subsequent unlock(),
4951           // after we've dropped the outer lock.
4952           if (ReleaseAfter != NULL) {
4953             ParkEvent::Release(ReleaseAfter);
4954           }
4955           return;
4956         }
4957         continue;      // Interference -- *Lock changed -- Just retry
4958       }
4959       assert(w & LOCKBIT, "invariant");
4960       ev->ListNext = (ParkEvent *) (w & ~LOCKBIT);
4961       if (Atomic::cmpxchg(intptr_t(ev)|LOCKBIT, Lock, w) == w) break;
4962     }
4963 
4964     while (ev->OnList != 0) {
4965       ev->park();
4966     }
4967   }
4968 }
4969 
4970 // Release() must extract a successor from the list and then wake that thread.
4971 // It can "pop" the front of the list or use a detach-modify-reattach (DMR) scheme
4972 // similar to that used by ParkEvent::Allocate() and ::Release().  DMR-based
4973 // Release() would :
4974 // (A) CAS() or swap() null to *Lock, releasing the lock and detaching the list.
4975 // (B) Extract a successor from the private list "in-hand"
4976 // (C) attempt to CAS() the residual back into *Lock over null.
4977 //     If there were any newly arrived threads and the CAS() would fail.
4978 //     In that case Release() would detach the RATs, re-merge the list in-hand
4979 //     with the RATs and repeat as needed.  Alternately, Release() might
4980 //     detach and extract a successor, but then pass the residual list to the wakee.
4981 //     The wakee would be responsible for reattaching and remerging before it
4982 //     competed for the lock.
4983 //
4984 // Both "pop" and DMR are immune from ABA corruption -- there can be
4985 // multiple concurrent pushers, but only one popper or detacher.
4986 // This implementation pops from the head of the list.  This is unfair,
4987 // but tends to provide excellent throughput as hot threads remain hot.
4988 // (We wake recently run threads first).
4989 //
4990 // All paths through muxRelease() will execute a CAS.
4991 // Release consistency -- We depend on the CAS in muxRelease() to provide full
4992 // bidirectional fence/MEMBAR semantics, ensuring that all prior memory operations
4993 // executed within the critical section are complete and globally visible before the
4994 // store (CAS) to the lock-word that releases the lock becomes globally visible.
4995 void Thread::muxRelease(volatile intptr_t * Lock)  {
4996   for (;;) {
4997     const intptr_t w = Atomic::cmpxchg((intptr_t)0, Lock, LOCKBIT);
4998     assert(w & LOCKBIT, "invariant");
4999     if (w == LOCKBIT) return;
5000     ParkEvent * const List = (ParkEvent *) (w & ~LOCKBIT);
5001     assert(List != NULL, "invariant");
5002     assert(List->OnList == intptr_t(Lock), "invariant");
5003     ParkEvent * const nxt = List->ListNext;
5004     guarantee((intptr_t(nxt) & LOCKBIT) == 0, "invariant");
5005 
5006     // The following CAS() releases the lock and pops the head element.
5007     // The CAS() also ratifies the previously fetched lock-word value.
5008     if (Atomic::cmpxchg(intptr_t(nxt), Lock, w) != w) {
5009       continue;
5010     }
5011     List->OnList = 0;
5012     OrderAccess::fence();
5013     List->unpark();
5014     return;
5015   }
5016 }
5017 
5018 
5019 void Threads::verify() {
5020   ALL_JAVA_THREADS(p) {
5021     p->verify();
5022   }
5023   VMThread* thread = VMThread::vm_thread();
5024   if (thread != NULL) thread->verify();
5025 }