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