< prev index next >

src/hotspot/share/runtime/thread.cpp

Print this page

  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/fieldDescriptor.inline.hpp"
  80 #include "runtime/flags/jvmFlagLimit.hpp"
  81 #include "runtime/deoptimization.hpp"
  82 #include "runtime/frame.inline.hpp"
  83 #include "runtime/handles.inline.hpp"
  84 #include "runtime/handshake.hpp"
  85 #include "runtime/init.hpp"
  86 #include "runtime/interfaceSupport.inline.hpp"
  87 #include "runtime/java.hpp"
  88 #include "runtime/javaCalls.hpp"
  89 #include "runtime/jniHandles.inline.hpp"
  90 #include "runtime/jniPeriodicChecker.hpp"
  91 #include "runtime/monitorDeflationThread.hpp"
  92 #include "runtime/mutexLocker.hpp"
  93 #include "runtime/nonJavaThread.hpp"
  94 #include "runtime/objectMonitor.hpp"
  95 #include "runtime/orderAccess.hpp"
  96 #include "runtime/osThread.hpp"

 253   // construct until the _MutexEvent is initialized ...
 254   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
 255   // we might instead use a stack of ParkEvents that we could provision on-demand.
 256   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
 257   // and ::Release()
 258   _ParkEvent   = ParkEvent::Allocate(this);
 259 
 260 #ifdef CHECK_UNHANDLED_OOPS
 261   if (CheckUnhandledOops) {
 262     _unhandled_oops = new UnhandledOops(this);
 263   }
 264 #endif // CHECK_UNHANDLED_OOPS
 265 
 266   // Notify the barrier set that a thread is being created. The initial
 267   // thread is created before the barrier set is available.  The call to
 268   // BarrierSet::on_thread_create() for this thread is therefore deferred
 269   // to BarrierSet::set_barrier_set().
 270   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 271   if (barrier_set != NULL) {
 272     barrier_set->on_thread_create(this);


 273   } else {
 274     // Only the main thread should be created before the barrier set
 275     // and that happens just before Thread::current is set. No other thread
 276     // can attach as the VM is not created yet, so they can't execute this code.
 277     // If the main thread creates other threads before the barrier set that is an error.
 278     assert(Thread::current_or_null() == NULL, "creating thread before barrier set");
 279   }
 280 
 281   MACOS_AARCH64_ONLY(DEBUG_ONLY(_wx_init = false));
 282 }
 283 
 284 void Thread::initialize_tlab() {
 285   if (UseTLAB) {
 286     tlab().initialize();
 287   }
 288 }
 289 
 290 void Thread::initialize_thread_current() {
 291 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 292   assert(_thr_current == NULL, "Thread::current already initialized");

 689   Handle main_instance = JavaCalls::construct_new_instance(
 690                             vmClasses::ThreadGroup_klass(),
 691                             vmSymbols::threadgroup_string_void_signature(),
 692                             system_instance,
 693                             string,
 694                             CHECK_NH);
 695   return main_instance;
 696 }
 697 
 698 // Creates the initial Thread, and sets it to running.
 699 static void create_initial_thread(Handle thread_group, JavaThread* thread,
 700                                  TRAPS) {
 701   InstanceKlass* ik = vmClasses::Thread_klass();
 702   assert(ik->is_initialized(), "must be");
 703   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 704 
 705   // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 706   // constructor calls Thread.current(), which must be set here for the
 707   // initial thread.
 708   java_lang_Thread::set_thread(thread_oop(), thread);
 709   java_lang_Thread::set_priority(thread_oop(), NormPriority);
 710   thread->set_threadObj(thread_oop());
 711 
 712   Handle string = java_lang_String::create_from_str("main", CHECK);
 713 
 714   JavaValue result(T_VOID);
 715   JavaCalls::call_special(&result, thread_oop,
 716                           ik,
 717                           vmSymbols::object_initializer_name(),
 718                           vmSymbols::threadgroup_string_void_signature(),
 719                           thread_group,
 720                           string,
 721                           CHECK);
 722 
 723   // Set thread status to running since main thread has
 724   // been started and running.
 725   java_lang_Thread::set_thread_status(thread_oop(),
 726                                       JavaThreadStatus::RUNNABLE);
 727 }
 728 
 729 // Extract version and vendor specific information from
 730 // java.lang.VersionProps fields.

 746   } else {
 747     return NULL;
 748   }
 749 }
 750 
 751 // General purpose hook into Java code, run once when the VM is initialized.
 752 // The Java library method itself may be changed independently from the VM.
 753 static void call_postVMInitHook(TRAPS) {
 754   Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
 755   if (klass != NULL) {
 756     JavaValue result(T_VOID);
 757     JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
 758                            vmSymbols::void_method_signature(),
 759                            CHECK);
 760   }
 761 }
 762 
 763 // Initialized by VMThread at vm_global_init
 764 static OopStorage* _thread_oop_storage = NULL;
 765 
 766 oop  JavaThread::threadObj() const    {
 767   return _threadObj.resolve();
 768 }
 769 
 770 void JavaThread::set_threadObj(oop p) {
 771   assert(_thread_oop_storage != NULL, "not yet initialized");
 772   _threadObj = OopHandle(_thread_oop_storage, p);




















 773 }
 774 
 775 OopStorage* JavaThread::thread_oop_storage() {
 776   assert(_thread_oop_storage != NULL, "not yet initialized");
 777   return _thread_oop_storage;
 778 }
 779 
 780 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
 781                                     bool daemon, TRAPS) {
 782   assert(thread_group.not_null(), "thread group should be specified");
 783   assert(threadObj() == NULL, "should only create Java thread object once");
 784 
 785   InstanceKlass* ik = vmClasses::Thread_klass();
 786   assert(ik->is_initialized(), "must be");
 787   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 788 
 789   // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
 790   // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 791   // constructor calls Thread.current(), which must be set here.
 792   java_lang_Thread::set_thread(thread_oop(), this);
 793   java_lang_Thread::set_priority(thread_oop(), NormPriority);
 794   set_threadObj(thread_oop());
 795 
 796   JavaValue result(T_VOID);
 797   if (thread_name != NULL) {
 798     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
 799     // Thread gets assigned specified name and null target
 800     JavaCalls::call_special(&result,
 801                             thread_oop,
 802                             ik,
 803                             vmSymbols::object_initializer_name(),
 804                             vmSymbols::threadgroup_string_void_signature(),
 805                             thread_group,
 806                             name,
 807                             THREAD);
 808   } else {
 809     // Thread gets assigned name "Thread-nnn" and null target
 810     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
 811     JavaCalls::call_special(&result,
 812                             thread_oop,
 813                             ik,
 814                             vmSymbols::object_initializer_name(),
 815                             vmSymbols::threadgroup_runnable_void_signature(),
 816                             thread_group,
 817                             Handle(),
 818                             THREAD);
 819   }
 820 
 821 
 822   if (daemon) {
 823     java_lang_Thread::set_daemon(thread_oop());
 824   }
 825 
 826   if (HAS_PENDING_EXCEPTION) {
 827     return;
 828   }
 829 
 830   Klass* group = vmClasses::ThreadGroup_klass();
 831   Handle threadObj(THREAD, this->threadObj());
 832 
 833   JavaCalls::call_special(&result,
 834                           thread_group,
 835                           group,
 836                           vmSymbols::add_method_name(),
 837                           vmSymbols::thread_void_signature(),
 838                           threadObj,          // Arg 1
 839                           THREAD);
 840 }
 841 
 842 // ======= JavaThread ========
 843 
 844 #if INCLUDE_JVMCI
 845 
 846 jlong* JavaThread::_jvmci_old_thread_counters;
 847 
 848 bool jvmci_counters_include(JavaThread* thread) {
 849   return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
 850 }
 851 
 852 void JavaThread::collect_counters(jlong* array, int length) {
 853   assert(length == JVMCICounterSize, "wrong value");
 854   for (int i = 0; i < length; i++) {
 855     array[i] = _jvmci_old_thread_counters[i];
 856   }
 857   for (JavaThread* tp : ThreadsListHandle()) {
 858     if (jvmci_counters_include(tp)) {
 859       for (int i = 0; i < length; i++) {

 972   if (GCALotAtAllSafepoints) {
 973     // We could enter a safepoint here and thus have a gc
 974     InterfaceSupport::check_gc_alot();
 975   }
 976 }
 977 #endif // ASSERT
 978 
 979 // A JavaThread is a normal Java thread
 980 
 981 JavaThread::JavaThread() :
 982   // Initialize fields
 983 
 984   _on_thread_list(false),
 985   DEBUG_ONLY(_java_call_counter(0) COMMA)
 986   _entry_point(nullptr),
 987   _deopt_mark(nullptr),
 988   _deopt_nmethod(nullptr),
 989   _vframe_array_head(nullptr),
 990   _vframe_array_last(nullptr),
 991   _jvmti_deferred_updates(nullptr),

 992   _callee_target(nullptr),
 993   _vm_result(nullptr),
 994   _vm_result_2(nullptr),
 995 
 996   _current_pending_monitor(NULL),
 997   _current_pending_monitor_is_from_java(true),
 998   _current_waiting_monitor(NULL),
 999   _Stalled(0),
1000 
1001   _monitor_chunks(nullptr),
1002 
1003   _suspend_flags(0),
1004   _pending_async_exception(nullptr),
1005 #ifdef ASSERT
1006   _is_unsafe_access_error(false),
1007 #endif
1008 
1009   _thread_state(_thread_new),
1010   _saved_exception_pc(nullptr),
1011 #ifdef ASSERT
1012   _no_safepoint_count(0),
1013   _visited_for_critical_count(false),
1014 #endif
1015 
1016   _terminated(_not_terminated),
1017   _in_deopt_handler(0),
1018   _doing_unsafe_access(false),
1019   _do_not_unlock_if_synchronized(false),




1020   _jni_attach_state(_not_attaching_via_jni),
1021 #if INCLUDE_JVMCI
1022   _pending_deoptimization(-1),
1023   _pending_monitorenter(false),
1024   _pending_transfer_to_interpreter(false),
1025   _in_retryable_allocation(false),
1026   _pending_failed_speculation(0),
1027   _jvmci{nullptr},
1028   _jvmci_counters(nullptr),
1029   _jvmci_reserved0(0),
1030   _jvmci_reserved1(0),
1031   _jvmci_reserved_oop0(nullptr),
1032 #endif // INCLUDE_JVMCI
1033 
1034   _exception_oop(oop()),
1035   _exception_pc(0),
1036   _exception_handler_pc(0),
1037   _is_method_handle_return(0),
1038 
1039   _jni_active_critical(0),
1040   _pending_jni_exception_check_fn(nullptr),
1041   _depth_first_number(0),
1042 
1043   // JVMTI PopFrame support
1044   _popframe_condition(popframe_inactive),
1045   _frames_to_pop_failed_realloc(0),
1046 








1047   _handshake(this),
1048 
1049   _popframe_preserved_args(nullptr),
1050   _popframe_preserved_args_size(0),
1051 
1052   _jvmti_thread_state(nullptr),
1053   _interp_only_mode(0),
1054   _should_post_on_exceptions_flag(JNI_FALSE),
1055   _thread_stat(new ThreadStatistics()),
1056 
1057   _parker(),
1058 
1059   _class_to_be_initialized(nullptr),
1060 
1061   _SleepEvent(ParkEvent::Allocate(this))
1062 {
1063   set_jni_functions(jni_functions());
1064 
1065 #if INCLUDE_JVMCI
1066   assert(_jvmci._implicit_exception_pc == nullptr, "must be");
1067   if (JVMCICounterSize > 0) {
1068     resize_counters(0, (int) JVMCICounterSize);
1069   }
1070 #endif // INCLUDE_JVMCI
1071 
1072   // Setup safepoint state info for this thread
1073   ThreadSafepointState::create(this);
1074 
1075   SafepointMechanism::initialize_header(this);
1076 
1077   set_requires_cross_modify_fence(false);
1078 
1079   pd_initialize();
1080   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1081 }
1082 
1083 JavaThread::JavaThread(bool is_attaching_via_jni) : JavaThread() {
1084   if (is_attaching_via_jni) {
1085     _jni_attach_state = _attaching_via_jni;
1086   }
1087 }
1088 
1089 
1090 // interrupt support
1091 

1167   os::ThreadType thr_type = os::java_thread;
1168   thr_type = entry_point == &CompilerThread::thread_entry ? os::compiler_thread :
1169                                                             os::java_thread;
1170   os::create_thread(this, thr_type, stack_sz);
1171   // The _osthread may be NULL here because we ran out of memory (too many threads active).
1172   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1173   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1174   // the exception consists of creating the exception object & initializing it, initialization
1175   // will leave the VM via a JavaCall and then all locks must be unlocked).
1176   //
1177   // The thread is still suspended when we reach here. Thread must be explicit started
1178   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1179   // by calling Threads:add. The reason why this is not done here, is because the thread
1180   // object must be fully initialized (take a look at JVM_Start)
1181 }
1182 
1183 JavaThread::~JavaThread() {
1184 
1185   // Ask ServiceThread to release the threadObj OopHandle
1186   ServiceThread::add_oop_handle_release(_threadObj);

1187 
1188   // Return the sleep event to the free list
1189   ParkEvent::Release(_SleepEvent);
1190   _SleepEvent = NULL;
1191 
1192   // Free any remaining  previous UnrollBlock
1193   vframeArray* old_array = vframe_array_last();
1194 
1195   if (old_array != NULL) {
1196     Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
1197     old_array->set_unroll_block(NULL);
1198     delete old_info;
1199     delete old_array;
1200   }
1201 
1202   JvmtiDeferredUpdates* updates = deferred_updates();
1203   if (updates != NULL) {
1204     // This can only happen if thread is destroyed before deoptimization occurs.
1205     assert(updates->count() > 0, "Updates holder not deleted");
1206     // free deferred updates.

1343       // Call method Thread.dispatchUncaughtException().
1344       Klass* thread_klass = vmClasses::Thread_klass();
1345       JavaValue result(T_VOID);
1346       JavaCalls::call_virtual(&result,
1347                               threadObj, thread_klass,
1348                               vmSymbols::dispatchUncaughtException_name(),
1349                               vmSymbols::throwable_void_signature(),
1350                               uncaught_exception,
1351                               THREAD);
1352       if (HAS_PENDING_EXCEPTION) {
1353         ResourceMark rm(this);
1354         jio_fprintf(defaultStream::error_stream(),
1355                     "\nException: %s thrown from the UncaughtExceptionHandler"
1356                     " in thread \"%s\"\n",
1357                     pending_exception()->klass()->external_name(),
1358                     name());
1359         CLEAR_PENDING_EXCEPTION;
1360       }
1361     }
1362 
1363     // Call Thread.exit(). We try 3 times in case we got another Thread.stop during
1364     // the execution of the method. If that is not enough, then we don't really care. Thread.stop
1365     // is deprecated anyhow.
1366     if (!is_Compiler_thread()) {
1367       int count = 3;
1368       while (java_lang_Thread::threadGroup(threadObj()) != NULL && (count-- > 0)) {
1369         EXCEPTION_MARK;
1370         JavaValue result(T_VOID);
1371         Klass* thread_klass = vmClasses::Thread_klass();
1372         JavaCalls::call_virtual(&result,
1373                                 threadObj, thread_klass,
1374                                 vmSymbols::exit_method_name(),
1375                                 vmSymbols::void_method_signature(),
1376                                 THREAD);
1377         CLEAR_PENDING_EXCEPTION;
1378       }
1379     }
1380     // notify JVMTI
1381     if (JvmtiExport::should_post_thread_life()) {
1382       JvmtiExport::post_thread_end(this);
1383     }
1384 
1385     // The careful dance between thread suspension and exit is handled here.
1386     // Since we are in thread_in_vm state and suspension is done with handshakes,
1387     // we can just put in the exiting state and it will be correctly handled.
1388     set_terminated(_thread_exiting);
1389 
1390     ThreadService::current_thread_exiting(this, is_daemon(threadObj()));
1391   } else {
1392     assert(!is_terminated() && !is_exiting(), "must not be exiting");
1393     // before_exit() has already posted JVMTI THREAD_END events
1394   }
1395 
1396   if (log_is_enabled(Debug, os, thread, timer)) {
1397     _timer_exit_phase1.stop();
1398     _timer_exit_phase2.start();

1411     _timer_exit_phase2.stop();
1412     _timer_exit_phase3.start();
1413   }
1414   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1415   // held by this thread must be released. The spec does not distinguish
1416   // between JNI-acquired and regular Java monitors. We can only see
1417   // regular Java monitors here if monitor enter-exit matching is broken.
1418   //
1419   // ensure_join() ignores IllegalThreadStateExceptions, and so does
1420   // ObjectSynchronizer::release_monitors_owned_by_thread().
1421   if (exit_type == jni_detach) {
1422     // Sanity check even though JNI DetachCurrentThread() would have
1423     // returned JNI_ERR if there was a Java frame. JavaThread exit
1424     // should be done executing Java code by the time we get here.
1425     assert(!this->has_last_Java_frame(),
1426            "should not have a Java frame when detaching or exiting");
1427     ObjectSynchronizer::release_monitors_owned_by_thread(this);
1428     assert(!this->has_pending_exception(), "release_monitors should have cleared");
1429   }
1430 


1431   // These things needs to be done while we are still a Java Thread. Make sure that thread
1432   // is in a consistent state, in case GC happens
1433   JFR_ONLY(Jfr::on_thread_exit(this);)
1434 
1435   if (active_handles() != NULL) {
1436     JNIHandleBlock* block = active_handles();
1437     set_active_handles(NULL);
1438     JNIHandleBlock::release_block(block);
1439   }
1440 
1441   if (free_handle_block() != NULL) {
1442     JNIHandleBlock* block = free_handle_block();
1443     set_free_handle_block(NULL);
1444     JNIHandleBlock::release_block(block);
1445   }
1446 
1447   // These have to be removed while this is still a valid thread.
1448   _stack_overflow_state.remove_stack_guard_pages();
1449 
1450   if (UseTLAB) {

1593       frame caller_fr = last_frame().sender(&map);
1594       assert(caller_fr.is_compiled_frame(), "what?");
1595       if (caller_fr.is_deoptimized_frame()) {
1596         log_info(exceptions)("deferred async exception at compiled safepoint");
1597         return;
1598       }
1599     }
1600   }
1601 
1602   if (!clear_async_exception_condition()) {
1603     return;
1604   }
1605 
1606   if (_pending_async_exception != NULL) {
1607     // Only overwrite an already pending exception if it is not a threadDeath.
1608     if (!has_pending_exception() || !pending_exception()->is_a(vmClasses::ThreadDeath_klass())) {
1609 
1610       // We cannot call Exceptions::_throw(...) here because we cannot block
1611       set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
1612 






1613       LogTarget(Info, exceptions) lt;
1614       if (lt.is_enabled()) {
1615         ResourceMark rm;
1616         LogStream ls(lt);
1617         ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this));
1618           if (has_last_Java_frame()) {
1619             frame f = last_frame();
1620            ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp()));
1621           }
1622         ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name());
1623       }
1624     }
1625     // Always null out the _pending_async_exception oop here since the async condition was
1626     // already cleared above and thus considered handled.
1627     _pending_async_exception = NULL;
1628   } else {
1629     assert(_is_unsafe_access_error, "must be");
1630     DEBUG_ONLY(_is_unsafe_access_error = false);
1631 
1632     // We may be at method entry which requires we save the do-not-unlock flag.

1649     default:
1650       ShouldNotReachHere();
1651     }
1652   }
1653 }
1654 
1655 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
1656 
1657   if (is_obj_deopt_suspend()) {
1658     frame_anchor()->make_walkable(this);
1659     wait_for_object_deoptimization();
1660   }
1661 
1662   // We might be here for reasons in addition to the self-suspend request
1663   // so check for other async requests.
1664   if (check_asyncs) {
1665     check_and_handle_async_exceptions();
1666   }
1667 
1668   JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)





