< prev index next >

src/hotspot/share/runtime/thread.hpp

Print this page

  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #ifndef SHARE_RUNTIME_THREAD_HPP
  27 #define SHARE_RUNTIME_THREAD_HPP
  28 
  29 #include "jni.h"
  30 #include "gc/shared/gcThreadLocalData.hpp"
  31 #include "gc/shared/threadLocalAllocBuffer.hpp"
  32 #include "memory/allocation.hpp"
  33 #include "oops/oop.hpp"
  34 #include "oops/oopHandle.hpp"


  35 #include "runtime/frame.hpp"
  36 #include "runtime/globals.hpp"
  37 #include "runtime/handshake.hpp"
  38 #include "runtime/javaFrameAnchor.hpp"
  39 #include "runtime/mutexLocker.hpp"
  40 #include "runtime/os.hpp"
  41 #include "runtime/park.hpp"
  42 #include "runtime/safepointMechanism.hpp"
  43 #include "runtime/stackWatermarkSet.hpp"
  44 #include "runtime/stackOverflow.hpp"
  45 #include "runtime/threadHeapSampler.hpp"
  46 #include "runtime/threadLocalStorage.hpp"
  47 #include "runtime/threadStatisticalInfo.hpp"
  48 #include "runtime/unhandledOops.hpp"
  49 #include "utilities/align.hpp"
  50 #include "utilities/exceptions.hpp"
  51 #include "utilities/globalDefinitions.hpp"
  52 #include "utilities/macros.hpp"
  53 #if INCLUDE_JFR
  54 #include "jfr/support/jfrThreadExtension.hpp"

 122 //      - this->post_run()  // virtual per-thread-type tear-down
 123 //      - // 'this' no longer referenceable
 124 //    - OS-level tear-down (minimal)
 125 //    - final logging
 126 //
 127 // For JavaThread:
 128 //   - this->run()  // virtual but not normally overridden
 129 //     - this->thread_main_inner()  // extra call level to ensure correct stack calculations
 130 //       - this->entry_point()  // set differently for each kind of JavaThread
 131 
 132 class Thread: public ThreadShadow {
 133   friend class VMStructs;
 134   friend class JVMCIVMStructs;
 135  private:
 136 
 137 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 138   // Current thread is maintained as a thread-local variable
 139   static THREAD_LOCAL Thread* _thr_current;
 140 #endif
 141 
















 142   // Thread local data area available to the GC. The internal
 143   // structure and contents of this data area is GC-specific.
 144   // Only GC and GC barrier code should access this data area.
 145   GCThreadLocalData _gc_data;
 146 
 147  public:
 148   static ByteSize gc_data_offset() {
 149     return byte_offset_of(Thread, _gc_data);
 150   }
 151 
 152   template <typename T> T* gc_data() {
 153     STATIC_ASSERT(sizeof(T) <= sizeof(_gc_data));
 154     return reinterpret_cast<T*>(&_gc_data);
 155   }
 156 
 157   // Exception handling
 158   // (Note: _pending_exception and friends are in ThreadShadow)
 159   //oop       _pending_exception;                // pending exception for current thread
 160   // const char* _exception_file;                   // file information for exception (debugging only)
 161   // int         _exception_line;                   // line information for exception (debugging only)

 671 #endif
 672 }
 673 
 674 inline Thread* Thread::current_or_null_safe() {
 675   if (ThreadLocalStorage::is_initialized()) {
 676     return ThreadLocalStorage::thread();
 677   }
 678   return NULL;
 679 }
 680 
 681 class CompilerThread;
 682 
 683 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
 684 
 685 class JavaThread: public Thread {
 686   friend class VMStructs;
 687   friend class JVMCIVMStructs;
 688   friend class WhiteBox;
 689   friend class ThreadsSMRSupport; // to access _threadObj for exiting_threads_oops_do
 690   friend class HandshakeState;

 691  private:
 692   bool           _on_thread_list;                // Is set when this JavaThread is added to the Threads list
 693   OopHandle      _threadObj;                     // The Java level thread object


 694 
 695 #ifdef ASSERT
 696  private:
 697   int _java_call_counter;
 698 
 699  public:
 700   int  java_call_counter()                       { return _java_call_counter; }
 701   void inc_java_call_counter()                   { _java_call_counter++; }
 702   void dec_java_call_counter() {
 703     assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper");
 704     _java_call_counter--;
 705   }
 706  private:  // restore original namespace restriction
 707 #endif  // ifdef ASSERT
 708 
 709   JavaFrameAnchor _anchor;                       // Encapsulation of current java frame and it state
 710 
 711   ThreadFunction _entry_point;
 712 
 713   JNIEnv        _jni_environment;
 714 
 715   // Deopt support
 716   DeoptResourceMark*  _deopt_mark;               // Holds special ResourceMark for deoptimization
 717 
 718   CompiledMethod*       _deopt_nmethod;         // CompiledMethod that is currently being deoptimized
 719   vframeArray*  _vframe_array_head;              // Holds the heap of the active vframeArrays
 720   vframeArray*  _vframe_array_last;              // Holds last vFrameArray we popped
 721   // Holds updates by JVMTI agents for compiled frames that cannot be performed immediately. They
 722   // will be carried out as soon as possible which, in most cases, is just before deoptimization of
 723   // the frame, when control returns to it.
 724   JvmtiDeferredUpdates* _jvmti_deferred_updates;

 725 
 726   // Handshake value for fixing 6243940. We need a place for the i2c
 727   // adapter to store the callee Method*. This value is NEVER live
 728   // across a gc point so it does NOT have to be gc'd
 729   // The handshake is open ended since we can't be certain that it will
 730   // be NULLed. This is because we rarely ever see the race and end up
 731   // in handle_wrong_method which is the backend of the handshake. See
 732   // code in i2c adapters and handle_wrong_method.
 733 
 734   Method*       _callee_target;
 735 
 736   // Used to pass back results to the interpreter or generated code running Java code.
 737   oop           _vm_result;    // oop result is GC-preserved
 738   Metadata*     _vm_result_2;  // non-oop result
 739 
 740   // See ReduceInitialCardMarks: this holds the precise space interval of
 741   // the most recent slow path allocation for which compiled code has
 742   // elided card-marks for performance along the fast-path.
 743   MemRegion     _deferred_card_mark;
 744 

 765     return _current_pending_monitor_is_from_java;
 766   }
 767   ObjectMonitor* current_waiting_monitor() {
 768     // See the comment in current_pending_monitor() above.
 769     return Atomic::load(&_current_waiting_monitor);
 770   }
 771   void set_current_waiting_monitor(ObjectMonitor* monitor) {
 772     Atomic::store(&_current_waiting_monitor, monitor);
 773   }
 774 
 775  private:
 776   MonitorChunk* _monitor_chunks;              // Contains the off stack monitors
 777                                               // allocated during deoptimization
 778                                               // and by JNI_MonitorEnter/Exit
 779 
 780   enum SuspendFlags {
 781     // NOTE: avoid using the sign-bit as cc generates different test code
 782     //       when the sign-bit is used, and sometimes incorrectly - see CR 6398077
 783     _has_async_exception    = 0x00000001U, // there is a pending async exception
 784     _trace_flag             = 0x00000004U, // call tracing backend
 785     _obj_deopt              = 0x00000008U  // suspend for object reallocation and relocking for JVMTI agent

 786   };
 787 
 788   // various suspension related flags - atomically updated
 789   // overloaded with async exceptions so that we do a single check when transitioning from native->Java
 790   volatile uint32_t _suspend_flags;
 791 
 792   inline void set_suspend_flag(SuspendFlags f);
 793   inline void clear_suspend_flag(SuspendFlags f);
 794 
 795  public:
 796   inline void set_trace_flag();
 797   inline void clear_trace_flag();
 798   inline void set_obj_deopt_flag();
 799   inline void clear_obj_deopt_flag();
 800   bool is_trace_suspend()      { return (_suspend_flags & _trace_flag) != 0; }
 801   bool is_obj_deopt_suspend()  { return (_suspend_flags & _obj_deopt) != 0; }
 802 
 803   // Asynchronous exceptions support
 804  private:
 805   oop     _pending_async_exception;

 870     _thread_exiting,                             // JavaThread::exit() has been called for this thread
 871     _thread_terminated,                          // JavaThread is removed from thread list
 872     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
 873                                                  // only VM_Exit can set _vm_exited
 874   };
 875 
 876  private:
 877   // In general a JavaThread's _terminated field transitions as follows:
 878   //
 879   //   _not_terminated => _thread_exiting => _thread_terminated
 880   //
 881   // _vm_exited is a special value to cover the case of a JavaThread
 882   // executing native code after the VM itself is terminated.
 883   volatile TerminatedTypes _terminated;
 884 
 885   jint                  _in_deopt_handler;       // count of deoptimization
 886                                                  // handlers thread is in
 887   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
 888   bool                  _do_not_unlock_if_synchronized;  // Do not unlock the receiver of a synchronized method (since it was
 889                                                          // never locked) when throwing an exception. Used by interpreter only.




 890 
 891   // JNI attach states:
 892   enum JNIAttachStates {
 893     _not_attaching_via_jni = 1,  // thread is not attaching via JNI
 894     _attaching_via_jni,          // thread is attaching via JNI
 895     _attached_via_jni            // thread has attached via JNI
 896   };
 897 
 898   // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
 899   // A native thread that is attaching via JNI starts with a value
 900   // of _attaching_via_jni and transitions to _attached_via_jni.
 901   volatile JNIAttachStates _jni_attach_state;
 902 
 903 
 904 #if INCLUDE_JVMCI
 905   // The _pending_* fields below are used to communicate extra information
 906   // from an uncommon trap in JVMCI compiled code to the uncommon trap handler.
 907 
 908   // Communicates the DeoptReason and DeoptAction of the uncommon trap
 909   int       _pending_deoptimization;

 990  private:
 991   // support for JNI critical regions
 992   jint    _jni_active_critical;                  // count of entries into JNI critical region
 993 
 994   // Checked JNI: function name requires exception check
 995   char* _pending_jni_exception_check_fn;
 996 
 997   // For deadlock detection.
 998   int _depth_first_number;
 999 
