1 /*
  2  * Copyright (c) 2000, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2012, 2026 SAP SE. 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 #include "compiler/oopMap.hpp"
 27 #include "interpreter/interpreter.hpp"
 28 #include "memory/resourceArea.hpp"
 29 #include "memory/universe.hpp"
 30 #include "oops/markWord.hpp"
 31 #include "oops/method.hpp"
 32 #include "oops/oop.inline.hpp"
 33 #include "runtime/frame.inline.hpp"
 34 #include "runtime/handles.inline.hpp"
 35 #include "runtime/javaCalls.hpp"
 36 #include "runtime/jniHandles.inline.hpp"
 37 #include "runtime/monitorChunk.hpp"
 38 #include "runtime/os.inline.hpp"
 39 #include "runtime/signature.hpp"
 40 #include "runtime/stackWatermarkSet.hpp"
 41 #include "runtime/stubCodeGenerator.hpp"
 42 #include "runtime/stubRoutines.hpp"
 43 #ifdef COMPILER1
 44 #include "c1/c1_Runtime1.hpp"
 45 #include "runtime/vframeArray.hpp"
 46 #endif
 47 
 48 #ifdef ASSERT
 49 void RegisterMap::check_location_valid() {
 50 }
 51 #endif // ASSERT
 52 
 53 bool frame::safe_for_sender(JavaThread *thread) {
 54   if (is_heap_frame()) {
 55     return true;
 56   }
 57   address sp = (address)_sp;
 58   address fp = (address)_fp;
 59   address unextended_sp = (address)_unextended_sp;
 60 
 61   // consider stack guards when trying to determine "safe" stack pointers
 62   // sp must be within the usable part of the stack (not in guards)
 63   if (!thread->is_in_usable_stack(sp)) {
 64     return false;
 65   }
 66 
 67   // Unextended sp must be within the stack
 68   if (!thread->is_in_full_stack_checked(unextended_sp)) {
 69     return false;
 70   }
 71 
 72   // An fp must be within the stack and above (but not equal) sp.
 73   bool fp_safe = thread->is_in_stack_range_excl(fp, sp);
 74   // An interpreter fp must be fp_safe.
 75   // Moreover, it must be at a distance at least the size of the ijava_state structure.
 76   bool fp_interp_safe = fp_safe && ((fp - sp) >= ijava_state_size);
 77 
 78   // We know sp/unextended_sp are safe, only fp is questionable here
 79 
 80   // If the current frame is known to the code cache then we can attempt to
 81   // construct the sender and do some validation of it. This goes a long way
 82   // toward eliminating issues when we get in frame construction code
 83 
 84   if (_cb != nullptr) {
 85 
 86     // First check if the frame is complete and the test is reliable.
 87     // Unfortunately we can only check frame completeness for runtime stubs
 88     // and nmethods. Other generic buffer blobs are more problematic
 89     // so we just assume they are OK.
 90     // Adapter blobs never have a complete frame and are never OK
 91     if (!_cb->is_frame_complete_at(_pc)) {
 92       if (_cb->is_nmethod() || _cb->is_adapter_blob() || _cb->is_runtime_stub()) {
 93         return false;
 94       }
 95     }
 96 
 97     // Could just be some random pointer within the codeBlob.
 98     if (!_cb->code_contains(_pc)) {
 99       return false;
100     }
101 
102     // Entry frame checks
103     if (is_entry_frame()) {
104       // An entry frame must have a valid fp.
105       return fp_safe && is_entry_frame_valid(thread);
106     }
107 
108     if (is_interpreted_frame() && !fp_interp_safe) {
109       return false;
110     }
111 
112     // At this point, there still is a chance that fp_safe is false.
113     // In particular, fp might be null. So let's check and
114     // bail out before we actually dereference from fp.
115     if (!fp_safe) {
116       return false;
117     }
118 
119     volatile common_abi* sender_abi = (common_abi*) fp; // May get updated concurrently by deoptimization!
120     intptr_t* sender_sp = (intptr_t*) fp;
121     address   sender_pc = (address) sender_abi->lr;
122 
123     DEBUG_ONLY(nmethod* nm = _cb->as_nmethod_or_null());
124     assert(nm == nullptr || !nm->needs_stack_repair(), "unsupported");
125 
126     if (Continuation::is_return_barrier_entry(sender_pc)) {
127       // sender_pc might be invalid so check that the frame
128       // actually belongs to a Continuation.
129       if (!Continuation::is_frame_in_continuation(thread, *this)) {
130         return false;
131       }
132       // If our sender_pc is the return barrier, then our "real" sender is the continuation entry
133       frame s = Continuation::continuation_bottom_sender(thread, *this, sender_sp);
134       sender_sp = s.sp();
135       sender_pc = s.pc();
136     }
137 
138     // We must always be able to find a recognizable pc.
139     CodeBlob* sender_blob = CodeCache::find_blob(sender_pc);
140     if (sender_blob == nullptr) {
141       return false;
142     }
143 
144     intptr_t* unextended_sender_sp = is_interpreted_frame() ? interpreter_frame_sender_sp() : sender_sp;
145 
146     // If the sender is a deoptimized nmethod we need to check if the original pc is valid.
147     nmethod* sender_nm = sender_blob->as_nmethod_or_null();
148     if (sender_nm != nullptr && sender_nm->is_deopt_pc(sender_pc)) {
149       address orig_pc = *(address*)((address)unextended_sender_sp + sender_nm->orig_pc_offset());
150       if (!sender_nm->insts_contains_inclusive(orig_pc)) return false;
151     }
152 
153     // It should be safe to construct the sender though it might not be valid.
154 
155     frame sender(sender_sp, sender_pc, unextended_sender_sp, nullptr /* fp */, sender_blob);
156 
157     // Do we have a valid fp?
158     address sender_fp = (address) sender.fp();
159 
160     // sender_fp must be within the stack and above (but not
161     // equal) current frame's fp.
162     if (!thread->is_in_stack_range_excl(sender_fp, fp)) {
163         return false;
164     }
165 
166     // If the potential sender is the interpreter then we can do some more checking.
167     if (Interpreter::contains(sender_pc)) {
168       return sender.is_interpreted_frame_valid(thread);
169     }
170 
171     // Could just be some random pointer within the codeBlob.
172     if (!sender.cb()->code_contains(sender_pc)) {
173       return false;
174     }
175 
176     // We should never be able to see an adapter if the current frame is something from code cache.
177     if (sender_blob->is_adapter_blob()) {
178       return false;
179     }
180 
181     if (sender.is_entry_frame()) {
182       return sender.is_entry_frame_valid(thread);
183     }
184 
185     // Frame size is always greater than zero. If the sender frame size is zero or less,
186     // something is really weird and we better give up.
187     if (sender_blob->frame_size() <= 0) {
188       return false;
189     }
190 
191     return true;
192   }
193 
194   // Must be native-compiled frame. Since sender will try and use fp to find
195   // linkages it must be safe
196 
197   if (!fp_safe) {
198     return false;
199   }
200 
201   if (sender_pc() == nullptr) {
202     // Likely the return pc was not yet stored to stack. We rather discard this
203     // sample also because we would hit an assertion in frame::setup(). We can
204     // find any other random value if the return pc was not yet stored to
205     // stack. We rely on consistency checks to handle this (see
206     // e.g. find_initial_Java_frame())
207     return false;
208   }
209 
210   return true;
211 }
212 
213 frame frame::sender_for_entry_frame(RegisterMap *map) const {
214   assert(map != nullptr, "map must be set");
215   // Java frame called from C; skip all C frames and return top C
216   // frame of that chunk as the sender.
217   JavaFrameAnchor* jfa = entry_frame_call_wrapper()->anchor();
218   assert(!entry_frame_is_first(), "next Java fp must be non zero");
219   assert(jfa->last_Java_sp() > _sp, "must be above this frame on stack");
220   map->clear();
221   assert(map->include_argument_oops(), "should be set by clear");
222 
223   if (jfa->last_Java_pc() != nullptr) {
224     frame fr(jfa->last_Java_sp(), jfa->last_Java_pc(), kind::code_blob);
225     return fr;
226   }
227   // Last_java_pc is not set, if we come here from compiled code. The
228   // constructor retrieves the PC from the stack.
229   frame fr(jfa->last_Java_sp(), nullptr, kind::code_blob);
230   return fr;
231 }
232 
233 UpcallStub::FrameData* UpcallStub::frame_data_for_frame(const frame& frame) const {
234   assert(frame.is_upcall_stub_frame(), "wrong frame");
235   // need unextended_sp here, since normal sp is wrong for interpreter callees
236   return reinterpret_cast<UpcallStub::FrameData*>(
237     reinterpret_cast<address>(frame.unextended_sp()) + in_bytes(_frame_data_offset));
238 }
239 
240 bool frame::upcall_stub_frame_is_first() const {
241   assert(is_upcall_stub_frame(), "must be optimzed entry frame");
242   UpcallStub* blob = _cb->as_upcall_stub();
243   JavaFrameAnchor* jfa = blob->jfa_for_frame(*this);
244   return jfa->last_Java_sp() == nullptr;
245 }
246 
247 frame frame::sender_for_upcall_stub_frame(RegisterMap* map) const {
248   assert(map != nullptr, "map must be set");
249   UpcallStub* blob = _cb->as_upcall_stub();
250   // Java frame called from C; skip all C frames and return top C
251   // frame of that chunk as the sender
252   JavaFrameAnchor* jfa = blob->jfa_for_frame(*this);
253   assert(!upcall_stub_frame_is_first(), "must have a frame anchor to go back to");
254   assert(jfa->last_Java_sp() > sp(), "must be above this frame on stack");
255   map->clear();
256   assert(map->include_argument_oops(), "should be set by clear");
257   frame fr(jfa->last_Java_sp(), jfa->last_Java_pc(), kind::code_blob);
258 
259   return fr;
260 }
261 
262 JavaThread** frame::saved_thread_address(const frame& f) {
263   // The current thread (JavaThread*) is never stored on the stack
264   return nullptr;
265 }
266 
267 frame frame::sender_for_interpreter_frame(RegisterMap *map) const {
268   // This is the sp before any possible extension (adapter/locals).
269   intptr_t* unextended_sp = interpreter_frame_sender_sp();
270   address sender_pc = this->sender_pc();
271   if (Continuation::is_return_barrier_entry(sender_pc)) {
272     if (map->walk_cont()) { // about to walk into an h-stack
273       return Continuation::top_frame(*this, map);
274     } else {
275       return Continuation::continuation_bottom_sender(map->thread(), *this, sender_sp());
276     }
277   }
278 
279   return frame(sender_sp(), sender_pc, unextended_sp);
280 }
281 
282 // locals
283 
284 void frame::interpreter_frame_set_locals(intptr_t* locs)  {
285   assert(is_interpreted_frame(), "interpreted frame expected");
286   // set relativized locals
287   *addr_at(ijava_idx(locals)) = (intptr_t) (locs - fp());
288 }
289 
290 // sender_sp
291 
292 intptr_t* frame::interpreter_frame_sender_sp() const {
293   assert(is_interpreted_frame(), "interpreted frame expected");
294   return (intptr_t*)at(ijava_idx(sender_sp));
295 }
296 
297 void frame::patch_pc(Thread* thread, address pc) {
298   assert(_cb == CodeCache::find_blob(pc), "unexpected pc");
299   address* pc_addr = (address*)&(own_abi()->lr);
300 
301   if (TracePcPatching) {
302     tty->print_cr("patch_pc at address " PTR_FORMAT " [" PTR_FORMAT " -> " PTR_FORMAT "]",
303                   p2i(&((address*) _sp)[-1]), p2i(((address*) _sp)[-1]), p2i(pc));
304   }
305   assert(!Continuation::is_return_barrier_entry(*pc_addr), "return barrier");
306   assert(_pc == *pc_addr || pc == *pc_addr || nullptr == *pc_addr,
307          "must be (pc: " INTPTR_FORMAT " _pc: " INTPTR_FORMAT " pc_addr: " INTPTR_FORMAT
308          " *pc_addr: " INTPTR_FORMAT  " sp: " INTPTR_FORMAT ")",
309          p2i(pc), p2i(_pc), p2i(pc_addr), p2i(*pc_addr), p2i(sp()));
310   DEBUG_ONLY(address old_pc = _pc;)
311   own_abi()->lr = (uint64_t)pc;
312   _pc = pc; // must be set before call to get_deopt_original_pc
313   address original_pc = get_deopt_original_pc();
314   if (original_pc != nullptr) {
315     assert(original_pc == old_pc, "expected original PC to be stored before patching");
316     _deopt_state = is_deoptimized;
317     _pc = original_pc;
318   } else {
319     _deopt_state = not_deoptimized;
320   }
321   assert(!is_compiled_frame() || !_cb->as_nmethod()->is_deopt_entry(_pc), "must be");
322 
323 #ifdef ASSERT
324   {
325     frame f(sp(), unextended_sp(), fp(), pc, cb(), oop_map(), is_heap_frame());
326     assert(f.is_deoptimized_frame() == this->is_deoptimized_frame() && f.pc() == this->pc() && f.raw_pc() == this->raw_pc(),
327            "must be (f.is_deoptimized_frame(): %d this->is_deoptimized_frame(): %d "
328            "f.pc(): " INTPTR_FORMAT " this->pc(): " INTPTR_FORMAT " f.raw_pc(): " INTPTR_FORMAT " this->raw_pc(): " INTPTR_FORMAT ")",
329            f.is_deoptimized_frame(), this->is_deoptimized_frame(), p2i(f.pc()), p2i(this->pc()), p2i(f.raw_pc()), p2i(this->raw_pc()));
330   }
331 #endif
332 }
333 
334 bool frame::is_interpreted_frame_valid(JavaThread* thread) const {
335   assert(is_interpreted_frame(), "Not an interpreted frame");
336   // These are reasonable sanity checks
337   if (fp() == nullptr || (intptr_t(fp()) & (wordSize-1)) != 0) {
338     return false;
339   }
340   if (sp() == nullptr || (intptr_t(sp()) & (wordSize-1)) != 0) {
341     return false;
342   }
343   int min_frame_slots = (parent_ijava_frame_abi_size + ijava_state_size) / sizeof(intptr_t);
344   if (fp() - min_frame_slots < sp()) {
345     return false;
346   }
347   // These are hacks to keep us out of trouble.
348   // The problem with these is that they mask other problems
349   if (fp() <= sp()) {        // this attempts to deal with unsigned comparison above
350     return false;
351   }
352 
353   // do some validation of frame elements
354 
355   // first the method
356 
357   Method* m = safe_interpreter_frame_method();
358 
359   // validate the method we'd find in this potential sender
360   if (!Method::is_valid_method(m)) return false;
361 
362   // stack frames shouldn't be much larger than max_stack elements
363   // this test requires the use of unextended_sp which is the sp as seen by
364   // the current frame, and not sp which is the "raw" pc which could point
365   // further because of local variables of the callee method inserted after
366   // method arguments
367   if (fp() - unextended_sp() > 1024 + m->max_stack()*Interpreter::stackElementSize) {
368     return false;
369   }
370 
371   // validate bci/bcx
372 
373   address  bcp    = interpreter_frame_bcp();
374   if (m->validate_bci_from_bcp(bcp) < 0) {
375     return false;
376   }
377 
378   // validate constantPoolCache*
379   ConstantPoolCache* cp = *interpreter_frame_cache_addr();
380   if (MetaspaceObj::is_valid(cp) == false) return false;
381 
382   // validate locals
383 
384   address locals =  (address)interpreter_frame_locals();
385   return thread->is_in_stack_range_incl(locals, (address)fp());
386 }
387 
388 BasicType frame::interpreter_frame_result(oop* oop_result, jvalue* value_result) {
389   assert(is_interpreted_frame(), "interpreted frame expected");
390   Method* method = interpreter_frame_method();
391   BasicType type = method->result_type();
392 
393   if (method->is_native()) {
394     // Prior to calling into the runtime to notify the method exit the possible
395     // result value is saved into the interpreter frame.
396     address lresult = (address)&(get_ijava_state()->lresult);
397     address fresult = (address)&(get_ijava_state()->fresult);
398 
399     switch (method->result_type()) {
400       case T_OBJECT:
401       case T_ARRAY: {
402         *oop_result = JNIHandles::resolve(*(jobject*)lresult);
403         break;
404       }
405       // We use std/stfd to store the values.
406       case T_BOOLEAN : value_result->z = (jboolean) *(unsigned long*)lresult; break;
407       case T_INT     : value_result->i = (jint)     *(long*)lresult;          break;
408       case T_CHAR    : value_result->c = (jchar)    *(unsigned long*)lresult; break;
409       case T_SHORT   : value_result->s = (jshort)   *(long*)lresult;          break;
410       case T_BYTE    : value_result->z = (jbyte)    *(long*)lresult;          break;
411       case T_LONG    : value_result->j = (jlong)    *(long*)lresult;          break;
412       case T_FLOAT   : value_result->f = (jfloat)   *(double*)fresult;        break;
413       case T_DOUBLE  : value_result->d = (jdouble)  *(double*)fresult;        break;
414       case T_VOID    : /* Nothing to do */ break;
415       default        : ShouldNotReachHere();
416     }
417   } else {
418     intptr_t* tos_addr = interpreter_frame_tos_address();
419     switch (method->result_type()) {
420       case T_OBJECT:
421       case T_ARRAY: {
422         oop obj = *(oop*)tos_addr;
423         assert(Universe::is_in_heap_or_null(obj), "sanity check");
424         *oop_result = obj;
425       }
426       case T_BOOLEAN : value_result->z = (jboolean) *(jint*)tos_addr; break;
427       case T_BYTE    : value_result->b = (jbyte) *(jint*)tos_addr; break;
428       case T_CHAR    : value_result->c = (jchar) *(jint*)tos_addr; break;
429       case T_SHORT   : value_result->s = (jshort) *(jint*)tos_addr; break;
430       case T_INT     : value_result->i = *(jint*)tos_addr; break;
431       case T_LONG    : value_result->j = *(jlong*)tos_addr; break;
432       case T_FLOAT   : value_result->f = *(jfloat*)tos_addr; break;
433       case T_DOUBLE  : value_result->d = *(jdouble*)tos_addr; break;
434       case T_VOID    : /* Nothing to do */ break;
435       default        : ShouldNotReachHere();
436     }
437   }
438   return type;
439 }
440 
441 #ifndef PRODUCT
442 
443 void frame::describe_pd(FrameValues& values, int frame_no) {
444   if (is_interpreted_frame()) {
445 #define DESCRIBE_ADDRESS(name) \
446   values.describe(frame_no, (intptr_t*)&(get_ijava_state()->name), #name);
447 
448       DESCRIBE_ADDRESS(method);
449       DESCRIBE_ADDRESS(mirror);
450       DESCRIBE_ADDRESS(locals);
451       DESCRIBE_ADDRESS(monitors);
452       DESCRIBE_ADDRESS(cpoolCache);
453       DESCRIBE_ADDRESS(bcp);
454       DESCRIBE_ADDRESS(esp);
455       DESCRIBE_ADDRESS(mdx);
456       DESCRIBE_ADDRESS(top_frame_sp);
457       DESCRIBE_ADDRESS(sender_sp);
458       DESCRIBE_ADDRESS(oop_tmp);
459       DESCRIBE_ADDRESS(lresult);
460       DESCRIBE_ADDRESS(fresult);
461   }
462 
463   if (is_java_frame() || Continuation::is_continuation_enterSpecial(*this)) {
464     DEBUG_ONLY(nmethod* nm = _cb->as_nmethod_or_null());
465     assert(nm == nullptr || !nm->needs_stack_repair(), "unsupported");
466     intptr_t* ret_pc_loc = (intptr_t*)&own_abi()->lr;
467     address ret_pc = *(address*)ret_pc_loc;
468     values.describe(frame_no, ret_pc_loc,
469       Continuation::is_return_barrier_entry(ret_pc) ? "return address (return barrier)" : "return address");
470   }
471 }
472 #endif
473 
474 intptr_t *frame::initial_deoptimization_info() {
475   // `this` is the caller of the deoptee. We want to trim it, if compiled, to
476   // unextended_sp. This is necessary if the deoptee frame is the bottom frame
477   // of a continuation on stack (more frames could be in a StackChunk) as it
478   // will pop its stack args. Otherwise the recursion in
479   // FreezeBase::recurse_freeze_java_frame() would not stop at the bottom frame.
480   return is_compiled_frame() ? unextended_sp() : sp();
481 }
482 
483 #ifndef PRODUCT
484 // This is a generic constructor which is only used by pns() in debug.cpp.
485 // fp is dropped and gets determined by backlink.
486 frame::frame(void* sp, void* fp, void* pc) : frame((intptr_t*)sp, (address)pc, kind::unknown) {}
487 #endif
488 
489 BasicObjectLock* frame::interpreter_frame_monitor_end() const {
490   BasicObjectLock* result = (BasicObjectLock*) at_relative(ijava_idx(monitors));
491   // make sure the pointer points inside the frame
492   assert(sp() <= (intptr_t*) result, "monitor end should be above the stack pointer");
493   assert((intptr_t*) result < fp(),  "monitor end should be strictly below the frame pointer: result: " INTPTR_FORMAT " fp: " INTPTR_FORMAT, p2i(result), p2i(fp()));
494   return result;
495 }
496 
497 intptr_t* frame::interpreter_frame_tos_at(jint offset) const {
498   return &interpreter_frame_tos_address()[offset];
499 }
500 
501 intptr_t* frame::repair_sender_sp(nmethod* nm, intptr_t* sp, intptr_t** saved_fp_addr) {
502   assert(nm != nullptr && nm->needs_stack_repair(), "");
503   Unimplemented();
504   return nullptr;
505 }
506 
507 bool frame::was_augmented_on_entry(int& real_size) const {
508   assert(is_compiled_frame(), "");
509   if (_cb->as_nmethod_or_null()->needs_stack_repair()) {
510     Unimplemented();
511   }
512   real_size = _cb->frame_size();
513   return false;
514 }