1669 }
1670 
1671 class InstallAsyncExceptionClosure : public HandshakeClosure {
1672   Handle _throwable; // The Throwable thrown at the target Thread
1673 public:
1674   InstallAsyncExceptionClosure(Handle throwable) : HandshakeClosure("InstallAsyncException"), _throwable(throwable) {}
1675 
1676   void do_thread(Thread* thr) {
1677     JavaThread* target = JavaThread::cast(thr);
1678     // Note that this now allows multiple ThreadDeath exceptions to be
1679     // thrown at a thread.
1680     // The target thread has run and has not exited yet.
1681     target->send_thread_stop(_throwable());
1682   }
1683 };
1684 
1685 void JavaThread::send_async_exception(JavaThread* target, oop java_throwable) {
1686   Handle throwable(Thread::current(), java_throwable);
1687   InstallAsyncExceptionClosure vm_stop(throwable);
1688   Handshake::execute(&vm_stop, target);

1718 
1719       // Set async. pending exception in thread.
1720       set_pending_async_exception(java_throwable);
1721 
1722       if (log_is_enabled(Info, exceptions)) {
1723          ResourceMark rm;
1724         log_info(exceptions)("Pending Async. exception installed of type: %s",
1725                              InstanceKlass::cast(_pending_async_exception->klass())->external_name());
1726       }
1727       // for AbortVMOnException flag
1728       Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name());
1729     }
1730   }
1731 
1732 
1733   // Interrupt thread so it will wake up from a potential wait()/sleep()/park()
1734   java_lang_Thread::set_interrupted(threadObj(), true);
1735   this->interrupt();
1736 }
1737 













1738 
1739 // External suspension mechanism.
1740 //
1741 // Guarantees on return (for a valid target thread):
1742 //   - Target thread will not execute any new bytecode.
1743 //   - Target thread will not enter any new monitors.
1744 //
1745 bool JavaThread::java_suspend() {












1746   ThreadsListHandle tlh;
1747   if (!tlh.includes(this)) {
1748     log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, no suspension", p2i(this));
1749     return false;
1750   }
1751   return this->handshake_state()->suspend();
1752 }
1753 
1754 bool JavaThread::java_resume() {
1755   ThreadsListHandle tlh;
1756   if (!tlh.includes(this)) {
1757     log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, nothing to resume", p2i(this));
1758     return false;
1759   }
1760   return this->handshake_state()->resume();
1761 }
1762 



















1763 // Wait for another thread to perform object reallocation and relocking on behalf of
1764 // this thread.
1765 // Raw thread state transition to _thread_blocked and back again to the original
1766 // state before returning are performed. The current thread is required to
1767 // change to _thread_blocked in order to be seen to be safepoint/handshake safe
1768 // whilst suspended and only after becoming handshake safe, the other thread can
1769 // complete the handshake used to synchronize with this thread and then perform
1770 // the reallocation and relocking. We cannot use the thread state transition
1771 // helpers because we arrive here in various states and also because the helpers
1772 // indirectly call this method.  After leaving _thread_blocked we have to check
1773 // for safepoint/handshake, except if _thread_in_native. The thread is safe
1774 // without blocking then. Allowed states are enumerated in
1775 // SafepointSynchronize::block(). See also EscapeBarrier::sync_and_suspend_*()
1776 
1777 void JavaThread::wait_for_object_deoptimization() {
1778   assert(!has_last_Java_frame() || frame_anchor()->walkable(), "should have walkable stack");
1779   assert(this == Thread::current(), "invariant");
1780   JavaThreadState state = thread_state();
1781 
1782   bool spin_wait = os::is_MP();

1903     if (fst.current()->can_be_deoptimized()) {
1904       // it is a Java nmethod
1905       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
1906       nm->make_not_entrant();
1907     }
1908   }
1909 }
1910 #endif // PRODUCT
1911 
1912 
1913 void JavaThread::deoptimize_marked_methods() {
1914   if (!has_last_Java_frame()) return;
1915   StackFrameStream fst(this, false /* update */, true /* process_frames */);
1916   for (; !fst.is_done(); fst.next()) {
1917     if (fst.current()->should_be_deoptimized()) {
1918       Deoptimization::deoptimize(this, *fst.current());
1919     }
1920   }
1921 }
1922 


