1000   // JVMTI PopFrame support
1001   // This is set to popframe_pending to signal that top Java frame should be popped immediately
1002   int _popframe_condition;
1003 
1004   // If reallocation of scalar replaced objects fails, we throw OOM
1005   // and during exception propagation, pop the top
1006   // _frames_to_pop_failed_realloc frames, the ones that reference
1007   // failed reallocations.
1008   int _frames_to_pop_failed_realloc;
1009 








1010   friend class VMThread;
1011   friend class ThreadWaitTransition;
1012   friend class VM_Exit;
1013 
1014   // Stack watermark barriers.
1015   StackWatermarks _stack_watermarks;
1016 
1017  public:
1018   inline StackWatermarks* stack_watermarks() { return &_stack_watermarks; }
1019 






1020  public:
1021   // Constructor
1022   JavaThread();                            // delegating constructor
1023   JavaThread(bool is_attaching_via_jni);   // for main thread and JNI attached threads
1024   JavaThread(ThreadFunction entry_point, size_t stack_size = 0);
1025   ~JavaThread();
1026 
1027 #ifdef ASSERT
1028   // verify this JavaThread hasn't be published in the Threads::list yet
1029   void verify_not_published();
1030 #endif // ASSERT
1031 
1032   StackOverflow* stack_overflow_state() { return &_stack_overflow_state; }
1033 
1034   //JNI functiontable getter/setter for JVMTI jni function table interception API.
1035   void set_jni_functions(struct JNINativeInterface_* functionTable) {
1036     _jni_environment.functions = functionTable;
1037   }
1038   struct JNINativeInterface_* get_jni_functions() {
1039     return (struct JNINativeInterface_ *)_jni_environment.functions;

1049   // Cleanup on thread exit
1050   enum ExitType {
1051     normal_exit,
1052     jni_detach
1053   };
1054   void exit(bool destroy_vm, ExitType exit_type = normal_exit);
1055 
1056   void cleanup_failed_attach_current_thread(bool is_daemon);
1057 
1058   // Testers
1059   virtual bool is_Java_thread() const            { return true;  }
1060   virtual bool can_call_java() const             { return true; }
1061 
1062   virtual bool is_active_Java_thread() const {
1063     return on_thread_list() && !is_terminated();
1064   }
1065 
1066   // Thread oop. threadObj() can be NULL for initial JavaThread
1067   // (or for threads attached via JNI)
1068   oop threadObj() const;
1069   void set_threadObj(oop p);






1070 
1071   // Prepare thread and add to priority queue.  If a priority is
1072   // not specified, use the priority of the thread object. Threads_lock
1073   // must be held while this function is called.
1074   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
1075 
1076   void set_saved_exception_pc(address pc)        { _saved_exception_pc = pc; }
1077   address saved_exception_pc()                   { return _saved_exception_pc; }
1078 
1079   ThreadFunction entry_point() const             { return _entry_point; }
1080 
1081   // Allocates a new Java level thread object for this thread. thread_name may be NULL.
1082   void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS);
1083 
1084   // Last frame anchor routines
1085 
1086   JavaFrameAnchor* frame_anchor(void)            { return &_anchor; }
1087 
1088   // last_Java_sp
1089   bool has_last_Java_frame() const               { return _anchor.has_last_Java_frame(); }

1112   // against the two non-terminated values so that a freed JavaThread
1113   // will also be considered terminated.
1114   bool check_is_terminated(TerminatedTypes l_terminated) const {
1115     return l_terminated != _not_terminated && l_terminated != _thread_exiting;
1116   }
1117   bool is_terminated() const;
1118   void set_terminated(TerminatedTypes t);
1119 
1120   void block_if_vm_exited();
1121 
1122   bool doing_unsafe_access()                     { return _doing_unsafe_access; }
1123   void set_doing_unsafe_access(bool val)         { _doing_unsafe_access = val; }
1124 
1125   bool do_not_unlock_if_synchronized()             { return _do_not_unlock_if_synchronized; }
1126   void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; }
1127 
1128   SafepointMechanism::ThreadData* poll_data() { return &_poll_data; }
1129 
1130   void set_requires_cross_modify_fence(bool val) PRODUCT_RETURN NOT_PRODUCT({ _requires_cross_modify_fence = val; })
1131 


















1132  private:
1133   DEBUG_ONLY(void verify_frame_info();)
1134 
1135   // Support for thread handshake operations
1136   HandshakeState _handshake;
1137  public:
1138   HandshakeState* handshake_state() { return &_handshake; }
1139 
1140   // A JavaThread can always safely operate on it self and other threads
1141   // can do it safely if they are the active handshaker.
1142   bool is_handshake_safe_for(Thread* th) const {
1143     return _handshake.active_handshaker() == th || this == th;
1144   }
1145 
1146   // Suspend/resume support for JavaThread
1147   bool java_suspend(); // higher-level suspension logic called by the public APIs
1148   bool java_resume();  // higher-level resume logic called by the public APIs

1149   bool is_suspended()     { return _handshake.is_suspended(); }
1150 





1151   // Check for async exception in addition to safepoint.
1152   static void check_special_condition_for_native_trans(JavaThread *thread);
1153 
1154   // Synchronize with another thread that is deoptimizing objects of the
1155   // current thread, i.e. reverts optimizations based on escape analysis.
1156   void wait_for_object_deoptimization();
1157 

















