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