1923 #ifdef ASSERT
1924 void JavaThread::verify_frame_info() {
1925   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
1926          (has_last_Java_frame() && java_call_counter() > 0),
1927          "unexpected frame info: has_last_frame=%s, java_call_counter=%d",
1928          has_last_Java_frame() ? "true" : "false", java_call_counter());
1929 }
1930 #endif
1931 
1932 void JavaThread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
1933   // Verify that the deferred card marks have been flushed.
1934   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
1935 
1936   // Traverse the GCHandles
1937   Thread::oops_do_no_frames(f, cf);
1938 
1939   DEBUG_ONLY(verify_frame_info();)
1940 
1941   if (has_last_Java_frame()) {
1942     // Traverse the monitor chunks

1950   // written
1951   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(this);
1952   if (list != NULL) {
1953     for (int i = 0; i < list->length(); i++) {
1954       list->at(i)->oops_do(f);
1955     }
1956   }
1957 
1958   // Traverse instance variables at the end since the GC may be moving things
1959   // around using this function
1960   f->do_oop((oop*) &_vm_result);
1961   f->do_oop((oop*) &_exception_oop);
1962   f->do_oop((oop*) &_pending_async_exception);
1963 #if INCLUDE_JVMCI
1964   f->do_oop((oop*) &_jvmci_reserved_oop0);
1965 #endif
1966 
1967   if (jvmti_thread_state() != NULL) {
1968     jvmti_thread_state()->oops_do(f, cf);
1969   }


1970 }
1971 
1972 void JavaThread::oops_do_frames(OopClosure* f, CodeBlobClosure* cf) {
1973   if (!has_last_Java_frame()) {
1974     return;
1975   }
1976   // Finish any pending lazy GC activity for the frames
1977   StackWatermarkSet::finish_processing(this, NULL /* context */, StackWatermarkKind::gc);
1978   // Traverse the execution stack
1979   for (StackFrameStream fst(this, true /* update */, false /* process_frames */); !fst.is_done(); fst.next()) {
1980     fst.current()->oops_do(f, cf, fst.register_map());
1981   }
1982 }
1983 
1984 #ifdef ASSERT
1985 void JavaThread::verify_states_for_handshake() {
1986   // This checks that the thread has a correct frame state during a handshake.
1987   verify_frame_info();
1988 }
1989 #endif

2023 }
2024 
2025 // Printing
2026 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2027   switch (_thread_state) {
2028   case _thread_uninitialized:     return "_thread_uninitialized";
2029   case _thread_new:               return "_thread_new";
2030   case _thread_new_trans:         return "_thread_new_trans";
2031   case _thread_in_native:         return "_thread_in_native";
2032   case _thread_in_native_trans:   return "_thread_in_native_trans";
2033   case _thread_in_vm:             return "_thread_in_vm";
2034   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
2035   case _thread_in_Java:           return "_thread_in_Java";
2036   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
2037   case _thread_blocked:           return "_thread_blocked";
2038   case _thread_blocked_trans:     return "_thread_blocked_trans";
2039   default:                        return "unknown thread state";
2040   }
2041 }
2042 
2043 #ifndef PRODUCT
2044 void JavaThread::print_thread_state_on(outputStream *st) const {
2045   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
2046 };
2047 #endif // PRODUCT


2048 
2049 // Called by Threads::print() for VM_PrintThreads operation
2050 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
2051   st->print_raw("\"");
2052   st->print_raw(name());
2053   st->print_raw("\" ");
2054   oop thread_oop = threadObj();
2055   if (thread_oop != NULL) {
2056     st->print("#" INT64_FORMAT " ", (int64_t)java_lang_Thread::thread_id(thread_oop));
2057     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
2058     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2059   }
2060   Thread::print_on(st, print_extended_info);
2061   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
2062   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
2063   if (thread_oop != NULL) {
2064     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
2065   }
2066 #ifndef PRODUCT
2067   _safepoint_state->print_on(st);
2068 #endif // PRODUCT
2069   if (is_Compiler_thread()) {
2070     CompileTask *task = ((CompilerThread*)this)->task();
2071     if (task != NULL) {
2072       st->print("   Compiling: ");
2073       task->print(st, NULL, true, false);
2074     } else {
2075       st->print("   No compile task");
2076     }

2083 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
2084   st->print("%s", get_thread_name_string(buf, buflen));
2085 }
2086 
2087 // Called by fatal error handler. The difference between this and
2088 // JavaThread::print() is that we can't grab lock or allocate memory.
2089 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
2090   st->print("%s \"%s\"", type_name(), get_thread_name_string(buf, buflen));
2091   oop thread_obj = threadObj();
2092   if (thread_obj != NULL) {
2093     if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
2094   }
2095   st->print(" [");
2096   st->print("%s", _get_thread_state_name(_thread_state));
2097   if (osthread()) {
2098     st->print(", id=%d", osthread()->thread_id());
2099   }
2100   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
2101             p2i(stack_end()), p2i(stack_base()));
2102   st->print("]");

2103 
2104   ThreadsSMRSupport::print_info_on(this, st);
2105   return;
2106 }
2107 
2108 
2109 // Verification
2110 
2111 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2112   // ignore if there is no stack
2113   if (!has_last_Java_frame()) return;
2114   // traverse the stack frames. Starts from top frame.
2115   for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2116     frame* fr = fst.current();
2117     f(fr, fst.register_map());
2118   }
2119 }
2120 
2121 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
2122 

2187 
2188   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2189   assert(NoPriority <= prio && prio <= MaxPriority, "sanity check");
2190   // Link Java Thread object <-> C++ Thread
2191 
2192   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
2193   // and put it into a new Handle.  The Handle "thread_oop" can then
2194   // be used to pass the C++ thread object to other methods.
2195 
2196   // Set the Java level thread object (jthread) field of the
2197   // new thread (a JavaThread *) to C++ thread object using the
2198   // "thread_oop" handle.
2199 
2200   // Set the thread field (a JavaThread *) of the
2201   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
2202 
2203   Handle thread_oop(Thread::current(),
2204                     JNIHandles::resolve_non_null(jni_thread));
2205   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
2206          "must be initialized");
2207   set_threadObj(thread_oop());
2208   java_lang_Thread::set_thread(thread_oop(), this);
2209 
2210   if (prio == NoPriority) {
2211     prio = java_lang_Thread::priority(thread_oop());
2212     assert(prio != NoPriority, "A valid priority should be present");
2213   }
2214 
2215   // Push the Java priority down to the native thread; needs Threads_lock
2216   Thread::set_priority(this, prio);
2217 
2218   // Add the new thread to the Threads list and set it in motion.
2219   // We must have threads lock in order to call Threads::add.
2220   // It is crucial that we do not block before the thread is
2221   // added to the Threads list for if a GC happens, then the java_thread oop
2222   // will not be visited by GC.
2223   Threads::add(this);
2224 }
2225 
2226 oop JavaThread::current_park_blocker() {
2227   // Support for JSR-166 locks
2228   oop thread_oop = threadObj();
2229   if (thread_oop != NULL) {
2230     return java_lang_Thread::park_blocker(thread_oop);
2231   }
2232   return NULL;
2233 }
2234 
2235 
2236 void JavaThread::print_stack_on(outputStream* st) {
2237   if (!has_last_Java_frame()) return;
2238 
2239   Thread* current_thread = Thread::current();
2240   ResourceMark rm(current_thread);
2241   HandleMark hm(current_thread);
2242 
2243   RegisterMap reg_map(this);
2244   vframe* start_vf = last_java_vframe(&reg_map);
2245   int count = 0;
2246   for (vframe* f = start_vf; f != NULL; f = f->sender()) {
2247     if (f->is_java_frame()) {
2248       javaVFrame* jvf = javaVFrame::cast(f);
2249       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
2250 
2251       // Print out lock information
2252       if (JavaMonitorsInStackTrace) {
2253         jvf->print_lock_info_on(st, count);
2254       }
2255     } else {
2256       // Ignore non-Java frames
2257     }
2258 
2259     // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0
2260     count++;
2261     if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return;
2262   }
2263 }
2264 














2265 
2266 // JVMTI PopFrame support
2267 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
2268   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
2269   if (in_bytes(size_in_bytes) != 0) {
2270     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
2271     _popframe_preserved_args_size = in_bytes(size_in_bytes);
2272     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
2273   }
2274 }
2275 
2276 void* JavaThread::popframe_preserved_args() {
2277   return _popframe_preserved_args;
2278 }
2279 
2280 ByteSize JavaThread::popframe_preserved_args_size() {
2281   return in_ByteSize(_popframe_preserved_args_size);
2282 }
2283 
2284 WordSize JavaThread::popframe_preserved_args_size_in_words() {

2318       } else {
2319         obj->print();
2320       }
2321     } else {
2322       tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
2323     }
2324     tty->cr();
2325   }
2326  public:
2327   virtual void do_oop(oop* p) { do_oop_work(p); }
2328   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
2329 };
2330 
2331 #ifdef ASSERT
2332 // Print or validate the layout of stack frames
2333 void JavaThread::print_frame_layout(int depth, bool validate_only) {
2334   ResourceMark rm;
2335   PreserveExceptionMark pm(this);
2336   FrameValues values;
2337   int frame_no = 0;
2338   for (StackFrameStream fst(this, false /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2339     fst.current()->describe(values, ++frame_no);

2340     if (depth == frame_no) break;
2341   }

2342   if (validate_only) {
2343     values.validate();
2344   } else {
2345     tty->print_cr("[Describe stack layout]");
2346     values.print(this);
2347   }
2348 }
2349 #endif
2350 
2351 void JavaThread::trace_stack_from(vframe* start_vf) {
2352   ResourceMark rm;
2353   int vframe_no = 1;
2354   for (vframe* f = start_vf; f; f = f->sender()) {
2355     if (f->is_java_frame()) {
2356       javaVFrame::cast(f)->print_activation(vframe_no++);
2357     } else {
2358       f->print();
2359     }
2360     if (vframe_no > StackPrintLimit) {
2361       tty->print_cr("...<more frames>...");
2362       return;
2363     }
2364   }
2365 }
2366 
2367 
2368 void JavaThread::trace_stack() {
2369   if (!has_last_Java_frame()) return;
2370   Thread* current_thread = Thread::current();
2371   ResourceMark rm(current_thread);
2372   HandleMark hm(current_thread);
2373   RegisterMap reg_map(this);
2374   trace_stack_from(last_java_vframe(&reg_map));
2375 }
2376 
2377 
2378 #endif // PRODUCT
2379 
2380 
2381 javaVFrame* JavaThread::last_java_vframe(RegisterMap *reg_map) {








2382   assert(reg_map != NULL, "a map must be given");
2383   frame f = last_frame();
2384   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
2385     if (vf->is_java_frame()) return javaVFrame::cast(vf);
2386   }
2387   return NULL;
2388 }
2389 
2390 
2391 Klass* JavaThread::security_get_caller_class(int depth) {



2392   vframeStream vfst(this);
2393   vfst.security_get_caller_frame(depth);
2394   if (!vfst.at_end()) {
2395     return vfst.method()->method_holder();
2396   }
2397   return NULL;
2398 }
2399 
2400 // java.lang.Thread.sleep support
2401 // Returns true if sleep time elapsed as expected, and false
2402 // if the thread was interrupted.
2403 bool JavaThread::sleep(jlong millis) {
2404   assert(this == Thread::current(),  "thread consistency check");
2405 
2406   ParkEvent * const slp = this->_SleepEvent;
2407   // Because there can be races with thread interruption sending an unpark()
2408   // to the event, we explicitly reset it here to avoid an immediate return.
2409   // The actual interrupt state will be checked before we park().
2410   slp->reset();
2411   // Thread interruption establishes a happens-before ordering in the

3693                VM_Version::vm_name(),
3694                VM_Version::vm_release(),
3695                VM_Version::vm_info_string());
3696   st->cr();
3697 
3698 #if INCLUDE_SERVICES
3699   // Dump concurrent locks
3700   ConcurrentLocksDump concurrent_locks;
3701   if (print_concurrent_locks) {
3702     concurrent_locks.dump_at_safepoint();
3703   }
3704 #endif // INCLUDE_SERVICES
3705 
3706   ThreadsSMRSupport::print_info_on(st);
3707   st->cr();
3708 
3709   ALL_JAVA_THREADS(p) {
3710     ResourceMark rm;
3711     p->print_on(st, print_extended_info);
3712     if (print_stacks) {






3713       if (internal_format) {
3714         p->trace_stack();
3715       } else {
3716         p->print_stack_on(st);
3717       }
3718     }
3719     st->cr();
3720 #if INCLUDE_SERVICES
3721     if (print_concurrent_locks) {
3722       concurrent_locks.print_locks_on(p, st);
3723     }
3724 #endif // INCLUDE_SERVICES
3725   }
3726 
3727   PrintOnClosure cl(st);
3728   cl.do_thread(VMThread::vm_thread());
3729   Universe::heap()->gc_threads_do(&cl);
3730   if (StringDedup::is_enabled()) {
3731     StringDedup::threads_do(&cl);
3732   }