1158   // these next two are also used for self-suspension and async exception support
1159   void handle_special_runtime_exit_condition(bool check_asyncs = true);
1160 
1161   // Return true if JavaThread has an asynchronous condition or
1162   // if external suspension is requested.
1163   bool has_special_runtime_exit_condition() {
1164     return (_suspend_flags & (_has_async_exception | _obj_deopt JFR_ONLY(| _trace_flag))) != 0;

1165   }
1166 
1167   // Fast-locking support
1168   bool is_lock_owned(address adr) const;
1169 
1170   // Accessors for vframe array top
1171   // The linked list of vframe arrays are sorted on sp. This means when we
1172   // unpack the head must contain the vframe array to unpack.
1173   void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; }
1174   vframeArray* vframe_array_head() const         { return _vframe_array_head;  }
1175 
1176   // Side structure for deferring update of java frame locals until deopt occurs
1177   JvmtiDeferredUpdates* deferred_updates() const      { return _jvmti_deferred_updates; }
1178   void set_deferred_updates(JvmtiDeferredUpdates* du) { _jvmti_deferred_updates = du; }
1179 



1180   // These only really exist to make debugging deopt problems simpler
1181 
1182   void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; }
1183   vframeArray* vframe_array_last() const         { return _vframe_array_last;  }
1184 
1185   // The special resourceMark used during deoptimization
1186 
1187   void set_deopt_mark(DeoptResourceMark* value)  { _deopt_mark = value; }
1188   DeoptResourceMark* deopt_mark(void)            { return _deopt_mark; }
1189 
1190   void set_deopt_compiled_method(CompiledMethod* nm)  { _deopt_nmethod = nm; }
1191   CompiledMethod* deopt_compiled_method()        { return _deopt_nmethod; }
1192 
1193   Method*    callee_target() const               { return _callee_target; }
1194   void set_callee_target  (Method* x)          { _callee_target   = x; }
1195 
1196   // Oop results of vm runtime calls
1197   oop  vm_result() const                         { return _vm_result; }
1198   void set_vm_result  (oop x)                    { _vm_result   = x; }
1199 

1229   void set_exception_handler_pc(address a)       { _exception_handler_pc = a; }
1230   void set_is_method_handle_return(bool value)   { _is_method_handle_return = value ? 1 : 0; }
1231 
1232   void clear_exception_oop_and_pc() {
1233     set_exception_oop(NULL);
1234     set_exception_pc(NULL);
1235   }
1236 
1237   // Check if address is in the usable part of the stack (excludes protected
1238   // guard pages). Can be applied to any thread and is an approximation for
1239   // using is_in_live_stack when the query has to happen from another thread.
1240   bool is_in_usable_stack(address adr) const {
1241     return is_in_stack_range_incl(adr, _stack_overflow_state.stack_reserved_zone_base());
1242   }
1243 
1244   // Misc. accessors/mutators
1245   void set_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = true; }
1246   void clr_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = false; }
1247   bool do_not_unlock(void)                       { return _do_not_unlock_if_synchronized; }
1248 


1249   // For assembly stub generation
1250   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj); }

1251   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment); }
1252   static ByteSize pending_jni_exception_check_fn_offset() {
1253     return byte_offset_of(JavaThread, _pending_jni_exception_check_fn);
1254   }
1255   static ByteSize last_Java_sp_offset() {
1256     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
1257   }
1258   static ByteSize last_Java_pc_offset() {
1259     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
1260   }
1261   static ByteSize frame_anchor_offset() {
1262     return byte_offset_of(JavaThread, _anchor);
1263   }
1264   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target); }
1265   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result); }
1266   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2); }
1267   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state); }
1268   static ByteSize polling_word_offset()          { return byte_offset_of(JavaThread, _poll_data) + byte_offset_of(SafepointMechanism::ThreadData, _polling_word);}
1269   static ByteSize polling_page_offset()          { return byte_offset_of(JavaThread, _poll_data) + byte_offset_of(SafepointMechanism::ThreadData, _polling_page);}
1270   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc); }

1285   // StackOverflow offsets
1286   static ByteSize stack_overflow_limit_offset()  {
1287     return byte_offset_of(JavaThread, _stack_overflow_state._stack_overflow_limit);
1288   }
1289   static ByteSize stack_guard_state_offset()     {
1290     return byte_offset_of(JavaThread, _stack_overflow_state._stack_guard_state);
1291   }
1292   static ByteSize reserved_stack_activation_offset() {
1293     return byte_offset_of(JavaThread, _stack_overflow_state._reserved_stack_activation);
1294   }
1295 
1296   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags); }
1297 
1298   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1299   static ByteSize should_post_on_exceptions_flag_offset() {
1300     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1301   }
1302   static ByteSize doing_unsafe_access_offset() { return byte_offset_of(JavaThread, _doing_unsafe_access); }
1303   NOT_PRODUCT(static ByteSize requires_cross_modify_fence_offset()  { return byte_offset_of(JavaThread, _requires_cross_modify_fence); })
1304 





1305   // Returns the jni environment for this thread
1306   JNIEnv* jni_environment()                      { return &_jni_environment; }
1307 
1308   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
1309     JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset()));
1310     // Only return NULL if thread is off the thread list; starting to
1311     // exit should not return NULL.
1312     if (thread_from_jni_env->is_terminated()) {
1313       thread_from_jni_env->block_if_vm_exited();
1314       return NULL;
1315     } else {
1316       return thread_from_jni_env;
1317     }
1318   }
1319 
1320   // JNI critical regions. These can nest.
1321   bool in_critical()    { return _jni_active_critical > 0; }
1322   bool in_last_critical()  { return _jni_active_critical == 1; }
1323   inline void enter_critical();
1324   void exit_critical() {

1372   void oops_do_frames(OopClosure* f, CodeBlobClosure* cf);
1373   void oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf);
1374 
1375   // Sweeper operations
1376   virtual void nmethods_do(CodeBlobClosure* cf);
1377 
1378   // RedefineClasses Support
1379   void metadata_do(MetadataClosure* f);
1380 
1381   // Debug method asserting thread states are correct during a handshake operation.
1382   DEBUG_ONLY(void verify_states_for_handshake();)
1383 
1384   // Misc. operations
1385   const char* name() const;
1386   const char* type_name() const { return "JavaThread"; }
1387   static const char* name_for(oop thread_obj);
1388 
1389   void print_on(outputStream* st, bool print_extended_info) const;
1390   void print_on(outputStream* st) const { print_on(st, false); }
1391   void print() const;
1392   void print_thread_state_on(outputStream*) const      PRODUCT_RETURN;

1393   void print_on_error(outputStream* st, char* buf, int buflen) const;
1394   void print_name_on_error(outputStream* st, char* buf, int buflen) const;
1395   void verify();
1396 
1397   // Accessing frames
1398   frame last_frame() {
1399     _anchor.make_walkable(this);
1400     return pd_last_frame();
1401   }
1402   javaVFrame* last_java_vframe(RegisterMap* reg_map);





1403 
1404   // Returns method at 'depth' java or native frames down the stack
1405   // Used for security checks
1406   Klass* security_get_caller_class(int depth);
1407 
1408   // Print stack trace in external format
1409   void print_stack_on(outputStream* st);
1410   void print_stack() { print_stack_on(tty); }
1411 
1412   // Print stack traces in various internal formats
1413   void trace_stack()                             PRODUCT_RETURN;
1414   void trace_stack_from(vframe* start_vf)        PRODUCT_RETURN;
1415   void trace_frames()                            PRODUCT_RETURN;
1416 
1417   // Print an annotated view of the stack frames
1418   void print_frame_layout(int depth = 0, bool validate_only = false) NOT_DEBUG_RETURN;
1419   void validate_frame_layout() {
1420     print_frame_layout(0, true);
1421   }
1422 
1423   // Function for testing deoptimization
1424   void deoptimize();
1425   void make_zombies();
1426 
1427   void deoptimize_marked_methods();

1428 
1429  public:
1430   // Returns the running thread as a JavaThread
1431   static JavaThread* current() {
1432     return JavaThread::cast(Thread::current());
1433   }
1434 
1435   // Returns the current thread as a JavaThread, or NULL if not attached
1436   static inline JavaThread* current_or_null();
1437 
1438   // Casts
1439   static JavaThread* cast(Thread* t) {
1440     assert(t->is_Java_thread(), "incorrect cast to JavaThread");
1441     return static_cast<JavaThread*>(t);
1442   }
1443 
1444   static const JavaThread* cast(const Thread* t) {
1445     assert(t->is_Java_thread(), "incorrect cast to const JavaThread");
1446     return static_cast<const JavaThread*>(t);
1447   }

