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