3811 
3812 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) {
3813   ALL_JAVA_THREADS(thread) {
3814     if (thread->is_Compiler_thread()) {
3815       CompilerThread* ct = (CompilerThread*) thread;
3816 
3817       // Keep task in local variable for NULL check.
3818       // ct->_task might be set to NULL by concurring compiler thread
3819       // because it completed the compilation. The task is never freed,
3820       // though, just returned to a free list.
3821       CompileTask* task = ct->task();
3822       if (task != NULL) {
3823         thread->print_name_on_error(st, buf, buflen);
3824         st->print("  ");
3825         task->print(st, NULL, short_form, true);
3826       }
3827     }
3828   }
3829 }
3830 
3831 
3832 // Ad-hoc mutual exclusion primitives: SpinLock
3833 //
3834 // We employ SpinLocks _only for low-contention, fixed-length
3835 // short-duration critical sections where we're concerned
3836 // about native mutex_t or HotSpot Mutex:: latency.
3837 //
3838 // TODO-FIXME: ListLock should be of type SpinLock.
3839 // We should make this a 1st-class type, integrated into the lock
3840 // hierarchy as leaf-locks.  Critically, the SpinLock structure
3841 // should have sufficient padding to avoid false-sharing and excessive
3842 // cache-coherency traffic.
3843 
3844 
3845 typedef volatile int SpinLockT;
3846 
3847 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
3848   if (Atomic::cmpxchg(adr, 0, 1) == 0) {
3849     return;   // normal fast-path return
3850   }
3851 

