1 /*
  2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2021, Azul Systems, Inc. All rights reserved.
  4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  5  *
  6  * This code is free software; you can redistribute it and/or modify it
  7  * under the terms of the GNU General Public License version 2 only, as
  8  * published by the Free Software Foundation.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  *
 24  */
 25 
 26 #ifndef SHARE_RUNTIME_INTERFACESUPPORT_INLINE_HPP
 27 #define SHARE_RUNTIME_INTERFACESUPPORT_INLINE_HPP
 28 
 29 // No interfaceSupport.hpp
 30 
 31 #include "gc/shared/gc_globals.hpp"
 32 #include "runtime/handles.inline.hpp"
 33 #include "runtime/mutexLocker.hpp"
 34 #include "runtime/orderAccess.hpp"
 35 #include "runtime/os.hpp"
 36 #include "runtime/safepointMechanism.inline.hpp"
 37 #include "runtime/safepointVerifiers.hpp"
 38 #include "runtime/thread.hpp"
 39 #include "runtime/threadWXSetters.inline.hpp"
 40 #include "runtime/vmOperations.hpp"
 41 #include "utilities/globalDefinitions.hpp"
 42 #include "utilities/macros.hpp"
 43 #include "utilities/preserveException.hpp"
 44 
 45 // Wrapper for all entry points to the virtual machine.
 46 
 47 // InterfaceSupport provides functionality used by the VM_LEAF_BASE and
 48 // VM_ENTRY_BASE macros. These macros are used to guard entry points into
 49 // the VM and perform checks upon leave of the VM.
 50 
 51 
 52 class InterfaceSupport: AllStatic {
 53 # ifdef ASSERT
 54  public:
 55   static unsigned int _scavenge_alot_counter;
 56   static unsigned int _fullgc_alot_counter;
 57   static int _fullgc_alot_invocation;
 58 
 59   // Helper methods used to implement +ScavengeALot and +FullGCALot
 60   static void check_gc_alot() { if (ScavengeALot || FullGCALot) gc_alot(); }
 61   static void gc_alot();
 62 
 63   static void walk_stack_from(vframe* start_vf);
 64   static void walk_stack();
 65 
 66   static void zombieAll();
 67   static void deoptimizeAll();
 68   static void verify_stack();
 69   static void verify_last_frame();
 70 # endif
 71 };
 72 
 73 
 74 // Basic class for all thread transition classes.
 75 
 76 class ThreadStateTransition : public StackObj {
 77  protected:
 78   JavaThread* _thread;
 79 
 80  public:
 81   ThreadStateTransition(JavaThread *thread) : _thread(thread) {
 82     assert(thread != NULL, "must be active Java thread");
 83     assert(thread == Thread::current(), "must be current thread");
 84   }
 85 
 86   static inline void transition_from_java(JavaThread *thread, JavaThreadState to) {
 87     assert(thread->thread_state() == _thread_in_Java, "coming from wrong thread state: %s", thread->thread_state_name());
 88     assert(to == _thread_in_vm || to == _thread_in_native, "invalid transition");
 89     thread->set_thread_state(to);
 90   }
 91 
 92   // We never install asynchronous exceptions when coming (back) in to the runtime
 93   // from native code because the runtime is not set up to handle exceptions floating
 94   // around at arbitrary points.
 95   static inline void transition_from_native(JavaThread *thread, JavaThreadState to, bool check_asyncs = true) {
 96     assert(thread->thread_state() == _thread_in_native, "coming from wrong thread state");
 97     assert(to == _thread_in_vm || to == _thread_in_Java, "invalid transition");
 98     assert(!thread->has_last_Java_frame() || thread->frame_anchor()->walkable(), "Unwalkable stack in native transition");
 99 
100     thread->set_thread_state_fence(_thread_in_vm);
101     SafepointMechanism::process_if_requested_with_exit_check(thread, to != _thread_in_Java ? false : check_asyncs);
102     thread->set_thread_state(to);
103   }
104 
105   static inline void transition_from_vm(JavaThread *thread, JavaThreadState to, bool check_asyncs = true) {
106     assert(thread->thread_state() == _thread_in_vm, "coming from wrong thread state");
107     if (to == _thread_in_Java) {
108       SafepointMechanism::process_if_requested_with_exit_check(thread, check_asyncs);
109       thread->set_thread_state(to);
110     } else {
111       assert(to == _thread_in_native || to == _thread_blocked, "invalid transition");
112       // Check NoSafepointVerifier. This also clears unhandled oops if CheckUnhandledOops is used.
113       thread->check_possible_safepoint();
114 
115       // Once we are in native/blocked vm expects stack to be walkable
116       thread->frame_anchor()->make_walkable(thread);
117       OrderAccess::storestore(); // Keep thread_state change and make_walkable() separate.
118       thread->set_thread_state(to);
119     }
120   }
121 };
122 
123 class ThreadInVMForHandshake : public ThreadStateTransition {
124   const JavaThreadState _original_state;
125  public:
126   ThreadInVMForHandshake(JavaThread* thread) : ThreadStateTransition(thread),
127       _original_state(thread->thread_state()) {
128 
129     if (thread->has_last_Java_frame()) {
130       thread->frame_anchor()->make_walkable(thread);
131     }
132 
133     thread->set_thread_state(_thread_in_vm);
134 
135     // Threads shouldn't block if they are in the middle of printing, but...
136     ttyLocker::break_tty_lock_for_safepoint(os::current_thread_id());
137   }
138 
139   ~ThreadInVMForHandshake() {
140     assert(_thread->thread_state() == _thread_in_vm, "should only call when leaving VM after handshake");
141     _thread->set_thread_state(_original_state);
142   }
143 
144 };
145 
146 class ThreadInVMfromJava : public ThreadStateTransition {
147   bool _check_asyncs;
148  public:
149   ThreadInVMfromJava(JavaThread* thread, bool check_asyncs = true) : ThreadStateTransition(thread), _check_asyncs(check_asyncs) {
150     transition_from_java(thread, _thread_in_vm);
151   }
152   ~ThreadInVMfromJava()  {
153     if (_thread->stack_overflow_state()->stack_yellow_reserved_zone_disabled()) {
154       _thread->stack_overflow_state()->enable_stack_yellow_reserved_zone();
155     }
156     // We prevent asynchronous exceptions from being installed on return to Java in situations
157     // where we can't tolerate them. See bugs: 4324348, 4854693, 4998314, 5040492, 5050705.
158     transition_from_vm(_thread, _thread_in_Java, _check_asyncs);
159   }
160 };
161 
162 
163 class ThreadInVMfromUnknown {
164   JavaThread* _thread;
165  public:
166   ThreadInVMfromUnknown() : _thread(NULL) {
167     Thread* t = Thread::current();
168     if (t->is_Java_thread()) {
169       JavaThread* t2 = JavaThread::cast(t);
170       if (t2->thread_state() == _thread_in_native) {
171         _thread = t2;
172         ThreadStateTransition::transition_from_native(t2, _thread_in_vm);
173         // Used to have a HandleMarkCleaner but that is dangerous as
174         // it could free a handle in our (indirect, nested) caller.
175         // We expect any handles will be short lived and figure we
176         // don't need an actual HandleMark.
177       }
178     }
179   }
180   ~ThreadInVMfromUnknown()  {
181     if (_thread) {
182       ThreadStateTransition::transition_from_vm(_thread, _thread_in_native);
183     }
184   }
185 };
186 
187 
188 class ThreadInVMfromNative : public ThreadStateTransition {
189   ResetNoHandleMark __rnhm;
190  public:
191   ThreadInVMfromNative(JavaThread* thread) : ThreadStateTransition(thread) {
192     transition_from_native(thread, _thread_in_vm);
193   }
194   ~ThreadInVMfromNative() {
195     // We cannot assert !_thread->owns_locks() since we have valid cases where
196     // we call known native code using this wrapper holding locks.
197     transition_from_vm(_thread, _thread_in_native);
198   }
199 };
200 
201 
202 class ThreadToNativeFromVM : public ThreadStateTransition {
203  public:
204   ThreadToNativeFromVM(JavaThread *thread) : ThreadStateTransition(thread) {
205     assert(!thread->owns_locks(), "must release all locks when leaving VM");
206     transition_from_vm(thread, _thread_in_native);
207   }
208   ~ThreadToNativeFromVM() {
209     transition_from_native(_thread, _thread_in_vm);
210     assert(!_thread->is_pending_jni_exception_check(), "Pending JNI Exception Check");
211     // We don't need to clear_walkable because it will happen automagically when we return to java
212   }
213 };
214 
215 // Perform a transition to _thread_blocked and take a call-back to be executed before
216 // SafepointMechanism::process_if_requested when returning to the VM. This allows us
217 // to perform an "undo" action if we might block processing a safepoint/handshake operation
218 // (such as thread suspension).
219 template <typename PRE_PROC = void(JavaThread*)>
220 class ThreadBlockInVMPreprocess : public ThreadStateTransition {
221  private:
222   PRE_PROC& _pr;
223   bool _allow_suspend;
224  public:
225   ThreadBlockInVMPreprocess(JavaThread* thread, PRE_PROC& pr = emptyOp, bool allow_suspend = false)
226     : ThreadStateTransition(thread), _pr(pr), _allow_suspend(allow_suspend) {
227     transition_from_vm(thread, _thread_blocked);
228   }
229   ~ThreadBlockInVMPreprocess() {
230     assert(_thread->thread_state() == _thread_blocked, "coming from wrong thread state");
231     // Change to transition state and ensure it is seen by the VM thread.
232     _thread->set_thread_state_fence(_thread_blocked_trans);
233 
234     if (SafepointMechanism::should_process(_thread, _allow_suspend)) {
235       _pr(_thread);
236       SafepointMechanism::process_if_requested(_thread, _allow_suspend);
237     }
238 
239     _thread->set_thread_state(_thread_in_vm);
240   }
241 
242   static void emptyOp(JavaThread* current) {}
243 };
244 
245 typedef ThreadBlockInVMPreprocess<> ThreadBlockInVM;
246 
247 
248 // Debug class instantiated in JRT_ENTRY macro.
249 // Can be used to verify properties on enter/exit of the VM.
250 
251 #ifdef ASSERT
252 class VMEntryWrapper {
253  public:
254   VMEntryWrapper();
255   ~VMEntryWrapper();
256 };
257 
258 
259 class VMNativeEntryWrapper {
260  public:
261   VMNativeEntryWrapper();
262   ~VMNativeEntryWrapper();
263 };
264 
265 #endif // ASSERT
266 
267 // LEAF routines do not lock, GC or throw exceptions
268 
269 // On macos/aarch64 we need to maintain the W^X state of the thread.  So we
270 // take WXWrite on the enter to VM from the "outside" world, so the rest of JVM
271 // code can assume writing (but not executing) codecache is always possible
272 // without preliminary actions.
273 // JavaThread state should be changed only after taking WXWrite. The state
274 // change may trigger a safepoint, that would need WXWrite to do bookkeeping
275 // in the codecache.
276 
277 #define VM_LEAF_BASE(result_type, header)                            \
278   debug_only(NoHandleMark __hm;)                                     \
279   MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite,                    \
280                                          JavaThread::current()));    \
281   os::verify_stack_alignment();                                      \
282   /* begin of body */
283 
284 #define VM_ENTRY_BASE_FROM_LEAF(result_type, header, thread)         \
285   debug_only(ResetNoHandleMark __rnhm;)                              \
286   HandleMarkCleaner __hm(thread);                                    \
287   JavaThread* THREAD = thread; /* For exception macros. */           \
288   os::verify_stack_alignment();                                      \
289   /* begin of body */
290 
291 
292 // ENTRY routines may lock, GC and throw exceptions
293 
294 #define VM_ENTRY_BASE(result_type, header, thread)                   \
295   HandleMarkCleaner __hm(thread);                                    \
296   JavaThread* THREAD = thread; /* For exception macros. */           \
297   os::verify_stack_alignment();                                      \
298   /* begin of body */
299 
300 
301 #define JRT_ENTRY(result_type, header)                               \
302   result_type header {                                               \
303     MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, current));       \
304     ThreadInVMfromJava __tiv(current);                               \
305     VM_ENTRY_BASE(result_type, header, current)                      \
306     debug_only(VMEntryWrapper __vew;)
307 
308 // JRT_LEAF currently can be called from either _thread_in_Java or
309 // _thread_in_native mode.
310 //
311 // JRT_LEAF rules:
312 // A JRT_LEAF method may not interfere with safepointing by
313 //   1) acquiring or blocking on a Mutex or JavaLock - checked
314 //   2) allocating heap memory - checked
315 //   3) executing a VM operation - checked
316 //   4) executing a system call (including malloc) that could block or grab a lock
317 //   5) invoking GC
318 //   6) reaching a safepoint
319 //   7) running too long
320 // Nor may any method it calls.
321 
322 #define JRT_LEAF(result_type, header)                                \
323   result_type header {                                               \
324   VM_LEAF_BASE(result_type, header)                                  \
325   debug_only(NoSafepointVerifier __nsv;)
326 
327 
328 #define JRT_ENTRY_NO_ASYNC(result_type, header)                      \
329   result_type header {                                               \
330     MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, current));       \
331     ThreadInVMfromJava __tiv(current, false /* check asyncs */);     \
332     VM_ENTRY_BASE(result_type, header, current)                      \
333     debug_only(VMEntryWrapper __vew;)
334 
335 // Same as JRT Entry but allows for return value after the safepoint
336 // to get back into Java from the VM
337 #define JRT_BLOCK_ENTRY(result_type, header)                         \
338   result_type header {                                               \
339     MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, current));       \
340     HandleMarkCleaner __hm(current);
341 
342 #define JRT_BLOCK                                                    \
343     {                                                                \
344     ThreadInVMfromJava __tiv(current);                               \
345     JavaThread* THREAD = current; /* For exception macros. */        \
346     debug_only(VMEntryWrapper __vew;)
347 
348 #define JRT_BLOCK_NO_ASYNC                                           \
349     {                                                                \
350     ThreadInVMfromJava __tiv(current, false /* check asyncs */);     \
351     JavaThread* THREAD = current; /* For exception macros. */        \
352     debug_only(VMEntryWrapper __vew;)
353 
354 #define JRT_BLOCK_END }
355 
356 #define JRT_END }
357 
358 // Definitions for JNI
359 
360 #define JNI_ENTRY(result_type, header)                               \
361     JNI_ENTRY_NO_PRESERVE(result_type, header)                       \
362     WeakPreserveExceptionMark __wem(thread);
363 
364 #define JNI_ENTRY_NO_PRESERVE(result_type, header)                   \
365 extern "C" {                                                         \
366   result_type JNICALL header {                                       \
367     JavaThread* thread=JavaThread::thread_from_jni_environment(env); \
368     assert( !VerifyJNIEnvThread || (thread == Thread::current()), "JNIEnv is only valid in same thread"); \
369     MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));        \
370     ThreadInVMfromNative __tiv(thread);                              \
371     debug_only(VMNativeEntryWrapper __vew;)                          \
372     VM_ENTRY_BASE(result_type, header, thread)
373 
374 
375 #define JNI_LEAF(result_type, header)                                \
376 extern "C" {                                                         \
377   result_type JNICALL header {                                       \
378     JavaThread* thread=JavaThread::thread_from_jni_environment(env); \
379     assert( !VerifyJNIEnvThread || (thread == Thread::current()), "JNIEnv is only valid in same thread"); \
380     VM_LEAF_BASE(result_type, header)
381 
382 
383 // Close the routine and the extern "C"
384 #define JNI_END } }
385 
386 
387 
388 // Definitions for JVM
389 
390 #define JVM_ENTRY(result_type, header)                               \
391 extern "C" {                                                         \
392   result_type JNICALL header {                                       \
393     JavaThread* thread=JavaThread::thread_from_jni_environment(env); \
394     MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));        \
395     ThreadInVMfromNative __tiv(thread);                              \
396     debug_only(VMNativeEntryWrapper __vew;)                          \
397     VM_ENTRY_BASE(result_type, header, thread)
398 
399 
400 #define JVM_ENTRY_NO_ENV(result_type, header)                        \
401 extern "C" {                                                         \
402   result_type JNICALL header {                                       \
403     JavaThread* thread = JavaThread::current();                      \
404     MACOS_AARCH64_ONLY(ThreadWXEnable __wx(WXWrite, thread));        \
405     ThreadInVMfromNative __tiv(thread);                              \
406     debug_only(VMNativeEntryWrapper __vew;)                          \
407     VM_ENTRY_BASE(result_type, header, thread)
408 
409 
410 #define JVM_LEAF(result_type, header)                                \
411 extern "C" {                                                         \
412   result_type JNICALL header {                                       \
413     VM_Exit::block_if_vm_exited();                                   \
414     VM_LEAF_BASE(result_type, header)
415 
416 
417 #define JVM_ENTRY_FROM_LEAF(env, result_type, header)                \
418   { {                                                                \
419     JavaThread* thread=JavaThread::thread_from_jni_environment(env); \
420     ThreadInVMfromNative __tiv(thread);                              \
421     debug_only(VMNativeEntryWrapper __vew;)                          \
422     VM_ENTRY_BASE_FROM_LEAF(result_type, header, thread)
423 
424 
425 #define JVM_END } }
426 
427 #endif // SHARE_RUNTIME_INTERFACESUPPORT_INLINE_HPP