1 /*
  2  * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "classfile/javaClasses.inline.hpp"
 27 #include "interpreter/bytecodeHistogram.hpp"
 28 #include "interpreter/bytecodeTracer.hpp"
 29 #include "interpreter/bytecodes.hpp"
 30 #include "interpreter/interpreter.hpp"
 31 #include "interpreter/interpreterRuntime.hpp"
 32 #include "memory/resourceArea.hpp"
 33 #include "oops/constantPool.inline.hpp"
 34 #include "oops/methodData.hpp"
 35 #include "oops/method.hpp"
 36 #include "runtime/mutexLocker.hpp"
 37 #include "runtime/osThread.hpp"
 38 #include "runtime/timer.hpp"
 39 #include "utilities/align.hpp"
 40 
 41 
 42 // Standard closure for BytecodeTracer: prints the current bytecode
 43 // and its attributes using bytecode-specific information.
 44 
 45 class BytecodePrinter: public BytecodeClosure {
 46  private:
 47   // %%% This field is not GC-ed, and so can contain garbage
 48   // between critical sections.  Use only pointer-comparison
 49   // operations on the pointer, except within a critical section.
 50   // (Also, ensure that occasional false positives are benign.)
 51   Method* _current_method;
 52   bool      _is_wide;
 53   Bytecodes::Code _code;
 54   address   _next_pc;                // current decoding position
 55 
 56   void      align()                  { _next_pc = align_up(_next_pc, sizeof(jint)); }
 57   int       get_byte()               { return *(jbyte*) _next_pc++; }  // signed
 58   short     get_short()              { short i=Bytes::get_Java_u2(_next_pc); _next_pc+=2; return i; }
 59   int       get_int()                { int i=Bytes::get_Java_u4(_next_pc); _next_pc+=4; return i; }
 60 
 61   int       get_index_u1()           { return *(address)_next_pc++; }
 62   int       get_index_u2()           { int i=Bytes::get_Java_u2(_next_pc); _next_pc+=2; return i; }
 63   int       get_index_u1_cpcache()   { return get_index_u1() + ConstantPool::CPCACHE_INDEX_TAG; }
 64   int       get_index_u2_cpcache()   { int i=Bytes::get_native_u2(_next_pc); _next_pc+=2; return i + ConstantPool::CPCACHE_INDEX_TAG; }
 65   int       get_index_u4()           { int i=Bytes::get_native_u4(_next_pc); _next_pc+=4; return i; }
 66   int       get_index_special()      { return (is_wide()) ? get_index_u2() : get_index_u1(); }
 67   Method* method()                 { return _current_method; }
 68   bool      is_wide()                { return _is_wide; }
 69   Bytecodes::Code raw_code()         { return Bytecodes::Code(_code); }
 70 
 71 
 72   bool      check_index(int i, int& cp_index, outputStream* st = tty);
 73   bool      check_cp_cache_index(int i, int& cp_index, outputStream* st = tty);
 74   bool      check_obj_index(int i, int& cp_index, outputStream* st = tty);
 75   bool      check_invokedynamic_index(int i, int& cp_index, outputStream* st = tty);
 76   void      print_constant(int i, outputStream* st = tty);
 77   void      print_field_or_method(int i, outputStream* st = tty);
 78   void      print_field_or_method(int orig_i, int i, outputStream* st = tty);
 79   void      print_attributes(int bci, outputStream* st = tty);
 80   void      bytecode_epilog(int bci, outputStream* st = tty);
 81 
 82  public:
 83   BytecodePrinter() {
 84     _is_wide = false;
 85     _code = Bytecodes::_illegal;
 86   }
 87 
 88   // This method is called while executing the raw bytecodes, so none of
 89   // the adjustments that BytecodeStream performs applies.
 90   void trace(const methodHandle& method, address bcp, uintptr_t tos, uintptr_t tos2, outputStream* st) {
 91     ResourceMark rm;
 92     if (_current_method != method()) {
 93       // Note 1: This code will not work as expected with true MT/MP.
 94       //         Need an explicit lock or a different solution.
 95       // It is possible for this block to be skipped, if a garbage
 96       // _current_method pointer happens to have the same bits as
 97       // the incoming method.  We could lose a line of trace output.
 98       // This is acceptable in a debug-only feature.
 99       st->cr();
100       st->print("[%ld] ", (long) Thread::current()->osthread()->thread_id());
101       method->print_name(st);
102       st->cr();
103       _current_method = method();
104     }
105     Bytecodes::Code code;
106     if (is_wide()) {
107       // bcp wasn't advanced if previous bytecode was _wide.
108       code = Bytecodes::code_at(method(), bcp+1);
109     } else {
110       code = Bytecodes::code_at(method(), bcp);
111     }
112     _code = code;
113      int bci = bcp - method->code_base();
114     st->print("[%ld] ", (long) Thread::current()->osthread()->thread_id());
115     if (Verbose) {
116       st->print("%8d  %4d  " INTPTR_FORMAT " " INTPTR_FORMAT " %s",
117            BytecodeCounter::counter_value(), bci, tos, tos2, Bytecodes::name(code));
118     } else {
119       st->print("%8d  %4d  %s",
120            BytecodeCounter::counter_value(), bci, Bytecodes::name(code));
121     }
122     _next_pc = is_wide() ? bcp+2 : bcp+1;
123     print_attributes(bci);
124     // Set is_wide for the next one, since the caller of this doesn't skip
125     // the next bytecode.
126     _is_wide = (code == Bytecodes::_wide);
127     _code = Bytecodes::_illegal;
128   }
129 
130   // Used for Method*::print_codes().  The input bcp comes from
131   // BytecodeStream, which will skip wide bytecodes.
132   void trace(const methodHandle& method, address bcp, outputStream* st) {
133     _current_method = method();
134     ResourceMark rm;
135     Bytecodes::Code code = Bytecodes::code_at(method(), bcp);
136     // Set is_wide
137     _is_wide = (code == Bytecodes::_wide);
138     if (is_wide()) {
139       code = Bytecodes::code_at(method(), bcp+1);
140     }
141     _code = code;
142     int bci = bcp - method->code_base();
143     // Print bytecode index and name
144     if (is_wide()) {
145       st->print("%d %s_w", bci, Bytecodes::name(code));
146     } else {
147       st->print("%d %s", bci, Bytecodes::name(code));
148     }
149     _next_pc = is_wide() ? bcp+2 : bcp+1;
150     print_attributes(bci, st);
151     bytecode_epilog(bci, st);
152   }
153 };
154 
155 
156 // Implementation of BytecodeTracer
157 
158 // %%% This set_closure thing seems overly general, given that
159 // nobody uses it.  Also, if BytecodePrinter weren't hidden
160 // then Method* could use instances of it directly and it
161 // would be easier to remove races on _current_method and bcp.
162 // Since this is not product functionality, we can defer cleanup.
163 
164 BytecodeClosure* BytecodeTracer::_closure = NULL;
165 
166 static BytecodePrinter std_closure;
167 BytecodeClosure* BytecodeTracer::std_closure() {
168   return &::std_closure;
169 }
170 
171 
172 void BytecodeTracer::trace(const methodHandle& method, address bcp, uintptr_t tos, uintptr_t tos2, outputStream* st) {
173   if (_closure == NULL) return;
174   if (TraceBytecodes && BytecodeCounter::counter_value() >= TraceBytecodesAt) {
175     ttyLocker ttyl;  // 5065316: keep the following output coherent
176     // The ttyLocker also prevents races between two threads
177     // trying to use the single instance of BytecodePrinter.
178     // Using the ttyLocker prevents the system from coming to
179     // a safepoint within this code, which is sensitive to Method*
180     // movement.
181     //
182     // There used to be a leaf mutex here, but the ttyLocker will
183     // work just as well, as long as the printing operations never block.
184     //
185     // We put the locker on the static trace method, not the
186     // virtual one, because the clients of this module go through
187     // the static method.
188     _closure->trace(method, bcp, tos, tos2, st);
189   }
190 }
191 
192 void BytecodeTracer::trace(const methodHandle& method, address bcp, outputStream* st) {
193   if (_closure == NULL) return;
194   ttyLocker ttyl;  // 5065316: keep the following output coherent
195   _closure->trace(method, bcp, st);
196 }
197 
198 void print_symbol(Symbol* sym, outputStream* st) {
199   char buf[40];
200   int len = sym->utf8_length();
201   if (len >= (int)sizeof(buf)) {
202     st->print_cr(" %s...[%d]", sym->as_C_string(buf, sizeof(buf)), len);
203   } else {
204     st->print(" ");
205     sym->print_on(st); st->cr();
206   }
207 }
208 
209 void print_oop(oop value, outputStream* st) {
210   if (value == NULL) {
211     st->print_cr(" NULL");
212   } else if (java_lang_String::is_instance(value)) {
213     char buf[40];
214     int len = java_lang_String::utf8_length(value);
215     java_lang_String::as_utf8_string(value, buf, sizeof(buf));
216     if (len >= (int)sizeof(buf)) {
217       st->print_cr(" %s...[%d]", buf, len);
218     } else {
219       st->print_cr(" %s", buf);
220     }
221   } else {
222     st->print_cr(" " INTPTR_FORMAT, p2i((void *)value));
223   }
224 }
225 
226 bool BytecodePrinter::check_index(int i, int& cp_index, outputStream* st) {
227   ConstantPool* constants = method()->constants();
228   int ilimit = constants->length();
229   Bytecodes::Code code = raw_code();
230 
231   if (Bytecodes::uses_cp_cache(code)) {
232     bool okay = true;
233     switch (code) {
234     case Bytecodes::_fast_aldc:
235     case Bytecodes::_fast_aldc_w:
236       okay = check_obj_index(i, cp_index, st);
237       break;
238     case Bytecodes::_invokedynamic:
239       okay = check_invokedynamic_index(i, cp_index, st);
240       break;
241     default:
242       okay = check_cp_cache_index(i, cp_index, st);
243       break;
244     }
245     if (!okay) return false;
246   }
247 
248 
249   // check cp index
250   if (cp_index >= 0 && cp_index < ilimit) {
251     if (WizardMode)  st->print(" cp[%d]", cp_index);
252     return true;
253   }
254 
255   st->print_cr(" CP[%d] not in CP", cp_index);
256   return false;
257 }
258 
259 bool BytecodePrinter::check_cp_cache_index(int i, int& cp_index, outputStream* st) {
260   ConstantPool* constants = method()->constants();
261   int climit = 0;
262 
263   ConstantPoolCache* cache = constants->cache();
264   // If rewriter hasn't run, the index is the cp_index
265   if (cache == NULL) {
266     cp_index = i;
267     return true;
268   }
269   //climit = cache->length();  // %%% private!
270   size_t size = cache->size() * wordSize;
271   size -= sizeof(ConstantPoolCache);
272   size /= sizeof(ConstantPoolCacheEntry);
273   climit = (int) size;
274 
275 #ifdef ASSERT
276   {
277     const int CPCACHE_INDEX_TAG = ConstantPool::CPCACHE_INDEX_TAG;
278     if (i >= CPCACHE_INDEX_TAG && i < climit + CPCACHE_INDEX_TAG) {
279       i -= CPCACHE_INDEX_TAG;
280     } else {
281       st->print_cr(" CP[%d] missing bias?", i);
282       return false;
283     }
284   }
285 #endif //ASSERT
286   if (i >= 0 && i < climit) {
287     cp_index = cache->entry_at(i)->constant_pool_index();
288   } else {
289     st->print_cr("%d not in CP[*]?", i);
290       return false;
291     }
292   return true;
293   }
294 
295 
296 bool BytecodePrinter::check_obj_index(int i, int& cp_index, outputStream* st) {
297   ConstantPool* constants = method()->constants();
298   i -= ConstantPool::CPCACHE_INDEX_TAG;
299 
300   if (i >= 0 && i < constants->resolved_references()->length()) {
301      cp_index = constants->object_to_cp_index(i);
302      return true;
303   } else {
304     st->print_cr("%d not in OBJ[*]?", i);
305   return false;
306 }
307 }
308 
309 
310 bool BytecodePrinter::check_invokedynamic_index(int i, int& cp_index, outputStream* st) {
311   assert(ConstantPool::is_invokedynamic_index(i), "not secondary index?");
312   i = ConstantPool::decode_invokedynamic_index(i) + ConstantPool::CPCACHE_INDEX_TAG;
313 
314   return check_cp_cache_index(i, cp_index, st);
315 }
316 
317 void BytecodePrinter::print_constant(int i, outputStream* st) {
318   int orig_i = i;
319   if (!check_index(orig_i, i, st))  return;
320 
321   ConstantPool* constants = method()->constants();
322   constantTag tag = constants->tag_at(i);
323 
324   if (tag.is_int()) {
325     st->print_cr(" " INT32_FORMAT, constants->int_at(i));
326   } else if (tag.is_long()) {
327     st->print_cr(" " INT64_FORMAT, (int64_t)(constants->long_at(i)));
328   } else if (tag.is_float()) {
329     st->print_cr(" %f", constants->float_at(i));
330   } else if (tag.is_double()) {
331     st->print_cr(" %f", constants->double_at(i));
332   } else if (tag.is_string()) {
333     const char* string = constants->string_at_noresolve(i);
334     st->print_cr(" %s", string);
335   } else if (tag.is_klass()) {
336     st->print_cr(" %s", constants->resolved_klass_at(i)->external_name());
337   } else if (tag.is_unresolved_klass()) {
338     st->print_cr(" <unresolved klass at %d>", i);
339   } else if (tag.is_method_type()) {
340     int i2 = constants->method_type_index_at(i);
341     st->print(" <MethodType> %d", i2);
342     print_symbol(constants->symbol_at(i2), st);
343   } else if (tag.is_method_handle()) {
344     int kind = constants->method_handle_ref_kind_at(i);
345     int i2 = constants->method_handle_index_at(i);
346     st->print(" <MethodHandle of kind %d index at %d>", kind, i2);
347     print_field_or_method(-i, i2, st);
348   } else {
349     st->print_cr(" bad tag=%d at %d", tag.value(), i);
350   }
351 }
352 
353 void BytecodePrinter::print_field_or_method(int i, outputStream* st) {
354   int orig_i = i;
355   if (!check_index(orig_i, i, st))  return;
356   print_field_or_method(orig_i, i, st);
357 }
358 
359 void BytecodePrinter::print_field_or_method(int orig_i, int i, outputStream* st) {
360   ConstantPool* constants = method()->constants();
361   constantTag tag = constants->tag_at(i);
362 
363   bool has_klass = true;
364 
365   switch (tag.value()) {
366   case JVM_CONSTANT_InterfaceMethodref:
367   case JVM_CONSTANT_Methodref:
368   case JVM_CONSTANT_Fieldref:
369     break;
370   case JVM_CONSTANT_NameAndType:
371   case JVM_CONSTANT_Dynamic:
372   case JVM_CONSTANT_InvokeDynamic:
373     has_klass = false;
374     break;
375   default:
376     st->print_cr(" bad tag=%d at %d", tag.value(), i);
377     return;
378   }
379 
380   Symbol* name = constants->uncached_name_ref_at(i);
381   Symbol* signature = constants->uncached_signature_ref_at(i);
382   const char* sep = (tag.is_field() ? "/" : "");
383   if (has_klass) {
384     Symbol* klass = constants->klass_name_at(constants->uncached_klass_ref_index_at(i));
385     st->print_cr(" %d <%s.%s%s%s> ", i, klass->as_C_string(), name->as_C_string(), sep, signature->as_C_string());
386   } else {
387     if (tag.is_dynamic_constant() || tag.is_invoke_dynamic()) {
388       int bsm = constants->bootstrap_method_ref_index_at(i);
389       st->print(" bsm=%d", bsm);
390     }
391     st->print_cr(" %d <%s%s%s>", i, name->as_C_string(), sep, signature->as_C_string());
392   }
393 }
394 
395 
396 void BytecodePrinter::print_attributes(int bci, outputStream* st) {
397   // Show attributes of pre-rewritten codes
398   Bytecodes::Code code = Bytecodes::java_code(raw_code());
399   // If the code doesn't have any fields there's nothing to print.
400   // note this is ==1 because the tableswitch and lookupswitch are
401   // zero size (for some reason) and we want to print stuff out for them.
402   if (Bytecodes::length_for(code) == 1) {
403     st->cr();
404     return;
405   }
406 
407   switch(code) {
408     // Java specific bytecodes only matter.
409     case Bytecodes::_bipush:
410       st->print_cr(" " INT32_FORMAT, get_byte());
411       break;
412     case Bytecodes::_sipush:
413       st->print_cr(" " INT32_FORMAT, get_short());
414       break;
415     case Bytecodes::_ldc:
416       if (Bytecodes::uses_cp_cache(raw_code())) {
417         print_constant(get_index_u1_cpcache(), st);
418       } else {
419         print_constant(get_index_u1(), st);
420       }
421       break;
422 
423     case Bytecodes::_ldc_w:
424     case Bytecodes::_ldc2_w:
425       if (Bytecodes::uses_cp_cache(raw_code())) {
426         print_constant(get_index_u2_cpcache(), st);
427       } else {
428         print_constant(get_index_u2(), st);
429       }
430       break;
431 
432     case Bytecodes::_iload:
433     case Bytecodes::_lload:
434     case Bytecodes::_fload:
435     case Bytecodes::_dload:
436     case Bytecodes::_aload:
437     case Bytecodes::_istore:
438     case Bytecodes::_lstore:
439     case Bytecodes::_fstore:
440     case Bytecodes::_dstore:
441     case Bytecodes::_astore:
442       st->print_cr(" #%d", get_index_special());
443       break;
444 
445     case Bytecodes::_iinc:
446       { int index = get_index_special();
447         jint offset = is_wide() ? get_short(): get_byte();
448         st->print_cr(" #%d " INT32_FORMAT, index, offset);
449       }
450       break;
451 
452     case Bytecodes::_newarray: {
453         BasicType atype = (BasicType)get_index_u1();
454         const char* str = type2name(atype);
455         if (str == NULL || is_reference_type(atype)) {
456           assert(false, "Unidentified basic type");
457         }
458         st->print_cr(" %s", str);
459       }
460       break;
461     case Bytecodes::_anewarray: {
462         int klass_index = get_index_u2();
463         ConstantPool* constants = method()->constants();
464         Symbol* name = constants->klass_name_at(klass_index);
465         st->print_cr(" %s ", name->as_C_string());
466       }
467       break;
468     case Bytecodes::_multianewarray: {
469         int klass_index = get_index_u2();
470         int nof_dims = get_index_u1();
471         ConstantPool* constants = method()->constants();
472         Symbol* name = constants->klass_name_at(klass_index);
473         st->print_cr(" %s %d", name->as_C_string(), nof_dims);
474       }
475       break;
476 
477     case Bytecodes::_ifeq:
478     case Bytecodes::_ifnull:
479     case Bytecodes::_iflt:
480     case Bytecodes::_ifle:
481     case Bytecodes::_ifne:
482     case Bytecodes::_ifnonnull:
483     case Bytecodes::_ifgt:
484     case Bytecodes::_ifge:
485     case Bytecodes::_if_icmpeq:
486     case Bytecodes::_if_icmpne:
487     case Bytecodes::_if_icmplt:
488     case Bytecodes::_if_icmpgt:
489     case Bytecodes::_if_icmple:
490     case Bytecodes::_if_icmpge:
491     case Bytecodes::_if_acmpeq:
492     case Bytecodes::_if_acmpne:
493     case Bytecodes::_goto:
494     case Bytecodes::_jsr:
495       st->print_cr(" %d", bci + get_short());
496       break;
497 
498     case Bytecodes::_goto_w:
499     case Bytecodes::_jsr_w:
500       st->print_cr(" %d", bci + get_int());
501       break;
502 
503     case Bytecodes::_ret: st->print_cr(" %d", get_index_special()); break;
504 
505     case Bytecodes::_tableswitch:
506       { align();
507         int  default_dest = bci + get_int();
508         int  lo           = get_int();
509         int  hi           = get_int();
510         int  len          = hi - lo + 1;
511         jint* dest        = NEW_RESOURCE_ARRAY(jint, len);
512         for (int i = 0; i < len; i++) {
513           dest[i] = bci + get_int();
514         }
515         st->print(" %d " INT32_FORMAT " " INT32_FORMAT " ",
516                       default_dest, lo, hi);
517         const char *comma = "";
518         for (int ll = lo; ll <= hi; ll++) {
519           int idx = ll - lo;
520           st->print("%s %d:" INT32_FORMAT " (delta: %d)", comma, ll, dest[idx], dest[idx]-bci);
521           comma = ",";
522         }
523         st->cr();
524       }
525       break;
526     case Bytecodes::_lookupswitch:
527       { align();
528         int  default_dest = bci + get_int();
529         int  len          = get_int();
530         jint* key         = NEW_RESOURCE_ARRAY(jint, len);
531         jint* dest        = NEW_RESOURCE_ARRAY(jint, len);
532         for (int i = 0; i < len; i++) {
533           key [i] = get_int();
534           dest[i] = bci + get_int();
535         };
536         st->print(" %d %d ", default_dest, len);
537         const char *comma = "";
538         for (int ll = 0; ll < len; ll++)  {
539           st->print("%s " INT32_FORMAT ":" INT32_FORMAT, comma, key[ll], dest[ll]);
540           comma = ",";
541         }
542         st->cr();
543       }
544       break;
545 
546     case Bytecodes::_putstatic:
547     case Bytecodes::_getstatic:
548     case Bytecodes::_putfield:
549     case Bytecodes::_getfield:
550       print_field_or_method(get_index_u2_cpcache(), st);
551       break;
552 
553     case Bytecodes::_invokevirtual:
554     case Bytecodes::_invokespecial:
555     case Bytecodes::_invokestatic:
556       print_field_or_method(get_index_u2_cpcache(), st);
557       break;
558 
559     case Bytecodes::_invokeinterface:
560       { int i = get_index_u2_cpcache();
561         int n = get_index_u1();
562         get_byte();            // ignore zero byte
563         print_field_or_method(i, st);
564       }
565       break;
566 
567     case Bytecodes::_invokedynamic:
568       print_field_or_method(get_index_u4(), st);
569       break;
570 
571     case Bytecodes::_new:
572     case Bytecodes::_checkcast:
573     case Bytecodes::_instanceof:
574       { int i = get_index_u2();
575         ConstantPool* constants = method()->constants();
576         Symbol* name = constants->klass_name_at(i);
577         st->print_cr(" %d <%s>", i, name->as_C_string());
578       }
579       break;
580 
581     case Bytecodes::_wide:
582       // length is zero not one, but printed with no more info.
583       break;
584 
585     default:
586       ShouldNotReachHere();
587       break;
588   }
589 }
590 
591 
592 void BytecodePrinter::bytecode_epilog(int bci, outputStream* st) {
593   MethodData* mdo = method()->method_data();
594   if (mdo != NULL) {
595     ProfileData* data = mdo->bci_to_data(bci);
596     if (data != NULL) {
597       st->print("  %d", mdo->dp_to_di(data->dp()));
598       st->fill_to(6);
599       data->print_data_on(st, mdo);
600     }
601   }
602 }