3885   // more than covers this on all platforms.
3886   *adr = 0;
3887 }
3888 
3889 
3890 void Threads::verify() {
3891   ALL_JAVA_THREADS(p) {
3892     p->verify();
3893   }
3894   VMThread* thread = VMThread::vm_thread();
3895   if (thread != NULL) thread->verify();
3896 }
3897 
3898 #ifndef PRODUCT
3899 void JavaThread::verify_cross_modify_fence_failure(JavaThread *thread) {
3900    report_vm_error(__FILE__, __LINE__, "Cross modify fence failure", "%p", thread);
3901 }
3902 #endif
3903 
3904 // Helper function to create the java.lang.Thread object for a
3905 // VM-internal thread. The thread will have the given name, be
3906 // part of the System ThreadGroup and if is_visible is true will be
3907 // discoverable via the system ThreadGroup.
3908 Handle JavaThread::create_system_thread_object(const char* name,
3909                                                bool is_visible, TRAPS) {
3910   Handle string = java_lang_String::create_from_str(name, CHECK_NH);
3911 
3912   // Initialize thread_oop to put it into the system threadGroup.
3913   // This is done by calling the Thread(ThreadGroup tg, String name)
3914   // constructor, which adds the new thread to the group as an unstarted
3915   // thread.
3916   Handle thread_group(THREAD, Universe::system_thread_group());
3917   Handle thread_oop =
3918     JavaCalls::construct_new_instance(vmClasses::Thread_klass(),
3919                                       vmSymbols::threadgroup_string_void_signature(),
3920                                       thread_group,
3921                                       string,
3922                                       CHECK_NH);
3923 
3924   // If the Thread is intended to be visible then we have to mimic what
3925   // Thread.start() would do, by adding it to its ThreadGroup: tg.add(t).
3926   if (is_visible) {
3927     Klass* group = vmClasses::ThreadGroup_klass();
3928     JavaValue result(T_VOID);
3929     JavaCalls::call_special(&result,
3930                             thread_group,
3931                             group,
3932                             vmSymbols::add_method_name(),
3933                             vmSymbols::thread_void_signature(),
3934                             thread_oop,
3935                             CHECK_NH);
3936   }
3937 
3938   return thread_oop;
3939 }
3940 
3941 // Starts the target JavaThread as a daemon of the given priority, and
3942 // bound to the given java.lang.Thread instance.
3943 // The Threads_lock is held for the duration.
3944 void JavaThread::start_internal_daemon(JavaThread* current, JavaThread* target,
3945                                        Handle thread_oop, ThreadPriority prio) {
3946 
3947   assert(target->osthread() != NULL, "target thread is not properly initialized");
3948 
3949   MutexLocker mu(current, Threads_lock);
3950 
3951   // Initialize the fields of the thread_oop first.
3952 
3953   java_lang_Thread::set_thread(thread_oop(), target); // isAlive == true now
3954 
3955   if (prio != NoPriority) {
3956     java_lang_Thread::set_priority(thread_oop(), prio);
3957     // Note: we don't call os::set_priority here. Possibly we should,
3958     // else all threads should call it themselves when they first run.
3959   }
3960 
3961   java_lang_Thread::set_daemon(thread_oop());
3962 
3963   // Now bind the thread_oop to the target JavaThread.
3964   target->set_threadObj(thread_oop());
3965 
3966   Threads::add(target); // target is now visible for safepoint/handshake
3967   Thread::start(target);
3968 }
3969 
3970 void JavaThread::vm_exit_on_osthread_failure(JavaThread* thread) {
3971   // At this point it may be possible that no osthread was created for the
3972   // JavaThread due to lack of resources. However, since this must work
3973   // for critical system threads just check and abort if this fails.
3974   if (thread->osthread() == nullptr) {
3975     // This isn't really an OOM condition, but historically this is what
3976     // we report.
3977     vm_exit_during_initialization("java.lang.OutOfMemoryError",
3978                                   os::native_thread_creation_failed_msg());
3979   }
3980 }

  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/barrierSetNMethod.hpp"
  43 #include "gc/shared/collectedHeap.hpp"
  44 #include "gc/shared/gcId.hpp"
  45 #include "gc/shared/gcLocker.inline.hpp"
  46 #include "gc/shared/gcVMOperations.hpp"
  47 #include "gc/shared/oopStorage.hpp"
  48 #include "gc/shared/oopStorageSet.hpp"
  49 #include "gc/shared/stringdedup/stringDedup.hpp"
  50 #include "gc/shared/tlab_globals.hpp"
  51 #include "interpreter/interpreter.hpp"
  52 #include "interpreter/linkResolver.hpp"
  53 #include "interpreter/oopMapCache.hpp"
  54 #include "jfr/jfrEvents.hpp"
  55 #include "jvmtifiles/jvmtiEnv.hpp"
  56 #include "logging/log.hpp"
  57 #include "logging/logAsyncWriter.hpp"
  58 #include "logging/logConfiguration.hpp"
  59 #include "logging/logStream.hpp"
  60 #include "memory/allocation.inline.hpp"
  61 #include "memory/iterator.hpp"
  62 #include "memory/oopFactory.hpp"
  63 #include "memory/resourceArea.hpp"
  64 #include "memory/universe.hpp"
  65 #include "oops/access.inline.hpp"
  66 #include "oops/instanceKlass.hpp"
  67 #include "oops/klass.inline.hpp"
  68 #include "oops/objArrayOop.hpp"
  69 #include "oops/oop.inline.hpp"
  70 #include "oops/oopHandle.inline.hpp"
  71 #include "oops/symbol.hpp"
  72 #include "oops/typeArrayOop.inline.hpp"
  73 #include "oops/verifyOopClosure.hpp"
  74 #include "prims/jvm_misc.hpp"
  75 #include "prims/jvmtiDeferredUpdates.hpp"
  76 #include "prims/jvmtiExport.hpp"
  77 #include "prims/jvmtiThreadState.inline.hpp"
  78 #include "runtime/arguments.hpp"
  79 #include "runtime/atomic.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"

 254   // construct until the _MutexEvent is initialized ...
 255   // CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
 256   // we might instead use a stack of ParkEvents that we could provision on-demand.
 257   // The stack would act as a cache to avoid calls to ParkEvent::Allocate()
 258   // and ::Release()
 259   _ParkEvent   = ParkEvent::Allocate(this);
 260 
 261 #ifdef CHECK_UNHANDLED_OOPS
 262   if (CheckUnhandledOops) {
 263     _unhandled_oops = new UnhandledOops(this);
 264   }
 265 #endif // CHECK_UNHANDLED_OOPS
 266 
 267   // Notify the barrier set that a thread is being created. The initial
 268   // thread is created before the barrier set is available.  The call to
 269   // BarrierSet::on_thread_create() for this thread is therefore deferred
 270   // to BarrierSet::set_barrier_set().
 271   BarrierSet* const barrier_set = BarrierSet::barrier_set();
 272   if (barrier_set != NULL) {
 273     barrier_set->on_thread_create(this);
 274     BarrierSetNMethod* bs_nm = barrier_set->barrier_set_nmethod();
 275     _nmethod_disarm_value = bs_nm->disarmed_value();
 276   } else {
 277     // Only the main thread should be created before the barrier set
 278     // and that happens just before Thread::current is set. No other thread
 279     // can attach as the VM is not created yet, so they can't execute this code.
 280     // If the main thread creates other threads before the barrier set that is an error.
 281     assert(Thread::current_or_null() == NULL, "creating thread before barrier set");
 282   }
 283 
 284   MACOS_AARCH64_ONLY(DEBUG_ONLY(_wx_init = false));
 285 }
 286 
 287 void Thread::initialize_tlab() {
 288   if (UseTLAB) {
 289     tlab().initialize();
 290   }
 291 }
 292 
 293 void Thread::initialize_thread_current() {
 294 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 295   assert(_thr_current == NULL, "Thread::current already initialized");

 692   Handle main_instance = JavaCalls::construct_new_instance(
 693                             vmClasses::ThreadGroup_klass(),
 694                             vmSymbols::threadgroup_string_void_signature(),
 695                             system_instance,
 696                             string,
 697                             CHECK_NH);
 698   return main_instance;
 699 }
 700 
 701 // Creates the initial Thread, and sets it to running.
 702 static void create_initial_thread(Handle thread_group, JavaThread* thread,
 703                                  TRAPS) {
 704   InstanceKlass* ik = vmClasses::Thread_klass();
 705   assert(ik->is_initialized(), "must be");
 706   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 707 
 708   // Cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 709   // constructor calls Thread.current(), which must be set here for the
 710   // initial thread.
 711   java_lang_Thread::set_thread(thread_oop(), thread);
 712   thread->set_threadOopHandles(thread_oop());

 713 
 714   Handle string = java_lang_String::create_from_str("main", CHECK);
 715 
 716   JavaValue result(T_VOID);
 717   JavaCalls::call_special(&result, thread_oop,
 718                           ik,
 719                           vmSymbols::object_initializer_name(),
 720                           vmSymbols::threadgroup_string_void_signature(),
 721                           thread_group,
 722                           string,
 723                           CHECK);
 724 
 725   // Set thread status to running since main thread has
 726   // been started and running.
 727   java_lang_Thread::set_thread_status(thread_oop(),
 728                                       JavaThreadStatus::RUNNABLE);
 729 }
 730 
 731 // Extract version and vendor specific information from
 732 // java.lang.VersionProps fields.

 748   } else {
 749     return NULL;
 750   }
 751 }
 752 
 753 // General purpose hook into Java code, run once when the VM is initialized.
 754 // The Java library method itself may be changed independently from the VM.
 755 static void call_postVMInitHook(TRAPS) {
 756   Klass* klass = SystemDictionary::resolve_or_null(vmSymbols::jdk_internal_vm_PostVMInitHook(), THREAD);
 757   if (klass != NULL) {
 758     JavaValue result(T_VOID);
 759     JavaCalls::call_static(&result, klass, vmSymbols::run_method_name(),
 760                            vmSymbols::void_method_signature(),
 761                            CHECK);
 762   }
 763 }
 764 
 765 // Initialized by VMThread at vm_global_init
 766 static OopStorage* _thread_oop_storage = NULL;
 767 
 768 oop JavaThread::threadObj() const    {
 769   return _threadObj.resolve();
 770 }
 771 
 772 void JavaThread::set_threadOopHandles(oop p) {
 773   assert(_thread_oop_storage != NULL, "not yet initialized");
 774   _threadObj   = OopHandle(_thread_oop_storage, p);
 775   _vthread     = OopHandle(_thread_oop_storage, p);
 776   _scopeLocalCache = OopHandle(_thread_oop_storage, NULL);
 777 }
 778 
 779 oop JavaThread::scopeLocalCache() const {
 780   return _scopeLocalCache.resolve();
 781 }
 782 
 783 oop JavaThread::vthread() const {
 784   return _vthread.resolve();
 785 }
 786 
 787 void JavaThread::set_vthread(oop p) {
 788   assert(_thread_oop_storage != NULL, "not yet initialized");
 789   _vthread.replace(p);
 790 }
 791 
 792 void JavaThread::set_scopeLocalCache(oop p) {
 793   assert(_thread_oop_storage != NULL, "not yet initialized");
 794   _scopeLocalCache.replace(p);
 795 }
 796 
 797 OopStorage* JavaThread::thread_oop_storage() {
 798   assert(_thread_oop_storage != NULL, "not yet initialized");
 799   return _thread_oop_storage;
 800 }
 801 
 802 void JavaThread::allocate_threadObj(Handle thread_group, const char* thread_name,
 803                                     bool daemon, TRAPS) {
 804   assert(thread_group.not_null(), "thread group should be specified");
 805   assert(threadObj() == NULL, "should only create Java thread object once");
 806 
 807   InstanceKlass* ik = vmClasses::Thread_klass();
 808   assert(ik->is_initialized(), "must be");
 809   instanceHandle thread_oop = ik->allocate_instance_handle(CHECK);
 810 
 811   // We are called from jni_AttachCurrentThread/jni_AttachCurrentThreadAsDaemon.
 812   // We cannot use JavaCalls::construct_new_instance because the java.lang.Thread
 813   // constructor calls Thread.current(), which must be set here.
 814   java_lang_Thread::set_thread(thread_oop(), this);
 815   set_threadOopHandles(thread_oop());

 816 
 817   JavaValue result(T_VOID);
 818   if (thread_name != NULL) {
 819     Handle name = java_lang_String::create_from_str(thread_name, CHECK);
 820     // Thread gets assigned specified name and null target
 821     JavaCalls::call_special(&result,
 822                             thread_oop,
 823                             ik,
 824                             vmSymbols::object_initializer_name(),
 825                             vmSymbols::threadgroup_string_void_signature(),
 826                             thread_group,
 827                             name,
 828                             THREAD);
 829   } else {
 830     // Thread gets assigned name "Thread-nnn" and null target
 831     // (java.lang.Thread doesn't have a constructor taking only a ThreadGroup argument)
 832     JavaCalls::call_special(&result,
 833                             thread_oop,
 834                             ik,
 835                             vmSymbols::object_initializer_name(),
 836                             vmSymbols::threadgroup_runnable_void_signature(),
 837                             thread_group,
 838                             Handle(),
 839                             THREAD);
 840   }
 841   os::set_priority(this, NormPriority);
 842 
 843   if (daemon) {
 844     java_lang_Thread::set_daemon(thread_oop());
 845   }















 846 }
 847 
 848 // ======= JavaThread ========
 849 
 850 #if INCLUDE_JVMCI
 851 
 852 jlong* JavaThread::_jvmci_old_thread_counters;
 853 
 854 bool jvmci_counters_include(JavaThread* thread) {
 855   return !JVMCICountersExcludeCompiler || !thread->is_Compiler_thread();
 856 }
 857 
 858 void JavaThread::collect_counters(jlong* array, int length) {
 859   assert(length == JVMCICounterSize, "wrong value");
 860   for (int i = 0; i < length; i++) {
 861     array[i] = _jvmci_old_thread_counters[i];
 862   }
 863   for (JavaThread* tp : ThreadsListHandle()) {
 864     if (jvmci_counters_include(tp)) {
 865       for (int i = 0; i < length; i++) {

 978   if (GCALotAtAllSafepoints) {
 979     // We could enter a safepoint here and thus have a gc
 980     InterfaceSupport::check_gc_alot();
 981   }
 982 }
 983 #endif // ASSERT
 984 
 985 // A JavaThread is a normal Java thread
 986 
 987 JavaThread::JavaThread() :
 988   // Initialize fields
 989 
 990   _on_thread_list(false),
 991   DEBUG_ONLY(_java_call_counter(0) COMMA)
 992   _entry_point(nullptr),
 993   _deopt_mark(nullptr),
 994   _deopt_nmethod(nullptr),
 995   _vframe_array_head(nullptr),
 996   _vframe_array_last(nullptr),
 997   _jvmti_deferred_updates(nullptr),
 998   _keepalive_cleanup(new (ResourceObj::C_HEAP, mtInternal) GrowableArray<WeakHandle>(16, mtInternal)),
 999   _callee_target(nullptr),
1000   _vm_result(nullptr),
1001   _vm_result_2(nullptr),
1002 
1003   _current_pending_monitor(NULL),
1004   _current_pending_monitor_is_from_java(true),
1005   _current_waiting_monitor(NULL),
1006   _Stalled(0),
1007 
1008   _monitor_chunks(nullptr),
1009 
1010   _suspend_flags(0),
1011   _pending_async_exception(nullptr),
1012 #ifdef ASSERT
1013   _is_unsafe_access_error(false),
1014 #endif
1015 
1016   _thread_state(_thread_new),
1017   _saved_exception_pc(nullptr),
1018 #ifdef ASSERT
1019   _no_safepoint_count(0),
1020   _visited_for_critical_count(false),
1021 #endif
1022 
1023   _terminated(_not_terminated),
1024   _in_deopt_handler(0),
1025   _doing_unsafe_access(false),
1026   _do_not_unlock_if_synchronized(false),
1027 #if INCLUDE_JVMTI
1028   _is_in_VTMT(false),
1029   _is_VTMT_disabler(false),
1030 #endif
1031   _jni_attach_state(_not_attaching_via_jni),
1032 #if INCLUDE_JVMCI
1033   _pending_deoptimization(-1),
1034   _pending_monitorenter(false),
1035   _pending_transfer_to_interpreter(false),
1036   _in_retryable_allocation(false),
1037   _pending_failed_speculation(0),
1038   _jvmci{nullptr},
1039   _jvmci_counters(nullptr),
1040   _jvmci_reserved0(0),
1041   _jvmci_reserved1(0),
1042   _jvmci_reserved_oop0(nullptr),
1043 #endif // INCLUDE_JVMCI
1044 
1045   _exception_oop(oop()),
1046   _exception_pc(0),
1047   _exception_handler_pc(0),
1048   _is_method_handle_return(0),
1049 
1050   _jni_active_critical(0),
1051   _pending_jni_exception_check_fn(nullptr),
1052   _depth_first_number(0),
1053 
1054   // JVMTI PopFrame support
1055   _popframe_condition(popframe_inactive),
1056   _frames_to_pop_failed_realloc(0),
1057 
1058   _cont_entry(nullptr),
1059   _cont_yield(false),
1060   _cont_preempt(false),
1061   _cont_fastpath_thread_state(1),
1062   _cont_fastpath(0),
1063   _held_monitor_count(0),
1064   _mounted_vthread(oop()),
1065 
1066   _handshake(this),
1067 
1068   _popframe_preserved_args(nullptr),
1069   _popframe_preserved_args_size(0),
1070 
1071   _jvmti_thread_state(nullptr),
1072   _interp_only_mode(0),
1073   _should_post_on_exceptions_flag(JNI_FALSE),
1074   _thread_stat(new ThreadStatistics()),
1075 
1076   _parker(),
1077 
1078   _class_to_be_initialized(nullptr),
1079 
1080   _SleepEvent(ParkEvent::Allocate(this))
1081 {
1082   set_jni_functions(jni_functions());

1083 #if INCLUDE_JVMCI
1084   assert(_jvmci._implicit_exception_pc == nullptr, "must be");
1085   if (JVMCICounterSize > 0) {
1086     resize_counters(0, (int) JVMCICounterSize);
1087   }
1088 #endif // INCLUDE_JVMCI

1089   // Setup safepoint state info for this thread
1090   ThreadSafepointState::create(this);
1091 
1092   SafepointMechanism::initialize_header(this);
1093 
1094   set_requires_cross_modify_fence(false);
1095 
1096   pd_initialize();
1097   assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
1098 }
1099 
1100 JavaThread::JavaThread(bool is_attaching_via_jni) : JavaThread() {
1101   if (is_attaching_via_jni) {
1102     _jni_attach_state = _attaching_via_jni;
1103   }
1104 }
1105 
1106 
1107 // interrupt support
1108 

1184   os::ThreadType thr_type = os::java_thread;
1185   thr_type = entry_point == &CompilerThread::thread_entry ? os::compiler_thread :
1186                                                             os::java_thread;
1187   os::create_thread(this, thr_type, stack_sz);
1188   // The _osthread may be NULL here because we ran out of memory (too many threads active).
1189   // We need to throw and OutOfMemoryError - however we cannot do this here because the caller
1190   // may hold a lock and all locks must be unlocked before throwing the exception (throwing
1191   // the exception consists of creating the exception object & initializing it, initialization
1192   // will leave the VM via a JavaCall and then all locks must be unlocked).
1193   //
1194   // The thread is still suspended when we reach here. Thread must be explicit started
1195   // by creator! Furthermore, the thread must also explicitly be added to the Threads list
1196   // by calling Threads:add. The reason why this is not done here, is because the thread
1197   // object must be fully initialized (take a look at JVM_Start)
1198 }
1199 
1200 JavaThread::~JavaThread() {
1201 
1202   // Ask ServiceThread to release the threadObj OopHandle
1203   ServiceThread::add_oop_handle_release(_threadObj);
1204   ServiceThread::add_oop_handle_release(_vthread);
1205 
1206   // Return the sleep event to the free list
1207   ParkEvent::Release(_SleepEvent);
1208   _SleepEvent = NULL;
1209 
1210   // Free any remaining  previous UnrollBlock
1211   vframeArray* old_array = vframe_array_last();
1212 
1213   if (old_array != NULL) {
1214     Deoptimization::UnrollBlock* old_info = old_array->unroll_block();
1215     old_array->set_unroll_block(NULL);
1216     delete old_info;
1217     delete old_array;
1218   }
1219 
1220   JvmtiDeferredUpdates* updates = deferred_updates();
1221   if (updates != NULL) {
1222     // This can only happen if thread is destroyed before deoptimization occurs.
1223     assert(updates->count() > 0, "Updates holder not deleted");
1224     // free deferred updates.

1361       // Call method Thread.dispatchUncaughtException().
1362       Klass* thread_klass = vmClasses::Thread_klass();
1363       JavaValue result(T_VOID);
1364       JavaCalls::call_virtual(&result,
1365                               threadObj, thread_klass,
1366                               vmSymbols::dispatchUncaughtException_name(),
1367                               vmSymbols::throwable_void_signature(),
1368                               uncaught_exception,
1369                               THREAD);
1370       if (HAS_PENDING_EXCEPTION) {
1371         ResourceMark rm(this);
1372         jio_fprintf(defaultStream::error_stream(),
1373                     "\nException: %s thrown from the UncaughtExceptionHandler"
1374                     " in thread \"%s\"\n",
1375                     pending_exception()->klass()->external_name(),
1376                     name());
1377         CLEAR_PENDING_EXCEPTION;
1378       }
1379     }
1380 
1381     // Call Thread.exit()


1382     if (!is_Compiler_thread()) {
1383       EXCEPTION_MARK;
1384       JavaValue result(T_VOID);
1385       Klass* thread_klass = vmClasses::Thread_klass();
1386       JavaCalls::call_virtual(&result,
1387                               threadObj, thread_klass,
1388                               vmSymbols::exit_method_name(),
1389                               vmSymbols::void_method_signature(),
1390                               THREAD);
1391       CLEAR_PENDING_EXCEPTION;



1392     }
1393     // notify JVMTI
1394     if (JvmtiExport::should_post_thread_life()) {
1395       JvmtiExport::post_thread_end(this);
1396     }
1397 
1398     // The careful dance between thread suspension and exit is handled here.
1399     // Since we are in thread_in_vm state and suspension is done with handshakes,
1400     // we can just put in the exiting state and it will be correctly handled.
1401     set_terminated(_thread_exiting);
1402 
1403     ThreadService::current_thread_exiting(this, is_daemon(threadObj()));
1404   } else {
1405     assert(!is_terminated() && !is_exiting(), "must not be exiting");
1406     // before_exit() has already posted JVMTI THREAD_END events
1407   }
1408 
1409   if (log_is_enabled(Debug, os, thread, timer)) {
1410     _timer_exit_phase1.stop();
1411     _timer_exit_phase2.start();

1424     _timer_exit_phase2.stop();
1425     _timer_exit_phase3.start();
1426   }
1427   // 6282335 JNI DetachCurrentThread spec states that all Java monitors
1428   // held by this thread must be released. The spec does not distinguish
1429   // between JNI-acquired and regular Java monitors. We can only see
1430   // regular Java monitors here if monitor enter-exit matching is broken.
1431   //
1432   // ensure_join() ignores IllegalThreadStateExceptions, and so does
1433   // ObjectSynchronizer::release_monitors_owned_by_thread().
1434   if (exit_type == jni_detach) {
1435     // Sanity check even though JNI DetachCurrentThread() would have
1436     // returned JNI_ERR if there was a Java frame. JavaThread exit
1437     // should be done executing Java code by the time we get here.
1438     assert(!this->has_last_Java_frame(),
1439            "should not have a Java frame when detaching or exiting");
1440     ObjectSynchronizer::release_monitors_owned_by_thread(this);
1441     assert(!this->has_pending_exception(), "release_monitors should have cleared");
1442   }
1443 
1444   assert(this->held_monitor_count() == 0, "held monitor count should be zero");
1445 
1446   // These things needs to be done while we are still a Java Thread. Make sure that thread
1447   // is in a consistent state, in case GC happens
1448   JFR_ONLY(Jfr::on_thread_exit(this);)
1449 
1450   if (active_handles() != NULL) {
1451     JNIHandleBlock* block = active_handles();
1452     set_active_handles(NULL);
1453     JNIHandleBlock::release_block(block);
1454   }
1455 
1456   if (free_handle_block() != NULL) {
1457     JNIHandleBlock* block = free_handle_block();
1458     set_free_handle_block(NULL);
1459     JNIHandleBlock::release_block(block);
1460   }
1461 
1462   // These have to be removed while this is still a valid thread.
1463   _stack_overflow_state.remove_stack_guard_pages();
1464 
1465   if (UseTLAB) {

1608       frame caller_fr = last_frame().sender(&map);
1609       assert(caller_fr.is_compiled_frame(), "what?");
1610       if (caller_fr.is_deoptimized_frame()) {
1611         log_info(exceptions)("deferred async exception at compiled safepoint");
1612         return;
1613       }
1614     }
1615   }
1616 
1617   if (!clear_async_exception_condition()) {
1618     return;
1619   }
1620 
1621   if (_pending_async_exception != NULL) {
1622     // Only overwrite an already pending exception if it is not a threadDeath.
1623     if (!has_pending_exception() || !pending_exception()->is_a(vmClasses::ThreadDeath_klass())) {
1624 
1625       // We cannot call Exceptions::_throw(...) here because we cannot block
1626       set_pending_exception(_pending_async_exception, __FILE__, __LINE__);
1627 
1628       // Clear any scope-local bindings on ThreadDeath
1629       set_scopeLocalCache(NULL);
1630       oop threadOop = threadObj();
1631       assert(threadOop != NULL, "must be");
1632       java_lang_Thread::clear_scopeLocalBindings(threadOop);
1633 
1634       LogTarget(Info, exceptions) lt;
1635       if (lt.is_enabled()) {
1636         ResourceMark rm;
1637         LogStream ls(lt);
1638         ls.print("Async. exception installed at runtime exit (" INTPTR_FORMAT ")", p2i(this));
1639           if (has_last_Java_frame()) {
1640             frame f = last_frame();
1641            ls.print(" (pc: " INTPTR_FORMAT " sp: " INTPTR_FORMAT " )", p2i(f.pc()), p2i(f.sp()));
1642           }
1643         ls.print_cr(" of type: %s", _pending_async_exception->klass()->external_name());
1644       }
1645     }
1646     // Always null out the _pending_async_exception oop here since the async condition was
1647     // already cleared above and thus considered handled.
1648     _pending_async_exception = NULL;
1649   } else {
1650     assert(_is_unsafe_access_error, "must be");
1651     DEBUG_ONLY(_is_unsafe_access_error = false);
1652 
1653     // We may be at method entry which requires we save the do-not-unlock flag.

1670     default:
1671       ShouldNotReachHere();
1672     }
1673   }
1674 }
1675 
1676 void JavaThread::handle_special_runtime_exit_condition(bool check_asyncs) {
1677 
1678   if (is_obj_deopt_suspend()) {
1679     frame_anchor()->make_walkable(this);
1680     wait_for_object_deoptimization();
1681   }
1682 
1683   // We might be here for reasons in addition to the self-suspend request
1684   // so check for other async requests.
1685   if (check_asyncs) {
1686     check_and_handle_async_exceptions();
1687   }
1688 
1689   JFR_ONLY(SUSPEND_THREAD_CONDITIONAL(this);)
1690 
1691   if (is_cont_force_yield()) {
1692     Continuation::jump_from_safepoint(this); // does not return
1693     ShouldNotReachHere();
1694   }
1695 }
1696 
1697 class InstallAsyncExceptionClosure : public HandshakeClosure {
1698   Handle _throwable; // The Throwable thrown at the target Thread
1699 public:
1700   InstallAsyncExceptionClosure(Handle throwable) : HandshakeClosure("InstallAsyncException"), _throwable(throwable) {}
1701 
1702   void do_thread(Thread* thr) {
1703     JavaThread* target = JavaThread::cast(thr);
1704     // Note that this now allows multiple ThreadDeath exceptions to be
1705     // thrown at a thread.
1706     // The target thread has run and has not exited yet.
1707     target->send_thread_stop(_throwable());
1708   }
1709 };
1710 
1711 void JavaThread::send_async_exception(JavaThread* target, oop java_throwable) {
1712   Handle throwable(Thread::current(), java_throwable);
1713   InstallAsyncExceptionClosure vm_stop(throwable);
1714   Handshake::execute(&vm_stop, target);

1744 
1745       // Set async. pending exception in thread.
1746       set_pending_async_exception(java_throwable);
1747 
1748       if (log_is_enabled(Info, exceptions)) {
1749          ResourceMark rm;
1750         log_info(exceptions)("Pending Async. exception installed of type: %s",
1751                              InstanceKlass::cast(_pending_async_exception->klass())->external_name());
1752       }
1753       // for AbortVMOnException flag
1754       Exceptions::debug_check_abort(_pending_async_exception->klass()->external_name());
1755     }
1756   }
1757 
1758 
1759   // Interrupt thread so it will wake up from a potential wait()/sleep()/park()
1760   java_lang_Thread::set_interrupted(threadObj(), true);
1761   this->interrupt();
1762 }
1763 
1764 #if INCLUDE_JVMTI
1765 void JavaThread::set_is_in_VTMT(bool val) {
1766   _is_in_VTMT = val;
1767   if (val) {
1768     assert(JvmtiVTMTDisabler::VTMT_disable_count() == 0, "must be 0");
1769   }
1770 }
1771 
1772 void JavaThread::set_is_VTMT_disabler(bool val) {
1773   _is_VTMT_disabler = val;
1774   assert(JvmtiVTMTDisabler::VTMT_count() == 0, "must be 0");
1775 }
1776 #endif
1777 
1778 // External suspension mechanism.
1779 //
1780 // Guarantees on return (for a valid target thread):
1781 //   - Target thread will not execute any new bytecode.
1782 //   - Target thread will not enter any new monitors.
1783 //
1784 bool JavaThread::java_suspend() {
1785 #if INCLUDE_JVMTI
1786   // Suspending a JavaThread in VTMT or disabling VTMT can cause deadlocks.
1787   assert(!is_in_VTMT(), "no suspend allowed in VTMT transition");
1788 #ifdef ASSERT
1789   if (is_VTMT_disabler()) { // TMP debugging code, should be removed after this assert is observed
1790     printf("DBG: JavaThread::java_suspend: suspended jt: %p current jt: %p\n", (void*)this, (void*)JavaThread::current());
1791     printf("DBG: JavaThread::java_suspend: VTMT_disable_count: %d\n", JvmtiVTMTDisabler::VTMT_disable_count());
1792   }
1793 #endif
1794   assert(!is_VTMT_disabler(), "no suspend allowed for VTMT disablers");
1795 #endif
1796 
1797   ThreadsListHandle tlh;
1798   if (!tlh.includes(this)) {
1799     log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, no suspension", p2i(this));
1800     return false;
1801   }
1802   return this->handshake_state()->suspend();
1803 }
1804 
1805 bool JavaThread::java_resume() {
1806   ThreadsListHandle tlh;
1807   if (!tlh.includes(this)) {
1808     log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, nothing to resume", p2i(this));
1809     return false;
1810   }
1811   return this->handshake_state()->resume();
1812 }
1813 
1814 bool JavaThread::block_suspend(JavaThread* caller) {
1815   ThreadsListHandle tlh;
1816   if (!tlh.includes(this)) {
1817     log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, no suspension", p2i(this));
1818     return false;
1819   }
1820   return this->handshake_state()->block_suspend(caller);
1821 }
1822 
1823 bool JavaThread::continue_resume(JavaThread* caller) {
1824   ThreadsListHandle tlh;
1825   if (!tlh.includes(this)) {
1826     log_trace(thread, suspend)("JavaThread:" INTPTR_FORMAT " not on ThreadsList, nothing to resume", p2i(this));
1827     return false;
1828   }
1829   return this->handshake_state()->continue_resume(caller);
1830 }
1831 
1832 
1833 // Wait for another thread to perform object reallocation and relocking on behalf of
1834 // this thread.
1835 // Raw thread state transition to _thread_blocked and back again to the original
1836 // state before returning are performed. The current thread is required to
1837 // change to _thread_blocked in order to be seen to be safepoint/handshake safe
1838 // whilst suspended and only after becoming handshake safe, the other thread can
1839 // complete the handshake used to synchronize with this thread and then perform
1840 // the reallocation and relocking. We cannot use the thread state transition
1841 // helpers because we arrive here in various states and also because the helpers
1842 // indirectly call this method.  After leaving _thread_blocked we have to check
1843 // for safepoint/handshake, except if _thread_in_native. The thread is safe
1844 // without blocking then. Allowed states are enumerated in
1845 // SafepointSynchronize::block(). See also EscapeBarrier::sync_and_suspend_*()
1846 
1847 void JavaThread::wait_for_object_deoptimization() {
1848   assert(!has_last_Java_frame() || frame_anchor()->walkable(), "should have walkable stack");
1849   assert(this == Thread::current(), "invariant");
1850   JavaThreadState state = thread_state();
1851 
1852   bool spin_wait = os::is_MP();

1973     if (fst.current()->can_be_deoptimized()) {
1974       // it is a Java nmethod
1975       nmethod* nm = CodeCache::find_nmethod(fst.current()->pc());
1976       nm->make_not_entrant();
1977     }
1978   }
1979 }
1980 #endif // PRODUCT
1981 
1982 
1983 void JavaThread::deoptimize_marked_methods() {
1984   if (!has_last_Java_frame()) return;
1985   StackFrameStream fst(this, false /* update */, true /* process_frames */);
1986   for (; !fst.is_done(); fst.next()) {
1987     if (fst.current()->should_be_deoptimized()) {
1988       Deoptimization::deoptimize(this, *fst.current());
1989     }
1990   }
1991 }
1992 
1993 void JavaThread::deoptimize_marked_methods_only_anchors() {
1994   if (!has_last_Java_frame()) return;
1995   bool java_callee = false;
1996   StackFrameStream fst(this, false /* update */, true /* process_frames */);
1997   for (; !fst.is_done(); fst.next()) {
1998     if (fst.current()->should_be_deoptimized()) {
1999       if (!java_callee) {
2000         //tty->print_cr("Patching RA");
2001         Deoptimization::deoptimize(this, *fst.current());
2002       } else {
2003         //tty->print_cr("Not patching RA");
2004       }
2005     }
2006     java_callee = fst.current()->is_compiled_frame();
2007   }
2008 }
2009 
2010 
2011 #ifdef ASSERT
2012 void JavaThread::verify_frame_info() {
2013   assert((!has_last_Java_frame() && java_call_counter() == 0) ||
2014          (has_last_Java_frame() && java_call_counter() > 0),
2015          "unexpected frame info: has_last_frame=%s, java_call_counter=%d",
2016          has_last_Java_frame() ? "true" : "false", java_call_counter());
2017 }
2018 #endif
2019 
2020 void JavaThread::oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf) {
2021   // Verify that the deferred card marks have been flushed.
2022   assert(deferred_card_mark().is_empty(), "Should be empty during GC");
2023 
2024   // Traverse the GCHandles
2025   Thread::oops_do_no_frames(f, cf);
2026 
2027   DEBUG_ONLY(verify_frame_info();)
2028 
2029   if (has_last_Java_frame()) {
2030     // Traverse the monitor chunks

2038   // written
2039   GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(this);
2040   if (list != NULL) {
2041     for (int i = 0; i < list->length(); i++) {
2042       list->at(i)->oops_do(f);
2043     }
2044   }
2045 
2046   // Traverse instance variables at the end since the GC may be moving things
2047   // around using this function
2048   f->do_oop((oop*) &_vm_result);
2049   f->do_oop((oop*) &_exception_oop);
2050   f->do_oop((oop*) &_pending_async_exception);
2051 #if INCLUDE_JVMCI
2052   f->do_oop((oop*) &_jvmci_reserved_oop0);
2053 #endif
2054 
2055   if (jvmti_thread_state() != NULL) {
2056     jvmti_thread_state()->oops_do(f, cf);
2057   }
2058 
2059   f->do_oop(&_mounted_vthread);
2060 }
2061 
2062 void JavaThread::oops_do_frames(OopClosure* f, CodeBlobClosure* cf) {
2063   if (!has_last_Java_frame()) {
2064     return;
2065   }
2066   // Finish any pending lazy GC activity for the frames
2067   StackWatermarkSet::finish_processing(this, NULL /* context */, StackWatermarkKind::gc);
2068   // Traverse the execution stack
2069   for (StackFrameStream fst(this, true /* update */, false /* process_frames */); !fst.is_done(); fst.next()) {
2070     fst.current()->oops_do(f, cf, fst.register_map());
2071   }
2072 }
2073 
2074 #ifdef ASSERT
2075 void JavaThread::verify_states_for_handshake() {
2076   // This checks that the thread has a correct frame state during a handshake.
2077   verify_frame_info();
2078 }
2079 #endif

2113 }
2114 
2115 // Printing
2116 const char* _get_thread_state_name(JavaThreadState _thread_state) {
2117   switch (_thread_state) {
2118   case _thread_uninitialized:     return "_thread_uninitialized";
2119   case _thread_new:               return "_thread_new";
2120   case _thread_new_trans:         return "_thread_new_trans";
2121   case _thread_in_native:         return "_thread_in_native";
2122   case _thread_in_native_trans:   return "_thread_in_native_trans";
2123   case _thread_in_vm:             return "_thread_in_vm";
2124   case _thread_in_vm_trans:       return "_thread_in_vm_trans";
2125   case _thread_in_Java:           return "_thread_in_Java";
2126   case _thread_in_Java_trans:     return "_thread_in_Java_trans";
2127   case _thread_blocked:           return "_thread_blocked";
2128   case _thread_blocked_trans:     return "_thread_blocked_trans";
2129   default:                        return "unknown thread state";
2130   }
2131 }
2132 

