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