1454 
1455  protected:
1456   virtual void pre_run();
1457   virtual void run();
1458   void thread_main_inner();
1459   virtual void post_run();
1460 
1461  public:
1462   // Thread local information maintained by JVMTI.
1463   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1464   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1465   // getter is used to get this JavaThread's JvmtiThreadState if it has
1466   // one which means NULL can be returned. JvmtiThreadState::state_for()
1467   // is used to get the specified JavaThread's JvmtiThreadState if it has
1468   // one or it allocates a new JvmtiThreadState for the JavaThread and
1469   // returns it. JvmtiThreadState::state_for() will return NULL only if
1470   // the specified JavaThread is exiting.
1471   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1472   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1473 





1474   // JVMTI PopFrame support
1475   // Setting and clearing popframe_condition
1476   // All of these enumerated values are bits. popframe_pending
1477   // indicates that a PopFrame() has been requested and not yet been
1478   // completed. popframe_processing indicates that that PopFrame() is in
1479   // the process of being completed. popframe_force_deopt_reexecution_bit
1480   // indicates that special handling is required when returning to a
1481   // deoptimized caller.
1482   enum PopCondition {
1483     popframe_inactive                      = 0x00,
1484     popframe_pending_bit                   = 0x01,
1485     popframe_processing_bit                = 0x02,
1486     popframe_force_deopt_reexecution_bit   = 0x04
1487   };
1488   PopCondition popframe_condition()                   { return (PopCondition) _popframe_condition; }
1489   void set_popframe_condition(PopCondition c)         { _popframe_condition = c; }
1490   void set_popframe_condition_bit(PopCondition c)     { _popframe_condition |= c; }
1491   void clear_popframe_condition()                     { _popframe_condition = popframe_inactive; }
1492   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1493   bool has_pending_popframe()                         { return (popframe_condition() & popframe_pending_bit) != 0; }

1516   void  popframe_free_preserved_args();
1517 
1518 
1519  private:
1520   JvmtiThreadState *_jvmti_thread_state;
1521 
1522   // Used by the interpreter in fullspeed mode for frame pop, method
1523   // entry, method exit and single stepping support. This field is
1524   // only set to non-zero at a safepoint or using a direct handshake
1525   // (see EnterInterpOnlyModeClosure).
1526   // It can be set to zero asynchronously to this threads execution (i.e., without
1527   // safepoint/handshake or a lock) so we have to be very careful.
1528   // Accesses by other threads are synchronized using JvmtiThreadState_lock though.
1529   int               _interp_only_mode;
1530 
1531  public:
1532   // used by the interpreter for fullspeed debugging support (see above)
1533   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1534   bool is_interp_only_mode()                { return (_interp_only_mode != 0); }
1535   int get_interp_only_mode()                { return _interp_only_mode; }

