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