1 /*
   2  * Copyright (c) 1997, 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/moduleEntry.hpp"
  26 #include "code/codeCache.hpp"
  27 #include "code/scopeDesc.hpp"
  28 #include "code/vmreg.inline.hpp"
  29 #include "compiler/abstractCompiler.hpp"
  30 #include "compiler/disassembler.hpp"
  31 #include "compiler/oopMap.hpp"
  32 #include "gc/shared/collectedHeap.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "interpreter/oopMapCache.hpp"
  35 #include "logging/log.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "memory/universe.hpp"
  38 #include "oops/inlineKlass.hpp"
  39 #include "oops/markWord.hpp"
  40 #include "oops/method.inline.hpp"
  41 #include "oops/methodData.hpp"
  42 #include "oops/oop.inline.hpp"
  43 #include "oops/stackChunkOop.inline.hpp"
  44 #include "oops/verifyOopClosure.hpp"
  45 #include "prims/methodHandles.hpp"
  46 #include "runtime/continuation.hpp"
  47 #include "runtime/continuationEntry.inline.hpp"
  48 #include "runtime/frame.inline.hpp"
  49 #include "runtime/handles.inline.hpp"
  50 #include "runtime/javaCalls.hpp"
  51 #include "runtime/javaThread.hpp"
  52 #include "runtime/monitorChunk.hpp"
  53 #include "runtime/os.hpp"
  54 #include "runtime/safefetch.hpp"
  55 #include "runtime/sharedRuntime.hpp"
  56 #include "runtime/signature.hpp"
  57 #include "runtime/stackValue.hpp"
  58 #include "runtime/stubCodeGenerator.hpp"
  59 #include "runtime/stubRoutines.hpp"
  60 #include "utilities/debug.hpp"
  61 #include "utilities/decoder.hpp"
  62 #include "utilities/formatBuffer.hpp"
  63 #ifdef COMPILER1
  64 #include "c1/c1_Runtime1.hpp"
  65 #endif
  66 
  67 RegisterMap::RegisterMap(JavaThread *thread, UpdateMap update_map, ProcessFrames process_frames, WalkContinuation walk_cont) {
  68   _thread         = thread;
  69   _update_map     = update_map == UpdateMap::include;
  70   _process_frames = process_frames == ProcessFrames::include;
  71   _walk_cont      = walk_cont == WalkContinuation::include;
  72   clear();
  73   DEBUG_ONLY (_update_for_id = nullptr;)
  74   NOT_PRODUCT(_skip_missing = false;)
  75   NOT_PRODUCT(_async = false;)
  76 
  77   if (walk_cont == WalkContinuation::include && thread != nullptr && thread->last_continuation() != nullptr) {
  78     _chunk = stackChunkHandle(Thread::current()->handle_area()->allocate_null_handle(), true /* dummy */);
  79   }
  80   _chunk_index = -1;
  81 
  82 #ifndef PRODUCT
  83   for (int i = 0; i < reg_count ; i++ ) _location[i] = nullptr;
  84 #endif /* PRODUCT */
  85 }
  86 
  87 RegisterMap::RegisterMap(oop continuation, UpdateMap update_map) {
  88   _thread         = nullptr;
  89   _update_map     = update_map == UpdateMap::include;
  90   _process_frames = false;
  91   _walk_cont      = true;
  92   clear();
  93   DEBUG_ONLY (_update_for_id = nullptr;)
  94   NOT_PRODUCT(_skip_missing = false;)
  95   NOT_PRODUCT(_async = false;)
  96 
  97   _chunk = stackChunkHandle(Thread::current()->handle_area()->allocate_null_handle(), true /* dummy */);
  98   _chunk_index = -1;
  99 
 100 #ifndef PRODUCT
 101   for (int i = 0; i < reg_count ; i++ ) _location[i] = nullptr;
 102 #endif /* PRODUCT */
 103 }
 104 
 105 RegisterMap::RegisterMap(const RegisterMap* map) {
 106   assert(map != this, "bad initialization parameter");
 107   assert(map != nullptr, "RegisterMap must be present");
 108   _thread                = map->thread();
 109   _update_map            = map->update_map();
 110   _process_frames        = map->process_frames();
 111   _walk_cont             = map->_walk_cont;
 112   _include_argument_oops = map->include_argument_oops();
 113   DEBUG_ONLY (_update_for_id = map->_update_for_id;)
 114   NOT_PRODUCT(_skip_missing = map->_skip_missing;)
 115   NOT_PRODUCT(_async = map->_async;)
 116 
 117   // only the original RegisterMap's handle lives long enough for StackWalker; this is bound to cause trouble with nested continuations.
 118   _chunk = map->_chunk;
 119   _chunk_index = map->_chunk_index;
 120 
 121   pd_initialize_from(map);
 122   if (update_map()) {
 123     for(int i = 0; i < location_valid_size; i++) {
 124       LocationValidType bits = map->_location_valid[i];
 125       _location_valid[i] = bits;
 126       // for whichever bits are set, pull in the corresponding map->_location
 127       int j = i*location_valid_type_size;
 128       while (bits != 0) {
 129         if ((bits & 1) != 0) {
 130           assert(0 <= j && j < reg_count, "range check");
 131           _location[j] = map->_location[j];
 132         }
 133         bits >>= 1;
 134         j += 1;
 135       }
 136     }
 137   }
 138 }
 139 
 140 oop RegisterMap::cont() const {
 141   return _chunk() != nullptr ? _chunk()->cont() : (oop)nullptr;
 142 }
 143 
 144 void RegisterMap::set_stack_chunk(stackChunkOop chunk) {
 145   assert(chunk == nullptr || _walk_cont, "");
 146   assert(chunk == nullptr || _chunk.not_null(), "");
 147   if (_chunk.is_null()) return;
 148   log_trace(continuations)("set_stack_chunk: " INTPTR_FORMAT " this: " INTPTR_FORMAT, p2i((oopDesc*)chunk), p2i(this));
 149   _chunk.replace(chunk); // reuse handle. see comment above in the constructor
 150   if (chunk == nullptr) {
 151     _chunk_index = -1;
 152   } else {
 153     _chunk_index++;
 154   }
 155 }
 156 
 157 void RegisterMap::clear() {
 158   set_include_argument_oops(true);
 159   if (update_map()) {
 160     for(int i = 0; i < location_valid_size; i++) {
 161       _location_valid[i] = 0;
 162     }
 163     pd_clear();
 164   } else {
 165     pd_initialize();
 166   }
 167 }
 168 
 169 #ifndef PRODUCT
 170 
 171 VMReg RegisterMap::find_register_spilled_here(void* p, intptr_t* sp) {
 172   for(int i = 0; i < RegisterMap::reg_count; i++) {
 173     VMReg r = VMRegImpl::as_VMReg(i);
 174     if (p == location(r, sp)) return r;
 175   }
 176   return nullptr;
 177 }
 178 
 179 void RegisterMap::print_on(outputStream* st) const {
 180   st->print_cr("Register map");
 181   for(int i = 0; i < reg_count; i++) {
 182 
 183     VMReg r = VMRegImpl::as_VMReg(i);
 184     intptr_t* src = (intptr_t*) location(r, nullptr);
 185     if (src != nullptr) {
 186 
 187       r->print_on(st);
 188       st->print(" [" INTPTR_FORMAT "] = ", p2i(src));
 189       if (((uintptr_t)src & (sizeof(*src)-1)) != 0) {
 190         st->print_cr("<misaligned>");
 191       } else {
 192         st->print_cr(INTPTR_FORMAT, *src);
 193       }
 194     }
 195   }
 196 }
 197 
 198 void RegisterMap::print() const {
 199   print_on(tty);
 200 }
 201 
 202 #endif
 203 // This returns the pc that if you were in the debugger you'd see. Not
 204 // the idealized value in the frame object. This undoes the magic conversion
 205 // that happens for deoptimized frames. In addition it makes the value the
 206 // hardware would want to see in the native frame. The only user (at this point)
 207 // is deoptimization. It likely no one else should ever use it.
 208 
 209 address frame::raw_pc() const {
 210   if (is_deoptimized_frame()) {
 211     nmethod* nm = cb()->as_nmethod_or_null();
 212     assert(nm != nullptr, "only nmethod is expected here");
 213     return nm->deopt_handler_entry() - pc_return_offset;
 214   } else {
 215     return (pc() - pc_return_offset);
 216   }
 217 }
 218 
 219 // Change the pc in a frame object. This does not change the actual pc in
 220 // actual frame. To do that use patch_pc.
 221 //
 222 void frame::set_pc(address newpc) {
 223 #ifdef ASSERT
 224   if (_cb != nullptr && _cb->is_nmethod()) {
 225     assert(!((nmethod*)_cb)->is_deopt_pc(_pc), "invariant violation");
 226   }
 227 #endif // ASSERT
 228 
 229   // Unsafe to use the is_deoptimized tester after changing pc
 230   _deopt_state = unknown;
 231   _pc = newpc;
 232   _cb = CodeCache::find_blob(_pc);
 233 }
 234 
 235 // This is optimized for intra-blob pc adjustments only.
 236 void frame::adjust_pc(address newpc) {
 237   assert(_cb != nullptr, "invariant");
 238   assert(_cb == CodeCache::find_blob(newpc), "invariant");
 239   // Unsafe to use the is_deoptimized tester after changing pc
 240   _deopt_state = unknown;
 241   _pc = newpc;
 242 }
 243 
 244 // type testers
 245 bool frame::is_ignored_frame() const {
 246   return false;  // FIXME: some LambdaForm frames should be ignored
 247 }
 248 
 249 bool frame::is_native_frame() const {
 250   return (_cb != nullptr &&
 251           _cb->is_nmethod() &&
 252           ((nmethod*)_cb)->is_native_method());
 253 }
 254 
 255 bool frame::is_java_frame() const {
 256   if (is_interpreted_frame()) return true;
 257   if (is_compiled_frame())    return true;
 258   return false;
 259 }
 260 
 261 bool frame::is_runtime_frame() const {
 262   return (_cb != nullptr && _cb->is_runtime_stub());
 263 }
 264 
 265 bool frame::is_safepoint_blob_frame() const {
 266   return (_cb != nullptr && _cb->is_safepoint_stub());
 267 }
 268 
 269 // testers
 270 
 271 bool frame::is_first_java_frame() const {
 272   RegisterMap map(JavaThread::current(),
 273                   RegisterMap::UpdateMap::skip,
 274                   RegisterMap::ProcessFrames::include,
 275                   RegisterMap::WalkContinuation::skip); // No update
 276   frame s;
 277   for (s = sender(&map); !(s.is_java_frame() || s.is_first_frame()); s = s.sender(&map));
 278   return s.is_first_frame();
 279 }
 280 
 281 bool frame::is_first_vthread_frame(JavaThread* thread) const {
 282   return Continuation::is_continuation_enterSpecial(*this)
 283     && Continuation::get_continuation_entry_for_entry_frame(thread, *this)->is_virtual_thread();
 284 }
 285 
 286 bool frame::entry_frame_is_first() const {
 287   return entry_frame_call_wrapper()->is_first_frame();
 288 }
 289 
 290 JavaCallWrapper* frame::entry_frame_call_wrapper_if_safe(JavaThread* thread) const {
 291   JavaCallWrapper** jcw = entry_frame_call_wrapper_addr();
 292   address addr = (address) jcw;
 293 
 294   // addr must be within the usable part of the stack
 295   if (thread->is_in_usable_stack(addr)) {
 296     return *jcw;
 297   }
 298 
 299   return nullptr;
 300 }
 301 
 302 bool frame::is_entry_frame_valid(JavaThread* thread) const {
 303   // Validate the JavaCallWrapper an entry frame must have
 304   address jcw = (address)entry_frame_call_wrapper();
 305   if (!thread->is_in_stack_range_excl(jcw, (address)fp())) {
 306     return false;
 307   }
 308 
 309   // Validate sp saved in the java frame anchor
 310   JavaFrameAnchor* jfa = entry_frame_call_wrapper()->anchor();
 311   return (jfa->last_Java_sp() > sp());
 312 }
 313 
 314 Method* frame::safe_interpreter_frame_method() const {
 315   Method** m_addr = interpreter_frame_method_addr();
 316   if (m_addr == nullptr) {
 317     return nullptr;
 318   }
 319   return (Method*) SafeFetchN((intptr_t*) m_addr, 0);
 320 }
 321 
 322 bool frame::should_be_deoptimized() const {
 323   if (_deopt_state == is_deoptimized ||
 324       !is_compiled_frame() ) return false;
 325   assert(_cb != nullptr && _cb->is_nmethod(), "must be an nmethod");
 326   nmethod* nm = _cb->as_nmethod();
 327   LogTarget(Debug, dependencies) lt;
 328   if (lt.is_enabled()) {
 329     LogStream ls(&lt);
 330     ls.print("checking (%s) ", nm->is_marked_for_deoptimization() ? "true" : "false");
 331     nm->print_value_on(&ls);
 332     ls.cr();
 333   }
 334 
 335   if( !nm->is_marked_for_deoptimization() )
 336     return false;
 337 
 338   // If at the return point, then the frame has already been popped, and
 339   // only the return needs to be executed. Don't deoptimize here.
 340   return !nm->is_at_poll_return(pc());
 341 }
 342 
 343 bool frame::can_be_deoptimized() const {
 344   if (!is_compiled_frame()) return false;
 345   nmethod* nm = _cb->as_nmethod();
 346 
 347   if(!nm->can_be_deoptimized())
 348     return false;
 349 
 350   return !nm->is_at_poll_return(pc());
 351 }
 352 
 353 void frame::deoptimize(JavaThread* thread) {
 354   assert(thread == nullptr
 355          || (thread->frame_anchor()->has_last_Java_frame() &&
 356              thread->frame_anchor()->walkable()), "must be");
 357   // Schedule deoptimization of an nmethod activation with this frame.
 358   assert(_cb != nullptr && _cb->is_nmethod(), "must be");
 359 
 360   // If the call site is a MethodHandle call site use the MH deopt handler.
 361   nmethod* nm = _cb->as_nmethod();
 362   address deopt = nm->deopt_handler_entry();
 363 
 364   NativePostCallNop* inst = nativePostCallNop_at(pc());
 365 
 366   // Save the original pc before we patch in the new one
 367   nm->set_original_pc(this, pc());
 368 
 369 #ifdef COMPILER1
 370   if (nm->is_compiled_by_c1() && nm->method()->has_scalarized_args() &&
 371       pc() < nm->verified_inline_entry_point()) {
 372     // The VEP and VIEP(RO) of C1-compiled methods call into the runtime to buffer scalarized value
 373     // type args. We can't deoptimize at that point because the buffers have not yet been initialized.
 374     // Also, if the method is synchronized, we first need to acquire the lock.
 375     // Don't patch the return pc to delay deoptimization until we enter the method body (the check
 376     // added in LIRGenerator::do_Base will detect the pending deoptimization by checking the original_pc).
 377 #if defined ASSERT && !defined AARCH64   // Stub call site does not look like NativeCall on AArch64
 378     NativeCall* call = nativeCall_before(this->pc());
 379     address dest = call->destination();
 380     assert(dest == Runtime1::entry_for(StubId::c1_buffer_inline_args_no_receiver_id) ||
 381            dest == Runtime1::entry_for(StubId::c1_buffer_inline_args_id), "unexpected safepoint in entry point");
 382 #endif
 383     return;
 384   }
 385 #endif
 386 
 387   patch_pc(thread, deopt);
 388   assert(is_deoptimized_frame(), "must be");
 389 
 390 #ifdef ASSERT
 391   if (thread != nullptr) {
 392     frame check = thread->last_frame();
 393     if (is_older(check.id())) {
 394       RegisterMap map(thread,
 395                       RegisterMap::UpdateMap::skip,
 396                       RegisterMap::ProcessFrames::include,
 397                       RegisterMap::WalkContinuation::skip);
 398       while (id() != check.id()) {
 399         check = check.sender(&map);
 400       }
 401       assert(check.is_deoptimized_frame(), "missed deopt");
 402     }
 403   }
 404 #endif // ASSERT
 405 }
 406 
 407 frame frame::java_sender() const {
 408   RegisterMap map(JavaThread::current(),
 409                   RegisterMap::UpdateMap::skip,
 410                   RegisterMap::ProcessFrames::include,
 411                   RegisterMap::WalkContinuation::skip);
 412   frame s;
 413   for (s = sender(&map); !(s.is_java_frame() || s.is_first_frame()); s = s.sender(&map)) ;
 414   guarantee(s.is_java_frame(), "tried to get caller of first java frame");
 415   return s;
 416 }
 417 
 418 frame frame::real_sender(RegisterMap* map) const {
 419   frame result = sender(map);
 420   while (result.is_runtime_frame() ||
 421          result.is_ignored_frame()) {
 422     result = result.sender(map);
 423   }
 424   return result;
 425 }
 426 
 427 // Interpreter frames
 428 
 429 
 430 Method* frame::interpreter_frame_method() const {
 431   assert(is_interpreted_frame(), "interpreted frame expected");
 432   Method* m = *interpreter_frame_method_addr();
 433   assert(m->is_method(), "not a Method*");
 434   return m;
 435 }
 436 
 437 void frame::interpreter_frame_set_method(Method* method) {
 438   assert(is_interpreted_frame(), "interpreted frame expected");
 439   *interpreter_frame_method_addr() = method;
 440 }
 441 
 442 void frame::interpreter_frame_set_mirror(oop mirror) {
 443   assert(is_interpreted_frame(), "interpreted frame expected");
 444   *interpreter_frame_mirror_addr() = mirror;
 445 }
 446 
 447 jint frame::interpreter_frame_bci() const {
 448   assert(is_interpreted_frame(), "interpreted frame expected");
 449   address bcp = interpreter_frame_bcp();
 450   return interpreter_frame_method()->bci_from(bcp);
 451 }
 452 
 453 address frame::interpreter_frame_bcp() const {
 454   assert(is_interpreted_frame(), "interpreted frame expected");
 455   address bcp = (address)*interpreter_frame_bcp_addr();
 456   return interpreter_frame_method()->bcp_from(bcp);
 457 }
 458 
 459 void frame::interpreter_frame_set_bcp(address bcp) {
 460   assert(is_interpreted_frame(), "interpreted frame expected");
 461   *interpreter_frame_bcp_addr() = (intptr_t)bcp;
 462 }
 463 
 464 address frame::interpreter_frame_mdp() const {
 465   assert(ProfileInterpreter, "must be profiling interpreter");
 466   assert(is_interpreted_frame(), "interpreted frame expected");
 467   return (address)*interpreter_frame_mdp_addr();
 468 }
 469 
 470 void frame::interpreter_frame_set_mdp(address mdp) {
 471   assert(is_interpreted_frame(), "interpreted frame expected");
 472   assert(ProfileInterpreter, "must be profiling interpreter");
 473   *interpreter_frame_mdp_addr() = (intptr_t)mdp;
 474 }
 475 
 476 BasicObjectLock* frame::next_monitor_in_interpreter_frame(BasicObjectLock* current) const {
 477   assert(is_interpreted_frame(), "Not an interpreted frame");
 478 #ifdef ASSERT
 479   interpreter_frame_verify_monitor(current);
 480 #endif
 481   BasicObjectLock* next = (BasicObjectLock*) (((intptr_t*) current) + interpreter_frame_monitor_size());
 482   return next;
 483 }
 484 
 485 BasicObjectLock* frame::previous_monitor_in_interpreter_frame(BasicObjectLock* current) const {
 486   assert(is_interpreted_frame(), "Not an interpreted frame");
 487 #ifdef ASSERT
 488 //   // This verification needs to be checked before being enabled
 489 //   interpreter_frame_verify_monitor(current);
 490 #endif
 491   BasicObjectLock* previous = (BasicObjectLock*) (((intptr_t*) current) - interpreter_frame_monitor_size());
 492   return previous;
 493 }
 494 
 495 // Interpreter locals and expression stack locations.
 496 
 497 intptr_t* frame::interpreter_frame_local_at(int index) const {
 498   const int n = Interpreter::local_offset_in_bytes(index)/wordSize;
 499   intptr_t* first = interpreter_frame_locals();
 500   return &(first[n]);
 501 }
 502 
 503 intptr_t* frame::interpreter_frame_expression_stack_at(jint offset) const {
 504   const int i = offset * interpreter_frame_expression_stack_direction();
 505   const int n = i * Interpreter::stackElementWords;
 506   return &(interpreter_frame_expression_stack()[n]);
 507 }
 508 
 509 jint frame::interpreter_frame_expression_stack_size() const {
 510   // Number of elements on the interpreter expression stack
 511   // Callers should span by stackElementWords
 512   int element_size = Interpreter::stackElementWords;
 513   size_t stack_size = 0;
 514   if (frame::interpreter_frame_expression_stack_direction() < 0) {
 515     stack_size = (interpreter_frame_expression_stack() -
 516                   interpreter_frame_tos_address() + 1)/element_size;
 517   } else {
 518     stack_size = (interpreter_frame_tos_address() -
 519                   interpreter_frame_expression_stack() + 1)/element_size;
 520   }
 521   assert(stack_size <= (size_t)max_jint, "stack size too big");
 522   return (jint)stack_size;
 523 }
 524 
 525 // (frame::interpreter_frame_sender_sp accessor is in frame_<arch>.cpp)
 526 
 527 const char* frame::print_name() const {
 528   if (is_native_frame())      return "Native";
 529   if (is_interpreted_frame()) return "Interpreted";
 530   if (is_compiled_frame()) {
 531     if (is_deoptimized_frame()) return "Deoptimized";
 532     return "Compiled";
 533   }
 534   if (sp() == nullptr)            return "Empty";
 535   return "C";
 536 }
 537 
 538 void frame::print_value_on(outputStream* st) const {
 539   NOT_PRODUCT(address begin = pc()-40;)
 540   NOT_PRODUCT(address end   = nullptr;)
 541 
 542   st->print("%s frame (sp=" INTPTR_FORMAT " unextended sp=" INTPTR_FORMAT, print_name(), p2i(sp()), p2i(unextended_sp()));
 543   if (sp() != nullptr)
 544     st->print(", fp=" INTPTR_FORMAT ", real_fp=" INTPTR_FORMAT ", pc=" INTPTR_FORMAT,
 545               p2i(fp()), p2i(real_fp()), p2i(pc()));
 546   st->print_cr(")");
 547 
 548   if (StubRoutines::contains(pc())) {
 549     StubCodeDesc* desc = StubCodeDesc::desc_for(pc());
 550     st->print("~Stub::%s", desc->name());
 551     NOT_PRODUCT(begin = desc->begin(); end = desc->end();)
 552   } else if (Interpreter::contains(pc())) {
 553     InterpreterCodelet* desc = Interpreter::codelet_containing(pc());
 554     if (desc != nullptr) {
 555       st->print("~");
 556       desc->print_on(st);
 557       NOT_PRODUCT(begin = desc->code_begin(); end = desc->code_end();)
 558     } else {
 559       st->print("~interpreter");
 560     }
 561   }
 562 
 563 #ifndef PRODUCT
 564   if (_cb != nullptr) {
 565     st->print("     ");
 566     _cb->print_value_on(st);
 567     if (end == nullptr) {
 568       begin = _cb->code_begin();
 569       end   = _cb->code_end();
 570     }
 571   }
 572   if (WizardMode && Verbose) Disassembler::decode(begin, end);
 573 #endif
 574 }
 575 
 576 void frame::print_on(outputStream* st) const {
 577   print_value_on(st);
 578   if (is_interpreted_frame()) {
 579     interpreter_frame_print_on(st);
 580   }
 581 }
 582 
 583 void frame::interpreter_frame_print_on(outputStream* st) const {
 584 #ifndef PRODUCT
 585   assert(is_interpreted_frame(), "Not an interpreted frame");
 586   jint i;
 587   for (i = 0; i < interpreter_frame_method()->max_locals(); i++ ) {
 588     intptr_t x = *interpreter_frame_local_at(i);
 589     st->print(" - local  [" INTPTR_FORMAT "]", x);
 590     st->fill_to(23);
 591     st->print_cr("; #%d", i);
 592   }
 593   for (i = interpreter_frame_expression_stack_size() - 1; i >= 0; --i ) {
 594     intptr_t x = *interpreter_frame_expression_stack_at(i);
 595     st->print(" - stack  [" INTPTR_FORMAT "]", x);
 596     st->fill_to(23);
 597     st->print_cr("; #%d", i);
 598   }
 599   // locks for synchronization
 600   for (BasicObjectLock* current = interpreter_frame_monitor_end();
 601        current < interpreter_frame_monitor_begin();
 602        current = next_monitor_in_interpreter_frame(current)) {
 603     st->print(" - obj    [%s", current->obj() == nullptr ? "null" : "");
 604     oop obj = current->obj();
 605     if (obj != nullptr) {
 606       if (!is_heap_frame()) {
 607         obj->print_value_on(st);
 608       } else {
 609         // Might be an invalid oop. We don't have the
 610         // stackChunk to correct it so just print address.
 611         st->print(INTPTR_FORMAT, p2i(obj));
 612       }
 613     }
 614     st->print_cr("]");
 615     st->print(" - lock   [");
 616     if (!is_heap_frame()) {
 617       current->lock()->print_on(st, obj);
 618     }
 619     st->print_cr("]");
 620   }
 621   // monitor
 622   st->print_cr(" - monitor[" INTPTR_FORMAT "]", p2i(interpreter_frame_monitor_begin()));
 623   // bcp
 624   st->print(" - bcp    [" INTPTR_FORMAT "]", p2i(interpreter_frame_bcp()));
 625   st->fill_to(23);
 626   st->print_cr("; @%d", interpreter_frame_bci());
 627   // locals
 628   st->print_cr(" - locals [" INTPTR_FORMAT "]", p2i(interpreter_frame_local_at(0)));
 629   // method
 630   st->print(" - method [" INTPTR_FORMAT "]", p2i(interpreter_frame_method()));
 631   st->fill_to(23);
 632   st->print("; ");
 633   interpreter_frame_method()->print_name(st);
 634   st->cr();
 635 #endif
 636 }
 637 
 638 // Print whether the frame is in the VM or OS indicating a HotSpot problem.
 639 // Otherwise, it's likely a bug in the native library that the Java code calls,
 640 // hopefully indicating where to submit bugs.
 641 void frame::print_C_frame(outputStream* st, char* buf, int buflen, address pc) {
 642   // C/C++ frame
 643   bool in_vm = os::address_is_in_vm(pc);
 644   st->print(in_vm ? "V" : "C");
 645 
 646   int offset;
 647   bool found;
 648 
 649   if (buf == nullptr || buflen < 1) return;
 650   // libname
 651   buf[0] = '\0';
 652   found = os::dll_address_to_library_name(pc, buf, buflen, &offset);
 653   if (found && buf[0] != '\0') {
 654     // skip directory names
 655     const char *p1, *p2;
 656     p1 = buf;
 657     int len = (int)strlen(os::file_separator());
 658     while ((p2 = strstr(p1, os::file_separator())) != nullptr) p1 = p2 + len;
 659     st->print("  [%s+0x%x]", p1, offset);
 660   } else {
 661     st->print("  " PTR_FORMAT, p2i(pc));
 662   }
 663 
 664   found = os::dll_address_to_function_name(pc, buf, buflen, &offset);
 665   if (found) {
 666     st->print("  %s+0x%x", buf, offset);
 667   }
 668 }
 669 
 670 // frame::print_on_error() is called by fatal error handler. Notice that we may
 671 // crash inside this function if stack frame is corrupted. The fatal error
 672 // handler can catch and handle the crash. Here we assume the frame is valid.
 673 //
 674 // First letter indicates type of the frame:
 675 //    J: Java frame (compiled)
 676 //    j: Java frame (interpreted)
 677 //    V: VM frame (C/C++)
 678 //    v: Other frames running VM generated code (e.g. stubs, adapters, etc.)
 679 //    C: C/C++ frame
 680 //
 681 // We don't need detailed frame type as that in frame::print_name(). "C"
 682 // suggests the problem is in user lib; everything else is likely a VM bug.
 683 
 684 void frame::print_on_error(outputStream* st, char* buf, int buflen, bool verbose) const {
 685   if (_cb != nullptr) {
 686     if (Interpreter::contains(pc())) {
 687       Method* m = this->interpreter_frame_method();
 688       if (m != nullptr) {
 689         m->name_and_sig_as_C_string(buf, buflen);
 690         st->print("j  %s", buf);
 691         st->print("+%d", this->interpreter_frame_bci());
 692         ModuleEntry* module = m->method_holder()->module();
 693         if (module->is_named()) {
 694           module->name()->as_C_string(buf, buflen);
 695           st->print(" %s", buf);
 696           if (module->version() != nullptr) {
 697             module->version()->as_C_string(buf, buflen);
 698             st->print("@%s", buf);
 699           }
 700         }
 701       } else {
 702         st->print("j  " PTR_FORMAT, p2i(pc()));
 703       }
 704     } else if (StubRoutines::contains(pc())) {
 705       StubCodeDesc* desc = StubCodeDesc::desc_for(pc());
 706       if (desc != nullptr) {
 707         st->print("v  ~StubRoutines::%s " PTR_FORMAT, desc->name(), p2i(pc()));
 708       } else {
 709         st->print("v  ~StubRoutines::" PTR_FORMAT, p2i(pc()));
 710       }
 711     } else if (_cb->is_buffer_blob()) {
 712       st->print("v  ~BufferBlob::%s " PTR_FORMAT, ((BufferBlob *)_cb)->name(), p2i(pc()));
 713     } else if (_cb->is_nmethod()) {
 714       nmethod* nm = _cb->as_nmethod();
 715       Method* m = nm->method();
 716       if (m != nullptr) {
 717         st->print("J %d%s", nm->compile_id(), (nm->is_osr_method() ? "%" : ""));
 718         st->print(" %s", nm->compiler_name());
 719         m->name_and_sig_as_C_string(buf, buflen);
 720         st->print(" %s", buf);
 721         ModuleEntry* module = m->method_holder()->module();
 722         if (module->is_named()) {
 723           module->name()->as_C_string(buf, buflen);
 724           st->print(" %s", buf);
 725           if (module->version() != nullptr) {
 726             module->version()->as_C_string(buf, buflen);
 727             st->print("@%s", buf);
 728           }
 729         }
 730         st->print(" (%d bytes) @ " PTR_FORMAT " [" PTR_FORMAT "+" INTPTR_FORMAT "]",
 731                   m->code_size(), p2i(_pc), p2i(_cb->code_begin()), _pc - _cb->code_begin());
 732 #if INCLUDE_JVMCI
 733         const char* jvmciName = nm->jvmci_name();
 734         if (jvmciName != nullptr) {
 735           st->print(" (%s)", jvmciName);
 736         }
 737 #endif
 738       } else {
 739         st->print("J  " PTR_FORMAT, p2i(pc()));
 740       }
 741     } else if (_cb->is_runtime_stub()) {
 742       st->print("v  ~RuntimeStub::%s " PTR_FORMAT, ((RuntimeStub *)_cb)->name(), p2i(pc()));
 743     } else if (_cb->is_deoptimization_stub()) {
 744       st->print("v  ~DeoptimizationBlob " PTR_FORMAT, p2i(pc()));
 745     } else if (_cb->is_exception_stub()) {
 746       st->print("v  ~ExceptionBlob " PTR_FORMAT, p2i(pc()));
 747     } else if (_cb->is_safepoint_stub()) {
 748       st->print("v  ~SafepointBlob " PTR_FORMAT, p2i(pc()));
 749     } else if (_cb->is_adapter_blob()) {
 750       st->print("v  ~AdapterBlob " PTR_FORMAT, p2i(pc()));
 751     } else if (_cb->is_vtable_blob()) {
 752       st->print("v  ~VtableBlob " PTR_FORMAT, p2i(pc()));
 753     } else if (_cb->is_method_handles_adapter_blob()) {
 754       st->print("v  ~MethodHandlesAdapterBlob " PTR_FORMAT, p2i(pc()));
 755     } else if (_cb->is_uncommon_trap_stub()) {
 756       st->print("v  ~UncommonTrapBlob " PTR_FORMAT, p2i(pc()));
 757     } else if (_cb->is_upcall_stub()) {
 758       st->print("v  ~UpcallStub::%s " PTR_FORMAT, _cb->name(), p2i(pc()));
 759     } else {
 760       st->print("v  blob " PTR_FORMAT, p2i(pc()));
 761     }
 762   } else {
 763     print_C_frame(st, buf, buflen, pc());
 764   }
 765 }
 766 
 767 
 768 /*
 769   The interpreter_frame_expression_stack_at method in the case of SPARC needs the
 770   max_stack value of the method in order to compute the expression stack address.
 771   It uses the Method* in order to get the max_stack value but during GC this
 772   Method* value saved on the frame is changed by reverse_and_push and hence cannot
 773   be used. So we save the max_stack value in the FrameClosure object and pass it
 774   down to the interpreter_frame_expression_stack_at method
 775 */
 776 class InterpreterFrameClosure : public OffsetClosure {
 777  private:
 778   const frame* _fr;
 779   OopClosure*  _f;
 780   int          _max_locals;
 781   int          _max_stack;
 782 
 783  public:
 784   InterpreterFrameClosure(const frame* fr, int max_locals, int max_stack,
 785                           OopClosure* f, BufferedValueClosure* bvt_f) {
 786     _fr         = fr;
 787     _max_locals = max_locals;
 788     _max_stack  = max_stack;
 789     _f          = f;
 790   }
 791 
 792   void offset_do(int offset) {
 793     oop* addr;
 794     if (offset < _max_locals) {
 795       addr = (oop*) _fr->interpreter_frame_local_at(offset);
 796       assert((intptr_t*)addr >= _fr->sp(), "must be inside the frame");
 797       if (_f != nullptr) {
 798         _f->do_oop(addr);
 799       }
 800     } else {
 801       addr = (oop*) _fr->interpreter_frame_expression_stack_at((offset - _max_locals));
 802       // In case of exceptions, the expression stack is invalid and the esp will be reset to express
 803       // this condition. Therefore, we call f only if addr is 'inside' the stack (i.e., addr >= esp for Intel).
 804       bool in_stack;
 805       if (frame::interpreter_frame_expression_stack_direction() > 0) {
 806         in_stack = (intptr_t*)addr <= _fr->interpreter_frame_tos_address();
 807       } else {
 808         in_stack = (intptr_t*)addr >= _fr->interpreter_frame_tos_address();
 809       }
 810       if (in_stack) {
 811         if (_f != nullptr) {
 812           _f->do_oop(addr);
 813         }
 814       }
 815     }
 816   }
 817 };
 818 
 819 
 820 class InterpretedArgumentOopFinder: public SignatureIterator {
 821  private:
 822   OopClosure*  _f;             // Closure to invoke
 823   int          _offset;        // TOS-relative offset, decremented with each argument
 824   bool         _has_receiver;  // true if the callee has a receiver
 825   const frame* _fr;
 826 
 827   friend class SignatureIterator;  // so do_parameters_on can call do_type
 828   void do_type(BasicType type) {
 829     _offset -= parameter_type_word_count(type);
 830     if (is_reference_type(type)) oop_offset_do();
 831    }
 832 
 833   void oop_offset_do() {
 834     oop* addr;
 835     addr = (oop*)_fr->interpreter_frame_tos_at(_offset);
 836     _f->do_oop(addr);
 837   }
 838 
 839  public:
 840   InterpretedArgumentOopFinder(Symbol* signature, bool has_receiver, const frame* fr, OopClosure* f) : SignatureIterator(signature), _has_receiver(has_receiver) {
 841     // compute size of arguments
 842     int args_size = ArgumentSizeComputer(signature).size() + (has_receiver ? 1 : 0);
 843     assert(!fr->is_interpreted_frame() ||
 844            args_size <= fr->interpreter_frame_expression_stack_size(),
 845             "args cannot be on stack anymore");
 846     // initialize InterpretedArgumentOopFinder
 847     _f         = f;
 848     _fr        = fr;
 849     _offset    = args_size;
 850   }
 851 
 852   void oops_do() {
 853     if (_has_receiver) {
 854       --_offset;
 855       oop_offset_do();
 856     }
 857     do_parameters_on(this);
 858   }
 859 };
 860 
 861 
 862 // Entry frame has following form (n arguments)
 863 //         +-----------+
 864 //   sp -> |  last arg |
 865 //         +-----------+
 866 //         :    :::    :
 867 //         +-----------+
 868 // (sp+n)->|  first arg|
 869 //         +-----------+
 870 
 871 
 872 
 873 // visits and GC's all the arguments in entry frame
 874 class EntryFrameOopFinder: public SignatureIterator {
 875  private:
 876   bool         _is_static;
 877   int          _offset;
 878   const frame* _fr;
 879   OopClosure*  _f;
 880 
 881   friend class SignatureIterator;  // so do_parameters_on can call do_type
 882   void do_type(BasicType type) {
 883     // decrement offset before processing the type
 884     _offset -= parameter_type_word_count(type);
 885     assert (_offset >= 0, "illegal offset");
 886     if (is_reference_type(type))  oop_at_offset_do(_offset);
 887  }
 888 
 889   void oop_at_offset_do(int offset) {
 890     assert (offset >= 0, "illegal offset");
 891     oop* addr = (oop*) _fr->entry_frame_argument_at(offset);
 892     _f->do_oop(addr);
 893   }
 894 
 895  public:
 896   EntryFrameOopFinder(const frame* frame, Symbol* signature, bool is_static) : SignatureIterator(signature) {
 897     _f = nullptr; // will be set later
 898     _fr = frame;
 899     _is_static = is_static;
 900     _offset = ArgumentSizeComputer(signature).size();  // pre-decremented down to zero
 901   }
 902 
 903   void arguments_do(OopClosure* f) {
 904     _f = f;
 905     if (!_is_static)  oop_at_offset_do(_offset); // do the receiver
 906     do_parameters_on(this);
 907   }
 908 
 909 };
 910 
 911 oop* frame::interpreter_callee_receiver_addr(Symbol* signature) {
 912   ArgumentSizeComputer asc(signature);
 913   int size = asc.size();
 914   return (oop *)interpreter_frame_tos_at(size);
 915 }
 916 
 917 oop frame::interpreter_callee_receiver(Symbol* signature) {
 918   return *interpreter_callee_receiver_addr(signature);
 919 }
 920 
 921 template <typename RegisterMapT>
 922 void frame::oops_interpreted_do(OopClosure* f, const RegisterMapT* map, bool query_oop_map_cache) const {
 923   assert(is_interpreted_frame(), "Not an interpreted frame");
 924   Thread *thread = Thread::current();
 925   methodHandle m (thread, interpreter_frame_method());
 926   jint      bci = interpreter_frame_bci();
 927 
 928   assert(!Universe::heap()->is_in(m()),
 929           "must be valid oop");
 930   assert(m->is_method(), "checking frame value");
 931   assert((m->is_native() && bci == 0)  ||
 932          (!m->is_native() && bci >= 0 && bci < m->code_size()),
 933          "invalid bci value");
 934 
 935   // Handle the monitor elements in the activation
 936   for (
 937     BasicObjectLock* current = interpreter_frame_monitor_end();
 938     current < interpreter_frame_monitor_begin();
 939     current = next_monitor_in_interpreter_frame(current)
 940   ) {
 941 #ifdef ASSERT
 942     interpreter_frame_verify_monitor(current);
 943 #endif
 944     current->oops_do(f);
 945   }
 946 
 947   if (m->is_native()) {
 948     f->do_oop(interpreter_frame_temp_oop_addr());
 949   }
 950 
 951   // The method pointer in the frame might be the only path to the method's
 952   // klass, and the klass needs to be kept alive while executing. The GCs
 953   // don't trace through method pointers, so the mirror of the method's klass
 954   // is installed as a GC root.
 955   f->do_oop(interpreter_frame_mirror_addr());
 956 
 957   int max_locals = m->is_native() ? m->size_of_parameters() : m->max_locals();
 958 
 959   // Process a callee's arguments if we are at a call site
 960   // (i.e., if we are at an invoke bytecode)
 961   // This is used sometimes for calling into the VM, not for another
 962   // interpreted or compiled frame.
 963   if (!m->is_native() && map != nullptr && map->include_argument_oops()) {
 964     Bytecode_invoke call = Bytecode_invoke_check(m, bci);
 965     if (call.is_valid() && interpreter_frame_expression_stack_size() > 0) {
 966       ResourceMark rm(thread);  // is this right ???
 967       Symbol* signature = call.signature();
 968       bool has_receiver = call.has_receiver();
 969       // We are at a call site & the expression stack is not empty
 970       // so we might have callee arguments we need to process.
 971       oops_interpreted_arguments_do(signature, has_receiver, f);
 972     }
 973   }
 974 
 975   InterpreterFrameClosure blk(this, max_locals, m->max_stack(), f, nullptr);
 976 
 977   // process locals & expression stack
 978   InterpreterOopMap mask;
 979   if (query_oop_map_cache) {
 980     m->mask_for(m, bci, &mask);
 981   } else {
 982     OopMapCache::compute_one_oop_map(m, bci, &mask);
 983   }
 984   mask.iterate_oop(&blk);
 985 }
 986 
 987 void frame::buffered_values_interpreted_do(BufferedValueClosure* f) {
 988   assert(is_interpreted_frame(), "Not an interpreted frame");
 989   Thread *thread = Thread::current();
 990   methodHandle m (thread, interpreter_frame_method());
 991   jint      bci = interpreter_frame_bci();
 992 
 993   assert(m->is_method(), "checking frame value");
 994   assert(!m->is_native() && bci >= 0 && bci < m->code_size(),
 995          "invalid bci value");
 996 
 997   InterpreterFrameClosure blk(this, m->max_locals(), m->max_stack(), nullptr, f);
 998 
 999   // process locals & expression stack
1000   InterpreterOopMap mask;
1001   m->mask_for(bci, &mask);
1002   mask.iterate_oop(&blk);
1003 }
1004 
1005 template void frame::oops_interpreted_do(OopClosure* f, const RegisterMap* map, bool query_oop_map_cache) const;
1006 template void frame::oops_interpreted_do(OopClosure* f, const SmallRegisterMapNoArgs* map, bool query_oop_map_cache) const;
1007 template void frame::oops_interpreted_do(OopClosure* f, const SmallRegisterMapWithArgs* map, bool query_oop_map_cache) const;
1008 
1009 void frame::oops_interpreted_arguments_do(Symbol* signature, bool has_receiver, OopClosure* f) const {
1010   InterpretedArgumentOopFinder finder(signature, has_receiver, this, f);
1011   finder.oops_do();
1012 }
1013 
1014 void frame::oops_nmethod_do(OopClosure* f, NMethodClosure* cf, DerivedOopClosure* df, DerivedPointerIterationMode derived_mode, const RegisterMap* reg_map) const {
1015   assert(_cb != nullptr, "sanity check");
1016   assert((oop_map() == nullptr) == (_cb->oop_maps() == nullptr), "frame and _cb must agree that oopmap is set or not");
1017   if (oop_map() != nullptr) {
1018     if (df != nullptr) {
1019       _oop_map->oops_do(this, reg_map, f, df);
1020     } else {
1021       _oop_map->oops_do(this, reg_map, f, derived_mode);
1022     }
1023 
1024     // Preserve potential arguments for a callee. We handle this by dispatching
1025     // on the codeblob. For c2i, we do
1026     if (reg_map->include_argument_oops() && _cb->is_nmethod()) {
1027       // Only nmethod preserves outgoing arguments at call.
1028       _cb->as_nmethod()->preserve_callee_argument_oops(*this, reg_map, f);
1029     }
1030   }
1031   // In cases where perm gen is collected, GC will want to mark
1032   // oops referenced from nmethods active on thread stacks so as to
1033   // prevent them from being collected. However, this visit should be
1034   // restricted to certain phases of the collection only. The
1035   // closure decides how it wants nmethods to be traced.
1036   if (cf != nullptr && _cb->is_nmethod())
1037     cf->do_nmethod(_cb->as_nmethod());
1038 }
1039 
1040 class CompiledArgumentOopFinder: public SignatureIterator {
1041  protected:
1042   OopClosure*     _f;
1043   int             _offset;        // the current offset, incremented with each argument
1044   bool            _has_receiver;  // true if the callee has a receiver
1045   bool            _has_appendix;  // true if the call has an appendix
1046   frame           _fr;
1047   RegisterMap*    _reg_map;
1048   int             _arg_size;
1049   VMRegPair*      _regs;        // VMReg list of arguments
1050 
1051   friend class SignatureIterator;  // so do_parameters_on can call do_type
1052   void do_type(BasicType type) {
1053     if (is_reference_type(type))  handle_oop_offset();
1054     _offset += parameter_type_word_count(type);
1055   }
1056 
1057   virtual void handle_oop_offset() {
1058     // Extract low order register number from register array.
1059     // In LP64-land, the high-order bits are valid but unhelpful.
1060     assert(_offset < _arg_size, "out of bounds");
1061     VMReg reg = _regs[_offset].first();
1062     oop *loc = _fr.oopmapreg_to_oop_location(reg, _reg_map);
1063   #ifdef ASSERT
1064     if (loc == nullptr) {
1065       if (_reg_map->should_skip_missing()) {
1066         return;
1067       }
1068       tty->print_cr("Error walking frame oops:");
1069       _fr.print_on(tty);
1070       assert(loc != nullptr, "missing register map entry reg: %d %s loc: " INTPTR_FORMAT, reg->value(), reg->name(), p2i(loc));
1071     }
1072   #endif
1073     _f->do_oop(loc);
1074   }
1075 
1076  public:
1077   CompiledArgumentOopFinder(Symbol* signature, bool has_receiver, bool has_appendix, OopClosure* f, frame fr, const RegisterMap* reg_map)
1078     : SignatureIterator(signature) {
1079 
1080     // initialize CompiledArgumentOopFinder
1081     _f         = f;
1082     _offset    = 0;
1083     _has_receiver = has_receiver;
1084     _has_appendix = has_appendix;
1085     _fr        = fr;
1086     _reg_map   = (RegisterMap*)reg_map;
1087     _regs = SharedRuntime::find_callee_arguments(signature, has_receiver, has_appendix, &_arg_size);
1088   }
1089 
1090   void oops_do() {
1091     if (_has_receiver) {
1092       handle_oop_offset();
1093       _offset++;
1094     }
1095     do_parameters_on(this);
1096     if (_has_appendix) {
1097       handle_oop_offset();
1098       _offset++;
1099     }
1100   }
1101 };
1102 
1103 void frame::oops_compiled_arguments_do(Symbol* signature, bool has_receiver, bool has_appendix,
1104                                        const RegisterMap* reg_map, OopClosure* f) const {
1105   // ResourceMark rm;
1106   CompiledArgumentOopFinder finder(signature, has_receiver, has_appendix, f, *this, reg_map);
1107   finder.oops_do();
1108 }
1109 
1110 // Get receiver out of callers frame, i.e. find parameter 0 in callers
1111 // frame.  Consult ADLC for where parameter 0 is to be found.  Then
1112 // check local reg_map for it being a callee-save register or argument
1113 // register, both of which are saved in the local frame.  If not found
1114 // there, it must be an in-stack argument of the caller.
1115 // Note: caller.sp() points to callee-arguments
1116 oop frame::retrieve_receiver(RegisterMap* reg_map) {
1117   frame caller = *this;
1118 
1119   // First consult the ADLC on where it puts parameter 0 for this signature.
1120   VMReg reg = SharedRuntime::name_for_receiver();
1121   oop* oop_adr = caller.oopmapreg_to_oop_location(reg, reg_map);
1122   if (oop_adr == nullptr) {
1123     guarantee(oop_adr != nullptr, "bad register save location");
1124     return nullptr;
1125   }
1126   oop r = *oop_adr;
1127   assert(Universe::heap()->is_in_or_null(r), "bad receiver: " INTPTR_FORMAT " (%zd)", p2i(r), p2i(r));
1128   return r;
1129 }
1130 
1131 
1132 BasicLock* frame::get_native_monitor() const {
1133   nmethod* nm = (nmethod*)_cb;
1134   assert(_cb != nullptr && _cb->is_nmethod() && nm->method()->is_native(),
1135          "Should not call this unless it's a native nmethod");
1136   int byte_offset = in_bytes(nm->native_basic_lock_sp_offset());
1137   assert(byte_offset >= 0, "should not see invalid offset");
1138   return (BasicLock*) &sp()[byte_offset / wordSize];
1139 }
1140 
1141 oop frame::get_native_receiver() const {
1142   nmethod* nm = (nmethod*)_cb;
1143   assert(_cb != nullptr && _cb->is_nmethod() && nm->method()->is_native(),
1144          "Should not call this unless it's a native nmethod");
1145   int byte_offset = in_bytes(nm->native_receiver_sp_offset());
1146   assert(byte_offset >= 0, "should not see invalid offset");
1147   oop owner = ((oop*) sp())[byte_offset / wordSize];
1148   assert( Universe::heap()->is_in(owner), "bad receiver" );
1149   return owner;
1150 }
1151 
1152 void frame::oops_entry_do(OopClosure* f, const RegisterMap* map) const {
1153   assert(map != nullptr, "map must be set");
1154   if (map->include_argument_oops()) {
1155     // must collect argument oops, as nobody else is doing it
1156     Thread *thread = Thread::current();
1157     methodHandle m (thread, entry_frame_call_wrapper()->callee_method());
1158     EntryFrameOopFinder finder(this, m->signature(), m->is_static());
1159     finder.arguments_do(f);
1160   }
1161   // Traverse the Handle Block saved in the entry frame
1162   entry_frame_call_wrapper()->oops_do(f);
1163 }
1164 
1165 void frame::oops_upcall_do(OopClosure* f, const RegisterMap* map) const {
1166   assert(map != nullptr, "map must be set");
1167   if (map->include_argument_oops()) {
1168     // Upcall stubs call a MethodHandle impl method of which only the receiver
1169     // is ever an oop.
1170     // Currently we should not be able to get here, since there are no
1171     // safepoints in the one resolve stub we can get into (handle_wrong_method)
1172     // Leave this here as a trap in case we ever do:
1173     ShouldNotReachHere(); // not implemented
1174   }
1175   _cb->as_upcall_stub()->oops_do(f, *this);
1176 }
1177 
1178 bool frame::is_deoptimized_frame() const {
1179   assert(_deopt_state != unknown, "not answerable");
1180   if (_deopt_state == is_deoptimized) {
1181     return true;
1182   }
1183 
1184   /* This method only checks if the frame is deoptimized
1185    * as in return address being patched.
1186    * It doesn't care if the OP that we return to is a
1187    * deopt instruction */
1188   /*if (_cb != nullptr && _cb->is_nmethod()) {
1189     return NativeDeoptInstruction::is_deopt_at(_pc);
1190   }*/
1191   return false;
1192 }
1193 
1194 void frame::oops_do_internal(OopClosure* f, NMethodClosure* cf,
1195                              DerivedOopClosure* df, DerivedPointerIterationMode derived_mode,
1196                              const RegisterMap* map, bool use_interpreter_oop_map_cache) const {
1197 #ifndef PRODUCT
1198   // simulate GC crash here to dump java thread in error report
1199   guarantee(!CrashGCForDumpingJavaThread, "");
1200 #endif
1201   if (is_interpreted_frame()) {
1202     oops_interpreted_do(f, map, use_interpreter_oop_map_cache);
1203   } else if (is_entry_frame()) {
1204     oops_entry_do(f, map);
1205   } else if (is_upcall_stub_frame()) {
1206     oops_upcall_do(f, map);
1207   } else if (CodeCache::contains(pc())) {
1208     oops_nmethod_do(f, cf, df, derived_mode, map);
1209   } else {
1210     ShouldNotReachHere();
1211   }
1212 }
1213 
1214 void frame::nmethod_do(NMethodClosure* cf) const {
1215   if (_cb != nullptr && _cb->is_nmethod()) {
1216     cf->do_nmethod(_cb->as_nmethod());
1217   }
1218 }
1219 
1220 
1221 // Call f closure on the interpreted Method*s in the stack.
1222 void frame::metadata_do(MetadataClosure* f) const {
1223   ResourceMark rm;
1224   if (is_interpreted_frame()) {
1225     Method* m = this->interpreter_frame_method();
1226     assert(m != nullptr, "expecting a method in this frame");
1227     f->do_metadata(m);
1228   }
1229 }
1230 
1231 void frame::verify(const RegisterMap* map) const {
1232 #ifndef PRODUCT
1233   if (TraceCodeBlobStacks) {
1234     tty->print_cr("*** verify");
1235     print_on(tty);
1236   }
1237 #endif
1238 
1239   // for now make sure receiver type is correct
1240   if (is_interpreted_frame()) {
1241     Method* method = interpreter_frame_method();
1242     guarantee(method->is_method(), "method is wrong in frame::verify");
1243     if (!method->is_static()) {
1244       // fetch the receiver
1245       oop* p = (oop*) interpreter_frame_local_at(0);
1246       // make sure we have the right receiver type
1247     }
1248   }
1249 #if COMPILER2_OR_JVMCI
1250   assert(DerivedPointerTable::is_empty(), "must be empty before verify");
1251 #endif
1252 
1253   if (map->update_map()) { // The map has to be up-to-date for the current frame
1254     oops_do_internal(&VerifyOopClosure::verify_oop, nullptr, nullptr, DerivedPointerIterationMode::_ignore, map, false);
1255   }
1256 }
1257 
1258 
1259 #ifdef ASSERT
1260 bool frame::verify_return_pc(address x) {
1261 #ifdef TARGET_ARCH_aarch64
1262   if (!pauth_ptr_is_raw(x)) {
1263     return false;
1264   }
1265 #endif
1266   if (StubRoutines::returns_to_call_stub(x)) {
1267     return true;
1268   }
1269   if (CodeCache::contains(x)) {
1270     return true;
1271   }
1272   if (Interpreter::contains(x)) {
1273     return true;
1274   }
1275   return false;
1276 }
1277 #endif
1278 
1279 #ifdef ASSERT
1280 void frame::interpreter_frame_verify_monitor(BasicObjectLock* value) const {
1281   assert(is_interpreted_frame(), "Not an interpreted frame");
1282   // verify that the value is in the right part of the frame
1283   address low_mark  = (address) interpreter_frame_monitor_end();
1284   address high_mark = (address) interpreter_frame_monitor_begin();
1285   address current   = (address) value;
1286 
1287   const int monitor_size = frame::interpreter_frame_monitor_size();
1288   guarantee((high_mark - current) % monitor_size  ==  0         , "Misaligned top of BasicObjectLock*");
1289   guarantee( high_mark > current                                , "Current BasicObjectLock* higher than high_mark");
1290 
1291   guarantee((current - low_mark) % monitor_size  ==  0         , "Misaligned bottom of BasicObjectLock*");
1292   guarantee( current >= low_mark                               , "Current BasicObjectLock* below than low_mark");
1293 }
1294 #endif
1295 
1296 #ifndef PRODUCT
1297 
1298 // Returns true iff the address p is readable and *(intptr_t*)p != errvalue
1299 extern "C" bool dbg_is_safe(const void* p, intptr_t errvalue);
1300 
1301 class FrameValuesOopClosure: public OopClosure, public DerivedOopClosure {
1302 private:
1303   GrowableArray<oop*>* _oops;
1304   GrowableArray<narrowOop*>* _narrow_oops;
1305   GrowableArray<derived_base*>* _base;
1306   GrowableArray<derived_pointer*>* _derived;
1307   NoSafepointVerifier nsv;
1308 
1309 public:
1310   FrameValuesOopClosure() {
1311     _oops = new (mtThread) GrowableArray<oop*>(100, mtThread);
1312     _narrow_oops = new (mtThread) GrowableArray<narrowOop*>(100, mtThread);
1313     _base = new (mtThread) GrowableArray<derived_base*>(100, mtThread);
1314     _derived = new (mtThread) GrowableArray<derived_pointer*>(100, mtThread);
1315   }
1316   ~FrameValuesOopClosure() {
1317     delete _oops;
1318     delete _narrow_oops;
1319     delete _base;
1320     delete _derived;
1321   }
1322 
1323   virtual void do_oop(oop* p) override { _oops->push(p); }
1324   virtual void do_oop(narrowOop* p) override { _narrow_oops->push(p); }
1325   virtual void do_derived_oop(derived_base* base_loc, derived_pointer* derived_loc) override {
1326     _base->push(base_loc);
1327     _derived->push(derived_loc);
1328   }
1329 
1330   bool is_good(oop* p) {
1331     return *p == nullptr || (dbg_is_safe(*p, -1) && dbg_is_safe((*p)->klass(), -1) && oopDesc::is_oop_or_null(*p));
1332   }
1333   void describe(FrameValues& values, int frame_no) {
1334     for (int i = 0; i < _oops->length(); i++) {
1335       oop* p = _oops->at(i);
1336       values.describe(frame_no, (intptr_t*)p, err_msg("oop%s for #%d", is_good(p) ? "" : " (BAD)", frame_no));
1337     }
1338     for (int i = 0; i < _narrow_oops->length(); i++) {
1339       narrowOop* p = _narrow_oops->at(i);
1340       // we can't check for bad compressed oops, as decoding them might crash
1341       values.describe(frame_no, (intptr_t*)p, err_msg("narrow oop for #%d", frame_no));
1342     }
1343     assert(_base->length() == _derived->length(), "should be the same");
1344     for (int i = 0; i < _base->length(); i++) {
1345       derived_base* base = _base->at(i);
1346       derived_pointer* derived = _derived->at(i);
1347       values.describe(frame_no, (intptr_t*)derived, err_msg("derived pointer (base: " INTPTR_FORMAT ") for #%d", p2i(base), frame_no));
1348     }
1349   }
1350 };
1351 
1352 class FrameValuesOopMapClosure: public OopMapClosure {
1353 private:
1354   const frame* _fr;
1355   const RegisterMap* _reg_map;
1356   FrameValues& _values;
1357   int _frame_no;
1358 
1359 public:
1360   FrameValuesOopMapClosure(const frame* fr, const RegisterMap* reg_map, FrameValues& values, int frame_no)
1361    : _fr(fr), _reg_map(reg_map), _values(values), _frame_no(frame_no) {}
1362 
1363   virtual void do_value(VMReg reg, OopMapValue::oop_types type) override {
1364     intptr_t* p = (intptr_t*)_fr->oopmapreg_to_location(reg, _reg_map);
1365     if (p != nullptr && (((intptr_t)p & WordAlignmentMask) == 0)) {
1366       const char* type_name = nullptr;
1367       switch(type) {
1368         case OopMapValue::oop_value:          type_name = "oop";          break;
1369         case OopMapValue::narrowoop_value:    type_name = "narrow oop";   break;
1370         case OopMapValue::callee_saved_value: type_name = "callee-saved"; break;
1371         case OopMapValue::derived_oop_value:  type_name = "derived";      break;
1372         // case OopMapValue::live_value:         type_name = "live";         break;
1373         default: break;
1374       }
1375       if (type_name != nullptr) {
1376         _values.describe(_frame_no, p, err_msg("%s for #%d", type_name, _frame_no));
1377       }
1378     }
1379   }
1380 };
1381 
1382 // callers need a ResourceMark because of name_and_sig_as_C_string() usage,
1383 // RA allocated string is returned to the caller
1384 void frame::describe(FrameValues& values, int frame_no, const RegisterMap* reg_map, bool top) {
1385   // boundaries: sp and the 'real' frame pointer
1386   values.describe(-1, sp(), err_msg("sp for #%d", frame_no), 0);
1387   if (top) {
1388     values.describe(-1, sp() - 1, err_msg("sp[-1] for #%d", frame_no), 0);
1389     values.describe(-1, sp() - 2, err_msg("sp[-2] for #%d", frame_no), 0);
1390   }
1391 
1392   intptr_t* frame_pointer = real_fp(); // Note: may differ from fp()
1393 
1394   // print frame info at the highest boundary
1395   intptr_t* info_address = MAX2(sp(), frame_pointer);
1396 
1397   if (info_address != frame_pointer) {
1398     // print frame_pointer explicitly if not marked by the frame info
1399     values.describe(-1, frame_pointer, err_msg("frame pointer for #%d", frame_no), 1);
1400   }
1401 
1402   if (is_entry_frame() || is_compiled_frame() || is_interpreted_frame() || is_native_frame()) {
1403     // Label values common to most frames
1404     values.describe(-1, unextended_sp(), err_msg("unextended_sp for #%d", frame_no), 0);
1405   }
1406 
1407   if (is_interpreted_frame()) {
1408     Method* m = interpreter_frame_method();
1409     int bci = interpreter_frame_bci();
1410     InterpreterCodelet* desc = Interpreter::codelet_containing(pc());
1411 
1412     // Label the method and current bci
1413     values.describe(-1, info_address,
1414                     FormatBuffer<1024>("#%d method %s @ %d", frame_no, m->name_and_sig_as_C_string(), bci), 3);
1415     if (desc != nullptr) {
1416       values.describe(-1, info_address, err_msg("- %s codelet: %s",
1417         desc->bytecode()    >= 0    ? Bytecodes::name(desc->bytecode()) : "",
1418         desc->description() != nullptr ? desc->description()               : "?"), 2);
1419     }
1420     values.describe(-1, info_address,
1421                     err_msg("- %d locals %d max stack", m->max_locals(), m->max_stack()), 2);
1422     // return address will be emitted by caller in describe_pd
1423     // values.describe(frame_no, (intptr_t*)sender_pc_addr(), Continuation::is_return_barrier_entry(*sender_pc_addr()) ? "return address (return barrier)" : "return address");
1424 
1425     if (m->max_locals() > 0) {
1426       intptr_t* l0 = interpreter_frame_local_at(0);
1427       intptr_t* ln = interpreter_frame_local_at(m->max_locals() - 1);
1428       values.describe(-1, MAX2(l0, ln), err_msg("locals for #%d", frame_no), 2);
1429       // Report each local and mark as owned by this frame
1430       for (int l = 0; l < m->max_locals(); l++) {
1431         intptr_t* l0 = interpreter_frame_local_at(l);
1432         values.describe(frame_no, l0, err_msg("local %d", l), 1);
1433       }
1434     }
1435 
1436     if (interpreter_frame_monitor_begin() != interpreter_frame_monitor_end()) {
1437       values.describe(frame_no, (intptr_t*)interpreter_frame_monitor_begin(), "monitors begin");
1438       values.describe(frame_no, (intptr_t*)interpreter_frame_monitor_end(), "monitors end");
1439     }
1440 
1441     // Compute the actual expression stack size
1442     InterpreterOopMap mask;
1443     OopMapCache::compute_one_oop_map(methodHandle(Thread::current(), m), bci, &mask);
1444     intptr_t* tos = nullptr;
1445     // Report each stack element and mark as owned by this frame
1446     for (int e = 0; e < mask.expression_stack_size(); e++) {
1447       tos = MAX2(tos, interpreter_frame_expression_stack_at(e));
1448       values.describe(frame_no, interpreter_frame_expression_stack_at(e),
1449                       err_msg("stack %d", e), 1);
1450     }
1451     if (tos != nullptr) {
1452       values.describe(-1, tos, err_msg("expression stack for #%d", frame_no), 2);
1453     }
1454 
1455     if (reg_map != nullptr) {
1456       FrameValuesOopClosure oopsFn;
1457       oops_do(&oopsFn, nullptr, &oopsFn, reg_map);
1458       oopsFn.describe(values, frame_no);
1459     }
1460   } else if (is_entry_frame()) {
1461     // For now just label the frame
1462     values.describe(-1, info_address, err_msg("#%d entry frame", frame_no), 2);
1463   } else if (is_compiled_frame()) {
1464     // For now just label the frame
1465     nmethod* nm = cb()->as_nmethod();
1466     values.describe(-1, info_address,
1467                     FormatBuffer<1024>("#%d nmethod (%s %d) " INTPTR_FORMAT " for method J %s%s", frame_no,
1468                                        nm->is_compiled_by_c1() ? "c1" : "c2", nm->frame_size(), p2i(nm),
1469                                        nm->method()->name_and_sig_as_C_string(),
1470                                        (_deopt_state == is_deoptimized) ?
1471                                        " (deoptimized)" :
1472                                        ((_deopt_state == unknown) ? " (state unknown)" : "")),
1473                     3);
1474 
1475     { // mark arguments (see nmethod::print_nmethod_labels)
1476       Method* m = nm->method();
1477 
1478       CompiledEntrySignature ces(m);
1479       ces.compute_calling_conventions(false);
1480       const GrowableArray<SigEntry>* sig_cc = nm->is_compiled_by_c2() ? ces.sig_cc() : ces.sig();
1481       const VMRegPair* regs = nm->is_compiled_by_c2() ? ces.regs_cc() : ces.regs();
1482 
1483       int stack_slot_offset = nm->frame_size() * wordSize; // offset, in bytes, to caller sp
1484       int out_preserve = SharedRuntime::out_preserve_stack_slots();
1485       int sig_index = 0;
1486       int arg_index = (m->is_static() ? 0 : -1);
1487       for (ExtendedSignature sig = ExtendedSignature(sig_cc, SigEntryFilter()); !sig.at_end(); ++sig) {
1488         bool at_this = (arg_index == -1);
1489         BasicType t = (*sig)._bt;
1490         VMReg fst = regs[sig_index].first();
1491         if (fst->is_stack()) {
1492           assert(((int)fst->reg2stack()) >= 0, "reg2stack: %d", fst->reg2stack());
1493           int offset = (fst->reg2stack() + out_preserve) * VMRegImpl::stack_slot_size + stack_slot_offset;
1494           intptr_t* stack_address = (intptr_t*)((address)unextended_sp() + offset);
1495           if (at_this) {
1496             values.describe(frame_no, stack_address, err_msg("this for #%d", frame_no), 1);
1497           } else {
1498             values.describe(frame_no, stack_address, err_msg("param %d %s for #%d", arg_index, type2name(t), frame_no), 1);
1499           }
1500         }
1501         sig_index += type2size[t];
1502         arg_index += 1;
1503       }
1504     }
1505 
1506     if (reg_map != nullptr && is_java_frame()) {
1507       int scope_no = 0;
1508       for (ScopeDesc* scope = nm->scope_desc_at(pc()); scope != nullptr; scope = scope->sender(), scope_no++) {
1509         Method* m = scope->method();
1510         int  bci = scope->bci();
1511         values.describe(-1, info_address, err_msg("- #%d scope %s @ %d", scope_no, m->name_and_sig_as_C_string(), bci), 2);
1512 
1513         { // mark locals
1514           GrowableArray<ScopeValue*>* scvs = scope->locals();
1515           int scvs_length = scvs != nullptr ? scvs->length() : 0;
1516           for (int i = 0; i < scvs_length; i++) {
1517             intptr_t* stack_address = (intptr_t*)StackValue::stack_value_address(this, reg_map, scvs->at(i));
1518             if (stack_address != nullptr) {
1519               values.describe(frame_no, stack_address, err_msg("local %d for #%d (scope %d)", i, frame_no, scope_no), 1);
1520             }
1521           }
1522         }
1523         { // mark expression stack
1524           GrowableArray<ScopeValue*>* scvs = scope->expressions();
1525           int scvs_length = scvs != nullptr ? scvs->length() : 0;
1526           for (int i = 0; i < scvs_length; i++) {
1527             intptr_t* stack_address = (intptr_t*)StackValue::stack_value_address(this, reg_map, scvs->at(i));
1528             if (stack_address != nullptr) {
1529               values.describe(frame_no, stack_address, err_msg("stack %d for #%d (scope %d)", i, frame_no, scope_no), 1);
1530             }
1531           }
1532         }
1533       }
1534 
1535       FrameValuesOopClosure oopsFn;
1536       oops_do(&oopsFn, nullptr, &oopsFn, reg_map);
1537       oopsFn.describe(values, frame_no);
1538 
1539       if (oop_map() != nullptr) {
1540         FrameValuesOopMapClosure valuesFn(this, reg_map, values, frame_no);
1541         // also OopMapValue::live_value ??
1542         oop_map()->all_type_do(this, OopMapValue::callee_saved_value, &valuesFn);
1543       }
1544     }
1545   } else if (is_native_frame()) {
1546     // For now just label the frame
1547     nmethod* nm = cb()->as_nmethod_or_null();
1548     values.describe(-1, info_address,
1549                     FormatBuffer<1024>("#%d nmethod " INTPTR_FORMAT " for native method %s", frame_no,
1550                                        p2i(nm), nm->method()->name_and_sig_as_C_string()), 2);
1551     if (nm->method()->is_continuation_enter_intrinsic()) {
1552       ContinuationEntry* ce = Continuation::get_continuation_entry_for_entry_frame(reg_map->thread(), *this); // (ContinuationEntry*)unextended_sp();
1553       ce->describe(values, frame_no);
1554     }
1555   } else {
1556     // provide default info if not handled before
1557     char *info = (char *) "special frame";
1558     if ((_cb != nullptr) &&
1559         (_cb->name() != nullptr)) {
1560       info = (char *)_cb->name();
1561     }
1562     values.describe(-1, info_address, err_msg("#%d <%s>", frame_no, info), 2);
1563   }
1564 
1565   // platform dependent additional data
1566   describe_pd(values, frame_no);
1567 }
1568 
1569 #endif
1570 
1571 /**
1572  * Gets the caller frame of `fr` for thread `t`.
1573  *
1574  * @returns an invalid frame (i.e. fr.pc() === 0) if the caller cannot be obtained
1575  */
1576 frame frame::next_frame(frame fr, Thread* t) {
1577   // Compiled code may use EBP register on x86 so it looks like
1578   // non-walkable C frame. Use frame.sender() for java frames.
1579   frame invalid;
1580   if (t != nullptr && t->is_Java_thread()) {
1581     // Catch very first native frame by using stack address.
1582     // For JavaThread stack_base and stack_size should be set.
1583     if (!t->is_in_full_stack((address)(fr.real_fp() + 1))) {
1584       return invalid;
1585     }
1586     if (fr.is_interpreted_frame() || (fr.cb() != nullptr && fr.cb()->frame_size() > 0)) {
1587       RegisterMap map(JavaThread::cast(t),
1588                       RegisterMap::UpdateMap::skip,
1589                       RegisterMap::ProcessFrames::include,
1590                       RegisterMap::WalkContinuation::skip); // No update
1591       return fr.sender(&map);
1592     } else {
1593       // is_first_C_frame() does only simple checks for frame pointer,
1594       // it will pass if java compiled code has a pointer in EBP.
1595       if (os::is_first_C_frame(&fr)) return invalid;
1596       return os::get_sender_for_C_frame(&fr);
1597     }
1598   } else {
1599     if (os::is_first_C_frame(&fr)) return invalid;
1600     return os::get_sender_for_C_frame(&fr);
1601   }
1602 }
1603 
1604 #ifndef PRODUCT
1605 
1606 void FrameValues::describe(int owner, intptr_t* location, const char* description, int priority) {
1607   FrameValue fv;
1608   fv.location = location;
1609   fv.owner = owner;
1610   fv.priority = priority;
1611   fv.description = NEW_RESOURCE_ARRAY(char, strlen(description) + 1);
1612   strcpy(fv.description, description);
1613   _values.append(fv);
1614 }
1615 
1616 
1617 #ifdef ASSERT
1618 void FrameValues::validate() {
1619   _values.sort(compare);
1620   bool error = false;
1621   FrameValue prev;
1622   prev.owner = -1;
1623   for (int i = _values.length() - 1; i >= 0; i--) {
1624     FrameValue fv = _values.at(i);
1625     if (fv.owner == -1) continue;
1626     if (prev.owner == -1) {
1627       prev = fv;
1628       continue;
1629     }
1630     if (prev.location == fv.location) {
1631       if (fv.owner != prev.owner) {
1632         tty->print_cr("overlapping storage");
1633         tty->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT " %s", p2i(prev.location), *prev.location, prev.description);
1634         tty->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT " %s", p2i(fv.location), *fv.location, fv.description);
1635         error = true;
1636       }
1637     } else {
1638       prev = fv;
1639     }
1640   }
1641   // if (error) { tty->cr(); print_on(static_cast<JavaThread*>(nullptr), tty); }
1642   assert(!error, "invalid layout");
1643 }
1644 #endif // ASSERT
1645 
1646 void FrameValues::print_on(JavaThread* thread, outputStream* st) {
1647   _values.sort(compare);
1648 
1649   // Sometimes values like the fp can be invalid values if the
1650   // register map wasn't updated during the walk.  Trim out values
1651   // that aren't actually in the stack of the thread.
1652   int min_index = 0;
1653   int max_index = _values.length() - 1;
1654   intptr_t* v0 = _values.at(min_index).location;
1655   intptr_t* v1 = _values.at(max_index).location;
1656 
1657   if (thread != nullptr) {
1658     if (thread == Thread::current()) {
1659       while (!thread->is_in_live_stack((address)v0)) v0 = _values.at(++min_index).location;
1660       while (!thread->is_in_live_stack((address)v1)) v1 = _values.at(--max_index).location;
1661     } else {
1662       while (!thread->is_in_full_stack((address)v0)) v0 = _values.at(++min_index).location;
1663       while (!thread->is_in_full_stack((address)v1)) v1 = _values.at(--max_index).location;
1664     }
1665   }
1666 
1667   print_on(st, min_index, max_index, v0, v1);
1668 }
1669 
1670 void FrameValues::print_on(stackChunkOop chunk, outputStream* st) {
1671   _values.sort(compare);
1672 
1673   intptr_t* start = chunk->start_address();
1674   intptr_t* end = chunk->end_address() + 1;
1675 
1676   int min_index = 0;
1677   int max_index = _values.length() - 1;
1678   intptr_t* v0 = _values.at(min_index).location;
1679   intptr_t* v1 = _values.at(max_index).location;
1680   while (!(start <= v0 && v0 <= end)) v0 = _values.at(++min_index).location;
1681   while (!(start <= v1 && v1 <= end)) v1 = _values.at(--max_index).location;
1682 
1683   print_on(st, min_index, max_index, v0, v1);
1684 }
1685 
1686 void FrameValues::print_on(outputStream* st, int min_index, int max_index, intptr_t* v0, intptr_t* v1) {
1687   intptr_t* min = MIN2(v0, v1);
1688   intptr_t* max = MAX2(v0, v1);
1689   intptr_t* cur = max;
1690   intptr_t* last = nullptr;
1691   intptr_t* fp = nullptr;
1692   for (int i = max_index; i >= min_index; i--) {
1693     FrameValue fv = _values.at(i);
1694     while (cur > fv.location) {
1695       st->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT, p2i(cur), *cur);
1696       cur--;
1697     }
1698     if (last == fv.location) {
1699       const char* spacer = "          " LP64_ONLY("        ");
1700       st->print_cr(" %s  %s %s", spacer, spacer, fv.description);
1701     } else {
1702       if (*fv.description == '#' && isdigit(fv.description[1])) {
1703         // The fv.description string starting with a '#' is the line for the
1704         // saved frame pointer eg. "#10 method java.lang.invoke.LambdaForm..."
1705         // basicaly means frame 10.
1706         fp = fv.location;
1707       }
1708       // To print a fp-relative value:
1709       //   1. The content of *fv.location must be such that we think it's a
1710       //      fp-relative number, i.e [-100..100].
1711       //   2. We must have found the frame pointer.
1712       //   3. The line can not be the line for the saved frame pointer.
1713       //   4. Recognize it as being part of the "fixed frame".
1714       if (*fv.location != 0 && *fv.location > -100 && *fv.location < 100
1715           && fp != nullptr && *fv.description != '#'
1716 #if !defined(PPC64)
1717           && (strncmp(fv.description, "interpreter_frame_", 18) == 0 || strstr(fv.description, " method "))
1718 #else  // !defined(PPC64)
1719           && (strcmp(fv.description, "sender_sp") == 0 || strcmp(fv.description, "top_frame_sp") == 0 ||
1720               strcmp(fv.description, "esp") == 0 || strcmp(fv.description, "monitors") == 0 ||
1721               strcmp(fv.description, "locals") == 0 || strstr(fv.description, " method "))
1722 #endif //!defined(PPC64)
1723           ) {
1724         st->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT " %-32s (relativized: fp%+d)",
1725                      p2i(fv.location), p2i(&fp[*fv.location]), fv.description, (int)*fv.location);
1726       } else {
1727         st->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT " %s", p2i(fv.location), *fv.location, fv.description);
1728       }
1729       last = fv.location;
1730       cur--;
1731     }
1732   }
1733 }
1734 
1735 #endif // ndef PRODUCT