1 /*
  2  * Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "classfile/vmSymbols.hpp"
 26 #include "gc/shared/barrierSetNMethod.hpp"
 27 #include "oops/method.inline.hpp"
 28 #include "oops/oop.inline.hpp"
 29 #include "prims/jvmtiThreadState.inline.hpp"
 30 #include "runtime/continuation.hpp"
 31 #include "runtime/continuationEntry.inline.hpp"
 32 #include "runtime/continuationHelper.inline.hpp"
 33 #include "runtime/continuationJavaClasses.inline.hpp"
 34 #include "runtime/continuationWrapper.inline.hpp"
 35 #include "runtime/interfaceSupport.inline.hpp"
 36 #include "runtime/javaThread.inline.hpp"
 37 #include "runtime/jniHandles.inline.hpp"
 38 #include "runtime/osThread.hpp"
 39 #include "runtime/vframe.inline.hpp"
 40 #include "runtime/vframe_hp.hpp"
 41 
 42 // defined in continuationFreezeThaw.cpp
 43 extern "C" jint JNICALL CONT_isPinned0(JNIEnv* env, jobject cont_scope);
 44 
 45 JVM_ENTRY(void, CONT_pin(JNIEnv* env, jclass cls)) {
 46   if (!Continuation::pin(JavaThread::thread_from_jni_environment(env))) {
 47      THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "pin overflow");
 48   }
 49 }
 50 JVM_END
 51 
 52 JVM_ENTRY(void, CONT_unpin(JNIEnv* env, jclass cls)) {
 53   if (!Continuation::unpin(JavaThread::thread_from_jni_environment(env))) {
 54      THROW_MSG(vmSymbols::java_lang_IllegalStateException(), "pin underflow");
 55   }
 56 }
 57 JVM_END
 58 
 59 #if INCLUDE_JVMTI
 60 class JvmtiUnmountBeginMark : public StackObj {
 61   Handle _vthread;
 62   JavaThread* _current;
 63   freeze_result _result;
 64   bool _failed;
 65 
 66  public:
 67   JvmtiUnmountBeginMark(JavaThread* t) :
 68     _vthread(t, t->vthread()), _current(t), _result(freeze_pinned_native), _failed(false) {
 69     assert(!_current->is_in_VTMS_transition(), "must be");
 70 
 71     if (JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events()) {
 72       JvmtiVTMSTransitionDisabler::VTMS_vthread_unmount((jthread)_vthread.raw_value(), true);
 73 
 74       // Don't preempt if there is a pending popframe or earlyret operation. This can
 75       // be installed in start_VTMS_transition() so we need to check it here.
 76       if (JvmtiExport::can_pop_frame() || JvmtiExport::can_force_early_return()) {
 77         JvmtiThreadState* state = _current->jvmti_thread_state();
 78         if (_current->has_pending_popframe() || (state != nullptr && state->is_earlyret_pending())) {
 79           _failed = true;
 80         }
 81       }
 82 
 83       // Don't preempt in case there is an async exception installed since
 84       // we would incorrectly throw it during the unmount logic in the carrier.
 85       if (_current->has_async_exception_condition()) {
 86         _failed = true;
 87       }
 88     } else {
 89       _current->set_is_in_VTMS_transition(true);
 90       java_lang_Thread::set_is_in_VTMS_transition(_vthread(), true);
 91     }
 92   }
 93   ~JvmtiUnmountBeginMark() {
 94     assert(!_current->is_suspended(), "must be");
 95 
 96     assert(_current->is_in_VTMS_transition(), "must be");
 97     assert(java_lang_Thread::is_in_VTMS_transition(_vthread()), "must be");
 98 
 99     // Read it again since for late binding agents the flag could have
100     // been set while blocked in the allocation path during freeze.
101     bool jvmti_present = JvmtiVTMSTransitionDisabler::VTMS_notify_jvmti_events();
102 
103     if (_result != freeze_ok) {
104       // Undo transition
105       if (jvmti_present) {
106         JvmtiVTMSTransitionDisabler::VTMS_vthread_mount((jthread)_vthread.raw_value(), false);
107       } else {
108         _current->set_is_in_VTMS_transition(false);
109         java_lang_Thread::set_is_in_VTMS_transition(_vthread(), false);
110       }
111     }
112   }
113   void set_result(freeze_result res) { _result = res; }
114   bool failed() { return _failed; }
115 };
116 
117 static bool is_vthread_safe_to_preempt_for_jvmti(JavaThread* current) {
118   if (current->is_in_VTMS_transition()) {
119     // We are at the end of a mount transition.
120     return false;
121   }
122   return true;
123 }
124 #endif // INCLUDE_JVMTI
125 
126 static bool is_vthread_safe_to_preempt(JavaThread* current, oop vthread) {
127   assert(java_lang_VirtualThread::is_instance(vthread), "");
128   if (java_lang_VirtualThread::state(vthread) != java_lang_VirtualThread::RUNNING) {  // inside transition
129     return false;
130   }
131   return JVMTI_ONLY(is_vthread_safe_to_preempt_for_jvmti(current)) NOT_JVMTI(true);
132 }
133 
134 typedef freeze_result (*FreezeContFnT)(JavaThread*, intptr_t*);
135 
136 static void verify_preempt_preconditions(JavaThread* current, oop continuation) {
137   assert(current == JavaThread::current(), "no support for external preemption");
138   assert(current->has_last_Java_frame(), "");
139   assert(!current->preempting(), "");
140   assert(current->last_continuation() != nullptr, "");
141   assert(current->last_continuation()->cont_oop(current) == continuation, "");
142   assert(Continuation::continuation_scope(continuation) == java_lang_VirtualThread::vthread_scope(), "");
143   assert(!current->has_pending_exception(), "");
144 }
145 
146 freeze_result Continuation::try_preempt(JavaThread* current, oop continuation) {
147   verify_preempt_preconditions(current, continuation);
148 
149   if (!is_vthread_safe_to_preempt(current, current->vthread())) {
150     return freeze_pinned_native;
151   }
152 
153   JVMTI_ONLY(JvmtiUnmountBeginMark jubm(current);)
154   JVMTI_ONLY(if (jubm.failed()) return freeze_pinned_native;)
155   freeze_result res = CAST_TO_FN_PTR(FreezeContFnT, freeze_preempt_entry())(current, current->last_Java_sp());
156   log_trace(continuations, preempt)("try_preempt: %d", res);
157   JVMTI_ONLY(jubm.set_result(res);)
158 
159   if (current->has_pending_exception()) {
160     assert(res == freeze_exception, "expecting an exception result from freeze");
161     // We don't want to throw exceptions, especially when returning
162     // from monitorenter since the compiler does not expect one. We
163     // just ignore the exception and pin the vthread to the carrier.
164     current->clear_pending_exception();
165   }
166   return res;
167 }
168 
169 #ifndef PRODUCT
170 static jlong java_tid(JavaThread* thread) {
171   return java_lang_Thread::thread_id(thread->threadObj());
172 }
173 #endif
174 
175 ContinuationEntry* Continuation::get_continuation_entry_for_continuation(JavaThread* thread, oop continuation) {
176   if (thread == nullptr || continuation == nullptr) {
177     return nullptr;
178   }
179 
180   for (ContinuationEntry* entry = thread->last_continuation(); entry != nullptr; entry = entry->parent()) {
181     if (continuation == entry->cont_oop(thread)) {
182       return entry;
183     }
184   }
185   return nullptr;
186 }
187 
188 static bool is_on_stack(JavaThread* thread, const ContinuationEntry* entry) {
189   if (entry == nullptr) {
190     return false;
191   }
192 
193   assert(thread->is_in_full_stack((address)entry), "");
194   return true;
195   // return false if called when transitioning to Java on return from freeze
196   // return !thread->has_last_Java_frame() || thread->last_Java_sp() < cont->entry_sp();
197 }
198 
199 bool Continuation::is_continuation_mounted(JavaThread* thread, oop continuation) {
200   return is_on_stack(thread, get_continuation_entry_for_continuation(thread, continuation));
201 }
202 
203 // When walking the virtual stack, this method returns true
204 // iff the frame is a thawed continuation frame whose
205 // caller is still frozen on the h-stack.
206 // The continuation object can be extracted from the thread.
207 bool Continuation::is_cont_barrier_frame(const frame& f) {
208   assert(f.is_interpreted_frame() || f.cb() != nullptr, "");
209   if (!Continuations::enabled()) return false;
210   return is_return_barrier_entry(f.is_interpreted_frame() ? ContinuationHelper::InterpretedFrame::return_pc(f)
211                                                           : ContinuationHelper::CompiledFrame::return_pc(f));
212 }
213 
214 bool Continuation::is_return_barrier_entry(const address pc) {
215   if (!Continuations::enabled()) return false;
216   return pc == StubRoutines::cont_returnBarrier();
217 }
218 
219 bool Continuation::is_continuation_enterSpecial(const frame& f) {
220   if (f.cb() == nullptr || !f.cb()->is_nmethod()) {
221     return false;
222   }
223   Method* m = f.cb()->as_nmethod()->method();
224   return (m != nullptr && m->is_continuation_enter_intrinsic());
225 }
226 
227 bool Continuation::is_continuation_entry_frame(const frame& f, const RegisterMap *map) {
228   // we can do this because the entry frame is never inlined
229   Method* m = (map != nullptr && map->in_cont() && f.is_interpreted_frame())
230                   ? map->stack_chunk()->interpreter_frame_method(f)
231                   : ContinuationHelper::Frame::frame_method(f);
232   return m != nullptr && m->intrinsic_id() == vmIntrinsics::_Continuation_enter;
233 }
234 
235 // The parameter `sp` should be the actual sp and not the unextended sp because at
236 // least on PPC64 unextended_sp < sp is possible as interpreted frames are trimmed
237 // to the actual size of the expression stack before calls. The problem there is
238 // that even unextended_sp < entry_sp < sp is possible for an interpreted frame.
239 static inline bool is_sp_in_continuation(const ContinuationEntry* entry, intptr_t* const sp) {
240   // entry_sp() returns the unextended_sp which is always greater or equal to the actual sp
241   return entry->entry_sp() > sp;
242 }
243 
244 bool Continuation::is_frame_in_continuation(const ContinuationEntry* entry, const frame& f) {
245   return is_sp_in_continuation(entry, f.sp());
246 }
247 
248 ContinuationEntry* Continuation::get_continuation_entry_for_sp(JavaThread* thread, intptr_t* const sp) {
249   assert(thread != nullptr, "");
250   ContinuationEntry* entry = thread->last_continuation();
251   while (entry != nullptr && !is_sp_in_continuation(entry, sp)) {
252     entry = entry->parent();
253   }
254   return entry;
255 }
256 
257 ContinuationEntry* Continuation::get_continuation_entry_for_entry_frame(JavaThread* thread, const frame& f) {
258   assert(is_continuation_enterSpecial(f), "");
259   ContinuationEntry* entry = (ContinuationEntry*)f.unextended_sp();
260   assert(entry == get_continuation_entry_for_sp(thread, f.sp()-2), "mismatched entry");
261   return entry;
262 }
263 
264 bool Continuation::is_frame_in_continuation(JavaThread* thread, const frame& f) {
265   return f.is_heap_frame() || (get_continuation_entry_for_sp(thread, f.sp()) != nullptr);
266 }
267 
268 static frame continuation_top_frame(const ContinuationWrapper& cont, RegisterMap* map) {
269   stackChunkOop chunk = cont.last_nonempty_chunk();
270   map->set_stack_chunk(chunk);
271   return chunk != nullptr ? chunk->top_frame(map) : frame();
272 }
273 
274 bool Continuation::has_last_Java_frame(oop continuation, frame* frame, RegisterMap* map) {
275   ContinuationWrapper cont(continuation);
276   if (!cont.is_empty()) {
277     *frame = continuation_top_frame(cont, map);
278     return true;
279   } else {
280     return false;
281   }
282 }
283 
284 frame Continuation::last_frame(oop continuation, RegisterMap *map) {
285   assert(map != nullptr, "a map must be given");
286   return continuation_top_frame(ContinuationWrapper(continuation), map);
287 }
288 
289 frame Continuation::top_frame(const frame& callee, RegisterMap* map) {
290   assert(map != nullptr, "");
291   ContinuationEntry* ce = get_continuation_entry_for_sp(map->thread(), callee.sp());
292   assert(ce != nullptr, "");
293   oop continuation = ce->cont_oop(map->thread());
294   ContinuationWrapper cont(continuation);
295   return continuation_top_frame(cont, map);
296 }
297 
298 javaVFrame* Continuation::last_java_vframe(Handle continuation, RegisterMap *map) {
299   assert(map != nullptr, "a map must be given");
300   if (!ContinuationWrapper(continuation()).is_empty()) {
301     frame f = last_frame(continuation(), map);
302     for (vframe* vf = vframe::new_vframe(&f, map, nullptr); vf; vf = vf->sender()) {
303       if (vf->is_java_frame()) {
304         return javaVFrame::cast(vf);
305       }
306     }
307   }
308   return nullptr;
309 }
310 
311 frame Continuation::continuation_parent_frame(RegisterMap* map) {
312   assert(map->in_cont(), "");
313   ContinuationWrapper cont(map);
314   assert(map->thread() != nullptr || !cont.is_mounted(), "");
315 
316   log_develop_trace(continuations)("continuation_parent_frame");
317   if (map->update_map()) {
318     // we need to register the link address for the entry frame
319     if (cont.entry() != nullptr) {
320       cont.entry()->update_register_map(map);
321     } else {
322       map->clear();
323     }
324   }
325 
326   if (!cont.is_mounted()) { // When we're walking an unmounted continuation and reached the end
327     oop parent = jdk_internal_vm_Continuation::parent(cont.continuation());
328     stackChunkOop chunk = parent != nullptr ? ContinuationWrapper(parent).last_nonempty_chunk() : nullptr;
329     if (chunk != nullptr) {
330       return chunk->top_frame(map);
331     }
332 
333     map->set_stack_chunk(nullptr);
334     return frame();
335   }
336 
337   map->set_stack_chunk(nullptr);
338 
339 #if (defined(X86) || defined(AARCH64) || defined(RISCV64) || defined(PPC64)) && !defined(ZERO)
340   frame sender(cont.entrySP(), cont.entryFP(), cont.entryPC());
341 #else
342   frame sender = frame();
343   Unimplemented();
344 #endif
345 
346   return sender;
347 }
348 
349 oop Continuation::continuation_scope(oop continuation) {
350   return continuation != nullptr ? jdk_internal_vm_Continuation::scope(continuation) : nullptr;
351 }
352 
353 bool Continuation::is_scope_bottom(oop cont_scope, const frame& f, const RegisterMap* map) {
354   if (cont_scope == nullptr || !is_continuation_entry_frame(f, map)) {
355     return false;
356   }
357 
358   oop continuation;
359   if (map->in_cont()) {
360     continuation = map->cont();
361   } else {
362     ContinuationEntry* ce = get_continuation_entry_for_sp(map->thread(), f.sp());
363     if (ce == nullptr) {
364       return false;
365     }
366     continuation = ce->cont_oop(map->thread());
367   }
368   if (continuation == nullptr) {
369     return false;
370   }
371 
372   oop sc = continuation_scope(continuation);
373   assert(sc != nullptr, "");
374   return sc == cont_scope;
375 }
376 
377 bool Continuation::is_in_usable_stack(address addr, const RegisterMap* map) {
378   ContinuationWrapper cont(map);
379   stackChunkOop chunk = cont.find_chunk_by_address(addr);
380   return chunk != nullptr ? chunk->is_usable_in_chunk(addr) : false;
381 }
382 
383 bool Continuation::pin(JavaThread* current) {
384   ContinuationEntry* ce = current->last_continuation();
385   if (ce == nullptr) {
386     return true; // no continuation mounted
387   }
388   return ce->pin();
389 }
390 
391 bool Continuation::unpin(JavaThread* current) {
392   ContinuationEntry* ce = current->last_continuation();
393   if (ce == nullptr) {
394     return true; // no continuation mounted
395   }
396   return ce->unpin();
397 }
398 
399 frame Continuation::continuation_bottom_sender(JavaThread* thread, const frame& callee, intptr_t* sender_sp) {
400   assert (thread != nullptr, "");
401   ContinuationEntry* ce = get_continuation_entry_for_sp(thread, callee.sp());
402   assert(ce != nullptr, "callee.sp(): " INTPTR_FORMAT, p2i(callee.sp()));
403 
404   log_develop_debug(continuations)("continuation_bottom_sender: [" JLONG_FORMAT "] [%d] callee: " INTPTR_FORMAT
405     " sender_sp: " INTPTR_FORMAT,
406     java_tid(thread), thread->osthread()->thread_id(), p2i(callee.sp()), p2i(sender_sp));
407 
408   frame entry = ce->to_frame();
409   if (callee.is_interpreted_frame()) {
410     entry.set_sp(sender_sp); // sp != unextended_sp
411   }
412   return entry;
413 }
414 
415 address Continuation::get_top_return_pc_post_barrier(JavaThread* thread, address pc) {
416   ContinuationEntry* ce;
417   if (thread != nullptr && is_return_barrier_entry(pc) && (ce = thread->last_continuation()) != nullptr) {
418     return ce->entry_pc();
419   }
420   return pc;
421 }
422 
423 void Continuation::set_cont_fastpath_thread_state(JavaThread* thread) {
424   assert(thread != nullptr, "");
425   bool fast = !thread->is_interp_only_mode();
426   thread->set_cont_fastpath_thread_state(fast);
427 }
428 
429 void Continuation::notify_deopt(JavaThread* thread, intptr_t* sp) {
430   ContinuationEntry* entry = thread->last_continuation();
431 
432   if (entry == nullptr) {
433     return;
434   }
435 
436   if (is_sp_in_continuation(entry, sp)) {
437     thread->push_cont_fastpath(sp);
438     return;
439   }
440 
441   ContinuationEntry* prev;
442   do {
443     prev = entry;
444     entry = entry->parent();
445   } while (entry != nullptr && !is_sp_in_continuation(entry, sp));
446 
447   if (entry == nullptr) {
448     return;
449   }
450   assert(is_sp_in_continuation(entry, sp), "");
451   if (sp > prev->parent_cont_fastpath()) {
452     prev->set_parent_cont_fastpath(sp);
453   }
454 }
455 
456 #ifndef PRODUCT
457 void Continuation::describe(FrameValues &values) {
458   JavaThread* thread = JavaThread::active();
459   if (thread != nullptr) {
460     for (ContinuationEntry* ce = thread->last_continuation(); ce != nullptr; ce = ce->parent()) {
461       intptr_t* bottom = ce->entry_sp();
462       if (bottom != nullptr) {
463         values.describe(-1, bottom, "continuation entry");
464       }
465     }
466   }
467 }
468 #endif
469 
470 #ifdef ASSERT
471 void Continuation::debug_verify_continuation(oop contOop) {
472   if (!VerifyContinuations) {
473     return;
474   }
475   assert(contOop != nullptr, "");
476   assert(oopDesc::is_oop(contOop), "");
477   ContinuationWrapper cont(contOop);
478 
479   assert(oopDesc::is_oop_or_null(cont.tail()), "");
480   assert(cont.chunk_invariant(), "");
481 
482   bool nonempty_chunk = false;
483   size_t max_size = 0;
484   int num_chunks = 0;
485   int num_frames = 0;
486   int num_interpreted_frames = 0;
487   int num_oops = 0;
488 
489   for (stackChunkOop chunk = cont.tail(); chunk != nullptr; chunk = chunk->parent()) {
490     log_develop_trace(continuations)("debug_verify_continuation chunk %d", num_chunks);
491     chunk->verify(&max_size, &num_oops, &num_frames, &num_interpreted_frames);
492     if (!chunk->is_empty()) {
493       nonempty_chunk = true;
494     }
495     num_chunks++;
496   }
497 
498   const bool is_empty = cont.is_empty();
499   assert(!nonempty_chunk || !is_empty, "");
500   assert(is_empty == (!nonempty_chunk && cont.last_frame().is_empty()), "");
501 }
502 
503 void Continuation::print(oop continuation) { print_on(tty, continuation); }
504 
505 void Continuation::print_on(outputStream* st, oop continuation) {
506   ContinuationWrapper cont(continuation);
507 
508   st->print_cr("CONTINUATION: " PTR_FORMAT " done: %d",
509     continuation->identity_hash(), jdk_internal_vm_Continuation::done(continuation));
510   st->print_cr("CHUNKS:");
511   for (stackChunkOop chunk = cont.tail(); chunk != nullptr; chunk = chunk->parent()) {
512     st->print("* ");
513     chunk->print_on(true, st);
514   }
515 }
516 #endif // ASSERT
517 
518 
519 void continuations_init() { Continuations::init(); }
520 
521 void Continuations::init() {
522   Continuation::init();
523 }
524 
525 bool Continuations::enabled() {
526   return VMContinuations;
527 }
528 
529 #define CC (char*)  /*cast a literal from (const char*)*/
530 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
531 
532 static JNINativeMethod CONT_methods[] = {
533     {CC"pin",              CC"()V",                                    FN_PTR(CONT_pin)},
534     {CC"unpin",            CC"()V",                                    FN_PTR(CONT_unpin)},
535     {CC"isPinned0",        CC"(Ljdk/internal/vm/ContinuationScope;)I", FN_PTR(CONT_isPinned0)},
536 };
537 
538 void CONT_RegisterNativeMethods(JNIEnv *env, jclass cls) {
539     JavaThread* thread = JavaThread::current();
540     ThreadToNativeFromVM trans(thread);
541     int status = env->RegisterNatives(cls, CONT_methods, sizeof(CONT_methods)/sizeof(JNINativeMethod));
542     guarantee(status == JNI_OK, "register jdk.internal.vm.Continuation natives");
543     guarantee(!env->ExceptionCheck(), "register jdk.internal.vm.Continuation natives");
544 }