2133 void JavaThread::print_thread_state_on(outputStream *st) const {
2134   st->print_cr("   JavaThread state: %s", _get_thread_state_name(_thread_state));
2135 };
2136 const char* JavaThread::thread_state_name() const {
2137   return _get_thread_state_name(_thread_state);
2138 }
2139 
2140 // Called by Threads::print() for VM_PrintThreads operation
2141 void JavaThread::print_on(outputStream *st, bool print_extended_info) const {
2142   st->print_raw("\"");
2143   st->print_raw(name());
2144   st->print_raw("\" ");
2145   oop thread_oop = threadObj();
2146   if (thread_oop != NULL) {
2147     st->print("#" INT64_FORMAT " [%ld] ", (int64_t)java_lang_Thread::thread_id(thread_oop), (long) osthread()->thread_id());
2148     if (java_lang_Thread::is_daemon(thread_oop))  st->print("daemon ");
2149     st->print("prio=%d ", java_lang_Thread::priority(thread_oop));
2150   }
2151   Thread::print_on(st, print_extended_info);
2152   // print guess for valid stack memory region (assume 4K pages); helps lock debugging
2153   st->print_cr("[" INTPTR_FORMAT "]", (intptr_t)last_Java_sp() & ~right_n_bits(12));
2154   if (thread_oop != NULL) {
2155     st->print_cr("   java.lang.Thread.State: %s", java_lang_Thread::thread_status_name(thread_oop));
2156   }
2157 #ifndef PRODUCT
2158   _safepoint_state->print_on(st);
2159 #endif // PRODUCT
2160   if (is_Compiler_thread()) {
2161     CompileTask *task = ((CompilerThread*)this)->task();
2162     if (task != NULL) {
2163       st->print("   Compiling: ");
2164       task->print(st, NULL, true, false);
2165     } else {
2166       st->print("   No compile task");
2167     }

2174 void JavaThread::print_name_on_error(outputStream* st, char *buf, int buflen) const {
2175   st->print("%s", get_thread_name_string(buf, buflen));
2176 }
2177 
2178 // Called by fatal error handler. The difference between this and
2179 // JavaThread::print() is that we can't grab lock or allocate memory.
2180 void JavaThread::print_on_error(outputStream* st, char *buf, int buflen) const {
2181   st->print("%s \"%s\"", type_name(), get_thread_name_string(buf, buflen));
2182   oop thread_obj = threadObj();
2183   if (thread_obj != NULL) {
2184     if (java_lang_Thread::is_daemon(thread_obj)) st->print(" daemon");
2185   }
2186   st->print(" [");
2187   st->print("%s", _get_thread_state_name(_thread_state));
2188   if (osthread()) {
2189     st->print(", id=%d", osthread()->thread_id());
2190   }
2191   st->print(", stack(" PTR_FORMAT "," PTR_FORMAT ")",
2192             p2i(stack_end()), p2i(stack_base()));
2193   st->print("]");
2194   DEBUG_ONLY(print_owned_locks_on(st);)
2195 
2196   ThreadsSMRSupport::print_info_on(this, st);
2197   return;
2198 }
2199 
2200 
2201 // Verification
2202 
2203 void JavaThread::frames_do(void f(frame*, const RegisterMap* map)) {
2204   // ignore if there is no stack
2205   if (!has_last_Java_frame()) return;
2206   // traverse the stack frames. Starts from top frame.
2207   for (StackFrameStream fst(this, true /* update */, true /* process_frames */); !fst.is_done(); fst.next()) {
2208     frame* fr = fst.current();
2209     f(fr, fst.register_map());
2210   }
2211 }
2212 
2213 static void frame_verify(frame* f, const RegisterMap *map) { f->verify(map); }
2214 

2279 
2280   assert(Threads_lock->owner() == Thread::current(), "must have threads lock");
2281   assert(NoPriority <= prio && prio <= MaxPriority, "sanity check");
2282   // Link Java Thread object <-> C++ Thread
2283 
2284   // Get the C++ thread object (an oop) from the JNI handle (a jthread)
2285   // and put it into a new Handle.  The Handle "thread_oop" can then
2286   // be used to pass the C++ thread object to other methods.
2287 
2288   // Set the Java level thread object (jthread) field of the
2289   // new thread (a JavaThread *) to C++ thread object using the
2290   // "thread_oop" handle.
2291 
2292   // Set the thread field (a JavaThread *) of the
2293   // oop representing the java_lang_Thread to the new thread (a JavaThread *).
2294 
2295   Handle thread_oop(Thread::current(),
2296                     JNIHandles::resolve_non_null(jni_thread));
2297   assert(InstanceKlass::cast(thread_oop->klass())->is_linked(),
2298          "must be initialized");
2299   set_threadOopHandles(thread_oop());
2300   java_lang_Thread::set_thread(thread_oop(), this);
2301 
2302   if (prio == NoPriority) {
2303     prio = java_lang_Thread::priority(thread_oop());
2304     assert(prio != NoPriority, "A valid priority should be present");
2305   }
2306 
2307   // Push the Java priority down to the native thread; needs Threads_lock
2308   Thread::set_priority(this, prio);
2309 
2310   // Add the new thread to the Threads list and set it in motion.
2311   // We must have threads lock in order to call Threads::add.
2312   // It is crucial that we do not block before the thread is
2313   // added to the Threads list for if a GC happens, then the java_thread oop
2314   // will not be visited by GC.
2315   Threads::add(this);
2316 }
2317 
2318 oop JavaThread::current_park_blocker() {
2319   // Support for JSR-166 locks
2320   oop thread_oop = threadObj();
2321   if (thread_oop != NULL) {
2322     return java_lang_Thread::park_blocker(thread_oop);
2323   }
2324   return NULL;
2325 }
2326 
2327 
2328 void JavaThread::print_stack_on(outputStream* st) {
2329   if (!has_last_Java_frame()) return;
2330 
2331   Thread* current_thread = Thread::current();
2332   ResourceMark rm(current_thread);
2333   HandleMark hm(current_thread);
2334 
2335   RegisterMap reg_map(this, true, true);
2336   vframe* start_vf = last_java_vframe(&reg_map);
2337   int count = 0;
2338   for (vframe* f = start_vf; f != NULL; f = f->sender()) {
2339     if (f->is_java_frame()) {
2340       javaVFrame* jvf = javaVFrame::cast(f);
2341       java_lang_Throwable::print_stack_element(st, jvf->method(), jvf->bci());
2342 
2343       // Print out lock information
2344       if (JavaMonitorsInStackTrace) {
2345         jvf->print_lock_info_on(st, count);
2346       }
2347     } else {
2348       // Ignore non-Java frames
2349     }
2350 
2351     // Bail-out case for too deep stacks if MaxJavaStackTraceDepth > 0
2352     count++;
2353     if (MaxJavaStackTraceDepth > 0 && MaxJavaStackTraceDepth == count) return;
2354   }
2355 }
2356 
2357 #if INCLUDE_JVMTI
2358 // Rebind JVMTI thread state from carrier to virtual or from virtual to carrier.
2359 JvmtiThreadState* JavaThread::rebind_to_jvmti_thread_state_of(oop thread_oop) {
2360   set_mounted_vthread(thread_oop);
2361 
2362   // unbind current JvmtiThreadState from JavaThread
2363   jvmti_thread_state()->unbind_from(this);
2364 
2365   // bind new JvmtiThreadState to JavaThread
2366   java_lang_Thread::jvmti_thread_state(thread_oop)->bind_to(this);
2367 
2368   return jvmti_thread_state();
2369 }
2370 #endif
2371 
2372 // JVMTI PopFrame support
2373 void JavaThread::popframe_preserve_args(ByteSize size_in_bytes, void* start) {
2374   assert(_popframe_preserved_args == NULL, "should not wipe out old PopFrame preserved arguments");
2375   if (in_bytes(size_in_bytes) != 0) {
2376     _popframe_preserved_args = NEW_C_HEAP_ARRAY(char, in_bytes(size_in_bytes), mtThread);
2377     _popframe_preserved_args_size = in_bytes(size_in_bytes);
2378     Copy::conjoint_jbytes(start, _popframe_preserved_args, _popframe_preserved_args_size);
2379   }
2380 }
2381 
2382 void* JavaThread::popframe_preserved_args() {
2383   return _popframe_preserved_args;
2384 }
2385 
2386 ByteSize JavaThread::popframe_preserved_args_size() {
2387   return in_ByteSize(_popframe_preserved_args_size);
2388 }
2389 
2390 WordSize JavaThread::popframe_preserved_args_size_in_words() {

2424       } else {
2425         obj->print();
2426       }
2427     } else {
2428       tty->print_cr("invalid oop: " INTPTR_FORMAT, p2i(obj));
2429     }
2430     tty->cr();
2431   }
2432  public:
2433   virtual void do_oop(oop* p) { do_oop_work(p); }
2434   virtual void do_oop(narrowOop* p)  { do_oop_work(p); }
2435 };
2436 
2437 #ifdef ASSERT
2438 // Print or validate the layout of stack frames
2439 void JavaThread::print_frame_layout(int depth, bool validate_only) {
2440   ResourceMark rm;
2441   PreserveExceptionMark pm(this);
2442   FrameValues values;
2443   int frame_no = 0;
2444   for (StackFrameStream fst(this, true, true, true); !fst.is_done(); fst.next()) {
2445     if (frame_no == 0) fst.current()->describe_top(values);
2446     fst.current()->describe(values, ++frame_no, fst.register_map());
2447     if (depth == frame_no) break;
2448   }
2449   Continuation::describe(values);
2450   if (validate_only) {
2451     values.validate();
2452   } else {
2453     tty->print_cr("[Describe stack layout]");
2454     values.print(this);
2455   }
2456 }
2457 #endif
2458 
2459 void JavaThread::trace_stack_from(vframe* start_vf) {
2460   ResourceMark rm;
2461   int vframe_no = 1;
2462   for (vframe* f = start_vf; f; f = f->sender()) {
2463     if (f->is_java_frame()) {
2464       javaVFrame::cast(f)->print_activation(vframe_no++);
2465     } else {
2466       f->print();
2467     }
2468     if (vframe_no > StackPrintLimit) {
2469       tty->print_cr("...<more frames>...");
2470       return;
2471     }
2472   }
2473 }
2474 
2475 
2476 void JavaThread::trace_stack() {
2477   if (!has_last_Java_frame()) return;
2478   Thread* current_thread = Thread::current();
2479   ResourceMark rm(current_thread);
2480   HandleMark hm(current_thread);
2481   RegisterMap reg_map(this, true, true);
2482   trace_stack_from(last_java_vframe(&reg_map));
2483 }
2484 
2485 
2486 #endif // PRODUCT
2487 
2488 
2489 frame JavaThread::vthread_carrier_last_frame(RegisterMap* reg_map) {
2490   ContinuationEntry* cont = last_continuation(java_lang_VirtualThread::vthread_scope());
2491   guarantee (cont != NULL, "Not a carrier thread");
2492   frame f = cont->to_frame();
2493   cont->update_register_map(reg_map);
2494   return f.sender(reg_map);
2495 }
2496 
2497 javaVFrame* JavaThread::last_java_vframe(const frame f, RegisterMap *reg_map) {
2498   assert(reg_map != NULL, "a map must be given");

2499   for (vframe* vf = vframe::new_vframe(&f, reg_map, this); vf; vf = vf->sender()) {
2500     if (vf->is_java_frame()) return javaVFrame::cast(vf);
2501   }
2502   return NULL;
2503 }
2504 

