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