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