1 /*
  2  * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
  3  * Copyright (c) 2014, 2020, Red Hat 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 #include "precompiled.hpp"
 27 #include "compiler/oopMap.hpp"
 28 #include "interpreter/interpreter.hpp"
 29 #include "memory/resourceArea.hpp"
 30 #include "memory/universe.hpp"
 31 #include "oops/markWord.hpp"
 32 #include "oops/method.hpp"
 33 #include "oops/oop.inline.hpp"
 34 #include "prims/methodHandles.hpp"
 35 #include "runtime/frame.inline.hpp"
 36 #include "runtime/handles.inline.hpp"
 37 #include "runtime/javaCalls.hpp"
 38 #include "runtime/monitorChunk.hpp"
 39 #include "runtime/os.inline.hpp"
 40 #include "runtime/signature.hpp"
 41 #include "runtime/stackWatermarkSet.hpp"
 42 #include "runtime/stubCodeGenerator.hpp"
 43 #include "runtime/stubRoutines.hpp"
 44 #include "vmreg_aarch64.inline.hpp"
 45 #ifdef COMPILER1
 46 #include "c1/c1_Runtime1.hpp"
 47 #include "runtime/vframeArray.hpp"
 48 #endif
 49 
 50 #ifdef ASSERT
 51 void RegisterMap::check_location_valid() {
 52 }
 53 #endif
 54 
 55 
 56 // Profiling/safepoint support
 57 
 58 bool frame::safe_for_sender(JavaThread *thread) {
 59   address   sp = (address)_sp;
 60   address   fp = (address)_fp;
 61   address   unextended_sp = (address)_unextended_sp;
 62 
 63   // consider stack guards when trying to determine "safe" stack pointers
 64   // sp must be within the usable part of the stack (not in guards)
 65   if (!thread->is_in_usable_stack(sp)) {
 66     return false;
 67   }
 68 
 69   // When we are running interpreted code the machine stack pointer, SP, is
 70   // set low enough so that the Java expression stack can grow and shrink
 71   // without ever exceeding the machine stack bounds.  So, ESP >= SP.
 72 
 73   // When we call out of an interpreted method, SP is incremented so that
 74   // the space between SP and ESP is removed.  The SP saved in the callee's
 75   // frame is the SP *before* this increment.  So, when we walk a stack of
 76   // interpreter frames the sender's SP saved in a frame might be less than
 77   // the SP at the point of call.
 78 
 79   // So unextended sp must be within the stack but we need not to check
 80   // that unextended sp >= sp
 81   if (!thread->is_in_full_stack_checked(unextended_sp)) {
 82     return false;
 83   }
 84 
 85   // an fp must be within the stack and above (but not equal) sp
 86   // second evaluation on fp+ is added to handle situation where fp is -1
 87   bool fp_safe = thread->is_in_stack_range_excl(fp, sp) &&
 88                  thread->is_in_full_stack_checked(fp + (return_addr_offset * sizeof(void*)));
 89 
 90   // We know sp/unextended_sp are safe only fp is questionable here
 91 
 92   // If the current frame is known to the code cache then we can attempt to
 93   // to construct the sender and do some validation of it. This goes a long way
 94   // toward eliminating issues when we get in frame construction code
 95 
 96   if (_cb != NULL ) {
 97 
 98     // First check if frame is complete and tester is reliable
 99     // Unfortunately we can only check frame complete for runtime stubs and nmethod
100     // other generic buffer blobs are more problematic so we just assume they are
101     // ok. adapter blobs never have a frame complete and are never ok.
102 
103     if (!_cb->is_frame_complete_at(_pc)) {
104       if (_cb->is_nmethod() || _cb->is_adapter_blob() || _cb->is_runtime_stub()) {
105         return false;
106       }
107     }
108 
109     // Could just be some random pointer within the codeBlob
110     if (!_cb->code_contains(_pc)) {
111       return false;
112     }
113 
114     // Entry frame checks
115     if (is_entry_frame()) {
116       // an entry frame must have a valid fp.
117       return fp_safe && is_entry_frame_valid(thread);
118     }
119 
120     intptr_t* sender_sp = NULL;
121     intptr_t* sender_unextended_sp = NULL;
122     address   sender_pc = NULL;
123     intptr_t* saved_fp =  NULL;
124 
125     if (is_interpreted_frame()) {
126       // fp must be safe
127       if (!fp_safe) {
128         return false;
129       }
130 
131       // for interpreted frames, the value below is the sender "raw" sp,
132       // which can be different from the sender unextended sp (the sp seen
133       // by the sender) because of current frame local variables
134       sender_sp = (intptr_t*) addr_at(sender_sp_offset);
135       sender_unextended_sp = (intptr_t*) this->fp()[interpreter_frame_sender_sp_offset];
136       saved_fp = (intptr_t*) this->fp()[link_offset];
137       sender_pc = pauth_strip_verifiable((address) this->fp()[return_addr_offset], (address)saved_fp);
138 
139     } else {
140       // must be some sort of compiled/runtime frame
141       // fp does not have to be safe (although it could be check for c1?)
142 
143       // check for a valid frame_size, otherwise we are unlikely to get a valid sender_pc
144       if (_cb->frame_size() <= 0) {
145         return false;
146       }
147 
148       sender_sp = _unextended_sp + _cb->frame_size();
149       // Is sender_sp safe?
150       if (!thread->is_in_full_stack_checked((address)sender_sp)) {
151         return false;
152       }
153       // Note: frame::sender_sp_offset is only valid for compiled frame
154       intptr_t **saved_fp_addr = (intptr_t**) (sender_sp - frame::sender_sp_offset);
155       saved_fp = *saved_fp_addr;
156       sender_pc = pauth_strip_verifiable((address) *(sender_sp-1), (address)saved_fp);
157 
158       // Repair the sender sp if this is a method with scalarized inline type args
159       sender_sp = repair_sender_sp(sender_sp, saved_fp_addr);
160       sender_unextended_sp = sender_sp;
161     }
162 
163     // If the potential sender is the interpreter then we can do some more checking
164     if (Interpreter::contains(sender_pc)) {
165 
166       // fp is always saved in a recognizable place in any code we generate. However
167       // only if the sender is interpreted/call_stub (c1 too?) are we certain that the saved fp
168       // is really a frame pointer.
169 
170       if (!thread->is_in_stack_range_excl((address)saved_fp, (address)sender_sp)) {
171         return false;
172       }
173 
174       // construct the potential sender
175 
176       frame sender(sender_sp, sender_unextended_sp, saved_fp, sender_pc);
177 
178       return sender.is_interpreted_frame_valid(thread);
179 
180     }
181 
182     // We must always be able to find a recognizable pc
183     CodeBlob* sender_blob = CodeCache::find_blob_unsafe(sender_pc);
184     if (sender_pc == NULL ||  sender_blob == NULL) {
185       return false;
186     }
187 
188     // Could be a zombie method
189     if (sender_blob->is_zombie() || sender_blob->is_unloaded()) {
190       return false;
191     }
192 
193     // Could just be some random pointer within the codeBlob
194     if (!sender_blob->code_contains(sender_pc)) {
195       return false;
196     }
197 
198     // We should never be able to see an adapter if the current frame is something from code cache
199     if (sender_blob->is_adapter_blob()) {
200       return false;
201     }
202 
203     // Could be the call_stub
204     if (StubRoutines::returns_to_call_stub(sender_pc)) {
205       if (!thread->is_in_stack_range_excl((address)saved_fp, (address)sender_sp)) {
206         return false;
207       }
208 
209       // construct the potential sender
210 
211       frame sender(sender_sp, sender_unextended_sp, saved_fp, sender_pc);
212 
213       // Validate the JavaCallWrapper an entry frame must have
214       address jcw = (address)sender.entry_frame_call_wrapper();
215 
216       return thread->is_in_stack_range_excl(jcw, (address)sender.fp());
217     }
218 
219     CompiledMethod* nm = sender_blob->as_compiled_method_or_null();
220     if (nm != NULL) {
221       if (nm->is_deopt_mh_entry(sender_pc) || nm->is_deopt_entry(sender_pc) ||
222           nm->method()->is_method_handle_intrinsic()) {
223         return false;
224       }
225     }
226 
227     // If the frame size is 0 something (or less) is bad because every nmethod has a non-zero frame size
228     // because the return address counts against the callee's frame.
229 
230     if (sender_blob->frame_size() <= 0) {
231       assert(!sender_blob->is_compiled(), "should count return address at least");
232       return false;
233     }
234 
235     // We should never be able to see anything here except an nmethod. If something in the
236     // code cache (current frame) is called by an entity within the code cache that entity
237     // should not be anything but the call stub (already covered), the interpreter (already covered)
238     // or an nmethod.
239 
240     if (!sender_blob->is_compiled()) {
241         return false;
242     }
243 
244     // Could put some more validation for the potential non-interpreted sender
245     // frame we'd create by calling sender if I could think of any. Wait for next crash in forte...
246 
247     // One idea is seeing if the sender_pc we have is one that we'd expect to call to current cb
248 
249     // We've validated the potential sender that would be created
250     return true;
251   }
252 
253   // Must be native-compiled frame. Since sender will try and use fp to find
254   // linkages it must be safe
255 
256   if (!fp_safe) {
257     return false;
258   }
259 
260   // Will the pc we fetch be non-zero (which we'll find at the oldest frame)
261 
262   if ( (address) this->fp()[return_addr_offset] == NULL) return false;
263 
264 
265   // could try and do some more potential verification of native frame if we could think of some...
266 
267   return true;
268 
269 }
270 
271 void frame::patch_pc(Thread* thread, address pc) {
272   assert(_cb == CodeCache::find_blob(pc), "unexpected pc");
273   address* pc_addr = &(((address*) sp())[-1]);
274   address signing_sp = (((address*) sp())[-2]);
275   address signed_pc = pauth_sign_return_address(pc, (address)signing_sp);
276   address pc_old = pauth_strip_verifiable(*pc_addr, (address)signing_sp);
277   if (TracePcPatching) {
278     tty->print("patch_pc at address " INTPTR_FORMAT " [" INTPTR_FORMAT " -> " INTPTR_FORMAT "]",
279                   p2i(pc_addr), p2i(pc_old), p2i(pc));
280     if (VM_Version::use_rop_protection()) {
281       tty->print(" [signed " INTPTR_FORMAT " -> " INTPTR_FORMAT "]", p2i(*pc_addr), p2i(signed_pc));
282     }
283     tty->print_cr("");
284   }
285 
286   // Either the return address is the original one or we are going to
287   // patch in the same address that's already there.
288   assert(_pc == pc_old || pc == pc_old, "must be");
289   *pc_addr = signed_pc;
290   address original_pc = CompiledMethod::get_deopt_original_pc(this);
291   if (original_pc != NULL) {
292     assert(original_pc == _pc, "expected original PC to be stored before patching");
293     _deopt_state = is_deoptimized;
294     // leave _pc as is
295   } else {
296     _deopt_state = not_deoptimized;
297     _pc = pc;
298   }
299 }
300 
301 bool frame::is_interpreted_frame() const  {
302   return Interpreter::contains(pc());
303 }
304 
305 int frame::frame_size(RegisterMap* map) const {
306   frame sender = this->sender(map);
307   return sender.sp() - sp();
308 }
309 
310 intptr_t* frame::entry_frame_argument_at(int offset) const {
311   // convert offset to index to deal with tsi
312   int index = (Interpreter::expr_offset_in_bytes(offset)/wordSize);
313   // Entry frame's arguments are always in relation to unextended_sp()
314   return &unextended_sp()[index];
315 }
316 
317 // sender_sp
318 intptr_t* frame::interpreter_frame_sender_sp() const {
319   assert(is_interpreted_frame(), "interpreted frame expected");
320   return (intptr_t*) at(interpreter_frame_sender_sp_offset);
321 }
322 
323 void frame::set_interpreter_frame_sender_sp(intptr_t* sender_sp) {
324   assert(is_interpreted_frame(), "interpreted frame expected");
325   ptr_at_put(interpreter_frame_sender_sp_offset, (intptr_t) sender_sp);
326 }
327 
328 
329 // monitor elements
330 
331 BasicObjectLock* frame::interpreter_frame_monitor_begin() const {
332   return (BasicObjectLock*) addr_at(interpreter_frame_monitor_block_bottom_offset);
333 }
334 
335 BasicObjectLock* frame::interpreter_frame_monitor_end() const {
336   BasicObjectLock* result = (BasicObjectLock*) *addr_at(interpreter_frame_monitor_block_top_offset);
337   // make sure the pointer points inside the frame
338   assert(sp() <= (intptr_t*) result, "monitor end should be above the stack pointer");
339   assert((intptr_t*) result < fp(),  "monitor end should be strictly below the frame pointer");
340   return result;
341 }
342 
343 void frame::interpreter_frame_set_monitor_end(BasicObjectLock* value) {
344   *((BasicObjectLock**)addr_at(interpreter_frame_monitor_block_top_offset)) = value;
345 }
346 
347 // Used by template based interpreter deoptimization
348 void frame::interpreter_frame_set_last_sp(intptr_t* sp) {
349     *((intptr_t**)addr_at(interpreter_frame_last_sp_offset)) = sp;
350 }
351 
352 frame frame::sender_for_entry_frame(RegisterMap* map) const {
353   assert(map != NULL, "map must be set");
354   // Java frame called from C; skip all C frames and return top C
355   // frame of that chunk as the sender
356   JavaFrameAnchor* jfa = entry_frame_call_wrapper()->anchor();
357   assert(!entry_frame_is_first(), "next Java fp must be non zero");
358   assert(jfa->last_Java_sp() > sp(), "must be above this frame on stack");
359   // Since we are walking the stack now this nested anchor is obviously walkable
360   // even if it wasn't when it was stacked.
361   if (!jfa->walkable()) {
362     // Capture _last_Java_pc (if needed) and mark anchor walkable.
363     jfa->capture_last_Java_pc();
364   }
365   map->clear();
366   assert(map->include_argument_oops(), "should be set by clear");
367   vmassert(jfa->last_Java_pc() != NULL, "not walkable");
368   frame fr(jfa->last_Java_sp(), jfa->last_Java_fp(), jfa->last_Java_pc());
369   fr.set_sp_is_trusted();
370 
371   return fr;
372 }
373 
374 OptimizedEntryBlob::FrameData* OptimizedEntryBlob::frame_data_for_frame(const frame& frame) const {
375   ShouldNotCallThis();
376   return nullptr;
377 }
378 
379 bool frame::optimized_entry_frame_is_first() const {
380   ShouldNotCallThis();
381   return false;
382 }
383 
384 frame frame::sender_for_optimized_entry_frame(RegisterMap* map) const {
385   ShouldNotCallThis();
386   return {};
387 }
388 
389 //------------------------------------------------------------------------------
390 // frame::verify_deopt_original_pc
391 //
392 // Verifies the calculated original PC of a deoptimization PC for the
393 // given unextended SP.
394 #ifdef ASSERT
395 void frame::verify_deopt_original_pc(CompiledMethod* nm, intptr_t* unextended_sp) {
396   frame fr;
397 
398   // This is ugly but it's better than to change {get,set}_original_pc
399   // to take an SP value as argument.  And it's only a debugging
400   // method anyway.
401   fr._unextended_sp = unextended_sp;
402 
403   address original_pc = nm->get_original_pc(&fr);
404   assert(nm->insts_contains_inclusive(original_pc),
405          "original PC must be in the main code section of the the compiled method (or must be immediately following it)");
406 }
407 #endif
408 
409 //------------------------------------------------------------------------------
410 // frame::adjust_unextended_sp
411 void frame::adjust_unextended_sp() {
412   // On aarch64, sites calling method handle intrinsics and lambda forms are treated
413   // as any other call site. Therefore, no special action is needed when we are
414   // returning to any of these call sites.
415 
416   if (_cb != NULL) {
417     CompiledMethod* sender_cm = _cb->as_compiled_method_or_null();
418     if (sender_cm != NULL) {
419       // If the sender PC is a deoptimization point, get the original PC.
420       if (sender_cm->is_deopt_entry(_pc) ||
421           sender_cm->is_deopt_mh_entry(_pc)) {
422         DEBUG_ONLY(verify_deopt_original_pc(sender_cm, _unextended_sp));
423       }
424     }
425   }
426 }
427 
428 //------------------------------------------------------------------------------
429 // frame::update_map_with_saved_link
430 void frame::update_map_with_saved_link(RegisterMap* map, intptr_t** link_addr) {
431   // The interpreter and compiler(s) always save fp in a known
432   // location on entry. We must record where that location is
433   // so that if fp was live on callout from c2 we can find
434   // the saved copy no matter what it called.
435 
436   // Since the interpreter always saves fp if we record where it is then
437   // we don't have to always save fp on entry and exit to c2 compiled
438   // code, on entry will be enough.
439   map->set_location(rfp->as_VMReg(), (address) link_addr);
440   // this is weird "H" ought to be at a higher address however the
441   // oopMaps seems to have the "H" regs at the same address and the
442   // vanilla register.
443   // XXXX make this go away
444   if (true) {
445     map->set_location(rfp->as_VMReg()->next(), (address) link_addr);
446   }
447 }
448 
449 
450 //------------------------------------------------------------------------------
451 // frame::sender_for_interpreter_frame
452 frame frame::sender_for_interpreter_frame(RegisterMap* map) const {
453   // SP is the raw SP from the sender after adapter or interpreter
454   // extension.
455   intptr_t* sender_sp = this->sender_sp();
456 
457   // This is the sp before any possible extension (adapter/locals).
458   intptr_t* unextended_sp = interpreter_frame_sender_sp();
459 
460 #if COMPILER2_OR_JVMCI
461   if (map->update_map()) {
462     update_map_with_saved_link(map, (intptr_t**) addr_at(link_offset));
463   }
464 #endif // COMPILER2_OR_JVMCI
465 
466   // For ROP protection, Interpreter will have signed the sender_pc, but there is no requirement to authenticate it here.
467   address sender_pc = pauth_strip_verifiable(sender_pc_maybe_signed(), (address)link());
468 
469   return frame(sender_sp, unextended_sp, link(), sender_pc);
470 }
471 
472 //------------------------------------------------------------------------------
473 // frame::sender_for_compiled_frame
474 frame frame::sender_for_compiled_frame(RegisterMap* map) const {
475   // When the sp of a compiled frame is correct, we can get the correct sender sp
476   // by unextended sp + frame size.
477   // For the following two scenarios, the sp of a compiled frame is correct:
478   //  a) This compiled frame is built from the anchor.
479   //  b) This compiled frame is built from a callee frame, and the callee frame can
480   //    calculate its sp correctly.
481   //
482   // For b), if the callee frame is a native code frame (such as leaf call), the sp of
483   // the compiled frame cannot be calculated correctly. There is currently no suitable
484   // solution to solve this problem perfectly. But when PreserveFramePointer is enabled,
485   // we can get the correct sender sp by fp + 2 (that is sender_sp()).
486 
487   assert(_cb->frame_size() >= 0, "must have non-zero frame size");
488   intptr_t* l_sender_sp = (!PreserveFramePointer || _sp_is_trusted) ? unextended_sp() + _cb->frame_size()
489                                                                     : sender_sp();
490 
491 #ifdef ASSERT
492   address sender_pc_copy = pauth_strip_verifiable((address) *(l_sender_sp-1), (address) *(l_sender_sp-2));
493 #endif
494 
495   intptr_t** saved_fp_addr = (intptr_t**) (l_sender_sp - frame::sender_sp_offset);
496 
497   // assert (sender_sp() == l_sender_sp, "should be");
498   // assert (*saved_fp_addr == link(), "should be");
499 
500   // Repair the sender sp if the frame has been extended
501   l_sender_sp = repair_sender_sp(l_sender_sp, saved_fp_addr);
502 
503   // the return_address is always the word on the stack
504 
505   // For ROP protection, C1/C2 will have signed the sender_pc, but there is no requirement to authenticate it here.
506   // The return address is always the first word on the stack
507   address sender_pc = pauth_strip_verifiable((address) *(l_sender_sp-1), (address) *(l_sender_sp-2));
508 
509 #ifdef ASSERT
510   if (sender_pc != sender_pc_copy) {
511     // When extending the stack in the callee method entry to make room for unpacking of value
512     // type args, we keep a copy of the sender pc at the expected location in the callee frame.
513     // If the sender pc is patched due to deoptimization, the copy is not consistent anymore.
514     nmethod* nm = CodeCache::find_blob(sender_pc)->as_nmethod();
515     assert(sender_pc == nm->deopt_mh_handler_begin() || sender_pc == nm->deopt_handler_begin(), "unexpected sender pc");
516   }
517 #endif
518 
519   if (map->update_map()) {
520     // Tell GC to use argument oopmaps for some runtime stubs that need it.
521     // For C1, the runtime stub might not have oop maps, so set this flag
522     // outside of update_register_map.
523     bool caller_args = _cb->caller_must_gc_arguments(map->thread());
524 #ifdef COMPILER1
525     if (!caller_args) {
526       nmethod* nm = _cb->as_nmethod_or_null();
527       if (nm != NULL && nm->is_compiled_by_c1() && nm->method()->has_scalarized_args() &&
528           pc() < nm->verified_inline_entry_point()) {
529         // The VEP and VIEP(RO) of C1-compiled methods call buffer_inline_args_xxx
530         // before doing any argument shuffling, so we need to scan the oops
531         // as the caller passes them.
532         caller_args = true;
533       }
534     }
535 #endif
536     map->set_include_argument_oops(caller_args);
537     if (_cb->oop_maps() != NULL) {
538       OopMapSet::update_register_map(this, map);
539     }
540 
541     // Since the prolog does the save and restore of FP there is no
542     // oopmap for it so we must fill in its location as if there was
543     // an oopmap entry since if our caller was compiled code there
544     // could be live jvm state in it.
545     update_map_with_saved_link(map, saved_fp_addr);
546   }
547 
548   return frame(l_sender_sp, l_sender_sp, *saved_fp_addr, sender_pc);
549 }
550 
551 //------------------------------------------------------------------------------
552 // frame::sender_raw
553 frame frame::sender_raw(RegisterMap* map) const {
554   // Default is we done have to follow them. The sender_for_xxx will
555   // update it accordingly
556    map->set_include_argument_oops(false);
557 
558   if (is_entry_frame())
559     return sender_for_entry_frame(map);
560   if (is_interpreted_frame())
561     return sender_for_interpreter_frame(map);
562   assert(_cb == CodeCache::find_blob(pc()),"Must be the same");
563 
564   // This test looks odd: why is it not is_compiled_frame() ?  That's
565   // because stubs also have OOP maps.
566   if (_cb != NULL) {
567     return sender_for_compiled_frame(map);
568   }
569 
570   // Must be native-compiled frame, i.e. the marshaling code for native
571   // methods that exists in the core system.
572 
573   // Native code may or may not have signed the return address, we have no way to be sure or what
574   // signing methods they used. Instead, just ensure the stripped value is used.
575 
576   return frame(sender_sp(), link(), sender_pc());
577 }
578 
579 frame frame::sender(RegisterMap* map) const {
580   frame result = sender_raw(map);
581 
582   if (map->process_frames()) {
583     StackWatermarkSet::on_iteration(map->thread(), result);
584   }
585 
586   return result;
587 }
588 
589 bool frame::is_interpreted_frame_valid(JavaThread* thread) const {
590   assert(is_interpreted_frame(), "Not an interpreted frame");
591   // These are reasonable sanity checks
592   if (fp() == 0 || (intptr_t(fp()) & (wordSize-1)) != 0) {
593     return false;
594   }
595   if (sp() == 0 || (intptr_t(sp()) & (wordSize-1)) != 0) {
596     return false;
597   }
598   if (fp() + interpreter_frame_initial_sp_offset < sp()) {
599     return false;
600   }
601   // These are hacks to keep us out of trouble.
602   // The problem with these is that they mask other problems
603   if (fp() <= sp()) {        // this attempts to deal with unsigned comparison above
604     return false;
605   }
606 
607   // do some validation of frame elements
608 
609   // first the method
610 
611   Method* m = *interpreter_frame_method_addr();
612 
613   // validate the method we'd find in this potential sender
614   if (!Method::is_valid_method(m)) return false;
615 
616   // stack frames shouldn't be much larger than max_stack elements
617   // this test requires the use of unextended_sp which is the sp as seen by
618   // the current frame, and not sp which is the "raw" pc which could point
619   // further because of local variables of the callee method inserted after
620   // method arguments
621   if (fp() - unextended_sp() > 1024 + m->max_stack()*Interpreter::stackElementSize) {
622     return false;
623   }
624 
625   // validate bci/bcx
626 
627   address  bcp    = interpreter_frame_bcp();
628   if (m->validate_bci_from_bcp(bcp) < 0) {
629     return false;
630   }
631 
632   // validate constantPoolCache*
633   ConstantPoolCache* cp = *interpreter_frame_cache_addr();
634   if (MetaspaceObj::is_valid(cp) == false) return false;
635 
636   // validate locals
637 
638   address locals =  (address) *interpreter_frame_locals_addr();
639   return thread->is_in_stack_range_incl(locals, (address)fp());
640 }
641 
642 BasicType frame::interpreter_frame_result(oop* oop_result, jvalue* value_result) {
643   assert(is_interpreted_frame(), "interpreted frame expected");
644   Method* method = interpreter_frame_method();
645   BasicType type = method->result_type();
646 
647   intptr_t* tos_addr;
648   if (method->is_native()) {
649     // TODO : ensure AARCH64 does the same as Intel here i.e. push v0 then r0
650     // Prior to calling into the runtime to report the method_exit the possible
651     // return value is pushed to the native stack. If the result is a jfloat/jdouble
652     // then ST0 is saved before EAX/EDX. See the note in generate_native_result
653     tos_addr = (intptr_t*)sp();
654     if (type == T_FLOAT || type == T_DOUBLE) {
655       // This is times two because we do a push(ltos) after pushing XMM0
656       // and that takes two interpreter stack slots.
657       tos_addr += 2 * Interpreter::stackElementWords;
658     }
659   } else {
660     tos_addr = (intptr_t*)interpreter_frame_tos_address();
661   }
662 
663   switch (type) {
664     case T_PRIMITIVE_OBJECT :
665     case T_OBJECT  :
666     case T_ARRAY   : {
667       oop obj;
668       if (method->is_native()) {
669         obj = cast_to_oop(at(interpreter_frame_oop_temp_offset));
670       } else {
671         oop* obj_p = (oop*)tos_addr;
672         obj = (obj_p == NULL) ? (oop)NULL : *obj_p;
673       }
674       assert(Universe::is_in_heap_or_null(obj), "sanity check");
675       *oop_result = obj;
676       break;
677     }
678     case T_BOOLEAN : value_result->z = *(jboolean*)tos_addr; break;
679     case T_BYTE    : value_result->b = *(jbyte*)tos_addr; break;
680     case T_CHAR    : value_result->c = *(jchar*)tos_addr; break;
681     case T_SHORT   : value_result->s = *(jshort*)tos_addr; break;
682     case T_INT     : value_result->i = *(jint*)tos_addr; break;
683     case T_LONG    : value_result->j = *(jlong*)tos_addr; break;
684     case T_FLOAT   : {
685         value_result->f = *(jfloat*)tos_addr;
686       break;
687     }
688     case T_DOUBLE  : value_result->d = *(jdouble*)tos_addr; break;
689     case T_VOID    : /* Nothing to do */ break;
690     default        : ShouldNotReachHere();
691   }
692 
693   return type;
694 }
695 
696 
697 intptr_t* frame::interpreter_frame_tos_at(jint offset) const {
698   int index = (Interpreter::expr_offset_in_bytes(offset)/wordSize);
699   return &interpreter_frame_tos_address()[index];
700 }
701 
702 #ifndef PRODUCT
703 
704 #define DESCRIBE_FP_OFFSET(name) \
705   values.describe(frame_no, fp() + frame::name##_offset, #name)
706 
707 void frame::describe_pd(FrameValues& values, int frame_no) {
708   if (is_interpreted_frame()) {
709     DESCRIBE_FP_OFFSET(interpreter_frame_sender_sp);
710     DESCRIBE_FP_OFFSET(interpreter_frame_last_sp);
711     DESCRIBE_FP_OFFSET(interpreter_frame_method);
712     DESCRIBE_FP_OFFSET(interpreter_frame_mdp);
713     DESCRIBE_FP_OFFSET(interpreter_frame_mirror);
714     DESCRIBE_FP_OFFSET(interpreter_frame_cache);
715     DESCRIBE_FP_OFFSET(interpreter_frame_locals);
716     DESCRIBE_FP_OFFSET(interpreter_frame_bcp);
717     DESCRIBE_FP_OFFSET(interpreter_frame_initial_sp);
718   }
719 }
720 #endif
721 
722 intptr_t *frame::initial_deoptimization_info() {
723   // Not used on aarch64, but we must return something.
724   return NULL;
725 }
726 
727 intptr_t* frame::real_fp() const {
728   if (_cb != NULL) {
729     // use the frame size if valid
730     int size = _cb->frame_size();
731     if (size > 0) {
732       return unextended_sp() + size;
733     }
734   }
735   // else rely on fp()
736   assert(! is_compiled_frame(), "unknown compiled frame size");
737   return fp();
738 }
739 
740 #undef DESCRIBE_FP_OFFSET
741 
742 #define DESCRIBE_FP_OFFSET(name)                     \
743   {                                                  \
744     uintptr_t *p = (uintptr_t *)fp;                  \
745     printf(INTPTR_FORMAT " " INTPTR_FORMAT " %s\n",  \
746            (uintptr_t)(p + frame::name##_offset),    \
747            p[frame::name##_offset], #name);          \
748   }
749 
750 static THREAD_LOCAL uintptr_t nextfp;
751 static THREAD_LOCAL uintptr_t nextpc;
752 static THREAD_LOCAL uintptr_t nextsp;
753 static THREAD_LOCAL RegisterMap *reg_map;
754 
755 static void printbc(Method *m, intptr_t bcx) {
756   const char *name;
757   char buf[16];
758   if (m->validate_bci_from_bcp((address)bcx) < 0
759       || !m->contains((address)bcx)) {
760     name = "???";
761     snprintf(buf, sizeof buf, "(bad)");
762   } else {
763     int bci = m->bci_from((address)bcx);
764     snprintf(buf, sizeof buf, "%d", bci);
765     name = Bytecodes::name(m->code_at(bci));
766   }
767   ResourceMark rm;
768   printf("%s : %s ==> %s\n", m->name_and_sig_as_C_string(), buf, name);
769 }
770 
771 void internal_pf(uintptr_t sp, uintptr_t fp, uintptr_t pc, uintptr_t bcx) {
772   if (! fp)
773     return;
774 
775   DESCRIBE_FP_OFFSET(return_addr);
776   DESCRIBE_FP_OFFSET(link);
777   DESCRIBE_FP_OFFSET(interpreter_frame_sender_sp);
778   DESCRIBE_FP_OFFSET(interpreter_frame_last_sp);
779   DESCRIBE_FP_OFFSET(interpreter_frame_method);
780   DESCRIBE_FP_OFFSET(interpreter_frame_mdp);
781   DESCRIBE_FP_OFFSET(interpreter_frame_cache);
782   DESCRIBE_FP_OFFSET(interpreter_frame_locals);
783   DESCRIBE_FP_OFFSET(interpreter_frame_bcp);
784   DESCRIBE_FP_OFFSET(interpreter_frame_initial_sp);
785   uintptr_t *p = (uintptr_t *)fp;
786 
787   // We want to see all frames, native and Java.  For compiled and
788   // interpreted frames we have special information that allows us to
789   // unwind them; for everything else we assume that the native frame
790   // pointer chain is intact.
791   frame this_frame((intptr_t*)sp, (intptr_t*)fp, (address)pc);
792   if (this_frame.is_compiled_frame() ||
793       this_frame.is_interpreted_frame()) {
794     frame sender = this_frame.sender(reg_map);
795     nextfp = (uintptr_t)sender.fp();
796     nextpc = (uintptr_t)sender.pc();
797     nextsp = (uintptr_t)sender.unextended_sp();
798   } else {
799     nextfp = p[frame::link_offset];
800     nextpc = p[frame::return_addr_offset];
801     nextsp = (uintptr_t)&p[frame::sender_sp_offset];
802   }
803 
804   if (bcx == -1ULL)
805     bcx = p[frame::interpreter_frame_bcp_offset];
806 
807   if (Interpreter::contains((address)pc)) {
808     Method* m = (Method*)p[frame::interpreter_frame_method_offset];
809     if(m && m->is_method()) {
810       printbc(m, bcx);
811     } else
812       printf("not a Method\n");
813   } else {
814     CodeBlob *cb = CodeCache::find_blob((address)pc);
815     if (cb != NULL) {
816       if (cb->is_nmethod()) {
817         ResourceMark rm;
818         nmethod* nm = (nmethod*)cb;
819         printf("nmethod %s\n", nm->method()->name_and_sig_as_C_string());
820       } else if (cb->name()) {
821         printf("CodeBlob %s\n", cb->name());
822       }
823     }
824   }
825 }
826 
827 extern "C" void npf() {
828   CodeBlob *cb = CodeCache::find_blob((address)nextpc);
829   // C2 does not always chain the frame pointers when it can, instead
830   // preferring to use fixed offsets from SP, so a simple leave() does
831   // not work.  Instead, it adds the frame size to SP then pops FP and
832   // LR.  We have to do the same thing to get a good call chain.
833   if (cb && cb->frame_size())
834     nextfp = nextsp + wordSize * (cb->frame_size() - 2);
835   internal_pf (nextsp, nextfp, nextpc, -1);
836 }
837 
838 extern "C" void pf(uintptr_t sp, uintptr_t fp, uintptr_t pc,
839                    uintptr_t bcx, uintptr_t thread) {
840   if (!reg_map) {
841     reg_map = NEW_C_HEAP_OBJ(RegisterMap, mtInternal);
842     ::new (reg_map) RegisterMap((JavaThread*)thread, false);
843   } else {
844     *reg_map = RegisterMap((JavaThread*)thread, false);
845   }
846 
847   {
848     CodeBlob *cb = CodeCache::find_blob((address)pc);
849     if (cb && cb->frame_size())
850       fp = sp + wordSize * (cb->frame_size() - 2);
851   }
852   internal_pf(sp, fp, pc, bcx);
853 }
854 
855 // support for printing out where we are in a Java method
856 // needs to be passed current fp and bcp register values
857 // prints method name, bc index and bytecode name
858 extern "C" void pm(uintptr_t fp, uintptr_t bcx) {
859   DESCRIBE_FP_OFFSET(interpreter_frame_method);
860   uintptr_t *p = (uintptr_t *)fp;
861   Method* m = (Method*)p[frame::interpreter_frame_method_offset];
862   printbc(m, bcx);
863 }
864 
865 #ifndef PRODUCT
866 // This is a generic constructor which is only used by pns() in debug.cpp.
867 frame::frame(void* sp, void* fp, void* pc) {
868   init((intptr_t*)sp, (intptr_t*)fp, (address)pc);
869 }
870 
871 #endif
872 
873 // Check for a method with scalarized inline type arguments that needs
874 // a stack repair and return the repaired sender stack pointer.
875 intptr_t* frame::repair_sender_sp(intptr_t* sender_sp, intptr_t** saved_fp_addr) const {
876   CompiledMethod* cm = _cb->as_compiled_method_or_null();
877   if (cm != NULL && cm->needs_stack_repair()) {
878     // The stack increment resides just below the saved FP on the stack and
879     // records the total frame size excluding the two words for saving FP and LR.
880     intptr_t* sp_inc_addr = (intptr_t*) (saved_fp_addr - 1);
881     assert(*sp_inc_addr % StackAlignmentInBytes == 0, "sp_inc not aligned");
882     int real_frame_size = (*sp_inc_addr / wordSize) + 2;
883     assert(real_frame_size >= _cb->frame_size() && real_frame_size <= 1000000, "invalid frame size");
884     sender_sp = unextended_sp() + real_frame_size;
885   }
886   return sender_sp;
887 }
888 
889 void JavaFrameAnchor::make_walkable(JavaThread* thread) {
890   // last frame set?
891   if (last_Java_sp() == NULL) return;
892   // already walkable?
893   if (walkable()) return;
894   vmassert(Thread::current() == (Thread*)thread, "not current thread");
895   vmassert(last_Java_sp() != NULL, "not called from Java code?");
896   vmassert(last_Java_pc() == NULL, "already walkable");
897   capture_last_Java_pc();
898   vmassert(walkable(), "something went wrong");
899 }
900 
901 void JavaFrameAnchor::capture_last_Java_pc() {
902   vmassert(_last_Java_sp != NULL, "no last frame set");
903   vmassert(_last_Java_pc == NULL, "already walkable");
904   _last_Java_pc = (address)_last_Java_sp[-1];
905 }