1536   void increment_interp_only_mode()         { ++_interp_only_mode; }
1537   void decrement_interp_only_mode()         { --_interp_only_mode; }
1538 
1539   // support for cached flag that indicates whether exceptions need to be posted for this thread
1540   // if this is false, we can avoid deoptimizing when events are thrown
1541   // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1542  private:
1543   int    _should_post_on_exceptions_flag;
1544 
1545  public:
1546   int   should_post_on_exceptions_flag()  { return _should_post_on_exceptions_flag; }
1547   void  set_should_post_on_exceptions_flag(int val)  { _should_post_on_exceptions_flag = val; }
1548 
1549  private:
1550   ThreadStatistics *_thread_stat;
1551 
1552  public:
1553   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1554 
1555   // Return a blocker object for which this thread is blocked parking.

  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #ifndef SHARE_RUNTIME_THREAD_HPP
  27 #define SHARE_RUNTIME_THREAD_HPP
  28 
  29 #include "jni.h"
  30 #include "gc/shared/gcThreadLocalData.hpp"
  31 #include "gc/shared/threadLocalAllocBuffer.hpp"
  32 #include "memory/allocation.hpp"
  33 #include "oops/oop.hpp"
  34 #include "oops/oopHandle.hpp"
  35 #include "oops/weakHandle.hpp"
  36 #include "runtime/continuation.hpp"
  37 #include "runtime/frame.hpp"
  38 #include "runtime/globals.hpp"
  39 #include "runtime/handshake.hpp"
  40 #include "runtime/javaFrameAnchor.hpp"
  41 #include "runtime/mutexLocker.hpp"
  42 #include "runtime/os.hpp"
  43 #include "runtime/park.hpp"
  44 #include "runtime/safepointMechanism.hpp"
  45 #include "runtime/stackWatermarkSet.hpp"
  46 #include "runtime/stackOverflow.hpp"
  47 #include "runtime/threadHeapSampler.hpp"
  48 #include "runtime/threadLocalStorage.hpp"
  49 #include "runtime/threadStatisticalInfo.hpp"
  50 #include "runtime/unhandledOops.hpp"
  51 #include "utilities/align.hpp"
  52 #include "utilities/exceptions.hpp"
  53 #include "utilities/globalDefinitions.hpp"
  54 #include "utilities/macros.hpp"
  55 #if INCLUDE_JFR
  56 #include "jfr/support/jfrThreadExtension.hpp"

 124 //      - this->post_run()  // virtual per-thread-type tear-down
 125 //      - // 'this' no longer referenceable
 126 //    - OS-level tear-down (minimal)
 127 //    - final logging
 128 //
 129 // For JavaThread:
 130 //   - this->run()  // virtual but not normally overridden
 131 //     - this->thread_main_inner()  // extra call level to ensure correct stack calculations
 132 //       - this->entry_point()  // set differently for each kind of JavaThread
 133 
 134 class Thread: public ThreadShadow {
 135   friend class VMStructs;
 136   friend class JVMCIVMStructs;
 137  private:
 138 
 139 #ifndef USE_LIBRARY_BASED_TLS_ONLY
 140   // Current thread is maintained as a thread-local variable
 141   static THREAD_LOCAL Thread* _thr_current;
 142 #endif
 143 
 144   int _nmethod_disarm_value;
 145 
 146  public:
 147   int nmethod_disarm_value() {
 148     return _nmethod_disarm_value;
 149   }
 150 
 151   void set_nmethod_disarm_value(int value) {
 152     _nmethod_disarm_value = value;
 153   }
 154 
 155   static ByteSize nmethod_disarmed_offset() {
 156     return byte_offset_of(Thread, _nmethod_disarm_value);
 157   }
 158 
 159  private:
 160   // Thread local data area available to the GC. The internal
 161   // structure and contents of this data area is GC-specific.
 162   // Only GC and GC barrier code should access this data area.
 163   GCThreadLocalData _gc_data;
 164 
 165  public:
 166   static ByteSize gc_data_offset() {
 167     return byte_offset_of(Thread, _gc_data);
 168   }
 169 
 170   template <typename T> T* gc_data() {
 171     STATIC_ASSERT(sizeof(T) <= sizeof(_gc_data));
 172     return reinterpret_cast<T*>(&_gc_data);
 173   }
 174 
 175   // Exception handling
 176   // (Note: _pending_exception and friends are in ThreadShadow)
 177   //oop       _pending_exception;                // pending exception for current thread
 178   // const char* _exception_file;                   // file information for exception (debugging only)
 179   // int         _exception_line;                   // line information for exception (debugging only)

 689 #endif
 690 }
 691 
 692 inline Thread* Thread::current_or_null_safe() {
 693   if (ThreadLocalStorage::is_initialized()) {
 694     return ThreadLocalStorage::thread();
 695   }
 696   return NULL;
 697 }
 698 
 699 class CompilerThread;
 700 
 701 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
 702 
 703 class JavaThread: public Thread {
 704   friend class VMStructs;
 705   friend class JVMCIVMStructs;
 706   friend class WhiteBox;
 707   friend class ThreadsSMRSupport; // to access _threadObj for exiting_threads_oops_do
 708   friend class HandshakeState;
 709   friend class Continuation;
 710  private:
 711   bool           _on_thread_list;                // Is set when this JavaThread is added to the Threads list
 712   OopHandle      _threadObj;                     // The Java level thread object
 713   OopHandle      _vthread;
 714   OopHandle      _scopeLocalCache;
 715 
 716 #ifdef ASSERT
 717  private:
 718   int _java_call_counter;
 719 
 720  public:
 721   int  java_call_counter()                       { return _java_call_counter; }
 722   void inc_java_call_counter()                   { _java_call_counter++; }
 723   void dec_java_call_counter() {
 724     assert(_java_call_counter > 0, "Invalid nesting of JavaCallWrapper");
 725     _java_call_counter--;
 726   }
 727  private:  // restore original namespace restriction
 728 #endif  // ifdef ASSERT
 729 
 730   JavaFrameAnchor _anchor;                       // Encapsulation of current java frame and it state
 731 
 732   ThreadFunction _entry_point;
 733 
 734   JNIEnv        _jni_environment;
 735 
 736   // Deopt support
 737   DeoptResourceMark*  _deopt_mark;               // Holds special ResourceMark for deoptimization
 738 
 739   CompiledMethod*       _deopt_nmethod;         // CompiledMethod that is currently being deoptimized
 740   vframeArray*  _vframe_array_head;              // Holds the heap of the active vframeArrays
 741   vframeArray*  _vframe_array_last;              // Holds last vFrameArray we popped
 742   // Holds updates by JVMTI agents for compiled frames that cannot be performed immediately. They
 743   // will be carried out as soon as possible which, in most cases, is just before deoptimization of
 744   // the frame, when control returns to it.
 745   JvmtiDeferredUpdates* _jvmti_deferred_updates;
 746   GrowableArray<WeakHandle>* _keepalive_cleanup;
 747 
 748   // Handshake value for fixing 6243940. We need a place for the i2c
 749   // adapter to store the callee Method*. This value is NEVER live
 750   // across a gc point so it does NOT have to be gc'd
 751   // The handshake is open ended since we can't be certain that it will
 752   // be NULLed. This is because we rarely ever see the race and end up
 753   // in handle_wrong_method which is the backend of the handshake. See
 754   // code in i2c adapters and handle_wrong_method.
 755 
 756   Method*       _callee_target;
 757 
 758   // Used to pass back results to the interpreter or generated code running Java code.
 759   oop           _vm_result;    // oop result is GC-preserved
 760   Metadata*     _vm_result_2;  // non-oop result
 761 
 762   // See ReduceInitialCardMarks: this holds the precise space interval of
 763   // the most recent slow path allocation for which compiled code has
 764   // elided card-marks for performance along the fast-path.
 765   MemRegion     _deferred_card_mark;
 766 

 787     return _current_pending_monitor_is_from_java;
 788   }
 789   ObjectMonitor* current_waiting_monitor() {
 790     // See the comment in current_pending_monitor() above.
 791     return Atomic::load(&_current_waiting_monitor);
 792   }
 793   void set_current_waiting_monitor(ObjectMonitor* monitor) {
 794     Atomic::store(&_current_waiting_monitor, monitor);
 795   }
 796 
 797  private:
 798   MonitorChunk* _monitor_chunks;              // Contains the off stack monitors
 799                                               // allocated during deoptimization
 800                                               // and by JNI_MonitorEnter/Exit
 801 
 802   enum SuspendFlags {
 803     // NOTE: avoid using the sign-bit as cc generates different test code
 804     //       when the sign-bit is used, and sometimes incorrectly - see CR 6398077
 805     _has_async_exception    = 0x00000001U, // there is a pending async exception
 806     _trace_flag             = 0x00000004U, // call tracing backend
 807     _obj_deopt              = 0x00000008U, // suspend for object reallocation and relocking for JVMTI agent
 808     _thread_suspended       = 0x00000010U  // non-virtual thread is externally suspended
 809   };
 810 
 811   // various suspension related flags - atomically updated
 812   // overloaded with async exceptions so that we do a single check when transitioning from native->Java
 813   volatile uint32_t _suspend_flags;
 814 
 815   inline void set_suspend_flag(SuspendFlags f);
 816   inline void clear_suspend_flag(SuspendFlags f);
 817 
 818  public:
 819   inline void set_trace_flag();
 820   inline void clear_trace_flag();
 821   inline void set_obj_deopt_flag();
 822   inline void clear_obj_deopt_flag();
 823   bool is_trace_suspend()      { return (_suspend_flags & _trace_flag) != 0; }
 824   bool is_obj_deopt_suspend()  { return (_suspend_flags & _obj_deopt) != 0; }
 825 
 826   // Asynchronous exceptions support
 827  private:
 828   oop     _pending_async_exception;

 893     _thread_exiting,                             // JavaThread::exit() has been called for this thread
 894     _thread_terminated,                          // JavaThread is removed from thread list
 895     _vm_exited                                   // JavaThread is still executing native code, but VM is terminated
 896                                                  // only VM_Exit can set _vm_exited
 897   };
 898 
 899  private:
 900   // In general a JavaThread's _terminated field transitions as follows:
 901   //
 902   //   _not_terminated => _thread_exiting => _thread_terminated
 903   //
 904   // _vm_exited is a special value to cover the case of a JavaThread
 905   // executing native code after the VM itself is terminated.
 906   volatile TerminatedTypes _terminated;
 907 
 908   jint                  _in_deopt_handler;       // count of deoptimization
 909                                                  // handlers thread is in
 910   volatile bool         _doing_unsafe_access;    // Thread may fault due to unsafe access
 911   bool                  _do_not_unlock_if_synchronized;  // Do not unlock the receiver of a synchronized method (since it was
 912                                                          // never locked) when throwing an exception. Used by interpreter only.
 913 #if INCLUDE_JVMTI
 914   bool                  _is_in_VTMT;             // thread is in virtual thread mount transition
 915   bool                  _is_VTMT_disabler;       // thread currently disabled VTMT
 916 #endif
 917 
 918   // JNI attach states:
 919   enum JNIAttachStates {
 920     _not_attaching_via_jni = 1,  // thread is not attaching via JNI
 921     _attaching_via_jni,          // thread is attaching via JNI
 922     _attached_via_jni            // thread has attached via JNI
 923   };
 924 
 925   // A regular JavaThread's _jni_attach_state is _not_attaching_via_jni.
 926   // A native thread that is attaching via JNI starts with a value
 927   // of _attaching_via_jni and transitions to _attached_via_jni.
 928   volatile JNIAttachStates _jni_attach_state;
 929 
 930 
 931 #if INCLUDE_JVMCI
 932   // The _pending_* fields below are used to communicate extra information
 933   // from an uncommon trap in JVMCI compiled code to the uncommon trap handler.
 934 
 935   // Communicates the DeoptReason and DeoptAction of the uncommon trap
 936   int       _pending_deoptimization;

