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   }
 577   // monitor
 578   st->print_cr(" - monitor[" INTPTR_FORMAT "]", p2i(interpreter_frame_monitor_begin()));
 579   // bcp
 580   st->print(" - bcp    [" INTPTR_FORMAT "]", p2i(interpreter_frame_bcp()));
 581   st->fill_to(23);
 582   st->print_cr("; @%d", interpreter_frame_bci());
 583   // locals
 584   st->print_cr(" - locals [" INTPTR_FORMAT "]", p2i(interpreter_frame_local_at(0)));
 585   // method
 586   st->print(" - method [" INTPTR_FORMAT "]", p2i(interpreter_frame_method()));
 587   st->fill_to(23);
 588   st->print("; ");
 589   interpreter_frame_method()->print_name(st);
 590   st->cr();
 591 #endif
 592 }
 593 
 594 // Print whether the frame is in the VM or OS indicating a HotSpot problem.
 595 // Otherwise, it's likely a bug in the native library that the Java code calls,
 596 // hopefully indicating where to submit bugs.
 597 void frame::print_C_frame(outputStream* st, char* buf, int buflen, address pc) {
 598   // C/C++ frame
 599   bool in_vm = os::address_is_in_vm(pc);
 600   st->print(in_vm ? "V" : "C");
 601 
 602   int offset;
 603   bool found;
 604 
 605   if (buf == NULL || buflen < 1) return;
 606   // libname
 607   buf[0] = '\0';
 608   found = os::dll_address_to_library_name(pc, buf, buflen, &offset);
 609   if (found && buf[0] != '\0') {
 610     // skip directory names
 611     const char *p1, *p2;
 612     p1 = buf;
 613     int len = (int)strlen(os::file_separator());
 614     while ((p2 = strstr(p1, os::file_separator())) != NULL) p1 = p2 + len;
 615     st->print("  [%s+0x%x]", p1, offset);
 616   } else {
 617     st->print("  " PTR_FORMAT, p2i(pc));
 618   }
 619 
 620   found = os::dll_address_to_function_name(pc, buf, buflen, &offset);
 621   if (found) {
 622     st->print("  %s+0x%x", buf, offset);
 623   }
 624 }
 625 
 626 // frame::print_on_error() is called by fatal error handler. Notice that we may
 627 // crash inside this function if stack frame is corrupted. The fatal error
 628 // handler can catch and handle the crash. Here we assume the frame is valid.
 629 //
 630 // First letter indicates type of the frame:
 631 //    J: Java frame (compiled)
 632 //    j: Java frame (interpreted)
 633 //    V: VM frame (C/C++)
 634 //    v: Other frames running VM generated code (e.g. stubs, adapters, etc.)
 635 //    C: C/C++ frame
 636 //
 637 // We don't need detailed frame type as that in frame::print_name(). "C"
 638 // suggests the problem is in user lib; everything else is likely a VM bug.
 639 
 640 void frame::print_on_error(outputStream* st, char* buf, int buflen, bool verbose) const {
 641   if (_cb != NULL) {
 642     if (Interpreter::contains(pc())) {
 643       Method* m = this->interpreter_frame_method();
 644       if (m != NULL) {
 645         m->name_and_sig_as_C_string(buf, buflen);
 646         st->print("j  %s", buf);
 647         st->print("+%d", this->interpreter_frame_bci());
 648         ModuleEntry* module = m->method_holder()->module();
 649         if (module->is_named()) {
 650           module->name()->as_C_string(buf, buflen);
 651           st->print(" %s", buf);
 652           if (module->version() != NULL) {
 653             module->version()->as_C_string(buf, buflen);
 654             st->print("@%s", buf);
 655           }
 656         }
 657       } else {
 658         st->print("j  " PTR_FORMAT, p2i(pc()));
 659       }
 660     } else if (StubRoutines::contains(pc())) {
 661       StubCodeDesc* desc = StubCodeDesc::desc_for(pc());
 662       if (desc != NULL) {
 663         st->print("v  ~StubRoutines::%s " PTR_FORMAT, desc->name(), p2i(pc()));
 664       } else {
 665         st->print("v  ~StubRoutines::" PTR_FORMAT, p2i(pc()));
 666       }
 667     } else if (_cb->is_buffer_blob()) {
 668       st->print("v  ~BufferBlob::%s " PTR_FORMAT, ((BufferBlob *)_cb)->name(), p2i(pc()));
 669     } else if (_cb->is_compiled()) {
 670       CompiledMethod* cm = (CompiledMethod*)_cb;
 671       Method* m = cm->method();
 672       if (m != NULL) {
 673         if (cm->is_nmethod()) {
 674           nmethod* nm = cm->as_nmethod();
 675           st->print("J %d%s", nm->compile_id(), (nm->is_osr_method() ? "%" : ""));
 676           st->print(" %s", nm->compiler_name());
 677         }
 678         m->name_and_sig_as_C_string(buf, buflen);
 679         st->print(" %s", buf);
 680         ModuleEntry* module = m->method_holder()->module();
 681         if (module->is_named()) {
 682           module->name()->as_C_string(buf, buflen);
 683           st->print(" %s", buf);
 684           if (module->version() != NULL) {
 685             module->version()->as_C_string(buf, buflen);
 686             st->print("@%s", buf);
 687           }
 688         }
 689         st->print(" (%d bytes) @ " PTR_FORMAT " [" PTR_FORMAT "+" INTPTR_FORMAT "]",
 690                   m->code_size(), p2i(_pc), p2i(_cb->code_begin()), _pc - _cb->code_begin());
 691 #if INCLUDE_JVMCI
 692         if (cm->is_nmethod()) {
 693           nmethod* nm = cm->as_nmethod();
 694           const char* jvmciName = nm->jvmci_name();
 695           if (jvmciName != NULL) {
 696             st->print(" (%s)", jvmciName);
 697           }
 698         }
 699 #endif
 700       } else {
 701         st->print("J  " PTR_FORMAT, p2i(pc()));
 702       }
 703     } else if (_cb->is_runtime_stub()) {
 704       st->print("v  ~RuntimeStub::%s " PTR_FORMAT, ((RuntimeStub *)_cb)->name(), p2i(pc()));
 705     } else if (_cb->is_deoptimization_stub()) {
 706       st->print("v  ~DeoptimizationBlob " PTR_FORMAT, p2i(pc()));
 707     } else if (_cb->is_exception_stub()) {
 708       st->print("v  ~ExceptionBlob " PTR_FORMAT, p2i(pc()));
 709     } else if (_cb->is_safepoint_stub()) {
 710       st->print("v  ~SafepointBlob " PTR_FORMAT, p2i(pc()));
 711     } else if (_cb->is_adapter_blob()) {
 712       st->print("v  ~AdapterBlob " PTR_FORMAT, p2i(pc()));
 713     } else if (_cb->is_vtable_blob()) {
 714       st->print("v  ~VtableBlob " PTR_FORMAT, p2i(pc()));
 715     } else if (_cb->is_method_handles_adapter_blob()) {
 716       st->print("v  ~MethodHandlesAdapterBlob " PTR_FORMAT, p2i(pc()));
 717     } else if (_cb->is_uncommon_trap_stub()) {
 718       st->print("v  ~UncommonTrapBlob " PTR_FORMAT, p2i(pc()));
 719     } else {
 720       st->print("v  blob " PTR_FORMAT, p2i(pc()));
 721     }
 722   } else {
 723     print_C_frame(st, buf, buflen, pc());
 724   }
 725 }
 726 
 727 
 728 /*
 729   The interpreter_frame_expression_stack_at method in the case of SPARC needs the
 730   max_stack value of the method in order to compute the expression stack address.
 731   It uses the Method* in order to get the max_stack value but during GC this
 732   Method* value saved on the frame is changed by reverse_and_push and hence cannot
 733   be used. So we save the max_stack value in the FrameClosure object and pass it
 734   down to the interpreter_frame_expression_stack_at method
 735 */
 736 class InterpreterFrameClosure : public OffsetClosure {
 737  private:
 738   const frame* _fr;
 739   OopClosure*  _f;
 740   int          _max_locals;
 741   int          _max_stack;
 742 
 743  public:
 744   InterpreterFrameClosure(const frame* fr, int max_locals, int max_stack,
 745                           OopClosure* f) {
 746     _fr         = fr;
 747     _max_locals = max_locals;
 748     _max_stack  = max_stack;
 749     _f          = f;
 750   }
 751 
 752   void offset_do(int offset) {
 753     oop* addr;
 754     if (offset < _max_locals) {
 755       addr = (oop*) _fr->interpreter_frame_local_at(offset);
 756       assert((intptr_t*)addr >= _fr->sp(), "must be inside the frame");
 757       _f->do_oop(addr);
 758     } else {
 759       addr = (oop*) _fr->interpreter_frame_expression_stack_at((offset - _max_locals));
 760       // In case of exceptions, the expression stack is invalid and the esp will be reset to express
 761       // this condition. Therefore, we call f only if addr is 'inside' the stack (i.e., addr >= esp for Intel).
 762       bool in_stack;
 763       if (frame::interpreter_frame_expression_stack_direction() > 0) {
 764         in_stack = (intptr_t*)addr <= _fr->interpreter_frame_tos_address();
 765       } else {
 766         in_stack = (intptr_t*)addr >= _fr->interpreter_frame_tos_address();
 767       }
 768       if (in_stack) {
 769         _f->do_oop(addr);
 770       }
 771     }
 772   }
 773 
 774   int max_locals()  { return _max_locals; }
 775 };
 776 
 777 
 778 class InterpretedArgumentOopFinder: public SignatureIterator {
 779  private:
 780   OopClosure*  _f;             // Closure to invoke
 781   int          _offset;        // TOS-relative offset, decremented with each argument
 782   bool         _has_receiver;  // true if the callee has a receiver
 783   const frame* _fr;
 784 
 785   friend class SignatureIterator;  // so do_parameters_on can call do_type
 786   void do_type(BasicType type) {
 787     _offset -= parameter_type_word_count(type);
 788     if (is_reference_type(type)) oop_offset_do();
 789    }
 790 
 791   void oop_offset_do() {
 792     oop* addr;
 793     addr = (oop*)_fr->interpreter_frame_tos_at(_offset);
 794     _f->do_oop(addr);
 795   }
 796 
 797  public:
 798   InterpretedArgumentOopFinder(Symbol* signature, bool has_receiver, const frame* fr, OopClosure* f) : SignatureIterator(signature), _has_receiver(has_receiver) {
 799     // compute size of arguments
 800     int args_size = ArgumentSizeComputer(signature).size() + (has_receiver ? 1 : 0);
 801     assert(!fr->is_interpreted_frame() ||
 802            args_size <= fr->interpreter_frame_expression_stack_size(),
 803             "args cannot be on stack anymore");
 804     // initialize InterpretedArgumentOopFinder
 805     _f         = f;
 806     _fr        = fr;
 807     _offset    = args_size;
 808   }
 809 
 810   void oops_do() {
 811     if (_has_receiver) {
 812       --_offset;
 813       oop_offset_do();
 814     }
 815     do_parameters_on(this);
 816   }
 817 };
 818 
 819 
 820 // Entry frame has following form (n arguments)
 821 //         +-----------+
 822 //   sp -> |  last arg |
 823 //         +-----------+
 824 //         :    :::    :
 825 //         +-----------+
 826 // (sp+n)->|  first arg|
 827 //         +-----------+
 828 
 829 
 830 
 831 // visits and GC's all the arguments in entry frame
 832 class EntryFrameOopFinder: public SignatureIterator {
 833  private:
 834   bool         _is_static;
 835   int          _offset;
 836   const frame* _fr;
 837   OopClosure*  _f;
 838 
 839   friend class SignatureIterator;  // so do_parameters_on can call do_type
 840   void do_type(BasicType type) {
 841     // decrement offset before processing the type
 842     _offset -= parameter_type_word_count(type);
 843     assert (_offset >= 0, "illegal offset");
 844     if (is_reference_type(type))  oop_at_offset_do(_offset);
 845  }
 846 
 847   void oop_at_offset_do(int offset) {
 848     assert (offset >= 0, "illegal offset");
 849     oop* addr = (oop*) _fr->entry_frame_argument_at(offset);
 850     _f->do_oop(addr);
 851   }
 852 
 853  public:
 854   EntryFrameOopFinder(const frame* frame, Symbol* signature, bool is_static) : SignatureIterator(signature) {
 855     _f = NULL; // will be set later
 856     _fr = frame;
 857     _is_static = is_static;
 858     _offset = ArgumentSizeComputer(signature).size();  // pre-decremented down to zero
 859   }
 860 
 861   void arguments_do(OopClosure* f) {
 862     _f = f;
 863     if (!_is_static)  oop_at_offset_do(_offset); // do the receiver
 864     do_parameters_on(this);
 865   }
 866 
 867 };
 868 
 869 oop* frame::interpreter_callee_receiver_addr(Symbol* signature) {
 870   ArgumentSizeComputer asc(signature);
 871   int size = asc.size();
 872   return (oop *)interpreter_frame_tos_at(size);
 873 }
 874 
 875 oop frame::interpreter_callee_receiver(Symbol* signature) {
 876   return *interpreter_callee_receiver_addr(signature);
 877 }
 878 
 879 void frame::oops_interpreted_do(OopClosure* f, const RegisterMap* map, bool query_oop_map_cache) const {
 880   assert(is_interpreted_frame(), "Not an interpreted frame");
 881   Thread *thread = Thread::current();
 882   methodHandle m (thread, interpreter_frame_method());
 883   jint      bci = interpreter_frame_bci();
 884 
 885   assert(!Universe::heap()->is_in(m()),
 886           "must be valid oop");
 887   assert(m->is_method(), "checking frame value");
 888   assert((m->is_native() && bci == 0)  ||
 889          (!m->is_native() && bci >= 0 && bci < m->code_size()),
 890          "invalid bci value");
 891 
 892   // Handle the monitor elements in the activation
 893   for (
 894     BasicObjectLock* current = interpreter_frame_monitor_end();
 895     current < interpreter_frame_monitor_begin();
 896     current = next_monitor_in_interpreter_frame(current)
 897   ) {
 898 #ifdef ASSERT
 899     interpreter_frame_verify_monitor(current);
 900 #endif
 901     current->oops_do(f);
 902   }
 903 
 904   if (m->is_native()) {
 905     f->do_oop(interpreter_frame_temp_oop_addr());
 906   }
 907 
 908   // The method pointer in the frame might be the only path to the method's
 909   // klass, and the klass needs to be kept alive while executing. The GCs
 910   // don't trace through method pointers, so the mirror of the method's klass
 911   // is installed as a GC root.
 912   f->do_oop(interpreter_frame_mirror_addr());
 913 
 914   int max_locals = m->is_native() ? m->size_of_parameters() : m->max_locals();
 915 
 916   Symbol* signature = NULL;
 917   bool has_receiver = false;
 918 
 919   // Process a callee's arguments if we are at a call site
 920   // (i.e., if we are at an invoke bytecode)
 921   // This is used sometimes for calling into the VM, not for another
 922   // interpreted or compiled frame.
 923   if (!m->is_native()) {
 924     Bytecode_invoke call = Bytecode_invoke_check(m, bci);
 925     if (map != nullptr && call.is_valid()) {
 926       signature = call.signature();
 927       has_receiver = call.has_receiver();
 928       if (map->include_argument_oops() &&
 929           interpreter_frame_expression_stack_size() > 0) {
 930         ResourceMark rm(thread);  // is this right ???
 931         // we are at a call site & the expression stack is not empty
 932         // => process callee's arguments
 933         //
 934         // Note: The expression stack can be empty if an exception
 935         //       occurred during method resolution/execution. In all
 936         //       cases we empty the expression stack completely be-
 937         //       fore handling the exception (the exception handling
 938         //       code in the interpreter calls a blocking runtime
 939         //       routine which can cause this code to be executed).
 940         //       (was bug gri 7/27/98)
 941         oops_interpreted_arguments_do(signature, has_receiver, f);
 942       }
 943     }
 944   }
 945 
 946   InterpreterFrameClosure blk(this, max_locals, m->max_stack(), f);
 947 
 948   // process locals & expression stack
 949   InterpreterOopMap mask;
 950   if (query_oop_map_cache) {
 951     m->mask_for(bci, &mask);
 952   } else {
 953     OopMapCache::compute_one_oop_map(m, bci, &mask);
 954   }
 955   mask.iterate_oop(&blk);
 956 }
 957 
 958 
 959 void frame::oops_interpreted_arguments_do(Symbol* signature, bool has_receiver, OopClosure* f) const {
 960   InterpretedArgumentOopFinder finder(signature, has_receiver, this, f);
 961   finder.oops_do();
 962 }
 963 
 964 void frame::oops_code_blob_do(OopClosure* f, CodeBlobClosure* cf, DerivedOopClosure* df, DerivedPointerIterationMode derived_mode, const RegisterMap* reg_map) const {
 965   assert(_cb != NULL, "sanity check");
 966   assert((oop_map() == NULL) == (_cb->oop_maps() == NULL), "frame and _cb must agree that oopmap is set or not");
 967   if (oop_map() != NULL) {
 968     if (df != NULL) {
 969       _oop_map->oops_do(this, reg_map, f, df);
 970     } else {
 971       _oop_map->oops_do(this, reg_map, f, derived_mode);
 972     }
 973 
 974     // Preserve potential arguments for a callee. We handle this by dispatching
 975     // on the codeblob. For c2i, we do
 976     if (reg_map->include_argument_oops()) {
 977       _cb->preserve_callee_argument_oops(*this, reg_map, f);
 978     }
 979   }
 980   // In cases where perm gen is collected, GC will want to mark
 981   // oops referenced from nmethods active on thread stacks so as to
 982   // prevent them from being collected. However, this visit should be
 983   // restricted to certain phases of the collection only. The
 984   // closure decides how it wants nmethods to be traced.
 985   if (cf != NULL)
 986     cf->do_code_blob(_cb);
 987 }
 988 
 989 class CompiledArgumentOopFinder: public SignatureIterator {
 990  protected:
 991   OopClosure*     _f;
 992   int             _offset;        // the current offset, incremented with each argument
 993   bool            _has_receiver;  // true if the callee has a receiver
 994   bool            _has_appendix;  // true if the call has an appendix
 995   frame           _fr;
 996   RegisterMap*    _reg_map;
 997   int             _arg_size;
 998   VMRegPair*      _regs;        // VMReg list of arguments
 999 
1000   friend class SignatureIterator;  // so do_parameters_on can call do_type
1001   void do_type(BasicType type) {
1002     if (is_reference_type(type))  handle_oop_offset();
1003     _offset += parameter_type_word_count(type);
1004   }
1005 
1006   virtual void handle_oop_offset() {
1007     // Extract low order register number from register array.
1008     // In LP64-land, the high-order bits are valid but unhelpful.
1009     VMReg reg = _regs[_offset].first();
1010     oop *loc = _fr.oopmapreg_to_oop_location(reg, _reg_map);
1011   #ifdef ASSERT
1012     if (loc == NULL) {
1013       if (_reg_map->should_skip_missing()) {
1014         return;
1015       }
1016       tty->print_cr("Error walking frame oops:");
1017       _fr.print_on(tty);
1018       assert(loc != NULL, "missing register map entry reg: " INTPTR_FORMAT " %s loc: " INTPTR_FORMAT, reg->value(), reg->name(), p2i(loc));
1019     }
1020   #endif
1021     _f->do_oop(loc);
1022   }
1023 
1024  public:
1025   CompiledArgumentOopFinder(Symbol* signature, bool has_receiver, bool has_appendix, OopClosure* f, frame fr, const RegisterMap* reg_map)
1026     : SignatureIterator(signature) {
1027 
1028     // initialize CompiledArgumentOopFinder
1029     _f         = f;
1030     _offset    = 0;
1031     _has_receiver = has_receiver;
1032     _has_appendix = has_appendix;
1033     _fr        = fr;
1034     _reg_map   = (RegisterMap*)reg_map;
1035     _arg_size  = ArgumentSizeComputer(signature).size() + (has_receiver ? 1 : 0) + (has_appendix ? 1 : 0);
1036 
1037     int arg_size;
1038     _regs = SharedRuntime::find_callee_arguments(signature, has_receiver, has_appendix, &arg_size);
1039     assert(arg_size == _arg_size, "wrong arg size");
1040   }
1041 
1042   void oops_do() {
1043     if (_has_receiver) {
1044       handle_oop_offset();
1045       _offset++;
1046     }
1047     do_parameters_on(this);
1048     if (_has_appendix) {
1049       handle_oop_offset();
1050       _offset++;
1051     }
1052   }
1053 };
1054 
1055 void frame::oops_compiled_arguments_do(Symbol* signature, bool has_receiver, bool has_appendix,
1056                                        const RegisterMap* reg_map, OopClosure* f) const {
1057   // ResourceMark rm;
1058   CompiledArgumentOopFinder finder(signature, has_receiver, has_appendix, f, *this, reg_map);
1059   finder.oops_do();
1060 }
1061 
1062 // Get receiver out of callers frame, i.e. find parameter 0 in callers
1063 // frame.  Consult ADLC for where parameter 0 is to be found.  Then
1064 // check local reg_map for it being a callee-save register or argument
1065 // register, both of which are saved in the local frame.  If not found
1066 // there, it must be an in-stack argument of the caller.
1067 // Note: caller.sp() points to callee-arguments
1068 oop frame::retrieve_receiver(RegisterMap* reg_map) {
1069   frame caller = *this;
1070 
1071   // First consult the ADLC on where it puts parameter 0 for this signature.
1072   VMReg reg = SharedRuntime::name_for_receiver();
1073   oop* oop_adr = caller.oopmapreg_to_oop_location(reg, reg_map);
1074   if (oop_adr == NULL) {
1075     guarantee(oop_adr != NULL, "bad register save location");
1076     return NULL;
1077   }
1078   oop r = *oop_adr;
1079   assert(Universe::heap()->is_in_or_null(r), "bad receiver: " INTPTR_FORMAT " (" INTX_FORMAT ")", p2i(r), p2i(r));
1080   return r;
1081 }
1082 
1083 
1084 oop frame::get_native_receiver() {
1085   nmethod* nm = (nmethod*)_cb;
1086   assert(_cb != NULL && _cb->is_nmethod() && nm->method()->is_native(),
1087          "Should not call this unless it's a native nmethod");
1088   int byte_offset = in_bytes(nm->native_receiver_sp_offset());
1089   assert(byte_offset >= 0, "should not see invalid offset");
1090   oop owner = ((oop*) sp())[byte_offset / wordSize];
1091   assert( Universe::heap()->is_in(owner), "bad receiver" );
1092   return owner;
1093 }
1094 
1095 void frame::oops_entry_do(OopClosure* f, const RegisterMap* map) const {
1096   assert(map != NULL, "map must be set");
1097   if (map->include_argument_oops()) {
1098     // must collect argument oops, as nobody else is doing it
1099     Thread *thread = Thread::current();
1100     methodHandle m (thread, entry_frame_call_wrapper()->callee_method());
1101     EntryFrameOopFinder finder(this, m->signature(), m->is_static());
1102     finder.arguments_do(f);
1103   }
1104   // Traverse the Handle Block saved in the entry frame
1105   entry_frame_call_wrapper()->oops_do(f);
1106 }
1107 
1108 bool frame::is_deoptimized_frame() const {
1109   assert(_deopt_state != unknown, "not answerable");
1110   if (_deopt_state == is_deoptimized) {
1111     return true;
1112   }
1113 
1114   /* This method only checks if the frame is deoptimized
1115    * as in return address being patched.
1116    * It doesn't care if the OP that we return to is a
1117    * deopt instruction */
1118   /*if (_cb != NULL && _cb->is_nmethod()) {
1119     return NativeDeoptInstruction::is_deopt_at(_pc);
1120   }*/
1121   return false;
1122 }
1123 
1124 void frame::oops_do_internal(OopClosure* f, CodeBlobClosure* cf,
1125                              DerivedOopClosure* df, DerivedPointerIterationMode derived_mode,
1126                              const RegisterMap* map, bool use_interpreter_oop_map_cache) const {
1127 #ifndef PRODUCT
1128   // simulate GC crash here to dump java thread in error report
1129   if (CrashGCForDumpingJavaThread) {
1130     char *t = NULL;
1131     *t = 'c';
1132   }
1133 #endif
1134   if (is_interpreted_frame()) {
1135     oops_interpreted_do(f, map, use_interpreter_oop_map_cache);
1136   } else if (is_entry_frame()) {
1137     oops_entry_do(f, map);
1138   } else if (is_upcall_stub_frame()) {
1139     _cb->as_upcall_stub()->oops_do(f, *this);
1140   } else if (CodeCache::contains(pc())) {
1141     oops_code_blob_do(f, cf, df, derived_mode, map);
1142   } else {
1143     ShouldNotReachHere();
1144   }
1145 }
1146 
1147 void frame::nmethods_do(CodeBlobClosure* cf) const {
1148   if (_cb != NULL && _cb->is_nmethod()) {
1149     cf->do_code_blob(_cb);
1150   }
1151 }
1152 
1153 
1154 // Call f closure on the interpreted Method*s in the stack.
1155 void frame::metadata_do(MetadataClosure* f) const {
1156   ResourceMark rm;
1157   if (is_interpreted_frame()) {
1158     Method* m = this->interpreter_frame_method();
1159     assert(m != NULL, "expecting a method in this frame");
1160     f->do_metadata(m);
1161   }
1162 }
1163 
1164 void frame::verify(const RegisterMap* map) const {
1165 #ifndef PRODUCT
1166   if (TraceCodeBlobStacks) {
1167     tty->print_cr("*** verify");
1168     print_on(tty);
1169   }
1170 #endif
1171 
1172   // for now make sure receiver type is correct
1173   if (is_interpreted_frame()) {
1174     Method* method = interpreter_frame_method();
1175     guarantee(method->is_method(), "method is wrong in frame::verify");
1176     if (!method->is_static()) {
1177       // fetch the receiver
1178       oop* p = (oop*) interpreter_frame_local_at(0);
1179       // make sure we have the right receiver type
1180     }
1181   }
1182 #if COMPILER2_OR_JVMCI
1183   assert(DerivedPointerTable::is_empty(), "must be empty before verify");
1184 #endif
1185 
1186   if (map->update_map()) { // The map has to be up-to-date for the current frame
1187     oops_do_internal(&VerifyOopClosure::verify_oop, NULL, NULL, DerivedPointerIterationMode::_ignore, map, false);
1188   }
1189 }
1190 
1191 
1192 #ifdef ASSERT
1193 bool frame::verify_return_pc(address x) {
1194 #ifdef TARGET_ARCH_aarch64
1195   if (!pauth_ptr_is_raw(x)) {
1196     return false;
1197   }
1198 #endif
1199   if (StubRoutines::returns_to_call_stub(x)) {
1200     return true;
1201   }
1202   if (CodeCache::contains(x)) {
1203     return true;
1204   }
1205   if (Interpreter::contains(x)) {
1206     return true;
1207   }
1208   return false;
1209 }
1210 #endif
1211 
1212 #ifdef ASSERT
1213 void frame::interpreter_frame_verify_monitor(BasicObjectLock* value) const {
1214   assert(is_interpreted_frame(), "Not an interpreted frame");
1215   // verify that the value is in the right part of the frame
1216   address low_mark  = (address) interpreter_frame_monitor_end();
1217   address high_mark = (address) interpreter_frame_monitor_begin();
1218   address current   = (address) value;
1219 
1220   const int monitor_size = frame::interpreter_frame_monitor_size();
1221   guarantee((high_mark - current) % monitor_size  ==  0         , "Misaligned top of BasicObjectLock*");
1222   guarantee( high_mark > current                                , "Current BasicObjectLock* higher than high_mark");
1223 
1224   guarantee((current - low_mark) % monitor_size  ==  0         , "Misaligned bottom of BasicObjectLock*");
1225   guarantee( current >= low_mark                               , "Current BasicObjectLock* below than low_mark");
1226 }
1227 #endif
1228 
1229 #ifndef PRODUCT
1230 
1231 // Returns true iff the address p is readable and *(intptr_t*)p != errvalue
1232 extern "C" bool dbg_is_safe(const void* p, intptr_t errvalue);
1233 
1234 class FrameValuesOopClosure: public OopClosure, public DerivedOopClosure {
1235 private:
1236   GrowableArray<oop*>* _oops;
1237   GrowableArray<narrowOop*>* _narrow_oops;
1238   GrowableArray<oop*>* _base;
1239   GrowableArray<derived_pointer*>* _derived;
1240   NoSafepointVerifier nsv;
1241 
1242 public:
1243   FrameValuesOopClosure() {
1244     _oops = new (ResourceObj::C_HEAP, mtThread) GrowableArray<oop*>(100, mtThread);
1245     _narrow_oops = new (ResourceObj::C_HEAP, mtThread) GrowableArray<narrowOop*>(100, mtThread);
1246     _base = new (ResourceObj::C_HEAP, mtThread) GrowableArray<oop*>(100, mtThread);
1247     _derived = new (ResourceObj::C_HEAP, mtThread) GrowableArray<derived_pointer*>(100, mtThread);
1248   }
1249   ~FrameValuesOopClosure() {
1250     delete _oops;
1251     delete _narrow_oops;
1252     delete _base;
1253     delete _derived;
1254   }
1255 
1256   virtual void do_oop(oop* p) override { _oops->push(p); }
1257   virtual void do_oop(narrowOop* p) override { _narrow_oops->push(p); }
1258   virtual void do_derived_oop(oop* base_loc, derived_pointer* derived_loc) override {
1259     _base->push(base_loc);
1260     _derived->push(derived_loc);
1261   }
1262 
1263   bool is_good(oop* p) {
1264     return *p == nullptr || (dbg_is_safe(*p, -1) && dbg_is_safe((*p)->klass(), -1) && oopDesc::is_oop_or_null(*p));
1265   }
1266   void describe(FrameValues& values, int frame_no) {
1267     for (int i = 0; i < _oops->length(); i++) {
1268       oop* p = _oops->at(i);
1269       values.describe(frame_no, (intptr_t*)p, err_msg("oop%s for #%d", is_good(p) ? "" : " (BAD)", frame_no));
1270     }
1271     for (int i = 0; i < _narrow_oops->length(); i++) {
1272       narrowOop* p = _narrow_oops->at(i);
1273       // we can't check for bad compressed oops, as decoding them might crash
1274       values.describe(frame_no, (intptr_t*)p, err_msg("narrow oop for #%d", frame_no));
1275     }
1276     assert(_base->length() == _derived->length(), "should be the same");
1277     for (int i = 0; i < _base->length(); i++) {
1278       oop* base = _base->at(i);
1279       derived_pointer* derived = _derived->at(i);
1280       values.describe(frame_no, (intptr_t*)derived, err_msg("derived pointer (base: " INTPTR_FORMAT ") for #%d", p2i(base), frame_no));
1281     }
1282   }
1283 };
1284 
1285 class FrameValuesOopMapClosure: public OopMapClosure {
1286 private:
1287   const frame* _fr;
1288   const RegisterMap* _reg_map;
1289   FrameValues& _values;
1290   int _frame_no;
1291 
1292 public:
1293   FrameValuesOopMapClosure(const frame* fr, const RegisterMap* reg_map, FrameValues& values, int frame_no)
1294    : _fr(fr), _reg_map(reg_map), _values(values), _frame_no(frame_no) {}
1295 
1296   virtual void do_value(VMReg reg, OopMapValue::oop_types type) override {
1297     intptr_t* p = (intptr_t*)_fr->oopmapreg_to_location(reg, _reg_map);
1298     if (p != NULL && (((intptr_t)p & WordAlignmentMask) == 0)) {
1299       const char* type_name = NULL;
1300       switch(type) {
1301         case OopMapValue::oop_value:          type_name = "oop";          break;
1302         case OopMapValue::narrowoop_value:    type_name = "narrow oop";   break;
1303         case OopMapValue::callee_saved_value: type_name = "callee-saved"; break;
1304         case OopMapValue::derived_oop_value:  type_name = "derived";      break;
1305         // case OopMapValue::live_value:         type_name = "live";         break;
1306         default: break;
1307       }
1308       if (type_name != NULL) {
1309         _values.describe(_frame_no, p, err_msg("%s for #%d", type_name, _frame_no));
1310       }
1311     }
1312   }
1313 };
1314 
1315 // callers need a ResourceMark because of name_and_sig_as_C_string() usage,
1316 // RA allocated string is returned to the caller
1317 void frame::describe(FrameValues& values, int frame_no, const RegisterMap* reg_map) {
1318   // boundaries: sp and the 'real' frame pointer
1319   values.describe(-1, sp(), err_msg("sp for #%d", frame_no), 0);
1320   intptr_t* frame_pointer = real_fp(); // Note: may differ from fp()
1321 
1322   // print frame info at the highest boundary
1323   intptr_t* info_address = MAX2(sp(), frame_pointer);
1324 
1325   if (info_address != frame_pointer) {
1326     // print frame_pointer explicitly if not marked by the frame info
1327     values.describe(-1, frame_pointer, err_msg("frame pointer for #%d", frame_no), 1);
1328   }
1329 
1330   if (is_entry_frame() || is_compiled_frame() || is_interpreted_frame() || is_native_frame()) {
1331     // Label values common to most frames
1332     values.describe(-1, unextended_sp(), err_msg("unextended_sp for #%d", frame_no), 0);
1333   }
1334 
1335   if (is_interpreted_frame()) {
1336     Method* m = interpreter_frame_method();
1337     int bci = interpreter_frame_bci();
1338     InterpreterCodelet* desc = Interpreter::codelet_containing(pc());
1339 
1340     // Label the method and current bci
1341     values.describe(-1, info_address,
1342                     FormatBuffer<1024>("#%d method %s @ %d", frame_no, m->name_and_sig_as_C_string(), bci), 3);
1343     if (desc != NULL) {
1344       values.describe(-1, info_address, err_msg("- %s codelet: %s",
1345         desc->bytecode()    >= 0    ? Bytecodes::name(desc->bytecode()) : "",
1346         desc->description() != NULL ? desc->description()               : "?"), 2);
1347     }
1348     values.describe(-1, info_address,
1349                     err_msg("- %d locals %d max stack", m->max_locals(), m->max_stack()), 2);
1350     // return address will be emitted by caller in describe_pd
1351     // values.describe(frame_no, (intptr_t*)sender_pc_addr(), Continuation::is_return_barrier_entry(*sender_pc_addr()) ? "return address (return barrier)" : "return address");
1352 
1353     if (m->max_locals() > 0) {
1354       intptr_t* l0 = interpreter_frame_local_at(0);
1355       intptr_t* ln = interpreter_frame_local_at(m->max_locals() - 1);
1356       values.describe(-1, MAX2(l0, ln), err_msg("locals for #%d", frame_no), 2);
1357       // Report each local and mark as owned by this frame
1358       for (int l = 0; l < m->max_locals(); l++) {
1359         intptr_t* l0 = interpreter_frame_local_at(l);
1360         values.describe(frame_no, l0, err_msg("local %d", l), 1);
1361       }
1362     }
1363 
1364     if (interpreter_frame_monitor_begin() != interpreter_frame_monitor_end()) {
1365       values.describe(frame_no, (intptr_t*)interpreter_frame_monitor_begin(), "monitors begin");
1366       values.describe(frame_no, (intptr_t*)interpreter_frame_monitor_end(), "monitors end");
1367     }
1368 
1369     // Compute the actual expression stack size
1370     InterpreterOopMap mask;
1371     OopMapCache::compute_one_oop_map(methodHandle(Thread::current(), m), bci, &mask);
1372     intptr_t* tos = NULL;
1373     // Report each stack element and mark as owned by this frame
1374     for (int e = 0; e < mask.expression_stack_size(); e++) {
1375       tos = MAX2(tos, interpreter_frame_expression_stack_at(e));
1376       values.describe(frame_no, interpreter_frame_expression_stack_at(e),
1377                       err_msg("stack %d", e), 1);
1378     }
1379     if (tos != NULL) {
1380       values.describe(-1, tos, err_msg("expression stack for #%d", frame_no), 2);
1381     }
1382 
1383     if (reg_map != NULL) {
1384       FrameValuesOopClosure oopsFn;
1385       oops_do(&oopsFn, NULL, &oopsFn, reg_map);
1386       oopsFn.describe(values, frame_no);
1387     }
1388   } else if (is_entry_frame()) {
1389     // For now just label the frame
1390     values.describe(-1, info_address, err_msg("#%d entry frame", frame_no), 2);
1391   } else if (cb()->is_compiled()) {
1392     // For now just label the frame
1393     CompiledMethod* cm = cb()->as_compiled_method();
1394     values.describe(-1, info_address,
1395                     FormatBuffer<1024>("#%d nmethod " INTPTR_FORMAT " for method J %s%s", frame_no,
1396                                        p2i(cm),
1397                                        cm->method()->name_and_sig_as_C_string(),
1398                                        (_deopt_state == is_deoptimized) ?
1399                                        " (deoptimized)" :
1400                                        ((_deopt_state == unknown) ? " (state unknown)" : "")),
1401                     3);
1402 
1403     { // mark arguments (see nmethod::print_nmethod_labels)
1404       Method* m = cm->method();
1405 
1406       int stack_slot_offset = cm->frame_size() * wordSize; // offset, in bytes, to caller sp
1407       int sizeargs = m->size_of_parameters();
1408 
1409       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
1410       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
1411       {
1412         int sig_index = 0;
1413         if (!m->is_static()) {
1414           sig_bt[sig_index++] = T_OBJECT; // 'this'
1415         }
1416         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
1417           BasicType t = ss.type();
1418           assert(type2size[t] == 1 || type2size[t] == 2, "size is 1 or 2");
1419           sig_bt[sig_index++] = t;
1420           if (type2size[t] == 2) {
1421             sig_bt[sig_index++] = T_VOID;
1422           }
1423         }
1424         assert(sig_index == sizeargs, "");
1425       }
1426       int stack_arg_slots = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);
1427       assert(stack_arg_slots ==  m->num_stack_arg_slots(), "");
1428       int out_preserve = SharedRuntime::out_preserve_stack_slots();
1429       int sig_index = 0;
1430       int arg_index = (m->is_static() ? 0 : -1);
1431       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
1432         bool at_this = (arg_index == -1);
1433         bool at_old_sp = false;
1434         BasicType t = (at_this ? T_OBJECT : ss.type());
1435         assert(t == sig_bt[sig_index], "sigs in sync");
1436         VMReg fst = regs[sig_index].first();
1437         if (fst->is_stack()) {
1438           assert(((int)fst->reg2stack()) >= 0, "reg2stack: " INTPTR_FORMAT, fst->reg2stack());
1439           int offset = (fst->reg2stack() + out_preserve) * VMRegImpl::stack_slot_size + stack_slot_offset;
1440           intptr_t* stack_address = (intptr_t*)((address)unextended_sp() + offset);
1441           if (at_this) {
1442             values.describe(frame_no, stack_address, err_msg("this for #%d", frame_no), 1);
1443           } else {
1444             values.describe(frame_no, stack_address, err_msg("param %d %s for #%d", arg_index, type2name(t), frame_no), 1);
1445           }
1446         }
1447         sig_index += type2size[t];
1448         arg_index += 1;
1449         if (!at_this) {
1450           ss.next();
1451         }
1452       }
1453     }
1454 
1455     if (reg_map != NULL && is_java_frame()) {
1456       int scope_no = 0;
1457       for (ScopeDesc* scope = cm->scope_desc_at(pc()); scope != NULL; scope = scope->sender(), scope_no++) {
1458         Method* m = scope->method();
1459         int  bci = scope->bci();
1460         values.describe(-1, info_address, err_msg("- #%d scope %s @ %d", scope_no, m->name_and_sig_as_C_string(), bci), 2);
1461 
1462         { // mark locals
1463           GrowableArray<ScopeValue*>* scvs = scope->locals();
1464           int scvs_length = scvs != NULL ? scvs->length() : 0;
1465           for (int i = 0; i < scvs_length; i++) {
1466             intptr_t* stack_address = (intptr_t*)StackValue::stack_value_address(this, reg_map, scvs->at(i));
1467             if (stack_address != NULL) {
1468               values.describe(frame_no, stack_address, err_msg("local %d for #%d (scope %d)", i, frame_no, scope_no), 1);
1469             }
1470           }
1471         }
1472         { // mark expression stack
1473           GrowableArray<ScopeValue*>* scvs = scope->expressions();
1474           int scvs_length = scvs != NULL ? scvs->length() : 0;
1475           for (int i = 0; i < scvs_length; i++) {
1476             intptr_t* stack_address = (intptr_t*)StackValue::stack_value_address(this, reg_map, scvs->at(i));
1477             if (stack_address != NULL) {
1478               values.describe(frame_no, stack_address, err_msg("stack %d for #%d (scope %d)", i, frame_no, scope_no), 1);
1479             }
1480           }
1481         }
1482       }
1483 
1484       FrameValuesOopClosure oopsFn;
1485       oops_do(&oopsFn, NULL, &oopsFn, reg_map);
1486       oopsFn.describe(values, frame_no);
1487 
1488       if (oop_map() != NULL) {
1489         FrameValuesOopMapClosure valuesFn(this, reg_map, values, frame_no);
1490         // also OopMapValue::live_value ??
1491         oop_map()->all_type_do(this, OopMapValue::callee_saved_value, &valuesFn);
1492       }
1493     }
1494 
1495     if (cm->method()->is_continuation_enter_intrinsic()) {
1496       ContinuationEntry* ce = Continuation::get_continuation_entry_for_entry_frame(reg_map->thread(), *this); // (ContinuationEntry*)unextended_sp();
1497       ce->describe(values, frame_no);
1498     }
1499   } else if (is_native_frame()) {
1500     // For now just label the frame
1501     nmethod* nm = cb()->as_nmethod_or_null();
1502     values.describe(-1, info_address,
1503                     FormatBuffer<1024>("#%d nmethod " INTPTR_FORMAT " for native method %s", frame_no,
1504                                        p2i(nm), nm->method()->name_and_sig_as_C_string()), 2);
1505   } else {
1506     // provide default info if not handled before
1507     char *info = (char *) "special frame";
1508     if ((_cb != NULL) &&
1509         (_cb->name() != NULL)) {
1510       info = (char *)_cb->name();
1511     }
1512     values.describe(-1, info_address, err_msg("#%d <%s>", frame_no, info), 2);
1513   }
1514 
1515   // platform dependent additional data
1516   describe_pd(values, frame_no);
1517 }
1518 
1519 #endif
1520 
1521 #ifndef PRODUCT
1522 
1523 void FrameValues::describe(int owner, intptr_t* location, const char* description, int priority) {
1524   FrameValue fv;
1525   fv.location = location;
1526   fv.owner = owner;
1527   fv.priority = priority;
1528   fv.description = NEW_RESOURCE_ARRAY(char, strlen(description) + 1);
1529   strcpy(fv.description, description);
1530   _values.append(fv);
1531 }
1532 
1533 
1534 #ifdef ASSERT
1535 void FrameValues::validate() {
1536   _values.sort(compare);
1537   bool error = false;
1538   FrameValue prev;
1539   prev.owner = -1;
1540   for (int i = _values.length() - 1; i >= 0; i--) {
1541     FrameValue fv = _values.at(i);
1542     if (fv.owner == -1) continue;
1543     if (prev.owner == -1) {
1544       prev = fv;
1545       continue;
1546     }
1547     if (prev.location == fv.location) {
1548       if (fv.owner != prev.owner) {
1549         tty->print_cr("overlapping storage");
1550         tty->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT " %s", p2i(prev.location), *prev.location, prev.description);
1551         tty->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT " %s", p2i(fv.location), *fv.location, fv.description);
1552         error = true;
1553       }
1554     } else {
1555       prev = fv;
1556     }
1557   }
1558   // if (error) { tty->cr(); print_on((JavaThread*)nullptr, tty); }
1559   assert(!error, "invalid layout");
1560 }
1561 #endif // ASSERT
1562 
1563 void FrameValues::print_on(JavaThread* thread, outputStream* st) {
1564   _values.sort(compare);
1565 
1566   // Sometimes values like the fp can be invalid values if the
1567   // register map wasn't updated during the walk.  Trim out values
1568   // that aren't actually in the stack of the thread.
1569   int min_index = 0;
1570   int max_index = _values.length() - 1;
1571   intptr_t* v0 = _values.at(min_index).location;
1572   intptr_t* v1 = _values.at(max_index).location;
1573 
1574   if (thread != NULL) {
1575     if (thread == Thread::current()) {
1576       while (!thread->is_in_live_stack((address)v0)) v0 = _values.at(++min_index).location;
1577       while (!thread->is_in_live_stack((address)v1)) v1 = _values.at(--max_index).location;
1578     } else {
1579       while (!thread->is_in_full_stack((address)v0)) v0 = _values.at(++min_index).location;
1580       while (!thread->is_in_full_stack((address)v1)) v1 = _values.at(--max_index).location;
1581     }
1582   }
1583 
1584   print_on(st, min_index, max_index, v0, v1);
1585 }
1586 
1587 void FrameValues::print_on(stackChunkOop chunk, outputStream* st) {
1588   _values.sort(compare);
1589 
1590   intptr_t* start = chunk->start_address();
1591   intptr_t* end = chunk->end_address() + 1;
1592 
1593   int min_index = 0;
1594   int max_index = _values.length() - 1;
1595   intptr_t* v0 = _values.at(min_index).location;
1596   intptr_t* v1 = _values.at(max_index).location;
1597   while (!(start <= v0 && v0 <= end)) v0 = _values.at(++min_index).location;
1598   while (!(start <= v1 && v1 <= end)) v1 = _values.at(--max_index).location;
1599 
1600   print_on(st, min_index, max_index, v0, v1, true /* on_heap */);
1601 }
1602 
1603 void FrameValues::print_on(outputStream* st, int min_index, int max_index, intptr_t* v0, intptr_t* v1, bool on_heap) {
1604   intptr_t* min = MIN2(v0, v1);
1605   intptr_t* max = MAX2(v0, v1);
1606   intptr_t* cur = max;
1607   intptr_t* last = NULL;
1608   for (int i = max_index; i >= min_index; i--) {
1609     FrameValue fv = _values.at(i);
1610     while (cur > fv.location) {
1611       st->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT, p2i(cur), *cur);
1612       cur--;
1613     }
1614     if (last == fv.location) {
1615       const char* spacer = "          " LP64_ONLY("        ");
1616       st->print_cr(" %s  %s %s", spacer, spacer, fv.description);
1617     } else {
1618       if (on_heap
1619           && *fv.location != 0 && *fv.location > -100 && *fv.location < 100
1620           && (strncmp(fv.description, "interpreter_frame_", 18) == 0 || strstr(fv.description, " method "))) {
1621         st->print_cr(" " INTPTR_FORMAT ": %18d %s", p2i(fv.location), (int)*fv.location, fv.description);
1622       } else {
1623         st->print_cr(" " INTPTR_FORMAT ": " INTPTR_FORMAT " %s", p2i(fv.location), *fv.location, fv.description);
1624       }
1625       last = fv.location;
1626       cur--;
1627     }
1628   }
1629 }
1630 
1631 #endif // ndef PRODUCT