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