1017  private:
1018   // support for JNI critical regions
1019   jint    _jni_active_critical;                  // count of entries into JNI critical region
1020 
1021   // Checked JNI: function name requires exception check
1022   char* _pending_jni_exception_check_fn;
1023 
1024   // For deadlock detection.
1025   int _depth_first_number;
1026 
1027   // JVMTI PopFrame support
1028   // This is set to popframe_pending to signal that top Java frame should be popped immediately
1029   int _popframe_condition;
1030 
1031   // If reallocation of scalar replaced objects fails, we throw OOM
1032   // and during exception propagation, pop the top
1033   // _frames_to_pop_failed_realloc frames, the ones that reference
1034   // failed reallocations.
1035   int _frames_to_pop_failed_realloc;
1036 
1037   ContinuationEntry* _cont_entry;
1038   bool _cont_yield; // a continuation yield is in progress
1039   bool _cont_preempt;
1040   int _cont_fastpath_thread_state; // whether global thread state allows continuation fastpath (JVMTI)
1041   intptr_t* _cont_fastpath; // the sp of the oldest known interpreted/call_stub frame inside the continuation that we know about
1042   int _held_monitor_count; // used by continuations for fast lock detection
1043 private:
1044 
1045   friend class VMThread;
1046   friend class ThreadWaitTransition;
1047   friend class VM_Exit;
1048 
1049   // Stack watermark barriers.
1050   StackWatermarks _stack_watermarks;
1051 
1052  public:
1053   inline StackWatermarks* stack_watermarks() { return &_stack_watermarks; }
1054 
1055  public:
1056   oop _mounted_vthread;
1057   jlong _scopeLocal_hash_table_shift;
1058 
1059   void allocate_scopeLocal_hash_table(int count);
1060 
1061  public:
1062   // Constructor
1063   JavaThread();                            // delegating constructor
1064   JavaThread(bool is_attaching_via_jni);   // for main thread and JNI attached threads
1065   JavaThread(ThreadFunction entry_point, size_t stack_size = 0);
1066   ~JavaThread();
1067 
1068 #ifdef ASSERT
1069   // verify this JavaThread hasn't be published in the Threads::list yet
1070   void verify_not_published();
1071 #endif // ASSERT
1072 
1073   StackOverflow* stack_overflow_state() { return &_stack_overflow_state; }
1074 
1075   //JNI functiontable getter/setter for JVMTI jni function table interception API.
1076   void set_jni_functions(struct JNINativeInterface_* functionTable) {
1077     _jni_environment.functions = functionTable;
1078   }
1079   struct JNINativeInterface_* get_jni_functions() {
1080     return (struct JNINativeInterface_ *)_jni_environment.functions;

1090   // Cleanup on thread exit
1091   enum ExitType {
1092     normal_exit,
1093     jni_detach
1094   };
1095   void exit(bool destroy_vm, ExitType exit_type = normal_exit);
1096 
1097   void cleanup_failed_attach_current_thread(bool is_daemon);
1098 
1099   // Testers
1100   virtual bool is_Java_thread() const            { return true;  }
1101   virtual bool can_call_java() const             { return true; }
1102 
1103   virtual bool is_active_Java_thread() const {
1104     return on_thread_list() && !is_terminated();
1105   }
1106 
1107   // Thread oop. threadObj() can be NULL for initial JavaThread
1108   // (or for threads attached via JNI)
1109   oop threadObj() const;
1110   void set_threadOopHandles(oop p);
1111   oop vthread() const;
1112   void set_vthread(oop p);
1113   oop scopeLocalCache() const;
1114   void set_scopeLocalCache(oop p);
1115   oop mounted_vthread() const                    { return _mounted_vthread; }
1116   void set_mounted_vthread(oop p)                { _mounted_vthread = p; }
1117 
1118   // Prepare thread and add to priority queue.  If a priority is
1119   // not specified, use the priority of the thread object. Threads_lock
1120   // must be held while this function is called.
1121   void prepare(jobject jni_thread, ThreadPriority prio=NoPriority);
1122 
1123   void set_saved_exception_pc(address pc)        { _saved_exception_pc = pc; }
1124   address saved_exception_pc()                   { return _saved_exception_pc; }
1125 
1126   ThreadFunction entry_point() const             { return _entry_point; }
1127 
1128   // Allocates a new Java level thread object for this thread. thread_name may be NULL.
1129   void allocate_threadObj(Handle thread_group, const char* thread_name, bool daemon, TRAPS);
1130 
1131   // Last frame anchor routines
1132 
1133   JavaFrameAnchor* frame_anchor(void)            { return &_anchor; }
1134 
1135   // last_Java_sp
1136   bool has_last_Java_frame() const               { return _anchor.has_last_Java_frame(); }

1159   // against the two non-terminated values so that a freed JavaThread
1160   // will also be considered terminated.
1161   bool check_is_terminated(TerminatedTypes l_terminated) const {
1162     return l_terminated != _not_terminated && l_terminated != _thread_exiting;
1163   }
1164   bool is_terminated() const;
1165   void set_terminated(TerminatedTypes t);
1166 
1167   void block_if_vm_exited();
1168 
1169   bool doing_unsafe_access()                     { return _doing_unsafe_access; }
1170   void set_doing_unsafe_access(bool val)         { _doing_unsafe_access = val; }
1171 
1172   bool do_not_unlock_if_synchronized()             { return _do_not_unlock_if_synchronized; }
1173   void set_do_not_unlock_if_synchronized(bool val) { _do_not_unlock_if_synchronized = val; }
1174 
1175   SafepointMechanism::ThreadData* poll_data() { return &_poll_data; }
1176 
1177   void set_requires_cross_modify_fence(bool val) PRODUCT_RETURN NOT_PRODUCT({ _requires_cross_modify_fence = val; })
1178 
1179   // Continuation support
1180   ContinuationEntry* last_continuation() const { return _cont_entry; }
1181   ContinuationEntry* last_continuation(oop cont_scope) const { return Continuation::last_continuation(this, cont_scope); }
1182   bool cont_yield() { return _cont_yield; }
1183   void set_cont_yield(bool x) { _cont_yield = x; }
1184   void set_cont_fastpath(intptr_t* x) { _cont_fastpath = x; }
1185   void push_cont_fastpath(intptr_t* sp) { if (sp > _cont_fastpath) _cont_fastpath = sp; }
1186   void set_cont_fastpath_thread_state(bool x) { _cont_fastpath_thread_state = (int)x; }
1187   intptr_t* raw_cont_fastpath() { return _cont_fastpath; }
1188   bool cont_fastpath() { return ((_cont_fastpath == NULL) & _cont_fastpath_thread_state) != 0; }
1189   bool cont_fastpath_thread_state() { return _cont_fastpath_thread_state != 0; }
1190   bool cont_preempt() { return _cont_preempt; }
1191   void set_cont_preempt(bool x) { _cont_preempt = x; }
1192   int held_monitor_count() { return _held_monitor_count; }
1193   void reset_held_monitor_count() { _held_monitor_count = 0; }
1194   void inc_held_monitor_count() { _held_monitor_count++; }
1195   void dec_held_monitor_count() { assert (_held_monitor_count > 0, ""); _held_monitor_count--; }
1196 
1197  private:
1198   DEBUG_ONLY(void verify_frame_info();)
1199 
1200   // Support for thread handshake operations
1201   HandshakeState _handshake;
1202  public:
1203   HandshakeState* handshake_state() { return &_handshake; }
1204 
1205   // A JavaThread can always safely operate on it self and other threads
1206   // can do it safely if they are the active handshaker.
1207   bool is_handshake_safe_for(Thread* th) const {
1208     return _handshake.active_handshaker() == th || this == th;
1209   }
1210 
1211   // Suspend/resume support for JavaThread
1212   // higher-level suspension/resume logic called by the public APIs
1213   bool java_suspend();
1214   bool java_resume();
1215   bool is_suspended()     { return _handshake.is_suspended(); }
1216 
1217   // lower-level blocking logic called by the JVM.  The caller suspends this
1218   // thread, does something, and then releases it.
1219   bool block_suspend(JavaThread* caller);
1220   bool continue_resume(JavaThread* caller);
1221 
1222   // Check for async exception in addition to safepoint.
1223   static void check_special_condition_for_native_trans(JavaThread *thread);
1224 
1225   // Synchronize with another thread that is deoptimizing objects of the
1226   // current thread, i.e. reverts optimizations based on escape analysis.
1227   void wait_for_object_deoptimization();
1228 
1229   inline void set_thread_suspended();
1230   inline void clear_thread_suspended();
1231 
1232   bool is_thread_suspended() const {
1233     return (_suspend_flags & _thread_suspended) != 0;
1234   }
1235 
1236 #if INCLUDE_JVMTI
1237   bool is_VTMT_disabler() const                  { return _is_VTMT_disabler; }
1238   bool is_in_VTMT() const                        { return _is_in_VTMT; }
1239 
1240   void set_is_in_VTMT(bool val);
1241   void set_is_VTMT_disabler(bool val);
1242 #endif
1243 
1244   bool is_cont_force_yield() { return cont_preempt(); }
1245 
1246   // these next two are also used for self-suspension and async exception support
1247   void handle_special_runtime_exit_condition(bool check_asyncs = true);
1248 
1249   // Return true if JavaThread has an asynchronous condition or
1250   // if external suspension is requested.
1251   bool has_special_runtime_exit_condition() {
1252     return (_suspend_flags & (_has_async_exception | _obj_deopt JFR_ONLY(| _trace_flag))) != 0
1253            || is_cont_force_yield();
1254   }
1255 
1256   // Fast-locking support
1257   bool is_lock_owned(address adr) const;
1258 
1259   // Accessors for vframe array top
1260   // The linked list of vframe arrays are sorted on sp. This means when we
1261   // unpack the head must contain the vframe array to unpack.
1262   void set_vframe_array_head(vframeArray* value) { _vframe_array_head = value; }
1263   vframeArray* vframe_array_head() const         { return _vframe_array_head;  }
1264 
1265   // Side structure for deferring update of java frame locals until deopt occurs
1266   JvmtiDeferredUpdates* deferred_updates() const      { return _jvmti_deferred_updates; }
1267   void set_deferred_updates(JvmtiDeferredUpdates* du) { _jvmti_deferred_updates = du; }
1268 
1269   void set_keepalive_cleanup(GrowableArray<WeakHandle>* lst) { _keepalive_cleanup = lst; }
1270   GrowableArray<WeakHandle>* keepalive_cleanup() const { return _keepalive_cleanup; }
1271 
1272   // These only really exist to make debugging deopt problems simpler
1273 
1274   void set_vframe_array_last(vframeArray* value) { _vframe_array_last = value; }
1275   vframeArray* vframe_array_last() const         { return _vframe_array_last;  }
1276 
1277   // The special resourceMark used during deoptimization
1278 
1279   void set_deopt_mark(DeoptResourceMark* value)  { _deopt_mark = value; }
1280   DeoptResourceMark* deopt_mark(void)            { return _deopt_mark; }
1281 
1282   void set_deopt_compiled_method(CompiledMethod* nm)  { _deopt_nmethod = nm; }
1283   CompiledMethod* deopt_compiled_method()        { return _deopt_nmethod; }
1284 
1285   Method*    callee_target() const               { return _callee_target; }
1286   void set_callee_target  (Method* x)          { _callee_target   = x; }
1287 
1288   // Oop results of vm runtime calls
1289   oop  vm_result() const                         { return _vm_result; }
1290   void set_vm_result  (oop x)                    { _vm_result   = x; }
1291 

1321   void set_exception_handler_pc(address a)       { _exception_handler_pc = a; }
1322   void set_is_method_handle_return(bool value)   { _is_method_handle_return = value ? 1 : 0; }
1323 
1324   void clear_exception_oop_and_pc() {
1325     set_exception_oop(NULL);
1326     set_exception_pc(NULL);
1327   }
1328 
1329   // Check if address is in the usable part of the stack (excludes protected
1330   // guard pages). Can be applied to any thread and is an approximation for
1331   // using is_in_live_stack when the query has to happen from another thread.
1332   bool is_in_usable_stack(address adr) const {
1333     return is_in_stack_range_incl(adr, _stack_overflow_state.stack_reserved_zone_base());
1334   }
1335 
1336   // Misc. accessors/mutators
1337   void set_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = true; }
1338   void clr_do_not_unlock(void)                   { _do_not_unlock_if_synchronized = false; }
1339   bool do_not_unlock(void)                       { return _do_not_unlock_if_synchronized; }
1340 
1341   static ByteSize scopeLocalCache_offset()       { return byte_offset_of(JavaThread, _scopeLocalCache); }
1342 
1343   // For assembly stub generation
1344   static ByteSize threadObj_offset()             { return byte_offset_of(JavaThread, _threadObj); }
1345   static ByteSize vthread_offset()               { return byte_offset_of(JavaThread, _vthread); }
1346   static ByteSize jni_environment_offset()       { return byte_offset_of(JavaThread, _jni_environment); }
1347   static ByteSize pending_jni_exception_check_fn_offset() {
1348     return byte_offset_of(JavaThread, _pending_jni_exception_check_fn);
1349   }
1350   static ByteSize last_Java_sp_offset() {
1351     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_sp_offset();
1352   }
1353   static ByteSize last_Java_pc_offset() {
1354     return byte_offset_of(JavaThread, _anchor) + JavaFrameAnchor::last_Java_pc_offset();
1355   }
1356   static ByteSize frame_anchor_offset() {
1357     return byte_offset_of(JavaThread, _anchor);
1358   }
1359   static ByteSize callee_target_offset()         { return byte_offset_of(JavaThread, _callee_target); }
1360   static ByteSize vm_result_offset()             { return byte_offset_of(JavaThread, _vm_result); }
1361   static ByteSize vm_result_2_offset()           { return byte_offset_of(JavaThread, _vm_result_2); }
1362   static ByteSize thread_state_offset()          { return byte_offset_of(JavaThread, _thread_state); }
1363   static ByteSize polling_word_offset()          { return byte_offset_of(JavaThread, _poll_data) + byte_offset_of(SafepointMechanism::ThreadData, _polling_word);}
1364   static ByteSize polling_page_offset()          { return byte_offset_of(JavaThread, _poll_data) + byte_offset_of(SafepointMechanism::ThreadData, _polling_page);}
1365   static ByteSize saved_exception_pc_offset()    { return byte_offset_of(JavaThread, _saved_exception_pc); }

