< 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"

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
















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

 660 #endif
 661 }
 662 
 663 inline Thread* Thread::current_or_null_safe() {
 664   if (ThreadLocalStorage::is_initialized()) {
 665     return ThreadLocalStorage::thread();
 666   }
 667   return NULL;
 668 }
 669 
 670 class CompilerThread;
 671 
 672 typedef void (*ThreadFunction)(JavaThread*, TRAPS);
 673 
 674 class JavaThread: public Thread {
 675   friend class VMStructs;
 676   friend class JVMCIVMStructs;
 677   friend class WhiteBox;
 678   friend class ThreadsSMRSupport; // to access _threadObj for exiting_threads_oops_do
 679   friend class HandshakeState;

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


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

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

 770 
 771   // JNI handle support
 772   JNIHandleBlock* active_handles() const         { return _active_handles; }
 773   void set_active_handles(JNIHandleBlock* block) { _active_handles = block; }
 774   JNIHandleBlock* free_handle_block() const      { return _free_handle_block; }
 775   void set_free_handle_block(JNIHandleBlock* block) { _free_handle_block = block; }
 776 
 777   void push_jni_handle_block();
 778   void pop_jni_handle_block();
 779 
 780  private:
 781   MonitorChunk* _monitor_chunks;              // Contains the off stack monitors
 782                                               // allocated during deoptimization
 783                                               // and by JNI_MonitorEnter/Exit
 784 
 785   enum SuspendFlags {
 786     // NOTE: avoid using the sign-bit as cc generates different test code
 787     //       when the sign-bit is used, and sometimes incorrectly - see CR 6398077
 788     _has_async_exception    = 0x00000001U, // there is a pending async exception
 789     _trace_flag             = 0x00000004U, // call tracing backend
 790     _obj_deopt              = 0x00000008U  // suspend for object reallocation and relocking for JVMTI agent

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

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




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

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








1015   friend class VMThread;
1016   friend class ThreadWaitTransition;
1017   friend class VM_Exit;
1018 
1019   // Stack watermark barriers.
1020   StackWatermarks _stack_watermarks;
1021 
1022  public:
1023   inline StackWatermarks* stack_watermarks() { return &_stack_watermarks; }
1024 






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

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






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

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


















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

1154   bool is_suspended()     { return _handshake.is_suspended(); }
1155 





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

















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

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



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

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


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

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

1292   // StackOverflow offsets
1293   static ByteSize stack_overflow_limit_offset()  {
1294     return byte_offset_of(JavaThread, _stack_overflow_state._stack_overflow_limit);
1295   }
1296   static ByteSize stack_guard_state_offset()     {
1297     return byte_offset_of(JavaThread, _stack_overflow_state._stack_guard_state);
1298   }
1299   static ByteSize reserved_stack_activation_offset() {
1300     return byte_offset_of(JavaThread, _stack_overflow_state._reserved_stack_activation);
1301   }
1302 
1303   static ByteSize suspend_flags_offset()         { return byte_offset_of(JavaThread, _suspend_flags); }
1304 
1305   static ByteSize do_not_unlock_if_synchronized_offset() { return byte_offset_of(JavaThread, _do_not_unlock_if_synchronized); }
1306   static ByteSize should_post_on_exceptions_flag_offset() {
1307     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
1308   }
1309   static ByteSize doing_unsafe_access_offset() { return byte_offset_of(JavaThread, _doing_unsafe_access); }
1310   NOT_PRODUCT(static ByteSize requires_cross_modify_fence_offset()  { return byte_offset_of(JavaThread, _requires_cross_modify_fence); })
1311 





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

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

1400   void print_on_error(outputStream* st, char* buf, int buflen) const;
1401   void print_name_on_error(outputStream* st, char* buf, int buflen) const;
1402   void verify();
1403 
1404   // Accessing frames
1405   frame last_frame() {
1406     _anchor.make_walkable(this);
1407     return pd_last_frame();
1408   }
1409   javaVFrame* last_java_vframe(RegisterMap* reg_map);





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

1435 
1436  public:
1437   // Returns the running thread as a JavaThread
1438   static JavaThread* current() {
1439     return JavaThread::cast(Thread::current());
1440   }
1441 
1442   // Returns the current thread as a JavaThread, or NULL if not attached
1443   static inline JavaThread* current_or_null();
1444 
1445   // Casts
1446   static JavaThread* cast(Thread* t) {
1447     assert(t->is_Java_thread(), "incorrect cast to JavaThread");
1448     return static_cast<JavaThread*>(t);
1449   }
1450 
1451   static const JavaThread* cast(const Thread* t) {
1452     assert(t->is_Java_thread(), "incorrect cast to const JavaThread");
1453     return static_cast<const JavaThread*>(t);
1454   }

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





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

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

1543   void increment_interp_only_mode()         { ++_interp_only_mode; }
1544   void decrement_interp_only_mode()         { --_interp_only_mode; }
1545 
1546   // support for cached flag that indicates whether exceptions need to be posted for this thread
1547   // if this is false, we can avoid deoptimizing when events are thrown
1548   // this gets set to reflect whether jvmtiExport::post_exception_throw would actually do anything
1549  private:
1550   int    _should_post_on_exceptions_flag;
1551 
1552  public:
1553   int   should_post_on_exceptions_flag()  { return _should_post_on_exceptions_flag; }
1554   void  set_should_post_on_exceptions_flag(int val)  { _should_post_on_exceptions_flag = val; }
1555 
1556  private:
1557   ThreadStatistics *_thread_stat;
1558 
1559  public:
1560   ThreadStatistics* get_thread_stat() const    { return _thread_stat; }
1561 
1562   // 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"

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

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

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

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

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

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

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

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

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

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

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

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