1 /* 2 * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2021, Azul Systems, Inc. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 * 24 */ 25 26 #include "precompiled.hpp" 27 #include "jvm.h" 28 #include "cds/dynamicArchive.hpp" 29 #include "cds/metaspaceShared.hpp" 30 #include "classfile/classLoader.hpp" 31 #include "classfile/javaClasses.hpp" 32 #include "classfile/javaThreadStatus.hpp" 33 #include "classfile/systemDictionary.hpp" 34 #include "classfile/vmClasses.hpp" 35 #include "classfile/vmSymbols.hpp" 36 #include "code/codeCache.hpp" 37 #include "code/scopeDesc.hpp" 38 #include "compiler/compileBroker.hpp" 39 #include "compiler/compileTask.hpp" 40 #include "compiler/compilerThread.hpp" 41 #include "gc/shared/barrierSet.hpp" 42 #include "gc/shared/collectedHeap.hpp" 43 #include "gc/shared/gcId.hpp" 44 #include "gc/shared/gcLocker.inline.hpp" 45 #include "gc/shared/gcVMOperations.hpp" 46 #include "gc/shared/oopStorage.hpp" 47 #include "gc/shared/oopStorageSet.hpp" 48 #include "gc/shared/stringdedup/stringDedup.hpp" 49 #include "gc/shared/tlab_globals.hpp" 50 #include "interpreter/interpreter.hpp" 51 #include "interpreter/linkResolver.hpp" 52 #include "interpreter/oopMapCache.hpp" 53 #include "jfr/jfrEvents.hpp" 54 #include "jvmtifiles/jvmtiEnv.hpp" 55 #include "logging/log.hpp" 56 #include "logging/logAsyncWriter.hpp" 57 #include "logging/logConfiguration.hpp" 58 #include "logging/logStream.hpp" 59 #include "memory/allocation.inline.hpp" 60 #include "memory/iterator.hpp" 61 #include "memory/oopFactory.hpp" 62 #include "memory/resourceArea.hpp" 63 #include "memory/universe.hpp" 64 #include "oops/access.inline.hpp" 65 #include "oops/instanceKlass.hpp" 66 #include "oops/klass.inline.hpp" 67 #include "oops/objArrayOop.hpp" 68 #include "oops/oop.inline.hpp" 69 #include "oops/oopHandle.inline.hpp" 70 #include "oops/symbol.hpp" 71 #include "oops/typeArrayOop.inline.hpp" 72 #include "oops/verifyOopClosure.hpp" 73 #include "prims/jvm_misc.hpp" 74 #include "prims/jvmtiDeferredUpdates.hpp" 75 #include "prims/jvmtiExport.hpp" 76 #include "prims/jvmtiThreadState.hpp" 77 #include "runtime/arguments.hpp" 78 #include "runtime/atomic.hpp" 79 #include "runtime/biasedLocking.hpp" 80 #include "runtime/fieldDescriptor.inline.hpp" 81 #include "runtime/flags/jvmFlagLimit.hpp" 82 #include "runtime/deoptimization.hpp" 83 #include "runtime/frame.inline.hpp" 84 #include "runtime/handles.inline.hpp" 85 #include "runtime/handshake.hpp" 86 #include "runtime/init.hpp" 87 #include "runtime/interfaceSupport.inline.hpp" 88 #include "runtime/java.hpp" 89 #include "runtime/javaCalls.hpp" 90 #include "runtime/jniHandles.inline.hpp" 91 #include "runtime/jniPeriodicChecker.hpp" 92 #include "runtime/monitorDeflationThread.hpp" 93 #include "runtime/mutexLocker.hpp" 94 #include "runtime/nonJavaThread.hpp" 95 #include "runtime/objectMonitor.hpp" 96 #include "runtime/orderAccess.hpp" 97 #include "runtime/osThread.hpp" 98 #include "runtime/prefetch.inline.hpp" 99 #include "runtime/safepoint.hpp" 100 #include "runtime/safepointMechanism.inline.hpp" 101 #include "runtime/safepointVerifiers.hpp" 102 #include "runtime/serviceThread.hpp" 103 #include "runtime/sharedRuntime.hpp" 104 #include "runtime/stackFrameStream.inline.hpp" 105 #include "runtime/stackWatermarkSet.hpp" 106 #include "runtime/statSampler.hpp" 107 #include "runtime/task.hpp" 108 #include "runtime/thread.inline.hpp" 109 #include "runtime/threadCritical.hpp" 110 #include "runtime/threadSMR.inline.hpp" 111 #include "runtime/threadStatisticalInfo.hpp" 112 #include "runtime/threadWXSetters.inline.hpp" 113 #include "runtime/timer.hpp" 114 #include "runtime/timerTrace.hpp" 115 #include "runtime/trimNativeHeap.hpp" 116 #include "runtime/vframe.inline.hpp" 117 #include "runtime/vframeArray.hpp" 118 #include "runtime/vframe_hp.hpp" 119 #include "runtime/vmThread.hpp" 120 #include "runtime/vmOperations.hpp" 121 #include "runtime/vm_version.hpp" 122 #include "services/attachListener.hpp" 123 #include "services/management.hpp" 124 #include "services/memTracker.hpp" 125 #include "services/threadService.hpp" 126 #include "utilities/align.hpp" 127 #include "utilities/copy.hpp" 128 #include "utilities/defaultStream.hpp" 129 #include "utilities/dtrace.hpp" 130 #include "utilities/events.hpp" 131 #include "utilities/macros.hpp" 132 #include "utilities/preserveException.hpp" 133 #include "utilities/spinYield.hpp" 134 #include "utilities/vmError.hpp" 135 #if INCLUDE_JVMCI 136 #include "jvmci/jvmci.hpp" 137 #include "jvmci/jvmciEnv.hpp" 138 #endif 139 #ifdef COMPILER1 140 #include "c1/c1_Compiler.hpp" 141 #endif 142 #ifdef COMPILER2 143 #include "opto/c2compiler.hpp" 144 #include "opto/idealGraphPrinter.hpp" 145 #endif 146 #if INCLUDE_RTM_OPT 147 #include "runtime/rtmLocking.hpp" 148 #endif 149 #if INCLUDE_JFR 150 #include "jfr/jfr.hpp" 151 #endif 152 153 // Initialization after module runtime initialization 154 void universe_post_module_init(); // must happen after call_initPhase2 155 156 #ifdef DTRACE_ENABLED 157 158 // Only bother with this argument setup if dtrace is available 159 160 #define HOTSPOT_THREAD_PROBE_start HOTSPOT_THREAD_START 161 #define HOTSPOT_THREAD_PROBE_stop HOTSPOT_THREAD_STOP 162 163 #define DTRACE_THREAD_PROBE(probe, javathread) \ 164 { \ 165 ResourceMark rm(this); \ 166 int len = 0; \ 167 const char* name = (javathread)->get_thread_name(); \ 168 len = strlen(name); \ 169 HOTSPOT_THREAD_PROBE_##probe(/* probe = start, stop */ \ 170 (char *) name, len, \ 171 java_lang_Thread::thread_id((javathread)->threadObj()), \ 172 (uintptr_t) (javathread)->osthread()->thread_id(), \ 173 java_lang_Thread::is_daemon((javathread)->threadObj())); \ 174 } 175 176 #else // ndef DTRACE_ENABLED 177 178 #define DTRACE_THREAD_PROBE(probe, javathread) 179 180 #endif // ndef DTRACE_ENABLED 181 182 #ifndef USE_LIBRARY_BASED_TLS_ONLY 183 // Current thread is maintained as a thread-local variable 184 THREAD_LOCAL Thread* Thread::_thr_current = NULL; 185 #endif 186 187 // ======= Thread ======== 188 // Support for forcing alignment of thread objects for biased locking 189 void* Thread::allocate(size_t size, bool throw_excpt, MEMFLAGS flags) { 190 if (UseBiasedLocking) { 191 const size_t alignment = markWord::biased_lock_alignment; 192 size_t aligned_size = size + (alignment - sizeof(intptr_t)); 193 void* real_malloc_addr = throw_excpt? AllocateHeap(aligned_size, flags, CURRENT_PC) 194 : AllocateHeap(aligned_size, flags, CURRENT_PC, 195 AllocFailStrategy::RETURN_NULL); 196 void* aligned_addr = align_up(real_malloc_addr, alignment); 197 assert(((uintptr_t) aligned_addr + (uintptr_t) size) <= 198 ((uintptr_t) real_malloc_addr + (uintptr_t) aligned_size), 199 "JavaThread alignment code overflowed allocated storage"); 200 if (aligned_addr != real_malloc_addr) { 201 log_info(biasedlocking)("Aligned thread " INTPTR_FORMAT " to " INTPTR_FORMAT, 202 p2i(real_malloc_addr), 203 p2i(aligned_addr)); 204 } 205 ((Thread*) aligned_addr)->_real_malloc_address = real_malloc_addr; 206 return aligned_addr; 207 } else { 208 return throw_excpt? AllocateHeap(size, flags, CURRENT_PC) 209 : AllocateHeap(size, flags, CURRENT_PC, AllocFailStrategy::RETURN_NULL); 210 } 211 } 212 213 void Thread::operator delete(void* p) { 214 if (UseBiasedLocking) { 215 FreeHeap(((Thread*) p)->_real_malloc_address); 216 } else { 217 FreeHeap(p); 218 } 219 } 220 221 void JavaThread::smr_delete() { 222 if (_on_thread_list) { 223 ThreadsSMRSupport::smr_delete(this); 224 } else { 225 delete this; 226 } 227 } 228 229 // Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread, 230 // JavaThread 231 232 DEBUG_ONLY(Thread* Thread::_starting_thread = NULL;) 233 234 Thread::Thread() { 235 236 DEBUG_ONLY(_run_state = PRE_CALL_RUN;) 237 238 // stack and get_thread 239 set_stack_base(NULL); 240 set_stack_size(0); 241 set_lgrp_id(-1); 242 DEBUG_ONLY(clear_suspendible_thread();) 243 244 // allocated data structures 245 set_osthread(NULL); 246 set_resource_area(new (mtThread)ResourceArea()); 247 DEBUG_ONLY(_current_resource_mark = NULL;) 248 set_handle_area(new (mtThread) HandleArea(NULL)); 249 set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(30, mtClass)); 250 set_active_handles(NULL); 251 set_free_handle_block(NULL); 252 set_last_handle_mark(NULL); 253 DEBUG_ONLY(_missed_ic_stub_refill_verifier = NULL); 254 255 // Initial value of zero ==> never claimed. 256 _threads_do_token = 0; 257 _threads_hazard_ptr = NULL; 258 _threads_list_ptr = NULL; 259 _nested_threads_hazard_ptr_cnt = 0; 260 _rcu_counter = 0; 261 262 // the handle mark links itself to last_handle_mark 263 new HandleMark(this); 264 265 // plain initialization 266 debug_only(_owned_locks = NULL;) 267 NOT_PRODUCT(_skip_gcalot = false;) 268 _jvmti_env_iteration_count = 0; 269 set_allocated_bytes(0); 270 _current_pending_raw_monitor = NULL; 271 272 // thread-specific hashCode stream generator state - Marsaglia shift-xor form 273 _hashStateX = os::random(); 274 _hashStateY = 842502087; 275 _hashStateZ = 0x8767; // (int)(3579807591LL & 0xffff) ; 276 _hashStateW = 273326509; 277 278 // Many of the following fields are effectively final - immutable 279 // Note that nascent threads can't use the Native Monitor-Mutex 280 // construct until the _MutexEvent is initialized ... 281 // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents 282 // we might instead use a stack of ParkEvents that we could provision on-demand. 283 // The stack would act as a cache to avoid calls to ParkEvent::Allocate() 284 // and ::Release() 285 _ParkEvent = ParkEvent::Allocate(this); 286 287 #ifdef CHECK_UNHANDLED_OOPS 288 if (CheckUnhandledOops) { 289 _unhandled_oops = new UnhandledOops(this); 290 } 291 #endif // CHECK_UNHANDLED_OOPS 292 #ifdef ASSERT 293 if (UseBiasedLocking) { 294 assert(is_aligned(this, markWord::biased_lock_alignment), "forced alignment of thread object failed"); 295 assert(this == _real_malloc_address || 296 this == align_up(_real_malloc_address, markWord::biased_lock_alignment), 297 "bug in forced alignment of thread objects"); 298 } 299 #endif // ASSERT 300 301 // Notify the barrier set that a thread is being created. The initial 302 // thread is created before the barrier set is available. The call to 303 // BarrierSet::on_thread_create() for this thread is therefore deferred 304 // to BarrierSet::set_barrier_set(). 305 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 306 if (barrier_set != NULL) { 307 barrier_set->on_thread_create(this); 308 } else { 309 // Only the main thread should be created before the barrier set 310 // and that happens just before Thread::current is set. No other thread 311 // can attach as the VM is not created yet, so they can't execute this code. 312 // If the main thread creates other threads before the barrier set that is an error. 313 assert(Thread::current_or_null() == NULL, "creating thread before barrier set"); 314 } 315 316 MACOS_AARCH64_ONLY(DEBUG_ONLY(_wx_init = false)); 317 } 318 319 void Thread::initialize_tlab() { 320 if (UseTLAB) { 321 tlab().initialize(); 322 } 323 } 324 325 void Thread::initialize_thread_current() { 326 #ifndef USE_LIBRARY_BASED_TLS_ONLY 327 assert(_thr_current == NULL, "Thread::current already initialized"); 328 _thr_current = this; 329 #endif 330 assert(ThreadLocalStorage::thread() == NULL, "ThreadLocalStorage::thread already initialized"); 331 ThreadLocalStorage::set_thread(this); 332 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 333 } 334 335 void Thread::clear_thread_current() { 336 assert(Thread::current() == ThreadLocalStorage::thread(), "TLS mismatch!"); 337 #ifndef USE_LIBRARY_BASED_TLS_ONLY 338 _thr_current = NULL; 339 #endif 340 ThreadLocalStorage::set_thread(NULL); 341 } 342 343 void Thread::record_stack_base_and_size() { 344 // Note: at this point, Thread object is not yet initialized. Do not rely on 345 // any members being initialized. Do not rely on Thread::current() being set. 346 // If possible, refrain from doing anything which may crash or assert since 347 // quite probably those crash dumps will be useless. 348 set_stack_base(os::current_stack_base()); 349 set_stack_size(os::current_stack_size()); 350 351 // Set stack limits after thread is initialized. 352 if (is_Java_thread()) { 353 as_Java_thread()->stack_overflow_state()->initialize(stack_base(), stack_end()); 354 } 355 } 356 357 #if INCLUDE_NMT 358 void Thread::register_thread_stack_with_NMT() { 359 MemTracker::record_thread_stack(stack_end(), stack_size()); 360 } 361 362 void Thread::unregister_thread_stack_with_NMT() { 363 MemTracker::release_thread_stack(stack_end(), stack_size()); 364 } 365 #endif // INCLUDE_NMT 366 367 void Thread::call_run() { 368 DEBUG_ONLY(_run_state = CALL_RUN;) 369 370 // At this point, Thread object should be fully initialized and 371 // Thread::current() should be set. 372 373 assert(Thread::current_or_null() != NULL, "current thread is unset"); 374 assert(Thread::current_or_null() == this, "current thread is wrong"); 375 376 // Perform common initialization actions 377 378 MACOS_AARCH64_ONLY(this->init_wx()); 379 380 register_thread_stack_with_NMT(); 381 382 JFR_ONLY(Jfr::on_thread_start(this);) 383 384 log_debug(os, thread)("Thread " UINTX_FORMAT " stack dimensions: " 385 PTR_FORMAT "-" PTR_FORMAT " (" SIZE_FORMAT "k).", 386 os::current_thread_id(), p2i(stack_end()), 387 p2i(stack_base()), stack_size()/1024); 388 389 // Perform <ChildClass> initialization actions 390 DEBUG_ONLY(_run_state = PRE_RUN;) 391 this->pre_run(); 392 393 // Invoke <ChildClass>::run() 394 DEBUG_ONLY(_run_state = RUN;) 395 this->run(); 396 // Returned from <ChildClass>::run(). Thread finished. 397 398 // Perform common tear-down actions 399 400 assert(Thread::current_or_null() != NULL, "current thread is unset"); 401 assert(Thread::current_or_null() == this, "current thread is wrong"); 402 403 // Perform <ChildClass> tear-down actions 404 DEBUG_ONLY(_run_state = POST_RUN;) 405 this->post_run(); 406 407 // Note: at this point the thread object may already have deleted itself, 408 // so from here on do not dereference *this*. Not all thread types currently 409 // delete themselves when they terminate. But no thread should ever be deleted 410 // asynchronously with respect to its termination - that is what _run_state can 411 // be used to check. 412 413 assert(Thread::current_or_null() == NULL, "current thread still present"); 414 } 415 416 Thread::~Thread() { 417 418 // Attached threads will remain in PRE_CALL_RUN, as will threads that don't actually 419 // get started due to errors etc. Any active thread should at least reach post_run 420 // before it is deleted (usually in post_run()). 421 assert(_run_state == PRE_CALL_RUN || 422 _run_state == POST_RUN, "Active Thread deleted before post_run(): " 423 "_run_state=%d", (int)_run_state); 424 425 // Notify the barrier set that a thread is being destroyed. Note that a barrier 426 // set might not be available if we encountered errors during bootstrapping. 427 BarrierSet* const barrier_set = BarrierSet::barrier_set(); 428 if (barrier_set != NULL) { 429 barrier_set->on_thread_destroy(this); 430 } 431 432 // deallocate data structures 433 delete resource_area(); 434 // since the handle marks are using the handle area, we have to deallocated the root 435 // handle mark before deallocating the thread's handle area, 436 assert(last_handle_mark() != NULL, "check we have an element"); 437 delete last_handle_mark(); 438 assert(last_handle_mark() == NULL, "check we have reached the end"); 439 440 ParkEvent::Release(_ParkEvent); 441 // Set to NULL as a termination indicator for has_terminated(). 442 Atomic::store(&_ParkEvent, (ParkEvent*)NULL); 443 444 delete handle_area(); 445 delete metadata_handles(); 446 447 // osthread() can be NULL, if creation of thread failed. 448 if (osthread() != NULL) os::free_thread(osthread()); 449 450 // Clear Thread::current if thread is deleting itself and it has not 451 // already been done. This must be done before the memory is deallocated. 452 // Needed to ensure JNI correctly detects non-attached threads. 453 if (this == Thread::current_or_null()) { 454 Thread::clear_thread_current(); 455 } 456 457 CHECK_UNHANDLED_OOPS_ONLY(if (CheckUnhandledOops) delete unhandled_oops();) 458 } 459 460 #ifdef ASSERT 461 // A JavaThread is considered dangling if it not handshake-safe with respect to 462 // the current thread, it is not on a ThreadsList, or not at safepoint. 463 void Thread::check_for_dangling_thread_pointer(Thread *thread) { 464 assert(!thread->is_Java_thread() || 465 thread->as_Java_thread()->is_handshake_safe_for(Thread::current()) || 466 !thread->as_Java_thread()->on_thread_list() || 467 SafepointSynchronize::is_at_safepoint() || 468 ThreadsSMRSupport::is_a_protected_JavaThread_with_lock(thread->as_Java_thread()), 469 "possibility of dangling Thread pointer"); 470 } 471 #endif 472 473 // Is the target JavaThread protected by the calling Thread 474 // or by some other mechanism: 475 bool Thread::is_JavaThread_protected(const JavaThread* p) { 476 // Do the simplest check first: 477 if (SafepointSynchronize::is_at_safepoint()) { 478 // The target is protected since JavaThreads cannot exit 479 // while we're at a safepoint. 480 return true; 481 } 482 483 // If the target hasn't been started yet then it is trivially 484 // "protected". We assume the caller is the thread that will do 485 // the starting. 486 if (p->osthread() == NULL || p->osthread()->get_state() <= INITIALIZED) { 487 return true; 488 } 489 490 // Now make the simple checks based on who the caller is: 491 Thread* current_thread = Thread::current(); 492 if (current_thread == p || Threads_lock->owner() == current_thread) { 493 // Target JavaThread is self or calling thread owns the Threads_lock. 494 // Second check is the same as Threads_lock->owner_is_self(), 495 // but we already have the current thread so check directly. 496 return true; 497 } 498 499 // Check the ThreadsLists associated with the calling thread (if any) 500 // to see if one of them protects the target JavaThread: 501 for (SafeThreadsListPtr* stlp = current_thread->_threads_list_ptr; 502 stlp != NULL; stlp = stlp->previous()) { 503 if (stlp->list()->includes(p)) { 504 // The target JavaThread is protected by this ThreadsList: 505 return true; 506 } 507 } 508 509 // Use this debug code with -XX:+UseNewCode to diagnose locations that 510 // are missing a ThreadsListHandle or other protection mechanism: 511 // guarantee(!UseNewCode, "current_thread=" INTPTR_FORMAT " is not protecting p=" 512 // INTPTR_FORMAT, p2i(current_thread), p2i(p)); 513 514 // Note: Since 'p' isn't protected by a TLH, the call to 515 // p->is_handshake_safe_for() may crash, but we have debug bits so 516 // we'll be able to figure out what protection mechanism is missing. 517 assert(p->is_handshake_safe_for(current_thread), "JavaThread=" INTPTR_FORMAT 518 " is not protected and not handshake safe.", p2i(p)); 519 520 // The target JavaThread is not protected so it is not safe to query: 521 return false; 522 } 523 524 ThreadPriority Thread::get_priority(const Thread* const thread) { 525 ThreadPriority priority; 526 // Can return an error! 527 (void)os::get_priority(thread, priority); 528 assert(MinPriority <= priority && priority <= MaxPriority, "non-Java priority found"); 529 return priority; 530 } 531 532 void Thread::set_priority(Thread* thread, ThreadPriority priority) { 533 debug_only(check_for_dangling_thread_pointer(thread);) 534 // Can return an error! 535 (void)os::set_priority(thread, priority); 536 } 537 538 539 void Thread::start(Thread* thread) { 540 // Start is different from resume in that its safety is guaranteed by context or 541 // being called from a Java method synchronized on the Thread object. 542 if (thread->is_Java_thread()) { 543 // Initialize the thread state to RUNNABLE before starting this thread. 544 // Can not set it after the thread started because we do not know the 545 // exact thread state at that time. It could be in MONITOR_WAIT or 546 // in SLEEPING or some other state. 547 java_lang_Thread::set_thread_status(thread->as_Java_thread()->threadObj(), 548 JavaThreadStatus::RUNNABLE); 549 } 550 os::start_thread(thread); 551 } 552 553 // GC Support 554 bool Thread::claim_par_threads_do(uintx claim_token) { 555 uintx token = _threads_do_token; 556 if (token != claim_token) { 557 uintx res = Atomic::cmpxchg(&_threads_do_token, token, claim_token); 558 if (res == token) { 559 return true; 560 } 561 guarantee(res == claim_token, "invariant"); 562 } 563 return false; 564 } 565 566 void Thread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) { 567 if (active_handles() != NULL) { 568 active_handles()->oops_do(f); 569 } 570 // Do oop for ThreadShadow 571 f->do_oop((oop*)&_pending_exception); 572 handle_area()->oops_do(f); 573 } 574 575 // If the caller is a NamedThread, then remember, in the current scope, 576 // the given JavaThread in its _processed_thread field. 577 class RememberProcessedThread: public StackObj { 578 NamedThread* _cur_thr; 579 public: 580 RememberProcessedThread(Thread* thread) { 581 Thread* self = Thread::current(); 582 if (self->is_Named_thread()) { 583 _cur_thr = (NamedThread *)self; 584 assert(_cur_thr->processed_thread() == NULL, "nesting not supported"); 585 _cur_thr->set_processed_thread(thread); 586 } else { 587 _cur_thr = NULL; 588 } 589 } 590 591 ~RememberProcessedThread() { 592 if (_cur_thr) { 593 assert(_cur_thr->processed_thread() != NULL, "nesting not supported"); 594 _cur_thr->set_processed_thread(NULL); 595 } 596 } 597 }; 598 599 void Thread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 600 // Record JavaThread to GC thread 601 RememberProcessedThread rpt(this); 602 oops_do_no_frames(f, cf); 603 oops_do_frames(f, cf); 604 } 605 606 void Thread::metadata_handles_do(void f(Metadata*)) { 607 // Only walk the Handles in Thread. 608 if (metadata_handles() != NULL) { 609 for (int i = 0; i< metadata_handles()->length(); i++) { 610 f(metadata_handles()->at(i)); 611 } 612 } 613 } 614 615 void Thread::print_on(outputStream* st, bool print_extended_info) const { 616 // get_priority assumes osthread initialized 617 if (osthread() != NULL) { 618 int os_prio; 619 if (os::get_native_priority(this, &os_prio) == OS_OK) { 620 st->print("os_prio=%d ", os_prio); 621 } 622 623 st->print("cpu=%.2fms ", 624 os::thread_cpu_time(const_cast<Thread*>(this), true) / 1000000.0 625 ); 626 st->print("elapsed=%.2fs ", 627 _statistical_info.getElapsedTime() / 1000.0 628 ); 629 if (is_Java_thread() && (PrintExtendedThreadInfo || print_extended_info)) { 630 size_t allocated_bytes = (size_t) const_cast<Thread*>(this)->cooked_allocated_bytes(); 631 st->print("allocated=" SIZE_FORMAT "%s ", 632 byte_size_in_proper_unit(allocated_bytes), 633 proper_unit_for_byte_size(allocated_bytes) 634 ); 635 st->print("defined_classes=" INT64_FORMAT " ", _statistical_info.getDefineClassCount()); 636 } 637 638 st->print("tid=" INTPTR_FORMAT " ", p2i(this)); 639 osthread()->print_on(st); 640 } 641 ThreadsSMRSupport::print_info_on(this, st); 642 st->print(" "); 643 debug_only(if (WizardMode) print_owned_locks_on(st);) 644 } 645 646 void Thread::print() const { print_on(tty); } 647 648 // Thread::print_on_error() is called by fatal error handler. Don't use 649 // any lock or allocate memory. 650 void Thread::print_on_error(outputStream* st, char* buf, int buflen) const { 651 assert(!(is_Compiler_thread() || is_Java_thread()), "Can't call name() here if it allocates"); 652 653 if (is_VM_thread()) { st->print("VMThread"); } 654 else if (is_GC_task_thread()) { st->print("GCTaskThread"); } 655 else if (is_Watcher_thread()) { st->print("WatcherThread"); } 656 else if (is_ConcurrentGC_thread()) { st->print("ConcurrentGCThread"); } 657 else if (this == AsyncLogWriter::instance()) { 658 st->print("%s", this->name()); 659 } else { st->print("Thread"); } 660 661 if (is_Named_thread()) { 662 st->print(" \"%s\"", name()); 663 } 664 665 OSThread* os_thr = osthread(); 666 if (os_thr != NULL) { 667 if (os_thr->get_state() != ZOMBIE) { 668 st->print(" [stack: " PTR_FORMAT "," PTR_FORMAT "]", 669 p2i(stack_end()), p2i(stack_base())); 670 st->print(" [id=%d]", osthread()->thread_id()); 671 } else { 672 st->print(" terminated"); 673 } 674 } else { 675 st->print(" unknown state (no osThread)"); 676 } 677 ThreadsSMRSupport::print_info_on(this, st); 678 } 679 680 void Thread::print_value_on(outputStream* st) const { 681 if (is_Named_thread()) { 682 st->print(" \"%s\" ", name()); 683 } 684 st->print(INTPTR_FORMAT, p2i(this)); // print address 685 } 686 687 #ifdef ASSERT 688 void Thread::print_owned_locks_on(outputStream* st) const { 689 Mutex* cur = _owned_locks; 690 if (cur == NULL) { 691 st->print(" (no locks) "); 692 } else { 693 st->print_cr(" Locks owned:"); 694 while (cur) { 695 cur->print_on(st); 696 cur = cur->next(); 697 } 698 } 699 } 700 #endif // ASSERT 701 702 // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter 703 // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being 704 // used for compilation in the future. If that change is made, the need for these methods 705 // should be revisited, and they should be removed if possible. 706 707 bool Thread::is_lock_owned(address adr) const { 708 return is_in_full_stack(adr); 709 } 710 711 bool Thread::set_as_starting_thread() { 712 assert(_starting_thread == NULL, "already initialized: " 713 "_starting_thread=" INTPTR_FORMAT, p2i(_starting_thread)); 714 // NOTE: this must be called inside the main thread. 715 DEBUG_ONLY(_starting_thread = this;) 716 return os::create_main_thread(this->as_Java_thread()); 717 } 718 719 static void initialize_class(Symbol* class_name, TRAPS) { 720 Klass* klass = SystemDictionary::resolve_or_fail(class_name, true, CHECK); 721 InstanceKlass::cast(klass)->initialize(CHECK); 722 } 723 724 725 // Creates the initial ThreadGroup 726 static Handle create_initial_thread_group(TRAPS) { 727 Handle system_instance = JavaCalls::construct_new_instance( 728 vmClasses::ThreadGroup_klass(), 729 vmSymbols::void_method_signature(), 730 CHECK_NH); 731 Universe::set_system_thread_group(system_instance()); 732 733 Handle string = java_lang_String::create_from_str("main", CHECK_NH); 734 Handle main_instance = JavaCalls::construct_new_instance( 735 vmClasses::ThreadGroup_klass(), 736 vmSymbols::threadgroup_string_void_signature(), 737 system_instance, 738 string, 739 CHECK_NH); 740 return main_instance; 741 } 742 743 // Creates the initial Thread, and sets it to running. 744 static void create_initial_thread(Handle thread_group, JavaThread* thread, 745 TRAPS) { 746 InstanceKlass* ik = vmClasses::Thread_klass(); 747 assert(ik->is_initialized(), "must be"); 748 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK); 749 750 // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread 751 // constructor calls Thread.current(), which must be set here for the 752 // initial thread. 753 java_lang_Thread::set_thread(thread_oop(), thread); 754 java_lang_Thread::set_priority(thread_oop(), NormPriority); 755 thread->set_threadObj(thread_oop()); 756 757 Handle string = java_lang_String::create_from_str("main", CHECK); 758 759 JavaValue result(T_VOID); 760 JavaCalls::call_special(&result, thread_oop, 761 ik, 762 vmSymbols::object_initializer_name(), 763 vmSymbols::threadgroup_string_void_signature(), 764 thread_group, 765 string, 766 CHECK); 767 768 // Set thread status to running since main thread has 769 // been started and running. 770 java_lang_Thread::set_thread_status(thread_oop(), 771 JavaThreadStatus::RUNNABLE); 772 } 773 774 // Extract version and vendor specific information from 775 // java.lang.VersionProps fields. 776 // Returned char* is allocated in the thread's resource area 777 // so must be copied for permanency. 778 static const char* get_java_version_info(InstanceKlass* ik, 779 Symbol* field_name) { 780 fieldDescriptor fd; 781 bool found = ik != NULL && 782 ik->find_local_field(field_name, 783 vmSymbols::string_signature(), &fd); 784 if (found) { 785 oop name_oop = ik->java_mirror()->obj_field(fd.offset()); 786 if (name_oop == NULL) { 787 return NULL; 788 } 789 const char* name = java_lang_String::as_utf8_string(name_oop); 790 return name; 791 } else { 792 return NULL; 793 } 794 } 795 796 // General purpose hook into Java code, run once when the VM is initialized. 797 // The Java library method itself may be changed independently from the VM. 798 static void call_postVMInitHook(TRAPS) { 799 Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD); 800 if (klass != NULL) { 801 JavaValue result(T_VOID); 802 JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(), 803 vmSymbols::void_method_signature(), 804 CHECK); 805 } 806 } 807 808 // Initialized by VMThread at vm_global_init 809 static OopStorage* _thread_oop_storage = NULL; 810 811 oop JavaThread::threadObj() const { 812 return _threadObj.resolve(); 813 } 814 815 void JavaThread::set_threadObj(oop p) { 816 assert(_thread_oop_storage != NULL, "not yet initialized"); 817 _threadObj = OopHandle(_thread_oop_storage, p); 818 } 819 820 OopStorage* JavaThread::thread_oop_storage() { 821 assert(_thread_oop_storage != NULL, "not yet initialized"); 822 return _thread_oop_storage; 823 } 824 825 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name, 826 bool daemon, TRAPS) { 827 assert(thread_group.not_null(), "thread group should be specified"); 828 assert(threadObj() == NULL, "should only create Java thread object once"); 829 830 InstanceKlass* ik = vmClasses::Thread_klass(); 831 assert(ik->is_initialized(), "must be"); 832 instanceHandle thread_oop = ik->allocate_instance_handle(CHECK); 833 834 // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon. 835 // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread 836 // constructor calls Thread.current(), which must be set here. 837 java_lang_Thread::set_thread(thread_oop(), this); 838 java_lang_Thread::set_priority(thread_oop(), NormPriority); 839 set_threadObj(thread_oop()); 840 841 JavaValue result(T_VOID); 842 if (thread_name != NULL) { 843 Handle name = java_lang_String::create_from_str(thread_name, CHECK); 844 // Thread gets assigned specified name and null target 845 JavaCalls::call_special(&result, 846 thread_oop, 847 ik, 848 vmSymbols::object_initializer_name(), 849 vmSymbols::threadgroup_string_void_signature(), 850 thread_group, 851 name, 852 THREAD); 853 } else { 854 // Thread gets assigned name "Thread-nnn" and null target 855 // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument) 856 JavaCalls::call_special(&result, 857 thread_oop, 858 ik, 859 vmSymbols::object_initializer_name(), 860 vmSymbols::threadgroup_runnable_void_signature(), 861 thread_group, 862 Handle(), 863 THREAD); 864 } 865 866 867 if (daemon) { 868 java_lang_Thread::set_daemon(thread_oop()); 869 } 870 871 if (HAS_PENDING_EXCEPTION) { 872 return; 873 } 874 875 Klass* group = vmClasses::ThreadGroup_klass(); 876 Handle threadObj(THREAD, this->threadObj()); 877 878 JavaCalls::call_special(&result, 879 thread_group, 880 group, 881 vmSymbols::add_method_name(), 882 vmSymbols::thread_void_signature(), 883 threadObj, // Arg 1 884 THREAD); 885 } 886 887 // ======= JavaThread ======== 888 889 #if INCLUDE_JVMCI 890 891 jlong* JavaThread::_jvmci_old_thread_counters; 892 893 bool jvmci_counters_include(JavaThread* thread) { 894 return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread(); 895 } 896 897 void JavaThread::collect_counters(jlong* array, int length) { 898 assert(length == JVMCICounterSize, "wrong value"); 899 for (int i = 0; i < length; i++) { 900 array[i] = _jvmci_old_thread_counters[i]; 901 } 902 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *tp = jtiwh.next(); ) { 903 if (jvmci_counters_include(tp)) { 904 for (int i = 0; i < length; i++) { 905 array[i] += tp->_jvmci_counters[i]; 906 } 907 } 908 } 909 } 910 911 // Attempt to enlarge the array for per thread counters. 912 jlong* resize_counters_array(jlong* old_counters, int current_size, int new_size) { 913 jlong* new_counters = NEW_C_HEAP_ARRAY_RETURN_NULL(jlong, new_size, mtJVMCI); 914 if (new_counters == NULL) { 915 return NULL; 916 } 917 if (old_counters == NULL) { 918 old_counters = new_counters; 919 memset(old_counters, 0, sizeof(jlong) * new_size); 920 } else { 921 for (int i = 0; i < MIN2((int) current_size, new_size); i++) { 922 new_counters[i] = old_counters[i]; 923 } 924 if (new_size > current_size) { 925 memset(new_counters + current_size, 0, sizeof(jlong) * (new_size - current_size)); 926 } 927 FREE_C_HEAP_ARRAY(jlong, old_counters); 928 } 929 return new_counters; 930 } 931 932 // Attempt to enlarge the array for per thread counters. 933 bool JavaThread::resize_counters(int current_size, int new_size) { 934 jlong* new_counters = resize_counters_array(_jvmci_counters, current_size, new_size); 935 if (new_counters == NULL) { 936 return false; 937 } else { 938 _jvmci_counters = new_counters; 939 return true; 940 } 941 } 942 943 class VM_JVMCIResizeCounters : public VM_Operation { 944 private: 945 int _new_size; 946 bool _failed; 947 948 public: 949 VM_JVMCIResizeCounters(int new_size) : _new_size(new_size), _failed(false) { } 950 VMOp_Type type() const { return VMOp_JVMCIResizeCounters; } 951 bool allow_nested_vm_operations() const { return true; } 952 void doit() { 953 // Resize the old thread counters array 954 jlong* new_counters = resize_counters_array(JavaThread::_jvmci_old_thread_counters, JVMCICounterSize, _new_size); 955 if (new_counters == NULL) { 956 _failed = true; 957 return; 958 } else { 959 JavaThread::_jvmci_old_thread_counters = new_counters; 960 } 961 962 // Now resize each threads array 963 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *tp = jtiwh.next(); ) { 964 if (!tp->resize_counters(JVMCICounterSize, _new_size)) { 965 _failed = true; 966 break; 967 } 968 } 969 if (!_failed) { 970 JVMCICounterSize = _new_size; 971 } 972 } 973 974 bool failed() { return _failed; } 975 }; 976 977 bool JavaThread::resize_all_jvmci_counters(int new_size) { 978 VM_JVMCIResizeCounters op(new_size); 979 VMThread::execute(&op); 980 return !op.failed(); 981 } 982 983 #endif // INCLUDE_JVMCI 984 985 #ifdef ASSERT 986 // Checks safepoint allowed and clears unhandled oops at potential safepoints. 987 void JavaThread::check_possible_safepoint() { 988 if (_no_safepoint_count > 0) { 989 print_owned_locks(); 990 assert(false, "Possible safepoint reached by thread that does not allow it"); 991 } 992 #ifdef CHECK_UNHANDLED_OOPS 993 // Clear unhandled oops in JavaThreads so we get a crash right away. 994 clear_unhandled_oops(); 995 #endif // CHECK_UNHANDLED_OOPS 996 } 997 998 void JavaThread::check_for_valid_safepoint_state() { 999 // Check NoSafepointVerifier, which is implied by locks taken that can be 1000 // shared with the VM thread. This makes sure that no locks with allow_vm_block 1001 // are held. 1002 check_possible_safepoint(); 1003 1004 if (thread_state() != _thread_in_vm) { 1005 fatal("LEAF method calling lock?"); 1006 } 1007 1008 if (GCALotAtAllSafepoints) { 1009 // We could enter a safepoint here and thus have a gc 1010 InterfaceSupport::check_gc_alot(); 1011 } 1012 } 1013 #endif // ASSERT 1014 1015 // A JavaThread is a normal Java thread 1016 1017 JavaThread::JavaThread() : 1018 // Initialize fields 1019 1020 _in_asgct(false), 1021 _on_thread_list(false), 1022 DEBUG_ONLY(_java_call_counter(0) COMMA) 1023 _entry_point(nullptr), 1024 _deopt_mark(nullptr), 1025 _deopt_nmethod(nullptr), 1026 _vframe_array_head(nullptr), 1027 _vframe_array_last(nullptr), 1028 _jvmti_deferred_updates(nullptr), 1029 _callee_target(nullptr), 1030 _vm_result(nullptr), 1031 _vm_result_2(nullptr), 1032 1033 _current_pending_monitor(NULL), 1034 _current_pending_monitor_is_from_java(true), 1035 _current_waiting_monitor(NULL), 1036 _Stalled(0), 1037 1038 _monitor_chunks(nullptr), 1039 1040 _suspend_flags(0), 1041 _async_exception_condition(_no_async_condition), 1042 _pending_async_exception(nullptr), 1043 1044 _thread_state(_thread_new), 1045 _saved_exception_pc(nullptr), 1046 #ifdef ASSERT 1047 _no_safepoint_count(0), 1048 _visited_for_critical_count(false), 1049 #endif 1050 1051 _terminated(_not_terminated), 1052 _in_deopt_handler(0), 1053 _doing_unsafe_access(false), 1054 _do_not_unlock_if_synchronized(false), 1055 _jni_attach_state(_not_attaching_via_jni), 1056 #if INCLUDE_JVMCI 1057 _pending_deoptimization(-1), 1058 _pending_monitorenter(false), 1059 _pending_transfer_to_interpreter(false), 1060 _in_retryable_allocation(false), 1061 _pending_failed_speculation(0), 1062 _jvmci{nullptr}, 1063 _jvmci_counters(nullptr), 1064 _jvmci_reserved0(0), 1065 _jvmci_reserved1(0), 1066 _jvmci_reserved_oop0(nullptr), 1067 #endif // INCLUDE_JVMCI 1068 1069 _exception_oop(oop()), 1070 _exception_pc(0), 1071 _exception_handler_pc(0), 1072 _is_method_handle_return(0), 1073 1074 _jni_active_critical(0), 1075 _pending_jni_exception_check_fn(nullptr), 1076 _depth_first_number(0), 1077 1078 // JVMTI PopFrame support 1079 _popframe_condition(popframe_inactive), 1080 _frames_to_pop_failed_realloc(0), 1081 1082 _handshake(this), 1083 1084 _popframe_preserved_args(nullptr), 1085 _popframe_preserved_args_size(0), 1086 1087 _jvmti_thread_state(nullptr), 1088 _interp_only_mode(0), 1089 _should_post_on_exceptions_flag(JNI_FALSE), 1090 _thread_stat(new ThreadStatistics()), 1091 1092 _parker(), 1093 _cached_monitor_info(nullptr), 1094 1095 _class_to_be_initialized(nullptr), 1096 1097 _SleepEvent(ParkEvent::Allocate(this)) 1098 { 1099 set_jni_functions(jni_functions()); 1100 1101 #if INCLUDE_JVMCI 1102 assert(_jvmci._implicit_exception_pc == nullptr, "must be"); 1103 if (JVMCICounterSize > 0) { 1104 resize_counters(0, (int) JVMCICounterSize); 1105 } 1106 #endif // INCLUDE_JVMCI 1107 1108 // Setup safepoint state info for this thread 1109 ThreadSafepointState::create(this); 1110 1111 SafepointMechanism::initialize_header(this); 1112 1113 set_requires_cross_modify_fence(false); 1114 1115 pd_initialize(); 1116 assert(deferred_card_mark().is_empty(), "Default MemRegion ctor"); 1117 } 1118 1119 JavaThread::JavaThread(bool is_attaching_via_jni) : JavaThread() { 1120 if (is_attaching_via_jni) { 1121 _jni_attach_state = _attaching_via_jni; 1122 } 1123 } 1124 1125 1126 // interrupt support 1127 1128 void JavaThread::interrupt() { 1129 // All callers should have 'this' thread protected by a 1130 // ThreadsListHandle so that it cannot terminate and deallocate 1131 // itself. 1132 debug_only(check_for_dangling_thread_pointer(this);) 1133 1134 // For Windows _interrupt_event 1135 osthread()->set_interrupted(true); 1136 1137 // For Thread.sleep 1138 _SleepEvent->unpark(); 1139 1140 // For JSR166 LockSupport.park 1141 parker()->unpark(); 1142 1143 // For ObjectMonitor and JvmtiRawMonitor 1144 _ParkEvent->unpark(); 1145 } 1146 1147 1148 bool JavaThread::is_interrupted(bool clear_interrupted) { 1149 debug_only(check_for_dangling_thread_pointer(this);) 1150 1151 if (_threadObj.peek() == NULL) { 1152 // If there is no j.l.Thread then it is impossible to have 1153 // been interrupted. We can find NULL during VM initialization 1154 // or when a JNI thread is still in the process of attaching. 1155 // In such cases this must be the current thread. 1156 assert(this == Thread::current(), "invariant"); 1157 return false; 1158 } 1159 1160 bool interrupted = java_lang_Thread::interrupted(threadObj()); 1161 1162 // NOTE that since there is no "lock" around the interrupt and 1163 // is_interrupted operations, there is the possibility that the 1164 // interrupted flag will be "false" but that the 1165 // low-level events will be in the signaled state. This is 1166 // intentional. The effect of this is that Object.wait() and 1167 // LockSupport.park() will appear to have a spurious wakeup, which 1168 // is allowed and not harmful, and the possibility is so rare that 1169 // it is not worth the added complexity to add yet another lock. 1170 // For the sleep event an explicit reset is performed on entry 1171 // to JavaThread::sleep, so there is no early return. It has also been 1172 // recommended not to put the interrupted flag into the "event" 1173 // structure because it hides the issue. 1174 // Also, because there is no lock, we must only clear the interrupt 1175 // state if we are going to report that we were interrupted; otherwise 1176 // an interrupt that happens just after we read the field would be lost. 1177 if (interrupted && clear_interrupted) { 1178 assert(this == Thread::current(), "only the current thread can clear"); 1179 java_lang_Thread::set_interrupted(threadObj(), false); 1180 osthread()->set_interrupted(false); 1181 } 1182 1183 return interrupted; 1184 } 1185 1186 void JavaThread::block_if_vm_exited() { 1187 if (_terminated == _vm_exited) { 1188 // _vm_exited is set at safepoint, and Threads_lock is never released 1189 // we will block here forever. 1190 // Here we can be doing a jump from a safe state to an unsafe state without 1191 // proper transition, but it happens after the final safepoint has begun. 1192 set_thread_state(_thread_in_vm); 1193 Threads_lock->lock(); 1194 ShouldNotReachHere(); 1195 } 1196 } 1197 1198 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) : JavaThread() { 1199 _jni_attach_state = _not_attaching_via_jni; 1200 set_entry_point(entry_point); 1201 // Create the native thread itself. 1202 // %note runtime_23 1203 os::ThreadType thr_type = os::java_thread; 1204 thr_type = entry_point == &CompilerThread::thread_entry ? os::compiler_thread : 1205 os::java_thread; 1206 os::create_thread(this, thr_type, stack_sz); 1207 // The _osthread may be NULL here because we ran out of memory (too many threads active). 1208 // We need to throw and OutOfMemoryError - however we cannot do this here because the caller 1209 // may hold a lock and all locks must be unlocked before throwing the exception (throwing 1210 // the exception consists of creating the exception object & initializing it, initialization 1211 // will leave the VM via a JavaCall and then all locks must be unlocked). 1212 // 1213 // The thread is still suspended when we reach here. Thread must be explicit started 1214 // by creator! Furthermore, the thread must also explicitly be added to the Threads list 1215 // by calling Threads:add. The reason why this is not done here, is because the thread 1216 // object must be fully initialized (take a look at JVM_Start) 1217 } 1218 1219 JavaThread::~JavaThread() { 1220 1221 // Ask ServiceThread to release the threadObj OopHandle 1222 ServiceThread::add_oop_handle_release(_threadObj); 1223 1224 // Return the sleep event to the free list 1225 ParkEvent::Release(_SleepEvent); 1226 _SleepEvent = NULL; 1227 1228 // Free any remaining previous UnrollBlock 1229 vframeArray* old_array = vframe_array_last(); 1230 1231 if (old_array != NULL) { 1232 Deoptimization::UnrollBlock* old_info = old_array->unroll_block(); 1233 old_array->set_unroll_block(NULL); 1234 delete old_info; 1235 delete old_array; 1236 } 1237 1238 JvmtiDeferredUpdates* updates = deferred_updates(); 1239 if (updates != NULL) { 1240 // This can only happen if thread is destroyed before deoptimization occurs. 1241 assert(updates->count() > 0, "Updates holder not deleted"); 1242 // free deferred updates. 1243 delete updates; 1244 set_deferred_updates(NULL); 1245 } 1246 1247 // All Java related clean up happens in exit 1248 ThreadSafepointState::destroy(this); 1249 if (_thread_stat != NULL) delete _thread_stat; 1250 1251 #if INCLUDE_JVMCI 1252 if (JVMCICounterSize > 0) { 1253 FREE_C_HEAP_ARRAY(jlong, _jvmci_counters); 1254 } 1255 #endif // INCLUDE_JVMCI 1256 } 1257 1258 1259 // First JavaThread specific code executed by a new Java thread. 1260 void JavaThread::pre_run() { 1261 // empty - see comments in run() 1262 } 1263 1264 // The main routine called by a new Java thread. This isn't overridden 1265 // by subclasses, instead different subclasses define a different "entry_point" 1266 // which defines the actual logic for that kind of thread. 1267 void JavaThread::run() { 1268 // initialize thread-local alloc buffer related fields 1269 initialize_tlab(); 1270 1271 _stack_overflow_state.create_stack_guard_pages(); 1272 1273 cache_global_variables(); 1274 1275 // Thread is now sufficiently initialized to be handled by the safepoint code as being 1276 // in the VM. Change thread state from _thread_new to _thread_in_vm 1277 ThreadStateTransition::transition(this, _thread_new, _thread_in_vm); 1278 // Before a thread is on the threads list it is always safe, so after leaving the 1279 // _thread_new we should emit a instruction barrier. The distance to modified code 1280 // from here is probably far enough, but this is consistent and safe. 1281 OrderAccess::cross_modify_fence(); 1282 1283 assert(JavaThread::current() == this, "sanity check"); 1284 assert(!Thread::current()->owns_locks(), "sanity check"); 1285 1286 DTRACE_THREAD_PROBE(start, this); 1287 1288 // This operation might block. We call that after all safepoint checks for a new thread has 1289 // been completed. 1290 set_active_handles(JNIHandleBlock::allocate_block()); 1291 1292 if (JvmtiExport::should_post_thread_life()) { 1293 JvmtiExport::post_thread_start(this); 1294 1295 } 1296 1297 // We call another function to do the rest so we are sure that the stack addresses used 1298 // from there will be lower than the stack base just computed. 1299 thread_main_inner(); 1300 } 1301 1302 void JavaThread::thread_main_inner() { 1303 assert(JavaThread::current() == this, "sanity check"); 1304 assert(_threadObj.peek() != NULL, "just checking"); 1305 1306 // Execute thread entry point unless this thread has a pending exception 1307 // or has been stopped before starting. 1308 // Note: Due to JVM_StopThread we can have pending exceptions already! 1309 if (!this->has_pending_exception() && 1310 !java_lang_Thread::is_stillborn(this->threadObj())) { 1311 { 1312 ResourceMark rm(this); 1313 this->set_native_thread_name(this->get_thread_name()); 1314 } 1315 HandleMark hm(this); 1316 this->entry_point()(this, this); 1317 } 1318 1319 DTRACE_THREAD_PROBE(stop, this); 1320 1321 // Cleanup is handled in post_run() 1322 } 1323 1324 // Shared teardown for all JavaThreads 1325 void JavaThread::post_run() { 1326 this->exit(false); 1327 this->unregister_thread_stack_with_NMT(); 1328 // Defer deletion to here to ensure 'this' is still referenceable in call_run 1329 // for any shared tear-down. 1330 this->smr_delete(); 1331 } 1332 1333 static void ensure_join(JavaThread* thread) { 1334 // We do not need to grab the Threads_lock, since we are operating on ourself. 1335 Handle threadObj(thread, thread->threadObj()); 1336 assert(threadObj.not_null(), "java thread object must exist"); 1337 ObjectLocker lock(threadObj, thread); 1338 // Ignore pending exception (ThreadDeath), since we are exiting anyway 1339 thread->clear_pending_exception(); 1340 // Thread is exiting. So set thread_status field in java.lang.Thread class to TERMINATED. 1341 java_lang_Thread::set_thread_status(threadObj(), JavaThreadStatus::TERMINATED); 1342 // Clear the native thread instance - this makes isAlive return false and allows the join() 1343 // to complete once we've done the notify_all below. Needs a release() to obey Java Memory Model 1344 // requirements. 1345 java_lang_Thread::release_set_thread(threadObj(), NULL); 1346 lock.notify_all(thread); 1347 // Ignore pending exception (ThreadDeath), since we are exiting anyway 1348 thread->clear_pending_exception(); 1349 } 1350 1351 static bool is_daemon(oop threadObj) { 1352 return (threadObj != NULL && java_lang_Thread::is_daemon(threadObj)); 1353 } 1354 1355 // For any new cleanup additions, please check to see if they need to be applied to 1356 // cleanup_failed_attach_current_thread as well. 1357 void JavaThread::exit(bool destroy_vm, ExitType exit_type) { 1358 assert(this == JavaThread::current(), "thread consistency check"); 1359 1360 elapsedTimer _timer_exit_phase1; 1361 elapsedTimer _timer_exit_phase2; 1362 elapsedTimer _timer_exit_phase3; 1363 elapsedTimer _timer_exit_phase4; 1364 1365 if (log_is_enabled(Debug, os, thread, timer)) { 1366 _timer_exit_phase1.start(); 1367 } 1368 1369 HandleMark hm(this); 1370 Handle uncaught_exception(this, this->pending_exception()); 1371 this->clear_pending_exception(); 1372 Handle threadObj(this, this->threadObj()); 1373 assert(threadObj.not_null(), "Java thread object should be created"); 1374 1375 if (!destroy_vm) { 1376 if (uncaught_exception.not_null()) { 1377 EXCEPTION_MARK; 1378 // Call method Thread.dispatchUncaughtException(). 1379 Klass* thread_klass = vmClasses::Thread_klass(); 1380 JavaValue result(T_VOID); 1381 JavaCalls::call_virtual(&result, 1382 threadObj, thread_klass, 1383 vmSymbols::dispatchUncaughtException_name(), 1384 vmSymbols::throwable_void_signature(), 1385 uncaught_exception, 1386 THREAD); 1387 if (HAS_PENDING_EXCEPTION) { 1388 ResourceMark rm(this); 1389 jio_fprintf(defaultStream::error_stream(), 1390 "\nException: %s thrown from the UncaughtExceptionHandler" 1391 " in thread \"%s\"\n", 1392 pending_exception()->klass()->external_name(), 1393 get_thread_name()); 1394 CLEAR_PENDING_EXCEPTION; 1395 } 1396 } 1397 1398 // Call Thread.exit(). We try 3 times in case we got another Thread.stop during 1399 // the execution of the method. If that is not enough, then we don't really care. Thread.stop 1400 // is deprecated anyhow. 1401 if (!is_Compiler_thread()) { 1402 int count = 3; 1403 while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) { 1404 EXCEPTION_MARK; 1405 JavaValue result(T_VOID); 1406 Klass* thread_klass = vmClasses::Thread_klass(); 1407 JavaCalls::call_virtual(&result, 1408 threadObj, thread_klass, 1409 vmSymbols::exit_method_name(), 1410 vmSymbols::void_method_signature(), 1411 THREAD); 1412 CLEAR_PENDING_EXCEPTION; 1413 } 1414 } 1415 // notify JVMTI 1416 if (JvmtiExport::should_post_thread_life()) { 1417 JvmtiExport::post_thread_end(this); 1418 } 1419 1420 // The careful dance between thread suspension and exit is handled here. 1421 // Since we are in thread_in_vm state and suspension is done with handshakes, 1422 // we can just put in the exiting state and it will be correctly handled. 1423 set_terminated(_thread_exiting); 1424 1425 ThreadService::current_thread_exiting(this, is_daemon(threadObj())); 1426 } else { 1427 assert(!is_terminated() && !is_exiting(), "must not be exiting"); 1428 // before_exit() has already posted JVMTI THREAD_END events 1429 } 1430 1431 if (log_is_enabled(Debug, os, thread, timer)) { 1432 _timer_exit_phase1.stop(); 1433 _timer_exit_phase2.start(); 1434 } 1435 1436 // Capture daemon status before the thread is marked as terminated. 1437 bool daemon = is_daemon(threadObj()); 1438 1439 // Notify waiters on thread object. This has to be done after exit() is called 1440 // on the thread (if the thread is the last thread in a daemon ThreadGroup the 1441 // group should have the destroyed bit set before waiters are notified). 1442 ensure_join(this); 1443 assert(!this->has_pending_exception(), "ensure_join should have cleared"); 1444 1445 if (log_is_enabled(Debug, os, thread, timer)) { 1446 _timer_exit_phase2.stop(); 1447 _timer_exit_phase3.start(); 1448 } 1449 // 6282335 JNI DetachCurrentThread spec states that all Java monitors 1450 // held by this thread must be released. The spec does not distinguish 1451 // between JNI-acquired and regular Java monitors. We can only see 1452 // regular Java monitors here if monitor enter-exit matching is broken. 1453 // 1454 // ensure_join() ignores IllegalThreadStateExceptions, and so does 1455 // ObjectSynchronizer::release_monitors_owned_by_thread(). 1456 if (exit_type == jni_detach) { 1457 // Sanity check even though JNI DetachCurrentThread() would have 1458 // returned JNI_ERR if there was a Java frame. JavaThread exit 1459 // should be done executing Java code by the time we get here. 1460 assert(!this->has_last_Java_frame(), 1461 "should not have a Java frame when detaching or exiting"); 1462 ObjectSynchronizer::release_monitors_owned_by_thread(this); 1463 assert(!this->has_pending_exception(), "release_monitors should have cleared"); 1464 } 1465 1466 // These things needs to be done while we are still a Java Thread. Make sure that thread 1467 // is in a consistent state, in case GC happens 1468 JFR_ONLY(Jfr::on_thread_exit(this);) 1469 1470 if (active_handles() != NULL) { 1471 JNIHandleBlock* block = active_handles(); 1472 set_active_handles(NULL); 1473 JNIHandleBlock::release_block(block); 1474 } 1475 1476 if (free_handle_block() != NULL) { 1477 JNIHandleBlock* block = free_handle_block(); 1478 set_free_handle_block(NULL); 1479 JNIHandleBlock::release_block(block); 1480 } 1481 1482 // These have to be removed while this is still a valid thread. 1483 _stack_overflow_state.remove_stack_guard_pages(); 1484 1485 if (UseTLAB) { 1486 tlab().retire(); 1487 } 1488 1489 if (JvmtiEnv::environments_might_exist()) { 1490 JvmtiExport::cleanup_thread(this); 1491 } 1492 1493 // We need to cache the thread name for logging purposes below as once 1494 // we have called on_thread_detach this thread must not access any oops. 1495 char* thread_name = NULL; 1496 if (log_is_enabled(Debug, os, thread, timer)) { 1497 ResourceMark rm(this); 1498 thread_name = os::strdup(get_thread_name()); 1499 } 1500 1501 log_info(os, thread)("JavaThread %s (tid: " UINTX_FORMAT ").", 1502 exit_type == JavaThread::normal_exit ? "exiting" : "detaching", 1503 os::current_thread_id()); 1504 1505 if (log_is_enabled(Debug, os, thread, timer)) { 1506 _timer_exit_phase3.stop(); 1507 _timer_exit_phase4.start(); 1508 } 1509 1510 #if INCLUDE_JVMCI 1511 if (JVMCICounterSize > 0) { 1512 if (jvmci_counters_include(this)) { 1513 for (int i = 0; i < JVMCICounterSize; i++) { 1514 _jvmci_old_thread_counters[i] += _jvmci_counters[i]; 1515 } 1516 } 1517 } 1518 #endif // INCLUDE_JVMCI 1519 1520 // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread 1521 Threads::remove(this, daemon); 1522 1523 if (log_is_enabled(Debug, os, thread, timer)) { 1524 _timer_exit_phase4.stop(); 1525 log_debug(os, thread, timer)("name='%s'" 1526 ", exit-phase1=" JLONG_FORMAT 1527 ", exit-phase2=" JLONG_FORMAT 1528 ", exit-phase3=" JLONG_FORMAT 1529 ", exit-phase4=" JLONG_FORMAT, 1530 thread_name, 1531 _timer_exit_phase1.milliseconds(), 1532 _timer_exit_phase2.milliseconds(), 1533 _timer_exit_phase3.milliseconds(), 1534 _timer_exit_phase4.milliseconds()); 1535 os::free(thread_name); 1536 } 1537 } 1538 1539 void JavaThread::cleanup_failed_attach_current_thread(bool is_daemon) { 1540 if (active_handles() != NULL) { 1541 JNIHandleBlock* block = active_handles(); 1542 set_active_handles(NULL); 1543 JNIHandleBlock::release_block(block); 1544 } 1545 1546 if (free_handle_block() != NULL) { 1547 JNIHandleBlock* block = free_handle_block(); 1548 set_free_handle_block(NULL); 1549 JNIHandleBlock::release_block(block); 1550 } 1551 1552 // These have to be removed while this is still a valid thread. 1553 _stack_overflow_state.remove_stack_guard_pages(); 1554 1555 if (UseTLAB) { 1556 tlab().retire(); 1557 } 1558 1559 Threads::remove(this, is_daemon); 1560 this->smr_delete(); 1561 } 1562 1563 JavaThread* JavaThread::active() { 1564 Thread* thread = Thread::current(); 1565 if (thread->is_Java_thread()) { 1566 return thread->as_Java_thread(); 1567 } else { 1568 assert(thread->is_VM_thread(), "this must be a vm thread"); 1569 VM_Operation* op = ((VMThread*) thread)->vm_operation(); 1570 JavaThread *ret = op == NULL ? NULL : op->calling_thread()->as_Java_thread(); 1571 return ret; 1572 } 1573 } 1574 1575 bool JavaThread::is_lock_owned(address adr) const { 1576 if (Thread::is_lock_owned(adr)) return true; 1577 1578 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 1579 if (chunk->contains(adr)) return true; 1580 } 1581 1582 return false; 1583 } 1584 1585 oop JavaThread::exception_oop() const { 1586 return Atomic::load(&_exception_oop); 1587 } 1588 1589 void JavaThread::set_exception_oop(oop o) { 1590 Atomic::store(&_exception_oop, o); 1591 } 1592 1593 void JavaThread::add_monitor_chunk(MonitorChunk* chunk) { 1594 chunk->set_next(monitor_chunks()); 1595 set_monitor_chunks(chunk); 1596 } 1597 1598 void JavaThread::remove_monitor_chunk(MonitorChunk* chunk) { 1599 guarantee(monitor_chunks() != NULL, "must be non empty"); 1600 if (monitor_chunks() == chunk) { 1601 set_monitor_chunks(chunk->next()); 1602 } else { 1603 MonitorChunk* prev = monitor_chunks(); 1604 while (prev->next() != chunk) prev = prev->next(); 1605 prev->set_next(chunk->next()); 1606 } 1607 } 1608 1609 1610 // Asynchronous exceptions support 1611 // 1612 // Note: this function shouldn't block if it's called in 1613 // _thread_in_native_trans state (such as from 1614 // check_special_condition_for_native_trans()). 1615 void JavaThread::check_and_handle_async_exceptions() { 1616 if (has_last_Java_frame() && has_async_exception_condition()) { 1617 // If we are at a polling page safepoint (not a poll return) 1618 // then we must defer async exception because live registers 1619 // will be clobbered by the exception path. Poll return is 1620 // ok because the call we a returning from already collides 1621 // with exception handling registers and so there is no issue. 1622 // (The exception handling path kills call result registers but 1623 // this is ok since the exception kills the result anyway). 1624 1625 if (is_at_poll_safepoint()) { 1626 // if the code we are returning to has deoptimized we must defer 1627 // the exception otherwise live registers get clobbered on the 1628 // exception path before deoptimization is able to retrieve them. 1629 // 1630 RegisterMap map(this, false); 1631 frame caller_fr = last_frame().sender(&map); 1632 assert(caller_fr.is_compiled_frame(), "what?"); 1633 if (caller_fr.is_deoptimized_frame()) { 1634 log_info(exceptions)("deferred async exception at compiled safepoint"); 1635 return; 1636 } 1637 } 1638 } 1639 1640 AsyncExceptionCondition condition = clear_async_exception_condition(); 1641 if (condition == _no_async_condition) { 1642 // Conditions have changed since has_special_runtime_exit_condition() 1643 // was called: 1644 // - if we were here only because of an external suspend request, 1645 // then that was taken care of above (or cancelled) so we are done 1646 // - if we were here because of another async request, then it has 1647 // been cleared between the has_special_runtime_exit_condition() 1648 // and now so again we are done 1649 return; 1650 } 1651 1652 // Check for pending async. exception 1653 if (_pending_async_exception != NULL) { 1654 // Only overwrite an already pending exception, if it is not a threadDeath. 1655 if (!has_pending_exception() || !pending_exception()->is_a(vmClasses::ThreadDeath_klass())) { 1656 1657 // We cannot call Exceptions::_throw(...) here because we cannot block 1658 set_pending_exception(_pending_async_exception, __FILE__, __LINE__); 1659 1660 LogTarget(Info, exceptions) lt; 1661 if (lt.is_enabled()) { 1662 ResourceMark rm; 1663 LogStream ls(lt); 1664 ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this)); 1665 if (has_last_Java_frame()) { 1666 frame f = last_frame(); 1667 ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp())); 1668 } 1669 ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name()); 1670 } 1671 _pending_async_exception = NULL; 1672 // Clear condition from _suspend_flags since we have finished processing it. 1673 clear_suspend_flag(_has_async_exception); 1674 } 1675 } 1676 1677 if (condition == _async_unsafe_access_error && !has_pending_exception()) { 1678 // We may be at method entry which requires we save the do-not-unlock flag. 1679 UnlockFlagSaver fs(this); 1680 switch (thread_state()) { 1681 case _thread_in_vm: { 1682 JavaThread* THREAD = this; 1683 Exceptions::throw_unsafe_access_internal_error(THREAD, __FILE__, __LINE__, "a fault occurred in an unsafe memory access operation"); 1684 return; 1685 } 1686 case _thread_in_native: { 1687 ThreadInVMfromNative tiv(this); 1688 JavaThread* THREAD = this; 1689 Exceptions::throw_unsafe_access_internal_error(THREAD, __FILE__, __LINE__, "a fault occurred in an unsafe memory access operation"); 1690 return; 1691 } 1692 case _thread_in_Java: { 1693 ThreadInVMfromJava tiv(this); 1694 JavaThread* THREAD = this; 1695 Exceptions::throw_unsafe_access_internal_error(THREAD, __FILE__, __LINE__, "a fault occurred in a recent unsafe memory access operation in compiled Java code"); 1696 return; 1697 } 1698 default: 1699 ShouldNotReachHere(); 1700 } 1701 } 1702 1703 assert(has_pending_exception(), "must have handled the async condition if no exception"); 1704 } 1705 1706 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) { 1707 1708 if (is_obj_deopt_suspend()) { 1709 frame_anchor()->make_walkable(); 1710 wait_for_object_deoptimization(); 1711 } 1712 1713 // We might be here for reasons in addition to the self-suspend request 1714 // so check for other async requests. 1715 if (check_asyncs) { 1716 check_and_handle_async_exceptions(); 1717 } 1718 1719 JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);) 1720 } 1721 1722 class InstallAsyncExceptionClosure : public HandshakeClosure { 1723 Handle _throwable; // The Throwable thrown at the target Thread 1724 public: 1725 InstallAsyncExceptionClosure(Handle throwable) : HandshakeClosure("InstallAsyncException"), _throwable(throwable) {} 1726 1727 void do_thread(Thread* thr) { 1728 JavaThread* target = thr->as_Java_thread(); 1729 // Note that this now allows multiple ThreadDeath exceptions to be 1730 // thrown at a thread. 1731 // The target thread has run and has not exited yet. 1732 target->send_thread_stop(_throwable()); 1733 } 1734 }; 1735 1736 void JavaThread::send_async_exception(oop java_thread, oop java_throwable) { 1737 Handle throwable(Thread::current(), java_throwable); 1738 JavaThread* target = java_lang_Thread::thread(java_thread); 1739 InstallAsyncExceptionClosure vm_stop(throwable); 1740 Handshake::execute(&vm_stop, target); 1741 } 1742 1743 void JavaThread::send_thread_stop(oop java_throwable) { 1744 ResourceMark rm; 1745 assert(is_handshake_safe_for(Thread::current()), 1746 "should be self or handshakee"); 1747 1748 // Do not throw asynchronous exceptions against the compiler thread 1749 // (the compiler thread should not be a Java thread -- fix in 1.4.2) 1750 if (!can_call_java()) return; 1751 1752 { 1753 // Actually throw the Throwable against the target Thread - however 1754 // only if there is no thread death exception installed already. 1755 if (_pending_async_exception == NULL || !_pending_async_exception->is_a(vmClasses::ThreadDeath_klass())) { 1756 // If the topmost frame is a runtime stub, then we are calling into 1757 // OptoRuntime from compiled code. Some runtime stubs (new, monitor_exit..) 1758 // must deoptimize the caller before continuing, as the compiled exception handler table 1759 // may not be valid 1760 if (has_last_Java_frame()) { 1761 frame f = last_frame(); 1762 if (f.is_runtime_frame() || f.is_safepoint_blob_frame()) { 1763 RegisterMap reg_map(this, false); 1764 frame compiled_frame = f.sender(®_map); 1765 if (!StressCompiledExceptionHandlers && compiled_frame.can_be_deoptimized()) { 1766 Deoptimization::deoptimize(this, compiled_frame); 1767 } 1768 } 1769 } 1770 1771 // Set async. pending exception in thread. 1772 set_pending_async_exception(java_throwable); 1773 1774 if (log_is_enabled(Info, exceptions)) { 1775 ResourceMark rm; 1776 log_info(exceptions)("Pending Async. exception installed of type: %s", 1777 InstanceKlass::cast(_pending_async_exception->klass())->external_name()); 1778 } 1779 // for AbortVMOnException flag 1780 Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name()); 1781 } 1782 } 1783 1784 1785 // Interrupt thread so it will wake up from a potential wait()/sleep()/park() 1786 java_lang_Thread::set_interrupted(threadObj(), true); 1787 this->interrupt(); 1788 } 1789 1790 1791 // External suspension mechanism. 1792 // 1793 // Guarantees on return (for a valid target thread): 1794 // - Target thread will not execute any new bytecode. 1795 // - Target thread will not enter any new monitors. 1796 // 1797 bool JavaThread::java_suspend() { 1798 ThreadsListHandle tlh; 1799 if (!tlh.includes(this)) { 1800 log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, no suspension", p2i(this)); 1801 return false; 1802 } 1803 return this->handshake_state()->suspend(); 1804 } 1805 1806 bool JavaThread::java_resume() { 1807 ThreadsListHandle tlh; 1808 if (!tlh.includes(this)) { 1809 log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, nothing to resume", p2i(this)); 1810 return false; 1811 } 1812 return this->handshake_state()->resume(); 1813 } 1814 1815 // Wait for another thread to perform object reallocation and relocking on behalf of 1816 // this thread. 1817 // Raw thread state transition to _thread_blocked and back again to the original 1818 // state before returning are performed. The current thread is required to 1819 // change to _thread_blocked in order to be seen to be safepoint/handshake safe 1820 // whilst suspended and only after becoming handshake safe, the other thread can 1821 // complete the handshake used to synchronize with this thread and then perform 1822 // the reallocation and relocking. We cannot use the thread state transition 1823 // helpers because we arrive here in various states and also because the helpers 1824 // indirectly call this method. After leaving _thread_blocked we have to check 1825 // for safepoint/handshake, except if _thread_in_native. The thread is safe 1826 // without blocking then. Allowed states are enumerated in 1827 // SafepointSynchronize::block(). See also EscapeBarrier::sync_and_suspend_*() 1828 1829 void JavaThread::wait_for_object_deoptimization() { 1830 assert(!has_last_Java_frame() || frame_anchor()->walkable(), "should have walkable stack"); 1831 assert(this == Thread::current(), "invariant"); 1832 JavaThreadState state = thread_state(); 1833 1834 bool spin_wait = os::is_MP(); 1835 do { 1836 set_thread_state(_thread_blocked); 1837 // Wait for object deoptimization if requested. 1838 if (spin_wait) { 1839 // A single deoptimization is typically very short. Microbenchmarks 1840 // showed 5% better performance when spinning. 1841 const uint spin_limit = 10 * SpinYield::default_spin_limit; 1842 SpinYield spin(spin_limit); 1843 for (uint i = 0; is_obj_deopt_suspend() && i < spin_limit; i++) { 1844 spin.wait(); 1845 } 1846 // Spin just once 1847 spin_wait = false; 1848 } else { 1849 MonitorLocker ml(this, EscapeBarrier_lock, Monitor::_no_safepoint_check_flag); 1850 if (is_obj_deopt_suspend()) { 1851 ml.wait(); 1852 } 1853 } 1854 // The current thread could have been suspended again. We have to check for 1855 // suspend after restoring the saved state. Without this the current thread 1856 // might return to _thread_in_Java and execute bytecode. 1857 set_thread_state_fence(state); 1858 1859 if (state != _thread_in_native) { 1860 SafepointMechanism::process_if_requested(this); 1861 } 1862 // A handshake for obj. deoptimization suspend could have been processed so 1863 // we must check after processing. 1864 } while (is_obj_deopt_suspend()); 1865 } 1866 1867 #ifdef ASSERT 1868 // Verify the JavaThread has not yet been published in the Threads::list, and 1869 // hence doesn't need protection from concurrent access at this stage. 1870 void JavaThread::verify_not_published() { 1871 // Cannot create a ThreadsListHandle here and check !tlh.includes(this) 1872 // since an unpublished JavaThread doesn't participate in the 1873 // Thread-SMR protocol for keeping a ThreadsList alive. 1874 assert(!on_thread_list(), "JavaThread shouldn't have been published yet!"); 1875 } 1876 #endif 1877 1878 // Slow path when the native==>Java barriers detect a safepoint/handshake is 1879 // pending, when _suspend_flags is non-zero or when we need to process a stack 1880 // watermark. Also check for pending async exceptions (except unsafe access error). 1881 // Note only the native==>Java barriers can call this function when thread state 1882 // is _thread_in_native_trans. 1883 void JavaThread::check_special_condition_for_native_trans(JavaThread *thread) { 1884 assert(thread->thread_state() == _thread_in_native_trans, "wrong state"); 1885 assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "Unwalkable stack in native->Java transition"); 1886 1887 // Enable WXWrite: called directly from interpreter native wrapper. 1888 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, thread)); 1889 1890 SafepointMechanism::process_if_requested_with_exit_check(thread, false /* check asyncs */); 1891 1892 // After returning from native, it could be that the stack frames are not 1893 // yet safe to use. We catch such situations in the subsequent stack watermark 1894 // barrier, which will trap unsafe stack frames. 1895 StackWatermarkSet::before_unwind(thread); 1896 1897 if (thread->has_async_exception_condition(false /* check unsafe access error */)) { 1898 // We are in _thread_in_native_trans state, don't handle unsafe 1899 // access error since that may block. 1900 thread->check_and_handle_async_exceptions(); 1901 } 1902 } 1903 1904 #ifndef PRODUCT 1905 // Deoptimization 1906 // Function for testing deoptimization 1907 void JavaThread::deoptimize() { 1908 StackFrameStream fst(this, false /* update */, true /* process_frames */); 1909 bool deopt = false; // Dump stack only if a deopt actually happens. 1910 bool only_at = strlen(DeoptimizeOnlyAt) > 0; 1911 // Iterate over all frames in the thread and deoptimize 1912 for (; !fst.is_done(); fst.next()) { 1913 if (fst.current()->can_be_deoptimized()) { 1914 1915 if (only_at) { 1916 // Deoptimize only at particular bcis. DeoptimizeOnlyAt 1917 // consists of comma or carriage return separated numbers so 1918 // search for the current bci in that string. 1919 address pc = fst.current()->pc(); 1920 nmethod* nm = (nmethod*) fst.current()->cb(); 1921 ScopeDesc* sd = nm->scope_desc_at(pc); 1922 char buffer[8]; 1923 jio_snprintf(buffer, sizeof(buffer), "%d", sd->bci()); 1924 size_t len = strlen(buffer); 1925 const char * found = strstr(DeoptimizeOnlyAt, buffer); 1926 while (found != NULL) { 1927 if ((found[len] == ',' || found[len] == '\n' || found[len] == '\0') && 1928 (found == DeoptimizeOnlyAt || found[-1] == ',' || found[-1] == '\n')) { 1929 // Check that the bci found is bracketed by terminators. 1930 break; 1931 } 1932 found = strstr(found + 1, buffer); 1933 } 1934 if (!found) { 1935 continue; 1936 } 1937 } 1938 1939 if (DebugDeoptimization && !deopt) { 1940 deopt = true; // One-time only print before deopt 1941 tty->print_cr("[BEFORE Deoptimization]"); 1942 trace_frames(); 1943 trace_stack(); 1944 } 1945 Deoptimization::deoptimize(this, *fst.current()); 1946 } 1947 } 1948 1949 if (DebugDeoptimization && deopt) { 1950 tty->print_cr("[AFTER Deoptimization]"); 1951 trace_frames(); 1952 } 1953 } 1954 1955 1956 // Make zombies 1957 void JavaThread::make_zombies() { 1958 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) { 1959 if (fst.current()->can_be_deoptimized()) { 1960 // it is a Java nmethod 1961 nmethod* nm = CodeCache::find_nmethod(fst.current()->pc()); 1962 nm->make_not_entrant(); 1963 } 1964 } 1965 } 1966 #endif // PRODUCT 1967 1968 1969 void JavaThread::deoptimize_marked_methods() { 1970 if (!has_last_Java_frame()) return; 1971 StackFrameStream fst(this, false /* update */, true /* process_frames */); 1972 for (; !fst.is_done(); fst.next()) { 1973 if (fst.current()->should_be_deoptimized()) { 1974 Deoptimization::deoptimize(this, *fst.current()); 1975 } 1976 } 1977 } 1978 1979 #ifdef ASSERT 1980 void JavaThread::verify_frame_info() { 1981 assert((!has_last_Java_frame() && java_call_counter() == 0) || 1982 (has_last_Java_frame() && java_call_counter() > 0), 1983 "unexpected frame info: has_last_frame=%s, java_call_counter=%d", 1984 has_last_Java_frame() ? "true" : "false", java_call_counter()); 1985 } 1986 #endif 1987 1988 void JavaThread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) { 1989 // Verify that the deferred card marks have been flushed. 1990 assert(deferred_card_mark().is_empty(), "Should be empty during GC"); 1991 1992 // Traverse the GCHandles 1993 Thread::oops_do_no_frames(f, cf); 1994 1995 DEBUG_ONLY(verify_frame_info();) 1996 1997 if (has_last_Java_frame()) { 1998 // Traverse the monitor chunks 1999 for (MonitorChunk* chunk = monitor_chunks(); chunk != NULL; chunk = chunk->next()) { 2000 chunk->oops_do(f); 2001 } 2002 } 2003 2004 assert(vframe_array_head() == NULL, "deopt in progress at a safepoint!"); 2005 // If we have deferred set_locals there might be oops waiting to be 2006 // written 2007 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(this); 2008 if (list != NULL) { 2009 for (int i = 0; i < list->length(); i++) { 2010 list->at(i)->oops_do(f); 2011 } 2012 } 2013 2014 // Traverse instance variables at the end since the GC may be moving things 2015 // around using this function 2016 f->do_oop((oop*) &_vm_result); 2017 f->do_oop((oop*) &_exception_oop); 2018 f->do_oop((oop*) &_pending_async_exception); 2019 #if INCLUDE_JVMCI 2020 f->do_oop((oop*) &_jvmci_reserved_oop0); 2021 #endif 2022 2023 if (jvmti_thread_state() != NULL) { 2024 jvmti_thread_state()->oops_do(f, cf); 2025 } 2026 } 2027 2028 void JavaThread::oops_do_frames(OopClosure* f, CodeBlobClosure* cf) { 2029 if (!has_last_Java_frame()) { 2030 return; 2031 } 2032 // Finish any pending lazy GC activity for the frames 2033 StackWatermarkSet::finish_processing(this, NULL /* context */, StackWatermarkKind::gc); 2034 // Traverse the execution stack 2035 for (StackFrameStream fst(this, true /* update */, false /* process_frames */); !fst.is_done(); fst.next()) { 2036 fst.current()->oops_do(f, cf, fst.register_map()); 2037 } 2038 } 2039 2040 #ifdef ASSERT 2041 void JavaThread::verify_states_for_handshake() { 2042 // This checks that the thread has a correct frame state during a handshake. 2043 verify_frame_info(); 2044 } 2045 #endif 2046 2047 void JavaThread::nmethods_do(CodeBlobClosure* cf) { 2048 DEBUG_ONLY(verify_frame_info();) 2049 2050 if (has_last_Java_frame()) { 2051 // Traverse the execution stack 2052 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) { 2053 fst.current()->nmethods_do(cf); 2054 } 2055 } 2056 2057 if (jvmti_thread_state() != NULL) { 2058 jvmti_thread_state()->nmethods_do(cf); 2059 } 2060 } 2061 2062 void JavaThread::metadata_do(MetadataClosure* f) { 2063 if (has_last_Java_frame()) { 2064 // Traverse the execution stack to call f() on the methods in the stack 2065 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) { 2066 fst.current()->metadata_do(f); 2067 } 2068 } else if (is_Compiler_thread()) { 2069 // need to walk ciMetadata in current compile tasks to keep alive. 2070 CompilerThread* ct = (CompilerThread*)this; 2071 if (ct->env() != NULL) { 2072 ct->env()->metadata_do(f); 2073 } 2074 CompileTask* task = ct->task(); 2075 if (task != NULL) { 2076 task->metadata_do(f); 2077 } 2078 } 2079 } 2080 2081 // Printing 2082 const char* _get_thread_state_name(JavaThreadState _thread_state) { 2083 switch (_thread_state) { 2084 case _thread_uninitialized: return "_thread_uninitialized"; 2085 case _thread_new: return "_thread_new"; 2086 case _thread_new_trans: return "_thread_new_trans"; 2087 case _thread_in_native: return "_thread_in_native"; 2088 case _thread_in_native_trans: return "_thread_in_native_trans"; 2089 case _thread_in_vm: return "_thread_in_vm"; 2090 case _thread_in_vm_trans: return "_thread_in_vm_trans"; 2091 case _thread_in_Java: return "_thread_in_Java"; 2092 case _thread_in_Java_trans: return "_thread_in_Java_trans"; 2093 case _thread_blocked: return "_thread_blocked"; 2094 case _thread_blocked_trans: return "_thread_blocked_trans"; 2095 default: return "unknown thread state"; 2096 } 2097 } 2098 2099 #ifndef PRODUCT 2100 void JavaThread::print_thread_state_on(outputStream *st) const { 2101 st->print_cr(" JavaThread state: %s", _get_thread_state_name(_thread_state)); 2102 }; 2103 #endif // PRODUCT 2104 2105 // Called by Threads::print() for VM_PrintThreads operation 2106 void JavaThread::print_on(outputStream *st, bool print_extended_info) const { 2107 st->print_raw("\""); 2108 st->print_raw(get_thread_name()); 2109 st->print_raw("\" "); 2110 oop thread_oop = threadObj(); 2111 if (thread_oop != NULL) { 2112 st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop)); 2113 if (java_lang_Thread::is_daemon(thread_oop)) st->print("daemon "); 2114 st->print("prio=%d ", java_lang_Thread::priority(thread_oop)); 2115 } 2116 Thread::print_on(st, print_extended_info); 2117 // print guess for valid stack memory region (assume 4K pages); helps lock debugging 2118 st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12)); 2119 if (thread_oop != NULL) { 2120 st->print_cr(" java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop)); 2121 } 2122 #ifndef PRODUCT 2123 _safepoint_state->print_on(st); 2124 #endif // PRODUCT 2125 if (is_Compiler_thread()) { 2126 CompileTask *task = ((CompilerThread*)this)->task(); 2127 if (task != NULL) { 2128 st->print(" Compiling: "); 2129 task->print(st, NULL, true, false); 2130 } else { 2131 st->print(" No compile task"); 2132 } 2133 st->cr(); 2134 } 2135 } 2136 2137 void JavaThread::print() const { print_on(tty); } 2138 2139 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const { 2140 st->print("%s", get_thread_name_string(buf, buflen)); 2141 } 2142 2143 // Called by fatal error handler. The difference between this and 2144 // JavaThread::print() is that we can't grab lock or allocate memory. 2145 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const { 2146 st->print("JavaThread \"%s\"", get_thread_name_string(buf, buflen)); 2147 oop thread_obj = threadObj(); 2148 if (thread_obj != NULL) { 2149 if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon"); 2150 } 2151 st->print(" ["); 2152 st->print("%s", _get_thread_state_name(_thread_state)); 2153 if (osthread()) { 2154 st->print(", id=%d", osthread()->thread_id()); 2155 } 2156 st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")", 2157 p2i(stack_end()), p2i(stack_base())); 2158 st->print("]"); 2159 2160 ThreadsSMRSupport::print_info_on(this, st); 2161 return; 2162 } 2163 2164 2165 // Verification 2166 2167 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) { 2168 // ignore if there is no stack 2169 if (!has_last_Java_frame()) return; 2170 // traverse the stack frames. Starts from top frame. 2171 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) { 2172 frame* fr = fst.current(); 2173 f(fr, fst.register_map()); 2174 } 2175 } 2176 2177 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); } 2178 2179 void JavaThread::verify() { 2180 // Verify oops in the thread. 2181 oops_do(&VerifyOopClosure::verify_oop, NULL); 2182 2183 // Verify the stack frames. 2184 frames_do(frame_verify); 2185 } 2186 2187 // CR 6300358 (sub-CR 2137150) 2188 // Most callers of this method assume that it can't return NULL but a 2189 // thread may not have a name whilst it is in the process of attaching to 2190 // the VM - see CR 6412693, and there are places where a JavaThread can be 2191 // seen prior to having its threadObj set (e.g., JNI attaching threads and 2192 // if vm exit occurs during initialization). These cases can all be accounted 2193 // for such that this method never returns NULL. 2194 const char* JavaThread::get_thread_name() const { 2195 if (Thread::is_JavaThread_protected(this)) { 2196 // The target JavaThread is protected so get_thread_name_string() is safe: 2197 return get_thread_name_string(); 2198 } 2199 2200 // The target JavaThread is not protected so we return the default: 2201 return Thread::name(); 2202 } 2203 2204 // Returns a non-NULL representation of this thread's name, or a suitable 2205 // descriptive string if there is no set name. 2206 const char* JavaThread::get_thread_name_string(char* buf, int buflen) const { 2207 const char* name_str; 2208 oop thread_obj = threadObj(); 2209 if (thread_obj != NULL) { 2210 oop name = java_lang_Thread::name(thread_obj); 2211 if (name != NULL) { 2212 if (buf == NULL) { 2213 name_str = java_lang_String::as_utf8_string(name); 2214 } else { 2215 name_str = java_lang_String::as_utf8_string(name, buf, buflen); 2216 } 2217 } else if (is_attaching_via_jni()) { // workaround for 6412693 - see 6404306 2218 name_str = "<no-name - thread is attaching>"; 2219 } else { 2220 name_str = Thread::name(); 2221 } 2222 } else { 2223 name_str = Thread::name(); 2224 } 2225 assert(name_str != NULL, "unexpected NULL thread name"); 2226 return name_str; 2227 } 2228 2229 // Helper to extract the name from the thread oop for logging. 2230 const char* JavaThread::name_for(oop thread_obj) { 2231 assert(thread_obj != NULL, "precondition"); 2232 oop name = java_lang_Thread::name(thread_obj); 2233 const char* name_str; 2234 if (name != NULL) { 2235 name_str = java_lang_String::as_utf8_string(name); 2236 } else { 2237 name_str = "<un-named>"; 2238 } 2239 return name_str; 2240 } 2241 2242 void JavaThread::prepare(jobject jni_thread, ThreadPriority prio) { 2243 2244 assert(Threads_lock->owner() == Thread::current(), "must have threads lock"); 2245 assert(NoPriority <= prio && prio <= MaxPriority, "sanity check"); 2246 // Link Java Thread object <-> C++ Thread 2247 2248 // Get the C++ thread object (an oop) from the JNI handle (a jthread) 2249 // and put it into a new Handle. The Handle "thread_oop" can then 2250 // be used to pass the C++ thread object to other methods. 2251 2252 // Set the Java level thread object (jthread) field of the 2253 // new thread (a JavaThread *) to C++ thread object using the 2254 // "thread_oop" handle. 2255 2256 // Set the thread field (a JavaThread *) of the 2257 // oop representing the java_lang_Thread to the new thread (a JavaThread *). 2258 2259 Handle thread_oop(Thread::current(), 2260 JNIHandles::resolve_non_null(jni_thread)); 2261 assert(InstanceKlass::cast(thread_oop->klass())->is_linked(), 2262 "must be initialized"); 2263 set_threadObj(thread_oop()); 2264 2265 if (prio == NoPriority) { 2266 prio = java_lang_Thread::priority(thread_oop()); 2267 assert(prio != NoPriority, "A valid priority should be present"); 2268 } 2269 2270 // Push the Java priority down to the native thread; needs Threads_lock 2271 Thread::set_priority(this, prio); 2272 2273 // Add the new thread to the Threads list and set it in motion. 2274 // We must have threads lock in order to call Threads::add. 2275 // It is crucial that we do not block before the thread is 2276 // added to the Threads list for if a GC happens, then the java_thread oop 2277 // will not be visited by GC. 2278 Threads::add(this); 2279 // Publish the JavaThread* in java.lang.Thread after the JavaThread* is 2280 // on a ThreadsList. We don't want to wait for the release when the 2281 // Theads_lock is dropped somewhere in the caller since the JavaThread* 2282 // is already visible to JVM/TI via the ThreadsList. 2283 java_lang_Thread::release_set_thread(thread_oop(), this); 2284 } 2285 2286 oop JavaThread::current_park_blocker() { 2287 // Support for JSR-166 locks 2288 oop thread_oop = threadObj(); 2289 if (thread_oop != NULL) { 2290 return java_lang_Thread::park_blocker(thread_oop); 2291 } 2292 return NULL; 2293 } 2294 2295 // Print current stack trace for checked JNI warnings and JNI fatal errors. 2296 // This is the external format, selecting the platform 2297 // as applicable, and allowing for a native-only stack. 2298 void JavaThread::print_jni_stack() { 2299 assert(this == JavaThread::current(), "Can't print stack of other threads"); 2300 if (!has_last_Java_frame()) { 2301 ResourceMark rm(this); 2302 char* buf = NEW_RESOURCE_ARRAY_RETURN_NULL(char, O_BUFLEN); 2303 if (buf == nullptr) { 2304 tty->print_cr("Unable to print native stack - out of memory"); 2305 return; 2306 } 2307 frame f = os::current_frame(); 2308 VMError::print_native_stack(tty, f, this, 2309 buf, O_BUFLEN); 2310 } else { 2311 print_stack_on(tty); 2312 } 2313 } 2314 2315 void JavaThread::print_stack_on(outputStream* st) { 2316 if (!has_last_Java_frame()) return; 2317 2318 Thread* current_thread = Thread::current(); 2319 ResourceMark rm(current_thread); 2320 HandleMark hm(current_thread); 2321 2322 RegisterMap reg_map(this); 2323 vframe* start_vf = last_java_vframe(®_map); 2324 int count = 0; 2325 for (vframe* f = start_vf; f != NULL; f = f->sender()) { 2326 if (f->is_java_frame()) { 2327 javaVFrame* jvf = javaVFrame::cast(f); 2328 java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci()); 2329 2330 // Print out lock information 2331 if (JavaMonitorsInStackTrace) { 2332 jvf->print_lock_info_on(st, count); 2333 } 2334 } else { 2335 // Ignore non-Java frames 2336 } 2337 2338 // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0 2339 count++; 2340 if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return; 2341 } 2342 } 2343 2344 2345 // JVMTI PopFrame support 2346 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) { 2347 assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments"); 2348 if (in_bytes(size_in_bytes) != 0) { 2349 _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread); 2350 _popframe_preserved_args_size = in_bytes(size_in_bytes); 2351 Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size); 2352 } 2353 } 2354 2355 void* JavaThread::popframe_preserved_args() { 2356 return _popframe_preserved_args; 2357 } 2358 2359 ByteSize JavaThread::popframe_preserved_args_size() { 2360 return in_ByteSize(_popframe_preserved_args_size); 2361 } 2362 2363 WordSize JavaThread::popframe_preserved_args_size_in_words() { 2364 int sz = in_bytes(popframe_preserved_args_size()); 2365 assert(sz % wordSize == 0, "argument size must be multiple of wordSize"); 2366 return in_WordSize(sz / wordSize); 2367 } 2368 2369 void JavaThread::popframe_free_preserved_args() { 2370 assert(_popframe_preserved_args != NULL, "should not free PopFrame preserved arguments twice"); 2371 FREE_C_HEAP_ARRAY(char, (char*)_popframe_preserved_args); 2372 _popframe_preserved_args = NULL; 2373 _popframe_preserved_args_size = 0; 2374 } 2375 2376 #ifndef PRODUCT 2377 2378 void JavaThread::trace_frames() { 2379 tty->print_cr("[Describe stack]"); 2380 int frame_no = 1; 2381 for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) { 2382 tty->print(" %d. ", frame_no++); 2383 fst.current()->print_value_on(tty, this); 2384 tty->cr(); 2385 } 2386 } 2387 2388 class PrintAndVerifyOopClosure: public OopClosure { 2389 protected: 2390 template <class T> inline void do_oop_work(T* p) { 2391 oop obj = RawAccess<>::oop_load(p); 2392 if (obj == NULL) return; 2393 tty->print(INTPTR_FORMAT ": ", p2i(p)); 2394 if (oopDesc::is_oop_or_null(obj)) { 2395 if (obj->is_objArray()) { 2396 tty->print_cr("valid objArray: " INTPTR_FORMAT, p2i(obj)); 2397 } else { 2398 obj->print(); 2399 } 2400 } else { 2401 tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj)); 2402 } 2403 tty->cr(); 2404 } 2405 public: 2406 virtual void do_oop(oop* p) { do_oop_work(p); } 2407 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 2408 }; 2409 2410 #ifdef ASSERT 2411 // Print or validate the layout of stack frames 2412 void JavaThread::print_frame_layout(int depth, bool validate_only) { 2413 ResourceMark rm; 2414 PreserveExceptionMark pm(this); 2415 FrameValues values; 2416 int frame_no = 0; 2417 for (StackFrameStream fst(this, false /* update */, true /* process_frames */); !fst.is_done(); fst.next()) { 2418 fst.current()->describe(values, ++frame_no); 2419 if (depth == frame_no) break; 2420 } 2421 if (validate_only) { 2422 values.validate(); 2423 } else { 2424 tty->print_cr("[Describe stack layout]"); 2425 values.print(this); 2426 } 2427 } 2428 #endif 2429 2430 void JavaThread::trace_stack_from(vframe* start_vf) { 2431 ResourceMark rm; 2432 int vframe_no = 1; 2433 for (vframe* f = start_vf; f; f = f->sender()) { 2434 if (f->is_java_frame()) { 2435 javaVFrame::cast(f)->print_activation(vframe_no++); 2436 } else { 2437 f->print(); 2438 } 2439 if (vframe_no > StackPrintLimit) { 2440 tty->print_cr("...<more frames>..."); 2441 return; 2442 } 2443 } 2444 } 2445 2446 2447 void JavaThread::trace_stack() { 2448 if (!has_last_Java_frame()) return; 2449 Thread* current_thread = Thread::current(); 2450 ResourceMark rm(current_thread); 2451 HandleMark hm(current_thread); 2452 RegisterMap reg_map(this); 2453 trace_stack_from(last_java_vframe(®_map)); 2454 } 2455 2456 2457 #endif // PRODUCT 2458 2459 2460 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) { 2461 assert(reg_map != NULL, "a map must be given"); 2462 frame f = last_frame(); 2463 for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) { 2464 if (vf->is_java_frame()) return javaVFrame::cast(vf); 2465 } 2466 return NULL; 2467 } 2468 2469 2470 Klass* JavaThread::security_get_caller_class(int depth) { 2471 vframeStream vfst(this); 2472 vfst.security_get_caller_frame(depth); 2473 if (!vfst.at_end()) { 2474 return vfst.method()->method_holder(); 2475 } 2476 return NULL; 2477 } 2478 2479 // java.lang.Thread.sleep support 2480 // Returns true if sleep time elapsed as expected, and false 2481 // if the thread was interrupted. 2482 bool JavaThread::sleep(jlong millis) { 2483 assert(this == Thread::current(), "thread consistency check"); 2484 2485 ParkEvent * const slp = this->_SleepEvent; 2486 // Because there can be races with thread interruption sending an unpark() 2487 // to the event, we explicitly reset it here to avoid an immediate return. 2488 // The actual interrupt state will be checked before we park(). 2489 slp->reset(); 2490 // Thread interruption establishes a happens-before ordering in the 2491 // Java Memory Model, so we need to ensure we synchronize with the 2492 // interrupt state. 2493 OrderAccess::fence(); 2494 2495 jlong prevtime = os::javaTimeNanos(); 2496 2497 for (;;) { 2498 // interruption has precedence over timing out 2499 if (this->is_interrupted(true)) { 2500 return false; 2501 } 2502 2503 if (millis <= 0) { 2504 return true; 2505 } 2506 2507 { 2508 ThreadBlockInVM tbivm(this); 2509 OSThreadWaitState osts(this->osthread(), false /* not Object.wait() */); 2510 slp->park(millis); 2511 } 2512 2513 // Update elapsed time tracking 2514 jlong newtime = os::javaTimeNanos(); 2515 if (newtime - prevtime < 0) { 2516 // time moving backwards, should only happen if no monotonic clock 2517 // not a guarantee() because JVM should not abort on kernel/glibc bugs 2518 assert(false, 2519 "unexpected time moving backwards detected in JavaThread::sleep()"); 2520 } else { 2521 millis -= (newtime - prevtime) / NANOSECS_PER_MILLISEC; 2522 } 2523 prevtime = newtime; 2524 } 2525 } 2526 2527 2528 // ======= Threads ======== 2529 2530 // The Threads class links together all active threads, and provides 2531 // operations over all threads. It is protected by the Threads_lock, 2532 // which is also used in other global contexts like safepointing. 2533 // ThreadsListHandles are used to safely perform operations on one 2534 // or more threads without the risk of the thread exiting during the 2535 // operation. 2536 // 2537 // Note: The Threads_lock is currently more widely used than we 2538 // would like. We are actively migrating Threads_lock uses to other 2539 // mechanisms in order to reduce Threads_lock contention. 2540 2541 int Threads::_number_of_threads = 0; 2542 int Threads::_number_of_non_daemon_threads = 0; 2543 int Threads::_return_code = 0; 2544 uintx Threads::_thread_claim_token = 1; // Never zero. 2545 size_t JavaThread::_stack_size_at_create = 0; 2546 2547 #ifdef ASSERT 2548 bool Threads::_vm_complete = false; 2549 #endif 2550 2551 static inline void *prefetch_and_load_ptr(void **addr, intx prefetch_interval) { 2552 Prefetch::read((void*)addr, prefetch_interval); 2553 return *addr; 2554 } 2555 2556 // Possibly the ugliest for loop the world has seen. C++ does not allow 2557 // multiple types in the declaration section of the for loop. In this case 2558 // we are only dealing with pointers and hence can cast them. It looks ugly 2559 // but macros are ugly and therefore it's fine to make things absurdly ugly. 2560 #define DO_JAVA_THREADS(LIST, X) \ 2561 for (JavaThread *MACRO_scan_interval = (JavaThread*)(uintptr_t)PrefetchScanIntervalInBytes, \ 2562 *MACRO_list = (JavaThread*)(LIST), \ 2563 **MACRO_end = ((JavaThread**)((ThreadsList*)MACRO_list)->threads()) + ((ThreadsList*)MACRO_list)->length(), \ 2564 **MACRO_current_p = (JavaThread**)((ThreadsList*)MACRO_list)->threads(), \ 2565 *X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval); \ 2566 MACRO_current_p != MACRO_end; \ 2567 MACRO_current_p++, \ 2568 X = (JavaThread*)prefetch_and_load_ptr((void**)MACRO_current_p, (intx)MACRO_scan_interval)) 2569 2570 // All JavaThreads 2571 #define ALL_JAVA_THREADS(X) DO_JAVA_THREADS(ThreadsSMRSupport::get_java_thread_list(), X) 2572 2573 // All NonJavaThreads (i.e., every non-JavaThread in the system). 2574 void Threads::non_java_threads_do(ThreadClosure* tc) { 2575 NoSafepointVerifier nsv; 2576 for (NonJavaThread::Iterator njti; !njti.end(); njti.step()) { 2577 tc->do_thread(njti.current()); 2578 } 2579 } 2580 2581 // All JavaThreads 2582 void Threads::java_threads_do(ThreadClosure* tc) { 2583 assert_locked_or_safepoint(Threads_lock); 2584 // ALL_JAVA_THREADS iterates through all JavaThreads. 2585 ALL_JAVA_THREADS(p) { 2586 tc->do_thread(p); 2587 } 2588 } 2589 2590 void Threads::java_threads_and_vm_thread_do(ThreadClosure* tc) { 2591 assert_locked_or_safepoint(Threads_lock); 2592 java_threads_do(tc); 2593 tc->do_thread(VMThread::vm_thread()); 2594 } 2595 2596 // All JavaThreads + all non-JavaThreads (i.e., every thread in the system). 2597 void Threads::threads_do(ThreadClosure* tc) { 2598 assert_locked_or_safepoint(Threads_lock); 2599 java_threads_do(tc); 2600 non_java_threads_do(tc); 2601 } 2602 2603 void Threads::possibly_parallel_threads_do(bool is_par, ThreadClosure* tc) { 2604 uintx claim_token = Threads::thread_claim_token(); 2605 ALL_JAVA_THREADS(p) { 2606 if (p->claim_threads_do(is_par, claim_token)) { 2607 tc->do_thread(p); 2608 } 2609 } 2610 VMThread* vmt = VMThread::vm_thread(); 2611 if (vmt->claim_threads_do(is_par, claim_token)) { 2612 tc->do_thread(vmt); 2613 } 2614 } 2615 2616 // The system initialization in the library has three phases. 2617 // 2618 // Phase 1: java.lang.System class initialization 2619 // java.lang.System is a primordial class loaded and initialized 2620 // by the VM early during startup. java.lang.System.<clinit> 2621 // only does registerNatives and keeps the rest of the class 2622 // initialization work later until thread initialization completes. 2623 // 2624 // System.initPhase1 initializes the system properties, the static 2625 // fields in, out, and err. Set up java signal handlers, OS-specific 2626 // system settings, and thread group of the main thread. 2627 static void call_initPhase1(TRAPS) { 2628 Klass* klass = vmClasses::System_klass(); 2629 JavaValue result(T_VOID); 2630 JavaCalls::call_static(&result, klass, vmSymbols::initPhase1_name(), 2631 vmSymbols::void_method_signature(), CHECK); 2632 } 2633 2634 // Phase 2. Module system initialization 2635 // This will initialize the module system. Only java.base classes 2636 // can be loaded until phase 2 completes. 2637 // 2638 // Call System.initPhase2 after the compiler initialization and jsr292 2639 // classes get initialized because module initialization runs a lot of java 2640 // code, that for performance reasons, should be compiled. Also, this will 2641 // enable the startup code to use lambda and other language features in this 2642 // phase and onward. 2643 // 2644 // After phase 2, The VM will begin search classes from -Xbootclasspath/a. 2645 static void call_initPhase2(TRAPS) { 2646 TraceTime timer("Initialize module system", TRACETIME_LOG(Info, startuptime)); 2647 2648 Klass* klass = vmClasses::System_klass(); 2649 2650 JavaValue result(T_INT); 2651 JavaCallArguments args; 2652 args.push_int(DisplayVMOutputToStderr); 2653 args.push_int(log_is_enabled(Debug, init)); // print stack trace if exception thrown 2654 JavaCalls::call_static(&result, klass, vmSymbols::initPhase2_name(), 2655 vmSymbols::boolean_boolean_int_signature(), &args, CHECK); 2656 if (result.get_jint() != JNI_OK) { 2657 vm_exit_during_initialization(); // no message or exception 2658 } 2659 2660 universe_post_module_init(); 2661 } 2662 2663 // Phase 3. final setup - set security manager, system class loader and TCCL 2664 // 2665 // This will instantiate and set the security manager, set the system class 2666 // loader as well as the thread context class loader. The security manager 2667 // and system class loader may be a custom class loaded from -Xbootclasspath/a, 2668 // other modules or the application's classpath. 2669 static void call_initPhase3(TRAPS) { 2670 Klass* klass = vmClasses::System_klass(); 2671 JavaValue result(T_VOID); 2672 JavaCalls::call_static(&result, klass, vmSymbols::initPhase3_name(), 2673 vmSymbols::void_method_signature(), CHECK); 2674 } 2675 2676 void Threads::initialize_java_lang_classes(JavaThread* main_thread, TRAPS) { 2677 TraceTime timer("Initialize java.lang classes", TRACETIME_LOG(Info, startuptime)); 2678 2679 if (EagerXrunInit && Arguments::init_libraries_at_startup()) { 2680 create_vm_init_libraries(); 2681 } 2682 2683 initialize_class(vmSymbols::java_lang_String(), CHECK); 2684 2685 // Inject CompactStrings value after the static initializers for String ran. 2686 java_lang_String::set_compact_strings(CompactStrings); 2687 2688 // Initialize java_lang.System (needed before creating the thread) 2689 initialize_class(vmSymbols::java_lang_System(), CHECK); 2690 // The VM creates & returns objects of this class. Make sure it's initialized. 2691 initialize_class(vmSymbols::java_lang_Class(), CHECK); 2692 initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK); 2693 Handle thread_group = create_initial_thread_group(CHECK); 2694 Universe::set_main_thread_group(thread_group()); 2695 initialize_class(vmSymbols::java_lang_Thread(), CHECK); 2696 create_initial_thread(thread_group, main_thread, CHECK); 2697 2698 // The VM creates objects of this class. 2699 initialize_class(vmSymbols::java_lang_Module(), CHECK); 2700 2701 #ifdef ASSERT 2702 InstanceKlass *k = vmClasses::UnsafeConstants_klass(); 2703 assert(k->is_not_initialized(), "UnsafeConstants should not already be initialized"); 2704 #endif 2705 2706 // initialize the hardware-specific constants needed by Unsafe 2707 initialize_class(vmSymbols::jdk_internal_misc_UnsafeConstants(), CHECK); 2708 jdk_internal_misc_UnsafeConstants::set_unsafe_constants(); 2709 2710 // The VM preresolves methods to these classes. Make sure that they get initialized 2711 initialize_class(vmSymbols::java_lang_reflect_Method(), CHECK); 2712 initialize_class(vmSymbols::java_lang_ref_Finalizer(), CHECK); 2713 2714 // Phase 1 of the system initialization in the library, java.lang.System class initialization 2715 call_initPhase1(CHECK); 2716 2717 // Get the Java runtime name, version, and vendor info after java.lang.System is initialized. 2718 // Some values are actually configure-time constants but some can be set via the jlink tool and 2719 // so must be read dynamically. We treat them all the same. 2720 InstanceKlass* ik = SystemDictionary::find_instance_klass(vmSymbols::java_lang_VersionProps(), 2721 Handle(), Handle()); 2722 { 2723 ResourceMark rm(main_thread); 2724 JDK_Version::set_java_version(get_java_version_info(ik, vmSymbols::java_version_name())); 2725 2726 JDK_Version::set_runtime_name(get_java_version_info(ik, vmSymbols::java_runtime_name_name())); 2727 2728 JDK_Version::set_runtime_version(get_java_version_info(ik, vmSymbols::java_runtime_version_name())); 2729 2730 JDK_Version::set_runtime_vendor_version(get_java_version_info(ik, vmSymbols::java_runtime_vendor_version_name())); 2731 2732 JDK_Version::set_runtime_vendor_vm_bug_url(get_java_version_info(ik, vmSymbols::java_runtime_vendor_vm_bug_url_name())); 2733 } 2734 2735 // an instance of OutOfMemory exception has been allocated earlier 2736 initialize_class(vmSymbols::java_lang_OutOfMemoryError(), CHECK); 2737 initialize_class(vmSymbols::java_lang_NullPointerException(), CHECK); 2738 initialize_class(vmSymbols::java_lang_ClassCastException(), CHECK); 2739 initialize_class(vmSymbols::java_lang_ArrayStoreException(), CHECK); 2740 initialize_class(vmSymbols::java_lang_ArithmeticException(), CHECK); 2741 initialize_class(vmSymbols::java_lang_StackOverflowError(), CHECK); 2742 initialize_class(vmSymbols::java_lang_IllegalMonitorStateException(), CHECK); 2743 initialize_class(vmSymbols::java_lang_IllegalArgumentException(), CHECK); 2744 } 2745 2746 void Threads::initialize_jsr292_core_classes(TRAPS) { 2747 TraceTime timer("Initialize java.lang.invoke classes", TRACETIME_LOG(Info, startuptime)); 2748 2749 initialize_class(vmSymbols::java_lang_invoke_MethodHandle(), CHECK); 2750 initialize_class(vmSymbols::java_lang_invoke_ResolvedMethodName(), CHECK); 2751 initialize_class(vmSymbols::java_lang_invoke_MemberName(), CHECK); 2752 initialize_class(vmSymbols::java_lang_invoke_MethodHandleNatives(), CHECK); 2753 } 2754 2755 jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { 2756 extern void JDK_Version_init(); 2757 2758 // Preinitialize version info. 2759 VM_Version::early_initialize(); 2760 2761 // Check version 2762 if (!is_supported_jni_version(args->version)) return JNI_EVERSION; 2763 2764 // Initialize library-based TLS 2765 ThreadLocalStorage::init(); 2766 2767 // Initialize the output stream module 2768 ostream_init(); 2769 2770 // Process java launcher properties. 2771 Arguments::process_sun_java_launcher_properties(args); 2772 2773 // Initialize the os module 2774 os::init(); 2775 2776 MACOS_AARCH64_ONLY(os::current_thread_enable_wx(WXWrite)); 2777 2778 // Record VM creation timing statistics 2779 TraceVmCreationTime create_vm_timer; 2780 create_vm_timer.start(); 2781 2782 // Initialize system properties. 2783 Arguments::init_system_properties(); 2784 2785 // So that JDK version can be used as a discriminator when parsing arguments 2786 JDK_Version_init(); 2787 2788 // Update/Initialize System properties after JDK version number is known 2789 Arguments::init_version_specific_system_properties(); 2790 2791 // Make sure to initialize log configuration *before* parsing arguments 2792 LogConfiguration::initialize(create_vm_timer.begin_time()); 2793 2794 // Parse arguments 2795 // Note: this internally calls os::init_container_support() 2796 jint parse_result = Arguments::parse(args); 2797 if (parse_result != JNI_OK) return parse_result; 2798 2799 #if INCLUDE_NMT 2800 // Initialize NMT right after argument parsing to keep the pre-NMT-init window small. 2801 MemTracker::initialize(); 2802 #endif // INCLUDE_NMT 2803 2804 os::init_before_ergo(); 2805 2806 jint ergo_result = Arguments::apply_ergo(); 2807 if (ergo_result != JNI_OK) return ergo_result; 2808 2809 // Final check of all ranges after ergonomics which may change values. 2810 if (!JVMFlagLimit::check_all_ranges()) { 2811 return JNI_EINVAL; 2812 } 2813 2814 // Final check of all 'AfterErgo' constraints after ergonomics which may change values. 2815 bool constraint_result = JVMFlagLimit::check_all_constraints(JVMFlagConstraintPhase::AfterErgo); 2816 if (!constraint_result) { 2817 return JNI_EINVAL; 2818 } 2819 2820 if (PauseAtStartup) { 2821 os::pause(); 2822 } 2823 2824 HOTSPOT_VM_INIT_BEGIN(); 2825 2826 // Timing (must come after argument parsing) 2827 TraceTime timer("Create VM", TRACETIME_LOG(Info, startuptime)); 2828 2829 // Initialize the os module after parsing the args 2830 jint os_init_2_result = os::init_2(); 2831 if (os_init_2_result != JNI_OK) return os_init_2_result; 2832 2833 #ifdef CAN_SHOW_REGISTERS_ON_ASSERT 2834 // Initialize assert poison page mechanism. 2835 if (ShowRegistersOnAssert) { 2836 initialize_assert_poison(); 2837 } 2838 #endif // CAN_SHOW_REGISTERS_ON_ASSERT 2839 2840 SafepointMechanism::initialize(); 2841 2842 jint adjust_after_os_result = Arguments::adjust_after_os(); 2843 if (adjust_after_os_result != JNI_OK) return adjust_after_os_result; 2844 2845 // Initialize output stream logging 2846 ostream_init_log(); 2847 2848 // Convert -Xrun to -agentlib: if there is no JVM_OnLoad 2849 // Must be before create_vm_init_agents() 2850 if (Arguments::init_libraries_at_startup()) { 2851 convert_vm_init_libraries_to_agents(); 2852 } 2853 2854 // Launch -agentlib/-agentpath and converted -Xrun agents 2855 if (Arguments::init_agents_at_startup()) { 2856 create_vm_init_agents(); 2857 } 2858 2859 // Initialize Threads state 2860 _number_of_threads = 0; 2861 _number_of_non_daemon_threads = 0; 2862 2863 // Initialize global data structures and create system classes in heap 2864 vm_init_globals(); 2865 2866 #if INCLUDE_JVMCI 2867 if (JVMCICounterSize > 0) { 2868 JavaThread::_jvmci_old_thread_counters = NEW_C_HEAP_ARRAY(jlong, JVMCICounterSize, mtJVMCI); 2869 memset(JavaThread::_jvmci_old_thread_counters, 0, sizeof(jlong) * JVMCICounterSize); 2870 } else { 2871 JavaThread::_jvmci_old_thread_counters = NULL; 2872 } 2873 #endif // INCLUDE_JVMCI 2874 2875 // Initialize OopStorage for threadObj 2876 _thread_oop_storage = OopStorageSet::create_strong("Thread OopStorage", mtThread); 2877 2878 // Attach the main thread to this os thread 2879 JavaThread* main_thread = new JavaThread(); 2880 main_thread->set_thread_state(_thread_in_vm); 2881 main_thread->initialize_thread_current(); 2882 // must do this before set_active_handles 2883 main_thread->record_stack_base_and_size(); 2884 main_thread->register_thread_stack_with_NMT(); 2885 main_thread->set_active_handles(JNIHandleBlock::allocate_block()); 2886 MACOS_AARCH64_ONLY(main_thread->init_wx()); 2887 2888 if (!main_thread->set_as_starting_thread()) { 2889 vm_shutdown_during_initialization( 2890 "Failed necessary internal allocation. Out of swap space"); 2891 main_thread->smr_delete(); 2892 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 2893 return JNI_ENOMEM; 2894 } 2895 2896 // Enable guard page *after* os::create_main_thread(), otherwise it would 2897 // crash Linux VM, see notes in os_linux.cpp. 2898 main_thread->stack_overflow_state()->create_stack_guard_pages(); 2899 2900 // Initialize Java-Level synchronization subsystem 2901 ObjectMonitor::Initialize(); 2902 ObjectSynchronizer::initialize(); 2903 2904 // Initialize global modules 2905 jint status = init_globals(); 2906 if (status != JNI_OK) { 2907 main_thread->smr_delete(); 2908 *canTryAgain = false; // don't let caller call JNI_CreateJavaVM again 2909 return status; 2910 } 2911 2912 JFR_ONLY(Jfr::on_create_vm_1();) 2913 2914 // Should be done after the heap is fully created 2915 main_thread->cache_global_variables(); 2916 2917 { MutexLocker mu(Threads_lock); 2918 Threads::add(main_thread); 2919 } 2920 2921 // Any JVMTI raw monitors entered in onload will transition into 2922 // real raw monitor. VM is setup enough here for raw monitor enter. 2923 JvmtiExport::transition_pending_onload_raw_monitors(); 2924 2925 // Create the VMThread 2926 { TraceTime timer("Start VMThread", TRACETIME_LOG(Info, startuptime)); 2927 2928 VMThread::create(); 2929 Thread* vmthread = VMThread::vm_thread(); 2930 2931 if (!os::create_thread(vmthread, os::vm_thread)) { 2932 vm_exit_during_initialization("Cannot create VM thread. " 2933 "Out of system resources."); 2934 } 2935 2936 // Wait for the VM thread to become ready, and VMThread::run to initialize 2937 // Monitors can have spurious returns, must always check another state flag 2938 { 2939 MonitorLocker ml(Notify_lock); 2940 os::start_thread(vmthread); 2941 while (vmthread->active_handles() == NULL) { 2942 ml.wait(); 2943 } 2944 } 2945 } 2946 2947 assert(Universe::is_fully_initialized(), "not initialized"); 2948 if (VerifyDuringStartup) { 2949 // Make sure we're starting with a clean slate. 2950 VM_Verify verify_op; 2951 VMThread::execute(&verify_op); 2952 } 2953 2954 // We need this to update the java.vm.info property in case any flags used 2955 // to initially define it have been changed. This is needed for both CDS 2956 // since UseSharedSpaces may be changed after java.vm.info 2957 // is initially computed. See Abstract_VM_Version::vm_info_string(). 2958 // This update must happen before we initialize the java classes, but 2959 // after any initialization logic that might modify the flags. 2960 Arguments::update_vm_info_property(VM_Version::vm_info_string()); 2961 2962 JavaThread* THREAD = JavaThread::current(); // For exception macros. 2963 HandleMark hm(THREAD); 2964 2965 // Always call even when there are not JVMTI environments yet, since environments 2966 // may be attached late and JVMTI must track phases of VM execution 2967 JvmtiExport::enter_early_start_phase(); 2968 2969 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 2970 JvmtiExport::post_early_vm_start(); 2971 2972 initialize_java_lang_classes(main_thread, CHECK_JNI_ERR); 2973 2974 quicken_jni_functions(); 2975 2976 // No more stub generation allowed after that point. 2977 StubCodeDesc::freeze(); 2978 2979 // Set flag that basic initialization has completed. Used by exceptions and various 2980 // debug stuff, that does not work until all basic classes have been initialized. 2981 set_init_completed(); 2982 2983 LogConfiguration::post_initialize(); 2984 Metaspace::post_initialize(); 2985 2986 HOTSPOT_VM_INIT_END(); 2987 2988 // record VM initialization completion time 2989 #if INCLUDE_MANAGEMENT 2990 Management::record_vm_init_completed(); 2991 #endif // INCLUDE_MANAGEMENT 2992 2993 // Signal Dispatcher needs to be started before VMInit event is posted 2994 os::initialize_jdk_signal_support(CHECK_JNI_ERR); 2995 2996 // Start Attach Listener if +StartAttachListener or it can't be started lazily 2997 if (!DisableAttachMechanism) { 2998 AttachListener::vm_start(); 2999 if (StartAttachListener || AttachListener::init_at_startup()) { 3000 AttachListener::init(); 3001 } 3002 } 3003 3004 // Launch -Xrun agents 3005 // Must be done in the JVMTI live phase so that for backward compatibility the JDWP 3006 // back-end can launch with -Xdebug -Xrunjdwp. 3007 if (!EagerXrunInit && Arguments::init_libraries_at_startup()) { 3008 create_vm_init_libraries(); 3009 } 3010 3011 Chunk::start_chunk_pool_cleaner_task(); 3012 3013 // Start the service thread 3014 // The service thread enqueues JVMTI deferred events and does various hashtable 3015 // and other cleanups. Needs to start before the compilers start posting events. 3016 ServiceThread::initialize(); 3017 3018 // Start the monitor deflation thread: 3019 MonitorDeflationThread::initialize(); 3020 3021 // initialize compiler(s) 3022 #if defined(COMPILER1) || COMPILER2_OR_JVMCI 3023 #if INCLUDE_JVMCI 3024 bool force_JVMCI_intialization = false; 3025 if (EnableJVMCI) { 3026 // Initialize JVMCI eagerly when it is explicitly requested. 3027 // Or when JVMCILibDumpJNIConfig or JVMCIPrintProperties is enabled. 3028 force_JVMCI_intialization = EagerJVMCI || JVMCIPrintProperties || JVMCILibDumpJNIConfig; 3029 3030 if (!force_JVMCI_intialization) { 3031 // 8145270: Force initialization of JVMCI runtime otherwise requests for blocking 3032 // compilations via JVMCI will not actually block until JVMCI is initialized. 3033 force_JVMCI_intialization = UseJVMCICompiler && (!UseInterpreter || !BackgroundCompilation); 3034 } 3035 } 3036 #endif 3037 CompileBroker::compilation_init_phase1(CHECK_JNI_ERR); 3038 // Postpone completion of compiler initialization to after JVMCI 3039 // is initialized to avoid timeouts of blocking compilations. 3040 if (JVMCI_ONLY(!force_JVMCI_intialization) NOT_JVMCI(true)) { 3041 CompileBroker::compilation_init_phase2(); 3042 } 3043 #endif 3044 3045 // Pre-initialize some JSR292 core classes to avoid deadlock during class loading. 3046 // It is done after compilers are initialized, because otherwise compilations of 3047 // signature polymorphic MH intrinsics can be missed 3048 // (see SystemDictionary::find_method_handle_intrinsic). 3049 initialize_jsr292_core_classes(CHECK_JNI_ERR); 3050 3051 // This will initialize the module system. Only java.base classes can be 3052 // loaded until phase 2 completes 3053 call_initPhase2(CHECK_JNI_ERR); 3054 3055 JFR_ONLY(Jfr::on_create_vm_2();) 3056 3057 // Always call even when there are not JVMTI environments yet, since environments 3058 // may be attached late and JVMTI must track phases of VM execution 3059 JvmtiExport::enter_start_phase(); 3060 3061 // Notify JVMTI agents that VM has started (JNI is up) - nop if no agents. 3062 JvmtiExport::post_vm_start(); 3063 3064 // Final system initialization including security manager and system class loader 3065 call_initPhase3(CHECK_JNI_ERR); 3066 3067 // cache the system and platform class loaders 3068 SystemDictionary::compute_java_loaders(CHECK_JNI_ERR); 3069 3070 #if INCLUDE_CDS 3071 // capture the module path info from the ModuleEntryTable 3072 ClassLoader::initialize_module_path(THREAD); 3073 if (HAS_PENDING_EXCEPTION) { 3074 java_lang_Throwable::print(PENDING_EXCEPTION, tty); 3075 vm_exit_during_initialization("ClassLoader::initialize_module_path() failed unexpectedly"); 3076 } 3077 #endif 3078 3079 #if INCLUDE_JVMCI 3080 if (force_JVMCI_intialization) { 3081 JVMCI::initialize_compiler(CHECK_JNI_ERR); 3082 CompileBroker::compilation_init_phase2(); 3083 } 3084 #endif 3085 3086 if (NativeHeapTrimmer::enabled()) { 3087 NativeHeapTrimmer::initialize(); 3088 } 3089 3090 // Always call even when there are not JVMTI environments yet, since environments 3091 // may be attached late and JVMTI must track phases of VM execution 3092 JvmtiExport::enter_live_phase(); 3093 3094 // Make perfmemory accessible 3095 PerfMemory::set_accessible(true); 3096 3097 // Notify JVMTI agents that VM initialization is complete - nop if no agents. 3098 JvmtiExport::post_vm_initialized(); 3099 3100 JFR_ONLY(Jfr::on_create_vm_3();) 3101 3102 #if INCLUDE_MANAGEMENT 3103 Management::initialize(THREAD); 3104 3105 if (HAS_PENDING_EXCEPTION) { 3106 // management agent fails to start possibly due to 3107 // configuration problem and is responsible for printing 3108 // stack trace if appropriate. Simply exit VM. 3109 vm_exit(1); 3110 } 3111 #endif // INCLUDE_MANAGEMENT 3112 3113 StatSampler::engage(); 3114 if (CheckJNICalls) JniPeriodicChecker::engage(); 3115 3116 BiasedLocking::init(); 3117 3118 #if INCLUDE_RTM_OPT 3119 RTMLockingCounters::init(); 3120 #endif 3121 3122 call_postVMInitHook(THREAD); 3123 // The Java side of PostVMInitHook.run must deal with all 3124 // exceptions and provide means of diagnosis. 3125 if (HAS_PENDING_EXCEPTION) { 3126 CLEAR_PENDING_EXCEPTION; 3127 } 3128 3129 { 3130 MutexLocker ml(PeriodicTask_lock); 3131 // Make sure the WatcherThread can be started by WatcherThread::start() 3132 // or by dynamic enrollment. 3133 WatcherThread::make_startable(); 3134 // Start up the WatcherThread if there are any periodic tasks 3135 // NOTE: All PeriodicTasks should be registered by now. If they 3136 // aren't, late joiners might appear to start slowly (we might 3137 // take a while to process their first tick). 3138 if (PeriodicTask::num_tasks() > 0) { 3139 WatcherThread::start(); 3140 } 3141 } 3142 3143 create_vm_timer.end(); 3144 #ifdef ASSERT 3145 _vm_complete = true; 3146 #endif 3147 3148 if (DumpSharedSpaces) { 3149 MetaspaceShared::preload_and_dump(); 3150 ShouldNotReachHere(); 3151 } 3152 3153 return JNI_OK; 3154 } 3155 3156 // type for the Agent_OnLoad and JVM_OnLoad entry points 3157 extern "C" { 3158 typedef jint (JNICALL *OnLoadEntry_t)(JavaVM *, char *, void *); 3159 } 3160 // Find a command line agent library and return its entry point for 3161 // -agentlib: -agentpath: -Xrun 3162 // num_symbol_entries must be passed-in since only the caller knows the number of symbols in the array. 3163 static OnLoadEntry_t lookup_on_load(AgentLibrary* agent, 3164 const char *on_load_symbols[], 3165 size_t num_symbol_entries) { 3166 OnLoadEntry_t on_load_entry = NULL; 3167 void *library = NULL; 3168 3169 if (!agent->valid()) { 3170 char buffer[JVM_MAXPATHLEN]; 3171 char ebuf[1024] = ""; 3172 const char *name = agent->name(); 3173 const char *msg = "Could not find agent library "; 3174 3175 // First check to see if agent is statically linked into executable 3176 if (os::find_builtin_agent(agent, on_load_symbols, num_symbol_entries)) { 3177 library = agent->os_lib(); 3178 } else if (agent->is_absolute_path()) { 3179 library = os::dll_load(name, ebuf, sizeof ebuf); 3180 if (library == NULL) { 3181 const char *sub_msg = " in absolute path, with error: "; 3182 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + strlen(ebuf) + 1; 3183 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 3184 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 3185 // If we can't find the agent, exit. 3186 vm_exit_during_initialization(buf, NULL); 3187 FREE_C_HEAP_ARRAY(char, buf); 3188 } 3189 } else { 3190 // Try to load the agent from the standard dll directory 3191 if (os::dll_locate_lib(buffer, sizeof(buffer), Arguments::get_dll_dir(), 3192 name)) { 3193 library = os::dll_load(buffer, ebuf, sizeof ebuf); 3194 } 3195 if (library == NULL) { // Try the library path directory. 3196 if (os::dll_build_name(buffer, sizeof(buffer), name)) { 3197 library = os::dll_load(buffer, ebuf, sizeof ebuf); 3198 } 3199 if (library == NULL) { 3200 const char *sub_msg = " on the library path, with error: "; 3201 const char *sub_msg2 = "\nModule java.instrument may be missing from runtime image."; 3202 3203 size_t len = strlen(msg) + strlen(name) + strlen(sub_msg) + 3204 strlen(ebuf) + strlen(sub_msg2) + 1; 3205 char *buf = NEW_C_HEAP_ARRAY(char, len, mtThread); 3206 if (!agent->is_instrument_lib()) { 3207 jio_snprintf(buf, len, "%s%s%s%s", msg, name, sub_msg, ebuf); 3208 } else { 3209 jio_snprintf(buf, len, "%s%s%s%s%s", msg, name, sub_msg, ebuf, sub_msg2); 3210 } 3211 // If we can't find the agent, exit. 3212 vm_exit_during_initialization(buf, NULL); 3213 FREE_C_HEAP_ARRAY(char, buf); 3214 } 3215 } 3216 } 3217 agent->set_os_lib(library); 3218 agent->set_valid(); 3219 } 3220 3221 // Find the OnLoad function. 3222 on_load_entry = 3223 CAST_TO_FN_PTR(OnLoadEntry_t, os::find_agent_function(agent, 3224 false, 3225 on_load_symbols, 3226 num_symbol_entries)); 3227 return on_load_entry; 3228 } 3229 3230 // Find the JVM_OnLoad entry point 3231 static OnLoadEntry_t lookup_jvm_on_load(AgentLibrary* agent) { 3232 const char *on_load_symbols[] = JVM_ONLOAD_SYMBOLS; 3233 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 3234 } 3235 3236 // Find the Agent_OnLoad entry point 3237 static OnLoadEntry_t lookup_agent_on_load(AgentLibrary* agent) { 3238 const char *on_load_symbols[] = AGENT_ONLOAD_SYMBOLS; 3239 return lookup_on_load(agent, on_load_symbols, sizeof(on_load_symbols) / sizeof(char*)); 3240 } 3241 3242 // For backwards compatibility with -Xrun 3243 // Convert libraries with no JVM_OnLoad, but which have Agent_OnLoad to be 3244 // treated like -agentpath: 3245 // Must be called before agent libraries are created 3246 void Threads::convert_vm_init_libraries_to_agents() { 3247 AgentLibrary* agent; 3248 AgentLibrary* next; 3249 3250 for (agent = Arguments::libraries(); agent != NULL; agent = next) { 3251 next = agent->next(); // cache the next agent now as this agent may get moved off this list 3252 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 3253 3254 // If there is an JVM_OnLoad function it will get called later, 3255 // otherwise see if there is an Agent_OnLoad 3256 if (on_load_entry == NULL) { 3257 on_load_entry = lookup_agent_on_load(agent); 3258 if (on_load_entry != NULL) { 3259 // switch it to the agent list -- so that Agent_OnLoad will be called, 3260 // JVM_OnLoad won't be attempted and Agent_OnUnload will 3261 Arguments::convert_library_to_agent(agent); 3262 } else { 3263 vm_exit_during_initialization("Could not find JVM_OnLoad or Agent_OnLoad function in the library", agent->name()); 3264 } 3265 } 3266 } 3267 } 3268 3269 // Create agents for -agentlib: -agentpath: and converted -Xrun 3270 // Invokes Agent_OnLoad 3271 // Called very early -- before JavaThreads exist 3272 void Threads::create_vm_init_agents() { 3273 extern struct JavaVM_ main_vm; 3274 AgentLibrary* agent; 3275 3276 JvmtiExport::enter_onload_phase(); 3277 3278 for (agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 3279 // CDS dumping does not support native JVMTI agent. 3280 // CDS dumping supports Java agent if the AllowArchivingWithJavaAgent diagnostic option is specified. 3281 if (Arguments::is_dumping_archive()) { 3282 if(!agent->is_instrument_lib()) { 3283 vm_exit_during_cds_dumping("CDS dumping does not support native JVMTI agent, name", agent->name()); 3284 } else if (!AllowArchivingWithJavaAgent) { 3285 vm_exit_during_cds_dumping( 3286 "Must enable AllowArchivingWithJavaAgent in order to run Java agent during CDS dumping"); 3287 } 3288 } 3289 3290 OnLoadEntry_t on_load_entry = lookup_agent_on_load(agent); 3291 3292 if (on_load_entry != NULL) { 3293 // Invoke the Agent_OnLoad function 3294 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 3295 if (err != JNI_OK) { 3296 vm_exit_during_initialization("agent library failed to init", agent->name()); 3297 } 3298 } else { 3299 vm_exit_during_initialization("Could not find Agent_OnLoad function in the agent library", agent->name()); 3300 } 3301 } 3302 3303 JvmtiExport::enter_primordial_phase(); 3304 } 3305 3306 extern "C" { 3307 typedef void (JNICALL *Agent_OnUnload_t)(JavaVM *); 3308 } 3309 3310 void Threads::shutdown_vm_agents() { 3311 // Send any Agent_OnUnload notifications 3312 const char *on_unload_symbols[] = AGENT_ONUNLOAD_SYMBOLS; 3313 size_t num_symbol_entries = ARRAY_SIZE(on_unload_symbols); 3314 extern struct JavaVM_ main_vm; 3315 for (AgentLibrary* agent = Arguments::agents(); agent != NULL; agent = agent->next()) { 3316 3317 // Find the Agent_OnUnload function. 3318 Agent_OnUnload_t unload_entry = CAST_TO_FN_PTR(Agent_OnUnload_t, 3319 os::find_agent_function(agent, 3320 false, 3321 on_unload_symbols, 3322 num_symbol_entries)); 3323 3324 // Invoke the Agent_OnUnload function 3325 if (unload_entry != NULL) { 3326 JavaThread* thread = JavaThread::current(); 3327 ThreadToNativeFromVM ttn(thread); 3328 HandleMark hm(thread); 3329 (*unload_entry)(&main_vm); 3330 } 3331 } 3332 } 3333 3334 // Called for after the VM is initialized for -Xrun libraries which have not been converted to agent libraries 3335 // Invokes JVM_OnLoad 3336 void Threads::create_vm_init_libraries() { 3337 extern struct JavaVM_ main_vm; 3338 AgentLibrary* agent; 3339 3340 for (agent = Arguments::libraries(); agent != NULL; agent = agent->next()) { 3341 OnLoadEntry_t on_load_entry = lookup_jvm_on_load(agent); 3342 3343 if (on_load_entry != NULL) { 3344 // Invoke the JVM_OnLoad function 3345 JavaThread* thread = JavaThread::current(); 3346 ThreadToNativeFromVM ttn(thread); 3347 HandleMark hm(thread); 3348 jint err = (*on_load_entry)(&main_vm, agent->options(), NULL); 3349 if (err != JNI_OK) { 3350 vm_exit_during_initialization("-Xrun library failed to init", agent->name()); 3351 } 3352 } else { 3353 vm_exit_during_initialization("Could not find JVM_OnLoad function in -Xrun library", agent->name()); 3354 } 3355 } 3356 } 3357 3358 3359 // Last thread running calls java.lang.Shutdown.shutdown() 3360 void JavaThread::invoke_shutdown_hooks() { 3361 HandleMark hm(this); 3362 3363 // We could get here with a pending exception, if so clear it now or 3364 // it will cause MetaspaceShared::link_and_cleanup_shared_classes to 3365 // fail for dynamic dump. 3366 if (this->has_pending_exception()) { 3367 this->clear_pending_exception(); 3368 } 3369 3370 #if INCLUDE_CDS 3371 // Link all classes for dynamic CDS dumping before vm exit. 3372 // Same operation is being done in JVM_BeforeHalt for handling the 3373 // case where the application calls System.exit(). 3374 if (DynamicDumpSharedSpaces) { 3375 DynamicArchive::prepare_for_dynamic_dumping_at_exit(); 3376 } 3377 #endif 3378 3379 EXCEPTION_MARK; 3380 Klass* shutdown_klass = 3381 SystemDictionary::resolve_or_null(vmSymbols::java_lang_Shutdown(), 3382 THREAD); 3383 if (shutdown_klass != NULL) { 3384 // SystemDictionary::resolve_or_null will return null if there was 3385 // an exception. If we cannot load the Shutdown class, just don't 3386 // call Shutdown.shutdown() at all. This will mean the shutdown hooks 3387 // won't be run. Note that if a shutdown hook was registered, 3388 // the Shutdown class would have already been loaded 3389 // (Runtime.addShutdownHook will load it). 3390 JavaValue result(T_VOID); 3391 JavaCalls::call_static(&result, 3392 shutdown_klass, 3393 vmSymbols::shutdown_name(), 3394 vmSymbols::void_method_signature(), 3395 THREAD); 3396 } 3397 CLEAR_PENDING_EXCEPTION; 3398 } 3399 3400 // Threads::destroy_vm() is normally called from jni_DestroyJavaVM() when 3401 // the program falls off the end of main(). Another VM exit path is through 3402 // vm_exit() when the program calls System.exit() to return a value or when 3403 // there is a serious error in VM. The two shutdown paths are not exactly 3404 // the same, but they share Shutdown.shutdown() at Java level and before_exit() 3405 // and VM_Exit op at VM level. 3406 // 3407 // Shutdown sequence: 3408 // + Shutdown native memory tracking if it is on 3409 // + Wait until we are the last non-daemon thread to execute 3410 // <-- every thing is still working at this moment --> 3411 // + Call java.lang.Shutdown.shutdown(), which will invoke Java level 3412 // shutdown hooks 3413 // + Call before_exit(), prepare for VM exit 3414 // > run VM level shutdown hooks (they are registered through JVM_OnExit(), 3415 // currently the only user of this mechanism is File.deleteOnExit()) 3416 // > stop StatSampler, watcher thread, 3417 // post thread end and vm death events to JVMTI, 3418 // stop signal thread 3419 // + Call JavaThread::exit(), it will: 3420 // > release JNI handle blocks, remove stack guard pages 3421 // > remove this thread from Threads list 3422 // <-- no more Java code from this thread after this point --> 3423 // + Stop VM thread, it will bring the remaining VM to a safepoint and stop 3424 // the compiler threads at safepoint 3425 // <-- do not use anything that could get blocked by Safepoint --> 3426 // + Disable tracing at JNI/JVM barriers 3427 // + Set _vm_exited flag for threads that are still running native code 3428 // + Call exit_globals() 3429 // > deletes tty 3430 // > deletes PerfMemory resources 3431 // + Delete this thread 3432 // + Return to caller 3433 3434 void Threads::destroy_vm() { 3435 JavaThread* thread = JavaThread::current(); 3436 3437 #ifdef ASSERT 3438 _vm_complete = false; 3439 #endif 3440 // Wait until we are the last non-daemon thread to execute 3441 { 3442 MonitorLocker nu(Threads_lock); 3443 while (Threads::number_of_non_daemon_threads() > 1) 3444 // This wait should make safepoint checks, wait without a timeout. 3445 nu.wait(0); 3446 } 3447 3448 EventShutdown e; 3449 if (e.should_commit()) { 3450 e.set_reason("No remaining non-daemon Java threads"); 3451 e.commit(); 3452 } 3453 3454 // Hang forever on exit if we are reporting an error. 3455 if (ShowMessageBoxOnError && VMError::is_error_reported()) { 3456 os::infinite_sleep(); 3457 } 3458 os::wait_for_keypress_at_exit(); 3459 3460 // run Java level shutdown hooks 3461 thread->invoke_shutdown_hooks(); 3462 3463 before_exit(thread); 3464 3465 thread->exit(true); 3466 3467 // We are no longer on the main thread list but could still be in a 3468 // secondary list where another thread may try to interact with us. 3469 // So wait until all such interactions are complete before we bring 3470 // the VM to the termination safepoint. Normally this would be done 3471 // using thread->smr_delete() below where we delete the thread, but 3472 // we can't call that after the termination safepoint is active as 3473 // we will deadlock on the Threads_lock. Once all interactions are 3474 // complete it is safe to directly delete the thread at any time. 3475 ThreadsSMRSupport::wait_until_not_protected(thread); 3476 3477 // Stop VM thread. 3478 { 3479 // 4945125 The vm thread comes to a safepoint during exit. 3480 // GC vm_operations can get caught at the safepoint, and the 3481 // heap is unparseable if they are caught. Grab the Heap_lock 3482 // to prevent this. The GC vm_operations will not be able to 3483 // queue until after the vm thread is dead. After this point, 3484 // we'll never emerge out of the safepoint before the VM exits. 3485 // Assert that the thread is terminated so that acquiring the 3486 // Heap_lock doesn't cause the terminated thread to participate in 3487 // the safepoint protocol. 3488 3489 assert(thread->is_terminated(), "must be terminated here"); 3490 MutexLocker ml(Heap_lock); 3491 3492 VMThread::wait_for_vm_thread_exit(); 3493 assert(SafepointSynchronize::is_at_safepoint(), "VM thread should exit at Safepoint"); 3494 VMThread::destroy(); 3495 } 3496 3497 // Now, all Java threads are gone except daemon threads. Daemon threads 3498 // running Java code or in VM are stopped by the Safepoint. However, 3499 // daemon threads executing native code are still running. But they 3500 // will be stopped at native=>Java/VM barriers. Note that we can't 3501 // simply kill or suspend them, as it is inherently deadlock-prone. 3502 3503 VM_Exit::set_vm_exited(); 3504 3505 // Clean up ideal graph printers after the VMThread has started 3506 // the final safepoint which will block all the Compiler threads. 3507 // Note that this Thread has already logically exited so the 3508 // clean_up() function's use of a JavaThreadIteratorWithHandle 3509 // would be a problem except set_vm_exited() has remembered the 3510 // shutdown thread which is granted a policy exception. 3511 #if defined(COMPILER2) && !defined(PRODUCT) 3512 IdealGraphPrinter::clean_up(); 3513 #endif 3514 3515 notify_vm_shutdown(); 3516 3517 // exit_globals() will delete tty 3518 exit_globals(); 3519 3520 // Deleting the shutdown thread here is safe. See comment on 3521 // wait_until_not_protected() above. 3522 delete thread; 3523 3524 #if INCLUDE_JVMCI 3525 if (JVMCICounterSize > 0) { 3526 FREE_C_HEAP_ARRAY(jlong, JavaThread::_jvmci_old_thread_counters); 3527 } 3528 #endif 3529 3530 LogConfiguration::finalize(); 3531 } 3532 3533 3534 jboolean Threads::is_supported_jni_version_including_1_1(jint version) { 3535 if (version == JNI_VERSION_1_1) return JNI_TRUE; 3536 return is_supported_jni_version(version); 3537 } 3538 3539 3540 jboolean Threads::is_supported_jni_version(jint version) { 3541 if (version == JNI_VERSION_1_2) return JNI_TRUE; 3542 if (version == JNI_VERSION_1_4) return JNI_TRUE; 3543 if (version == JNI_VERSION_1_6) return JNI_TRUE; 3544 if (version == JNI_VERSION_1_8) return JNI_TRUE; 3545 if (version == JNI_VERSION_9) return JNI_TRUE; 3546 if (version == JNI_VERSION_10) return JNI_TRUE; 3547 return JNI_FALSE; 3548 } 3549 3550 3551 void Threads::add(JavaThread* p, bool force_daemon) { 3552 // The threads lock must be owned at this point 3553 assert(Threads_lock->owned_by_self(), "must have threads lock"); 3554 3555 BarrierSet::barrier_set()->on_thread_attach(p); 3556 3557 // Once a JavaThread is added to the Threads list, smr_delete() has 3558 // to be used to delete it. Otherwise we can just delete it directly. 3559 p->set_on_thread_list(); 3560 3561 _number_of_threads++; 3562 oop threadObj = p->threadObj(); 3563 bool daemon = true; 3564 // Bootstrapping problem: threadObj can be null for initial 3565 // JavaThread (or for threads attached via JNI) 3566 if ((!force_daemon) && !is_daemon((threadObj))) { 3567 _number_of_non_daemon_threads++; 3568 daemon = false; 3569 } 3570 3571 ThreadService::add_thread(p, daemon); 3572 3573 // Maintain fast thread list 3574 ThreadsSMRSupport::add_thread(p); 3575 3576 // Increase the ObjectMonitor ceiling for the new thread. 3577 ObjectSynchronizer::inc_in_use_list_ceiling(); 3578 3579 // Possible GC point. 3580 Events::log(p, "Thread added: " INTPTR_FORMAT, p2i(p)); 3581 3582 // Make new thread known to active EscapeBarrier 3583 EscapeBarrier::thread_added(p); 3584 } 3585 3586 void Threads::remove(JavaThread* p, bool is_daemon) { 3587 // Extra scope needed for Thread_lock, so we can check 3588 // that we do not remove thread without safepoint code notice 3589 { MonitorLocker ml(Threads_lock); 3590 3591 // BarrierSet state must be destroyed after the last thread transition 3592 // before the thread terminates. Thread transitions result in calls to 3593 // StackWatermarkSet::on_safepoint(), which performs GC processing, 3594 // requiring the GC state to be alive. 3595 BarrierSet::barrier_set()->on_thread_detach(p); 3596 3597 assert(ThreadsSMRSupport::get_java_thread_list()->includes(p), "p must be present"); 3598 3599 // Maintain fast thread list 3600 ThreadsSMRSupport::remove_thread(p); 3601 3602 _number_of_threads--; 3603 if (!is_daemon) { 3604 _number_of_non_daemon_threads--; 3605 3606 // Only one thread left, do a notify on the Threads_lock so a thread waiting 3607 // on destroy_vm will wake up. 3608 if (number_of_non_daemon_threads() == 1) { 3609 ml.notify_all(); 3610 } 3611 } 3612 ThreadService::remove_thread(p, is_daemon); 3613 3614 // Make sure that safepoint code disregard this thread. This is needed since 3615 // the thread might mess around with locks after this point. This can cause it 3616 // to do callbacks into the safepoint code. However, the safepoint code is not aware 3617 // of this thread since it is removed from the queue. 3618 p->set_terminated(JavaThread::_thread_terminated); 3619 3620 // Notify threads waiting in EscapeBarriers 3621 EscapeBarrier::thread_removed(p); 3622 } // unlock Threads_lock 3623 3624 // Reduce the ObjectMonitor ceiling for the exiting thread. 3625 ObjectSynchronizer::dec_in_use_list_ceiling(); 3626 3627 // Since Events::log uses a lock, we grab it outside the Threads_lock 3628 Events::log(p, "Thread exited: " INTPTR_FORMAT, p2i(p)); 3629 } 3630 3631 // Operations on the Threads list for GC. These are not explicitly locked, 3632 // but the garbage collector must provide a safe context for them to run. 3633 // In particular, these things should never be called when the Threads_lock 3634 // is held by some other thread. (Note: the Safepoint abstraction also 3635 // uses the Threads_lock to guarantee this property. It also makes sure that 3636 // all threads gets blocked when exiting or starting). 3637 3638 void Threads::oops_do(OopClosure* f, CodeBlobClosure* cf) { 3639 ALL_JAVA_THREADS(p) { 3640 p->oops_do(f, cf); 3641 } 3642 VMThread::vm_thread()->oops_do(f, cf); 3643 } 3644 3645 void Threads::change_thread_claim_token() { 3646 if (++_thread_claim_token == 0) { 3647 // On overflow of the token counter, there is a risk of future 3648 // collisions between a new global token value and a stale token 3649 // for a thread, because not all iterations visit all threads. 3650 // (Though it's pretty much a theoretical concern for non-trivial 3651 // token counter sizes.) To deal with the possibility, reset all 3652 // the thread tokens to zero on global token overflow. 3653 struct ResetClaims : public ThreadClosure { 3654 virtual void do_thread(Thread* t) { 3655 t->claim_threads_do(false, 0); 3656 } 3657 } reset_claims; 3658 Threads::threads_do(&reset_claims); 3659 // On overflow, update the global token to non-zero, to 3660 // avoid the special "never claimed" initial thread value. 3661 _thread_claim_token = 1; 3662 } 3663 } 3664 3665 #ifdef ASSERT 3666 void assert_thread_claimed(const char* kind, Thread* t, uintx expected) { 3667 const uintx token = t->threads_do_token(); 3668 assert(token == expected, 3669 "%s " PTR_FORMAT " has incorrect value " UINTX_FORMAT " != " 3670 UINTX_FORMAT, kind, p2i(t), token, expected); 3671 } 3672 3673 void Threads::assert_all_threads_claimed() { 3674 ALL_JAVA_THREADS(p) { 3675 assert_thread_claimed("Thread", p, _thread_claim_token); 3676 } 3677 assert_thread_claimed("VMThread", VMThread::vm_thread(), _thread_claim_token); 3678 } 3679 #endif // ASSERT 3680 3681 class ParallelOopsDoThreadClosure : public ThreadClosure { 3682 private: 3683 OopClosure* _f; 3684 CodeBlobClosure* _cf; 3685 public: 3686 ParallelOopsDoThreadClosure(OopClosure* f, CodeBlobClosure* cf) : _f(f), _cf(cf) {} 3687 void do_thread(Thread* t) { 3688 t->oops_do(_f, _cf); 3689 } 3690 }; 3691 3692 void Threads::possibly_parallel_oops_do(bool is_par, OopClosure* f, CodeBlobClosure* cf) { 3693 ParallelOopsDoThreadClosure tc(f, cf); 3694 possibly_parallel_threads_do(is_par, &tc); 3695 } 3696 3697 void Threads::metadata_do(MetadataClosure* f) { 3698 ALL_JAVA_THREADS(p) { 3699 p->metadata_do(f); 3700 } 3701 } 3702 3703 class ThreadHandlesClosure : public ThreadClosure { 3704 void (*_f)(Metadata*); 3705 public: 3706 ThreadHandlesClosure(void f(Metadata*)) : _f(f) {} 3707 virtual void do_thread(Thread* thread) { 3708 thread->metadata_handles_do(_f); 3709 } 3710 }; 3711 3712 void Threads::metadata_handles_do(void f(Metadata*)) { 3713 // Only walk the Handles in Thread. 3714 ThreadHandlesClosure handles_closure(f); 3715 threads_do(&handles_closure); 3716 } 3717 3718 // Get count Java threads that are waiting to enter the specified monitor. 3719 GrowableArray<JavaThread*>* Threads::get_pending_threads(ThreadsList * t_list, 3720 int count, 3721 address monitor) { 3722 GrowableArray<JavaThread*>* result = new GrowableArray<JavaThread*>(count); 3723 3724 int i = 0; 3725 DO_JAVA_THREADS(t_list, p) { 3726 if (!p->can_call_java()) continue; 3727 3728 // The first stage of async deflation does not affect any field 3729 // used by this comparison so the ObjectMonitor* is usable here. 3730 address pending = (address)p->current_pending_monitor(); 3731 if (pending == monitor) { // found a match 3732 if (i < count) result->append(p); // save the first count matches 3733 i++; 3734 } 3735 } 3736 3737 return result; 3738 } 3739 3740 3741 JavaThread *Threads::owning_thread_from_monitor_owner(ThreadsList * t_list, 3742 address owner) { 3743 // NULL owner means not locked so we can skip the search 3744 if (owner == NULL) return NULL; 3745 3746 DO_JAVA_THREADS(t_list, p) { 3747 // first, see if owner is the address of a Java thread 3748 if (owner == (address)p) return p; 3749 } 3750 3751 // Cannot assert on lack of success here since this function may be 3752 // used by code that is trying to report useful problem information 3753 // like deadlock detection. 3754 if (UseHeavyMonitors) return NULL; 3755 3756 // If we didn't find a matching Java thread and we didn't force use of 3757 // heavyweight monitors, then the owner is the stack address of the 3758 // Lock Word in the owning Java thread's stack. 3759 // 3760 JavaThread* the_owner = NULL; 3761 DO_JAVA_THREADS(t_list, q) { 3762 if (q->is_lock_owned(owner)) { 3763 the_owner = q; 3764 break; 3765 } 3766 } 3767 3768 // cannot assert on lack of success here; see above comment 3769 return the_owner; 3770 } 3771 3772 class PrintOnClosure : public ThreadClosure { 3773 private: 3774 outputStream* _st; 3775 3776 public: 3777 PrintOnClosure(outputStream* st) : 3778 _st(st) {} 3779 3780 virtual void do_thread(Thread* thread) { 3781 if (thread != NULL) { 3782 thread->print_on(_st); 3783 _st->cr(); 3784 } 3785 } 3786 }; 3787 3788 // Threads::print_on() is called at safepoint by VM_PrintThreads operation. 3789 void Threads::print_on(outputStream* st, bool print_stacks, 3790 bool internal_format, bool print_concurrent_locks, 3791 bool print_extended_info) { 3792 char buf[32]; 3793 st->print_raw_cr(os::local_time_string(buf, sizeof(buf))); 3794 3795 st->print_cr("Full thread dump %s (%s %s):", 3796 VM_Version::vm_name(), 3797 VM_Version::vm_release(), 3798 VM_Version::vm_info_string()); 3799 st->cr(); 3800 3801 #if INCLUDE_SERVICES 3802 // Dump concurrent locks 3803 ConcurrentLocksDump concurrent_locks; 3804 if (print_concurrent_locks) { 3805 concurrent_locks.dump_at_safepoint(); 3806 } 3807 #endif // INCLUDE_SERVICES 3808 3809 ThreadsSMRSupport::print_info_on(st); 3810 st->cr(); 3811 3812 ALL_JAVA_THREADS(p) { 3813 ResourceMark rm; 3814 p->print_on(st, print_extended_info); 3815 if (print_stacks) { 3816 if (internal_format) { 3817 p->trace_stack(); 3818 } else { 3819 p->print_stack_on(st); 3820 } 3821 } 3822 st->cr(); 3823 #if INCLUDE_SERVICES 3824 if (print_concurrent_locks) { 3825 concurrent_locks.print_locks_on(p, st); 3826 } 3827 #endif // INCLUDE_SERVICES 3828 } 3829 3830 PrintOnClosure cl(st); 3831 cl.do_thread(VMThread::vm_thread()); 3832 Universe::heap()->gc_threads_do(&cl); 3833 if (StringDedup::is_enabled()) { 3834 StringDedup::threads_do(&cl); 3835 } 3836 cl.do_thread(WatcherThread::watcher_thread()); 3837 cl.do_thread(AsyncLogWriter::instance()); 3838 3839 st->flush(); 3840 } 3841 3842 void Threads::print_on_error(Thread* this_thread, outputStream* st, Thread* current, char* buf, 3843 int buflen, bool* found_current) { 3844 if (this_thread != NULL) { 3845 bool is_current = (current == this_thread); 3846 *found_current = *found_current || is_current; 3847 st->print("%s", is_current ? "=>" : " "); 3848 3849 st->print(PTR_FORMAT, p2i(this_thread)); 3850 st->print(" "); 3851 this_thread->print_on_error(st, buf, buflen); 3852 st->cr(); 3853 } 3854 } 3855 3856 class PrintOnErrorClosure : public ThreadClosure { 3857 outputStream* _st; 3858 Thread* _current; 3859 char* _buf; 3860 int _buflen; 3861 bool* _found_current; 3862 public: 3863 PrintOnErrorClosure(outputStream* st, Thread* current, char* buf, 3864 int buflen, bool* found_current) : 3865 _st(st), _current(current), _buf(buf), _buflen(buflen), _found_current(found_current) {} 3866 3867 virtual void do_thread(Thread* thread) { 3868 Threads::print_on_error(thread, _st, _current, _buf, _buflen, _found_current); 3869 } 3870 }; 3871 3872 // Threads::print_on_error() is called by fatal error handler. It's possible 3873 // that VM is not at safepoint and/or current thread is inside signal handler. 3874 // Don't print stack trace, as the stack may not be walkable. Don't allocate 3875 // memory (even in resource area), it might deadlock the error handler. 3876 void Threads::print_on_error(outputStream* st, Thread* current, char* buf, 3877 int buflen) { 3878 ThreadsSMRSupport::print_info_on(st); 3879 st->cr(); 3880 3881 bool found_current = false; 3882 st->print_cr("Java Threads: ( => current thread )"); 3883 ALL_JAVA_THREADS(thread) { 3884 print_on_error(thread, st, current, buf, buflen, &found_current); 3885 } 3886 st->cr(); 3887 3888 st->print_cr("Other Threads:"); 3889 print_on_error(VMThread::vm_thread(), st, current, buf, buflen, &found_current); 3890 print_on_error(WatcherThread::watcher_thread(), st, current, buf, buflen, &found_current); 3891 print_on_error(AsyncLogWriter::instance(), st, current, buf, buflen, &found_current); 3892 3893 if (Universe::heap() != NULL) { 3894 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current); 3895 Universe::heap()->gc_threads_do(&print_closure); 3896 } 3897 3898 if (StringDedup::is_enabled()) { 3899 PrintOnErrorClosure print_closure(st, current, buf, buflen, &found_current); 3900 StringDedup::threads_do(&print_closure); 3901 } 3902 3903 if (!found_current) { 3904 st->cr(); 3905 st->print("=>" PTR_FORMAT " (exited) ", p2i(current)); 3906 current->print_on_error(st, buf, buflen); 3907 st->cr(); 3908 } 3909 st->cr(); 3910 3911 st->print_cr("Threads with active compile tasks:"); 3912 print_threads_compiling(st, buf, buflen); 3913 } 3914 3915 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) { 3916 ALL_JAVA_THREADS(thread) { 3917 if (thread->is_Compiler_thread()) { 3918 CompilerThread* ct = (CompilerThread*) thread; 3919 3920 // Keep task in local variable for NULL check. 3921 // ct->_task might be set to NULL by concurring compiler thread 3922 // because it completed the compilation. The task is never freed, 3923 // though, just returned to a free list. 3924 CompileTask* task = ct->task(); 3925 if (task != NULL) { 3926 thread->print_name_on_error(st, buf, buflen); 3927 st->print(" "); 3928 task->print(st, NULL, short_form, true); 3929 } 3930 } 3931 } 3932 } 3933 3934 3935 // Ad-hoc mutual exclusion primitives: SpinLock 3936 // 3937 // We employ SpinLocks _only for low-contention, fixed-length 3938 // short-duration critical sections where we're concerned 3939 // about native mutex_t or HotSpot Mutex:: latency. 3940 // 3941 // TODO-FIXME: ListLock should be of type SpinLock. 3942 // We should make this a 1st-class type, integrated into the lock 3943 // hierarchy as leaf-locks. Critically, the SpinLock structure 3944 // should have sufficient padding to avoid false-sharing and excessive 3945 // cache-coherency traffic. 3946 3947 3948 typedef volatile int SpinLockT; 3949 3950 void Thread::SpinAcquire(volatile int * adr, const char * LockName) { 3951 if (Atomic::cmpxchg(adr, 0, 1) == 0) { 3952 return; // normal fast-path return 3953 } 3954 3955 // Slow-path : We've encountered contention -- Spin/Yield/Block strategy. 3956 int ctr = 0; 3957 int Yields = 0; 3958 for (;;) { 3959 while (*adr != 0) { 3960 ++ctr; 3961 if ((ctr & 0xFFF) == 0 || !os::is_MP()) { 3962 if (Yields > 5) { 3963 os::naked_short_sleep(1); 3964 } else { 3965 os::naked_yield(); 3966 ++Yields; 3967 } 3968 } else { 3969 SpinPause(); 3970 } 3971 } 3972 if (Atomic::cmpxchg(adr, 0, 1) == 0) return; 3973 } 3974 } 3975 3976 void Thread::SpinRelease(volatile int * adr) { 3977 assert(*adr != 0, "invariant"); 3978 OrderAccess::fence(); // guarantee at least release consistency. 3979 // Roach-motel semantics. 3980 // It's safe if subsequent LDs and STs float "up" into the critical section, 3981 // but prior LDs and STs within the critical section can't be allowed 3982 // to reorder or float past the ST that releases the lock. 3983 // Loads and stores in the critical section - which appear in program 3984 // order before the store that releases the lock - must also appear 3985 // before the store that releases the lock in memory visibility order. 3986 // Conceptually we need a #loadstore|#storestore "release" MEMBAR before 3987 // the ST of 0 into the lock-word which releases the lock, so fence 3988 // more than covers this on all platforms. 3989 *adr = 0; 3990 } 3991 3992 3993 void Threads::verify() { 3994 ALL_JAVA_THREADS(p) { 3995 p->verify(); 3996 } 3997 VMThread* thread = VMThread::vm_thread(); 3998 if (thread != NULL) thread->verify(); 3999 } 4000 4001 #ifndef PRODUCT 4002 void JavaThread::verify_cross_modify_fence_failure(JavaThread *thread) { 4003 report_vm_error(__FILE__, __LINE__, "Cross modify fence failure", "%p", thread); 4004 } 4005 #endif 4006 4007 // Starts the target JavaThread as a daemon of the given priority, and 4008 // bound to the given java.lang.Thread instance. 4009 // The Threads_lock is held for the duration. 4010 void JavaThread::start_internal_daemon(JavaThread* current, JavaThread* target, 4011 Handle thread_oop, ThreadPriority prio) { 4012 4013 assert(target->osthread()!= NULL, "target thread is not properly initialized"); 4014 4015 MutexLocker mu(current, Threads_lock); 4016 4017 // Initialize the fields of the thread_oop first. 4018 if (prio != NoPriority) { 4019 java_lang_Thread::set_priority(thread_oop(), prio); 4020 // Note: we don't call os::set_priority here. Possibly we should, 4021 // else all threads should call it themselves when they first run. 4022 } 4023 4024 java_lang_Thread::set_daemon(thread_oop()); 4025 4026 // Now bind the thread_oop to the target JavaThread. 4027 target->set_threadObj(thread_oop()); 4028 4029 Threads::add(target); // target is now visible for safepoint/handshake 4030 // Publish the JavaThread* in java.lang.Thread after the JavaThread* is 4031 // on a ThreadsList. We don't want to wait for the release when the 4032 // Theads_lock is dropped when the 'mu' destructor is run since the 4033 // JavaThread* is already visible to JVM/TI via the ThreadsList. 4034 java_lang_Thread::release_set_thread(thread_oop(), target); // isAlive == true now 4035 Thread::start(target); 4036 } 4037 4038 void JavaThread::vm_exit_on_osthread_failure(JavaThread* thread) { 4039 // At this point it may be possible that no osthread was created for the 4040 // JavaThread due to lack of resources. However, since this must work 4041 // for critical system threads just check and abort if this fails. 4042 if (thread->osthread() == nullptr) { 4043 // This isn't really an OOM condition, but historically this is what 4044 // we report. 4045 vm_exit_during_initialization("java.lang.OutOfMemoryError", 4046 os::native_thread_creation_failed_msg()); 4047 } 4048 }