1380   // StackOverflow offsets
1381   static ByteSize stack_overflow_limit_offset()  {
1382     return byte_offset_of(JavaThread, _stack_overflow_state._stack_overflow_limit);
1383   }
1384   static ByteSize stack_guard_state_offset()     {
1385     return byte_offset_of(JavaThread, _stack_overflow_state._stack_guard_state);
1386   }
1387   static ByteSize reserved_stack_activation_offset() {
1388     return byte_offset_of(JavaThread, _stack_overflow_state._reserved_stack_activation);
1389   }
1390 
1391   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags); }
1392 
1393   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1394   static ByteSize should_post_on_exceptions_flag_offset() {
1395     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1396   }
1397   static ByteSize doing_unsafe_access_offset() { return byte_offset_of(JavaThread, _doing_unsafe_access); }
1398   NOT_PRODUCT(static ByteSize requires_cross_modify_fence_offset()  { return byte_offset_of(JavaThread, _requires_cross_modify_fence); })
1399 
1400   static ByteSize cont_entry_offset()         { return byte_offset_of(JavaThread, _cont_entry); }
1401   static ByteSize cont_fastpath_offset()      { return byte_offset_of(JavaThread, _cont_fastpath); }
1402   static ByteSize cont_preempt_offset()       { return byte_offset_of(JavaThread, _cont_preempt); }
1403   static ByteSize held_monitor_count_offset() { return byte_offset_of(JavaThread, _held_monitor_count); }
1404 
1405   // Returns the jni environment for this thread
1406   JNIEnv* jni_environment()                      { return &_jni_environment; }
1407 
1408   static JavaThread* thread_from_jni_environment(JNIEnv* env) {
1409     JavaThread *thread_from_jni_env = (JavaThread*)((intptr_t)env - in_bytes(jni_environment_offset()));
1410     // Only return NULL if thread is off the thread list; starting to
1411     // exit should not return NULL.
1412     if (thread_from_jni_env->is_terminated()) {
1413       thread_from_jni_env->block_if_vm_exited();
1414       return NULL;
1415     } else {
1416       return thread_from_jni_env;
1417     }
1418   }
1419 
1420   // JNI critical regions. These can nest.
1421   bool in_critical()    { return _jni_active_critical > 0; }
1422   bool in_last_critical()  { return _jni_active_critical == 1; }
1423   inline void enter_critical();
1424   void exit_critical() {

1472   void oops_do_frames(OopClosure* f, CodeBlobClosure* cf);
1473   void oops_do_no_frames(OopClosure* f, CodeBlobClosure* cf);
1474 
1475   // Sweeper operations
1476   virtual void nmethods_do(CodeBlobClosure* cf);
1477 
1478   // RedefineClasses Support
1479   void metadata_do(MetadataClosure* f);
1480 
1481   // Debug method asserting thread states are correct during a handshake operation.
1482   DEBUG_ONLY(void verify_states_for_handshake();)
1483 
1484   // Misc. operations
1485   const char* name() const;
1486   const char* type_name() const { return "JavaThread"; }
1487   static const char* name_for(oop thread_obj);
1488 
1489   void print_on(outputStream* st, bool print_extended_info) const;
1490   void print_on(outputStream* st) const { print_on(st, false); }
1491   void print() const;
1492   void print_thread_state_on(outputStream*) const;
1493   const char* thread_state_name() const;
1494   void print_on_error(outputStream* st, char* buf, int buflen) const;
1495   void print_name_on_error(outputStream* st, char* buf, int buflen) const;
1496   void verify();
1497 
1498   // Accessing frames
1499   frame last_frame() {
1500     _anchor.make_walkable(this);
1501     return pd_last_frame();
1502   }
1503   javaVFrame* last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(last_frame(), reg_map); }
1504 
1505   frame vthread_carrier_last_frame(RegisterMap* reg_map);
1506   javaVFrame* vthread_carrier_last_java_vframe(RegisterMap* reg_map) { return last_java_vframe(vthread_carrier_last_frame(reg_map), reg_map); }
1507 
1508   javaVFrame* last_java_vframe(const frame f, RegisterMap* reg_map);
1509 
1510   // Returns method at 'depth' java or native frames down the stack
1511   // Used for security checks
1512   Klass* security_get_caller_class(int depth);
1513 
1514   // Print stack trace in external format
1515   void print_stack_on(outputStream* st);
1516   void print_stack() { print_stack_on(tty); }
1517 
1518   // Print stack traces in various internal formats
1519   void trace_stack()                             PRODUCT_RETURN;
1520   void trace_stack_from(vframe* start_vf)        PRODUCT_RETURN;
1521   void trace_frames()                            PRODUCT_RETURN;
1522 
1523   // Print an annotated view of the stack frames
1524   void print_frame_layout(int depth = 0, bool validate_only = false) NOT_DEBUG_RETURN;
1525   void validate_frame_layout() {
1526     print_frame_layout(0, true);
1527   }
1528 
1529   // Function for testing deoptimization
1530   void deoptimize();
1531   void make_zombies();
1532 
1533   void deoptimize_marked_methods();
1534   void deoptimize_marked_methods_only_anchors();
1535 
1536  public:
1537   // Returns the running thread as a JavaThread
1538   static JavaThread* current() {
1539     return JavaThread::cast(Thread::current());
1540   }
1541 
1542   // Returns the current thread as a JavaThread, or NULL if not attached
1543   static inline JavaThread* current_or_null();
1544 
1545   // Casts
1546   static JavaThread* cast(Thread* t) {
1547     assert(t->is_Java_thread(), "incorrect cast to JavaThread");
1548     return static_cast<JavaThread*>(t);
1549   }
1550 
1551   static const JavaThread* cast(const Thread* t) {
1552     assert(t->is_Java_thread(), "incorrect cast to const JavaThread");
1553     return static_cast<const JavaThread*>(t);
1554   }

