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