2505 Klass* JavaThread::security_get_caller_class(int depth) {
2506   ResetNoHandleMark rnhm;
2507   HandleMark hm(Thread::current());
2508 
2509   vframeStream vfst(this);
2510   vfst.security_get_caller_frame(depth);
2511   if (!vfst.at_end()) {
2512     return vfst.method()->method_holder();
2513   }
2514   return NULL;
2515 }
2516 
2517 // java.lang.Thread.sleep support
2518 // Returns true if sleep time elapsed as expected, and false
2519 // if the thread was interrupted.
2520 bool JavaThread::sleep(jlong millis) {
2521   assert(this == Thread::current(),  "thread consistency check");
2522 
2523   ParkEvent * const slp = this->_SleepEvent;
2524   // Because there can be races with thread interruption sending an unpark()
2525   // to the event, we explicitly reset it here to avoid an immediate return.
2526   // The actual interrupt state will be checked before we park().
2527   slp->reset();
2528   // Thread interruption establishes a happens-before ordering in the

3810                VM_Version::vm_name(),
3811                VM_Version::vm_release(),
3812                VM_Version::vm_info_string());
3813   st->cr();
3814 
3815 #if INCLUDE_SERVICES
3816   // Dump concurrent locks
3817   ConcurrentLocksDump concurrent_locks;
3818   if (print_concurrent_locks) {
3819     concurrent_locks.dump_at_safepoint();
3820   }
3821 #endif // INCLUDE_SERVICES
3822 
3823   ThreadsSMRSupport::print_info_on(st);
3824   st->cr();
3825 
3826   ALL_JAVA_THREADS(p) {
3827     ResourceMark rm;
3828     p->print_on(st, print_extended_info);
3829     if (print_stacks) {
3830       // if (p->has_last_Java_frame()) {
3831       //   static char buf[O_BUFLEN];
3832       //   frame fr = p->last_frame();
3833       //   VMError::print_native_stack(tty, fr, p, buf, sizeof(buf));
3834       // }
3835 
3836       if (internal_format) {
3837         p->trace_stack();
3838       } else {
3839         p->print_stack_on(st);
3840       }
3841     }
3842     st->cr();
3843 #if INCLUDE_SERVICES
3844     if (print_concurrent_locks) {
3845       concurrent_locks.print_locks_on(p, st);
3846     }
3847 #endif // INCLUDE_SERVICES
3848   }
3849 
3850   PrintOnClosure cl(st);
3851   cl.do_thread(VMThread::vm_thread());
3852   Universe::heap()->gc_threads_do(&cl);
3853   if (StringDedup::is_enabled()) {
3854     StringDedup::threads_do(&cl);
3855   }