1561 
1562  protected:
1563   virtual void pre_run();
1564   virtual void run();
1565   void thread_main_inner();
1566   virtual void post_run();
1567 
1568  public:
1569   // Thread local information maintained by JVMTI.
1570   void set_jvmti_thread_state(JvmtiThreadState *value)                           { _jvmti_thread_state = value; }
1571   // A JvmtiThreadState is lazily allocated. This jvmti_thread_state()
1572   // getter is used to get this JavaThread's JvmtiThreadState if it has
1573   // one which means NULL can be returned. JvmtiThreadState::state_for()
1574   // is used to get the specified JavaThread's JvmtiThreadState if it has
1575   // one or it allocates a new JvmtiThreadState for the JavaThread and
1576   // returns it. JvmtiThreadState::state_for() will return NULL only if
1577   // the specified JavaThread is exiting.
1578   JvmtiThreadState *jvmti_thread_state() const                                   { return _jvmti_thread_state; }
1579   static ByteSize jvmti_thread_state_offset()                                    { return byte_offset_of(JavaThread, _jvmti_thread_state); }
1580 
1581 #if INCLUDE_JVMTI
1582   // Rebind JVMTI thread state from carrier to virtual or from virtual to carrier.
1583   JvmtiThreadState *rebind_to_jvmti_thread_state_of(oop thread_oop);
1584 #endif
1585 
1586   // JVMTI PopFrame support
1587   // Setting and clearing popframe_condition
1588   // All of these enumerated values are bits. popframe_pending
1589   // indicates that a PopFrame() has been requested and not yet been
1590   // completed. popframe_processing indicates that that PopFrame() is in
1591   // the process of being completed. popframe_force_deopt_reexecution_bit
1592   // indicates that special handling is required when returning to a
1593   // deoptimized caller.
1594   enum PopCondition {
1595     popframe_inactive                      = 0x00,
1596     popframe_pending_bit                   = 0x01,
1597     popframe_processing_bit                = 0x02,
1598     popframe_force_deopt_reexecution_bit   = 0x04
1599   };
1600   PopCondition popframe_condition()                   { return (PopCondition) _popframe_condition; }
1601   void set_popframe_condition(PopCondition c)         { _popframe_condition = c; }
1602   void set_popframe_condition_bit(PopCondition c)     { _popframe_condition |= c; }
1603   void clear_popframe_condition()                     { _popframe_condition = popframe_inactive; }
1604   static ByteSize popframe_condition_offset()         { return byte_offset_of(JavaThread, _popframe_condition); }
1605   bool has_pending_popframe()                         { return (popframe_condition() & popframe_pending_bit) != 0; }

1628   void  popframe_free_preserved_args();
1629 
1630 
1631  private:
1632   JvmtiThreadState *_jvmti_thread_state;
1633 
1634   // Used by the interpreter in fullspeed mode for frame pop, method
1635   // entry, method exit and single stepping support. This field is
1636   // only set to non-zero at a safepoint or using a direct handshake
1637   // (see EnterInterpOnlyModeClosure).
1638   // It can be set to zero asynchronously to this threads execution (i.e., without
1639   // safepoint/handshake or a lock) so we have to be very careful.
1640   // Accesses by other threads are synchronized using JvmtiThreadState_lock though.
1641   int               _interp_only_mode;
1642 
1643  public:
1644   // used by the interpreter for fullspeed debugging support (see above)
1645   static ByteSize interp_only_mode_offset() { return byte_offset_of(JavaThread, _interp_only_mode); }
1646   bool is_interp_only_mode()                { return (_interp_only_mode != 0); }
1647   int get_interp_only_mode()                { return _interp_only_mode; }
1648   int set_interp_only_mode(int val)         { return _interp_only_mode = val; }
1649   void increment_interp_only_mode()         { ++_interp_only_mode; }
1650   void decrement_interp_only_mode()         { --_interp_only_mode; }
1651 
1652   // support for cached flag that indicates whether exceptions need to be posted for this thread
1653   // if this is false, we can avoid deoptimizing when events are thrown
1654   // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1655  private:
1656   int    _should_post_on_exceptions_flag;
1657 
1658  public:
1659   int   should_post_on_exceptions_flag()  { return _should_post_on_exceptions_flag; }
1660   void  set_should_post_on_exceptions_flag(int val)  { _should_post_on_exceptions_flag = val; }
1661 
1662  private:
1663   ThreadStatistics *_thread_stat;
1664 
1665  public:
1666   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1667 
1668   // Return a blocker object for which this thread is blocked parking.
< prev index next >