3934 
3935 void Threads::print_threads_compiling(outputStream* st, char* buf, int buflen, bool short_form) {
3936   ALL_JAVA_THREADS(thread) {
3937     if (thread->is_Compiler_thread()) {
3938       CompilerThread* ct = (CompilerThread*) thread;
3939 
3940       // Keep task in local variable for NULL check.
3941       // ct->_task might be set to NULL by concurring compiler thread
3942       // because it completed the compilation. The task is never freed,
3943       // though, just returned to a free list.
3944       CompileTask* task = ct->task();
3945       if (task != NULL) {
3946         thread->print_name_on_error(st, buf, buflen);
3947         st->print("  ");
3948         task->print(st, NULL, short_form, true);
3949       }
3950     }
3951   }
3952 }
3953 

3954 // Ad-hoc mutual exclusion primitives: SpinLock
3955 //
3956 // We employ SpinLocks _only for low-contention, fixed-length
3957 // short-duration critical sections where we're concerned
3958 // about native mutex_t or HotSpot Mutex:: latency.
3959 //
3960 // TODO-FIXME: ListLock should be of type SpinLock.
3961 // We should make this a 1st-class type, integrated into the lock
3962 // hierarchy as leaf-locks.  Critically, the SpinLock structure
3963 // should have sufficient padding to avoid false-sharing and excessive
3964 // cache-coherency traffic.
3965 
3966 
3967 typedef volatile int SpinLockT;
3968 
3969 void Thread::SpinAcquire(volatile int * adr, const char * LockName) {
3970   if (Atomic::cmpxchg(adr, 0, 1) == 0) {
3971     return;   // normal fast-path return
3972   }
3973 

4007   // more than covers this on all platforms.
4008   *adr = 0;
4009 }
4010 
4011 
4012 void Threads::verify() {
4013   ALL_JAVA_THREADS(p) {
4014     p->verify();
4015   }
4016   VMThread* thread = VMThread::vm_thread();
4017   if (thread != NULL) thread->verify();
4018 }
4019 
4020 #ifndef PRODUCT
4021 void JavaThread::verify_cross_modify_fence_failure(JavaThread *thread) {
4022    report_vm_error(__FILE__, __LINE__, "Cross modify fence failure", "%p", thread);
4023 }
4024 #endif
4025 
4026 // Helper function to create the java.lang.Thread object for a
4027 // VM-internal thread. The thread will have the given name, and be
4028 // a member of the "system" ThreadGroup.

4029 Handle JavaThread::create_system_thread_object(const char* name,
4030                                                bool is_visible, TRAPS) {
4031   Handle string = java_lang_String::create_from_str(name, CHECK_NH);
4032 
4033   // Initialize thread_oop to put it into the system threadGroup.
4034   // This is done by calling the Thread(ThreadGroup group, String name) constructor.


4035   Handle thread_group(THREAD, Universe::system_thread_group());
4036   Handle thread_oop =
4037     JavaCalls::construct_new_instance(vmClasses::Thread_klass(),
4038                                       vmSymbols::threadgroup_string_void_signature(),
4039                                       thread_group,
4040                                       string,
4041                                       CHECK_NH);
4042 














4043   return thread_oop;
4044 }
4045 
4046 // Starts the target JavaThread as a daemon of the given priority, and
4047 // bound to the given java.lang.Thread instance.
4048 // The Threads_lock is held for the duration.
4049 void JavaThread::start_internal_daemon(JavaThread* current, JavaThread* target,
4050                                        Handle thread_oop, ThreadPriority prio) {
4051 
4052   assert(target->osthread() != NULL, "target thread is not properly initialized");
4053 
4054   MutexLocker mu(current, Threads_lock);
4055 
4056   // Initialize the fields of the thread_oop first.
4057 
4058   java_lang_Thread::set_thread(thread_oop(), target); // isAlive == true now
4059 
4060   if (prio != NoPriority) {
4061     java_lang_Thread::set_priority(thread_oop(), prio);
4062     // Note: we don't call os::set_priority here. Possibly we should,
4063     // else all threads should call it themselves when they first run.
4064   }
4065 
4066   java_lang_Thread::set_daemon(thread_oop());
4067 
4068   // Now bind the thread_oop to the target JavaThread.
4069   target->set_threadOopHandles(thread_oop());
4070 
4071   Threads::add(target); // target is now visible for safepoint/handshake
4072   Thread::start(target);
4073 }
4074 
4075 void JavaThread::vm_exit_on_osthread_failure(JavaThread* thread) {
4076   // At this point it may be possible that no osthread was created for the
4077   // JavaThread due to lack of resources. However, since this must work
4078   // for critical system threads just check and abort if this fails.
4079   if (thread->osthread() == nullptr) {
4080     // This isn't really an OOM condition, but historically this is what
4081     // we report.
4082     vm_exit_during_initialization("java.lang.OutOfMemoryError",
4083                                   os::native_thread_creation_failed_msg());
4084   }
4085 }
< prev index next >