1 /*
   2  * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/classFileParser.hpp"
  28 #include "classfile/classFileStream.hpp"
  29 #include "classfile/javaClasses.hpp"
  30 #include "classfile/stackMapTable.hpp"
  31 #include "classfile/verificationType.hpp"
  32 #include "interpreter/bytecodes.hpp"
  33 #include "jfr/instrumentation/jfrEventClassTransformer.hpp"
  34 #include "jfr/jfr.hpp"
  35 #include "jfr/jni/jfrJavaSupport.hpp"
  36 #include "jfr/jni/jfrUpcalls.hpp"
  37 #include "jfr/support/jfrEventClass.hpp"
  38 #include "jfr/utilities/jfrBigEndian.hpp"
  39 #include "jfr/writers/jfrBigEndianWriter.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/resourceArea.hpp"
  42 //#include "oops/array.hpp"
  43 #include "oops/instanceKlass.hpp"
  44 #include "oops/method.hpp"
  45 #include "prims/jvmtiRedefineClasses.hpp"
  46 #include "runtime/handles.inline.hpp"
  47 #include "runtime/os.hpp"
  48 #include "runtime/thread.inline.hpp"
  49 #include "utilities/exceptions.hpp"
  50 #include "utilities/globalDefinitions.hpp"
  51 #include "utilities/macros.hpp"
  52 
  53 static const u2 number_of_new_methods = 5;
  54 static const u2 number_of_new_fields = 3;
  55 static const int extra_stream_bytes = 0x280;
  56 static const u2 invalid_cp_index = 0;
  57 
  58 static const char* utf8_constants[] = {
  59   "Code",         // 0
  60   "J",            // 1
  61   "commit",       // 2
  62   "eventHandler", // 3
  63   "Ljdk/jfr/proxy/internal/EventHandlerProxy;", // 4
  64   "duration",     // 5
  65   "begin",        // 6
  66   "()V",          // 7
  67   "isEnabled",    // 8
  68   "()Z",          // 9
  69   "end",          // 10
  70   "shouldCommit", // 11
  71   "startTime",    // 12
  72   "<clinit>",     // 13
  73   "jdk/jfr/FlightRecorder", // 14
  74   "register", // 15
  75   "(Ljava/lang/Class;)V", // 16 // LAST_REQUIRED_UTF8
  76   "StackMapTable", // 17
  77   "Exceptions", // 18
  78   "LineNumberTable", // 20
  79   "LocalVariableTable", // 21
  80   "LocalVariableTypeTable", // 22
  81   "RuntimeVisibleAnnotation" // 23
  82 };
  83 
  84 enum utf8_req_symbols {
  85   UTF8_REQ_Code,
  86   UTF8_REQ_J_FIELD_DESC,
  87   UTF8_REQ_commit,
  88   UTF8_REQ_eventHandler,
  89   UTF8_REQ_eventHandler_FIELD_DESC,
  90   UTF8_REQ_duration,
  91   UTF8_REQ_begin,
  92   UTF8_REQ_EMPTY_VOID_METHOD_DESC,
  93   UTF8_REQ_isEnabled,
  94   UTF8_REQ_EMPTY_BOOLEAN_METHOD_DESC,
  95   UTF8_REQ_end,
  96   UTF8_REQ_shouldCommit,
  97   UTF8_REQ_startTime,
  98   UTF8_REQ_clinit,
  99   UTF8_REQ_FlightRecorder,
 100   UTF8_REQ_register,
 101   UTF8_REQ_CLASS_VOID_METHOD_DESC,
 102   NOF_UTF8_REQ_SYMBOLS
 103 };
 104 
 105 enum utf8_opt_symbols {
 106   UTF8_OPT_StackMapTable = NOF_UTF8_REQ_SYMBOLS,
 107   UTF8_OPT_Exceptions,
 108   UTF8_OPT_LineNumberTable,
 109   UTF8_OPT_LocalVariableTable,
 110   UTF8_OPT_LocalVariableTypeTable,
 111   UTF8_OPT_RuntimeVisibleAnnotation,
 112   NOF_UTF8_SYMBOLS
 113 };
 114 
 115 static u1 empty_void_method_code_attribute[] = {
 116   0x0,
 117   0x0,
 118   0x0,
 119   0xd, // attribute len
 120   0x0,
 121   0x0, // max stack
 122   0x0,
 123   0x1, // max locals
 124   0x0,
 125   0x0,
 126   0x0,
 127   0x1, // code length
 128   Bytecodes::_return,
 129   0x0,
 130   0x0, // ex table len
 131   0x0,
 132   0x0  // attributes_count
 133 };
 134 
 135 static u1 boolean_method_code_attribute[] = {
 136   0x0,
 137   0x0,
 138   0x0,
 139   0xe,
 140   0x0,
 141   0x1, // max stack
 142   0x0,
 143   0x1, // max locals
 144   0x0,
 145   0x0,
 146   0x0,
 147   0x2,
 148   Bytecodes::_iconst_0,
 149   Bytecodes::_ireturn,
 150   0x0,
 151   0x0, // ex table len
 152   0x0,
 153   0x0, // attributes_count
 154 };
 155 
 156 // annotation processing support
 157 
 158 enum {  // initial annotation layout
 159   atype_off = 0,      // utf8 such as 'Ljava/lang/annotation/Retention;'
 160   count_off = 2,      // u2   such as 1 (one value)
 161   member_off = 4,     // utf8 such as 'value'
 162   tag_off = 6,        // u1   such as 'c' (type) or 'e' (enum)
 163   e_tag_val = 'e',
 164   e_type_off = 7,   // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'
 165   e_con_off = 9,    // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'
 166   e_size = 11,     // end of 'e' annotation
 167   c_tag_val = 'c',    // payload is type
 168   c_con_off = 7,    // utf8 payload, such as 'I'
 169   c_size = 9,       // end of 'c' annotation
 170   s_tag_val = 's',    // payload is String
 171   s_con_off = 7,    // utf8 payload, such as 'Ljava/lang/String;'
 172   s_size = 9,
 173   min_size = 6        // smallest possible size (zero members)
 174 };
 175 
 176 static int skip_annotation_value(const address, int, int); // fwd decl
 177 
 178 // Skip an annotation.  Return >=limit if there is any problem.
 179 static int next_annotation_index(const address buffer, int limit, int index) {
 180   assert(buffer != NULL, "invariant");
 181   index += 2;  // skip atype
 182   if ((index += 2) >= limit) {
 183     return limit;
 184   }
 185   int nof_members = JfrBigEndian::read<u2>(buffer + index - 2);
 186   while (--nof_members >= 0 && index < limit) {
 187     index += 2; // skip member
 188     index = skip_annotation_value(buffer, limit, index);
 189   }
 190   return index;
 191 }
 192 
 193 // Skip an annotation value.  Return >=limit if there is any problem.
 194 static int skip_annotation_value(const address buffer, int limit, int index) {
 195   assert(buffer != NULL, "invariant");
 196   // value := switch (tag:u1) {
 197   //   case B, C, I, S, Z, D, F, J, c: con:u2;
 198   //   case e: e_class:u2 e_name:u2;
 199   //   case s: s_con:u2;
 200   //   case [: do(nval:u2) {value};
 201   //   case @: annotation;
 202   //   case s: s_con:u2;
 203   // }
 204   if ((index += 1) >= limit) {
 205     return limit;
 206   }
 207   const u1 tag = buffer[index - 1];
 208   switch (tag) {
 209     case 'B':
 210     case 'C':
 211     case 'I':
 212     case 'S':
 213     case 'Z':
 214     case 'D':
 215     case 'F':
 216     case 'J':
 217     case 'c':
 218     case 's':
 219       index += 2;  // skip con or s_con
 220       break;
 221     case 'e':
 222       index += 4;  // skip e_class, e_name
 223       break;
 224     case '[':
 225       {
 226         if ((index += 2) >= limit) {
 227           return limit;
 228         }
 229         int nof_values = JfrBigEndian::read<u2>(buffer + index - 2);
 230         while (--nof_values >= 0 && index < limit) {
 231           index = skip_annotation_value(buffer, limit, index);
 232         }
 233       }
 234       break;
 235     case '@':
 236       index = next_annotation_index(buffer, limit, index);
 237       break;
 238     default:
 239       return limit;  //  bad tag byte
 240   }
 241   return index;
 242 }
 243 
 244 static const u2 number_of_elements_offset = (u2)2;
 245 static const u2 element_name_offset = (u2)(number_of_elements_offset + 2);
 246 static const u2 element_name_size = (u2)2;
 247 static const u2 value_type_relative_offset = (u2)2;
 248 static const u2 value_relative_offset = (u2)(value_type_relative_offset + 1);
 249 
 250 // see JVMS - 4.7.16. The RuntimeVisibleAnnotations Attribute
 251 
 252 class AnnotationElementIterator : public StackObj {
 253  private:
 254   const InstanceKlass* _ik;
 255   const address _buffer;
 256   const u2 _limit; // length of annotation
 257   mutable u2 _current; // element
 258   mutable u2 _next; // element
 259   u2 value_index() const {
 260     return JfrBigEndian::read<u2>(_buffer + _current + value_relative_offset);
 261   }
 262 
 263  public:
 264   AnnotationElementIterator(const InstanceKlass* ik, address buffer, u2 limit) : _ik(ik),
 265                                                                                  _buffer(buffer),
 266                                                                                  _limit(limit),
 267                                                                                  _next(element_name_offset),
 268                                                                                  _current(element_name_offset) {
 269     assert(_buffer != NULL, "invariant");
 270     assert(_next == element_name_offset, "invariant");
 271     assert(_current == element_name_offset, "invariant");
 272   }
 273 
 274   bool has_next() const {
 275     return _next < _limit;
 276   }
 277 
 278   void move_to_next() const {
 279     assert(has_next(), "invariant");
 280     _current = _next;
 281     if (_next < _limit) {
 282       _next = skip_annotation_value(_buffer, _limit, _next + element_name_size);
 283     }
 284     assert(_next <= _limit, "invariant");
 285     assert(_current <= _limit, "invariant");
 286   }
 287 
 288   u2 number_of_elements() const {
 289     return JfrBigEndian::read<u2>(_buffer + number_of_elements_offset);
 290   }
 291 
 292   const Symbol* name() const {
 293     assert(_current < _next, "invariant");
 294     return _ik->constants()->symbol_at(JfrBigEndian::read<u2>(_buffer + _current));
 295   }
 296 
 297   char value_type() const {
 298     return JfrBigEndian::read<u1>(_buffer + _current + value_type_relative_offset);
 299   }
 300 
 301   jint read_int() const {
 302     return _ik->constants()->int_at(value_index());
 303   }
 304 
 305   bool read_bool() const {
 306     return read_int() != 0;
 307   }
 308 };
 309 
 310 class AnnotationIterator : public StackObj {
 311  private:
 312   const InstanceKlass* _ik;
 313   // ensure _limit field is declared before _buffer
 314   u2 _limit; // length of annotations array
 315   const address _buffer;
 316   mutable u2 _current; // annotation
 317   mutable u2 _next; // annotation
 318 
 319  public:
 320   AnnotationIterator(const InstanceKlass* ik, AnnotationArray* ar) : _ik(ik),
 321                                                                      _current(0),
 322                                                                      _next(0),
 323                                                                      _limit(ar != NULL ? ar->length() : 0),
 324                                                                      _buffer(_limit > 2 ? ar->adr_at(2) : NULL) {
 325     if (_buffer != NULL) {
 326       _limit -= 2; // subtract sizeof(u2) number of annotations field
 327     }
 328   }
 329   bool has_next() const {
 330     return _next < _limit;
 331   }
 332 
 333   void move_to_next() const {
 334     assert(has_next(), "invariant");
 335     _current = _next;
 336     if (_next < _limit) {
 337       _next = next_annotation_index(_buffer, _limit, _next);
 338     }
 339     assert(_next <= _limit, "invariant");
 340     assert(_current <= _limit, "invariant");
 341   }
 342   const AnnotationElementIterator elements() const {
 343     assert(_current < _next, "invariant");
 344     return AnnotationElementIterator(_ik, _buffer + _current, _next - _current);
 345   }
 346   const Symbol* type() const {
 347     assert(_buffer != NULL, "invariant");
 348     assert(_current < _limit, "invariant");
 349     return _ik->constants()->symbol_at(JfrBigEndian::read<u2>(_buffer + _current));
 350   }
 351 };
 352 
 353 static unsigned int unused_hash = 0;
 354 static const char value_name[] = "value";
 355 static bool has_registered_annotation(const InstanceKlass* ik, const Symbol* annotation_type, bool& value) {
 356   assert(annotation_type != NULL, "invariant");
 357   AnnotationArray* class_annotations = ik->class_annotations();
 358   if (class_annotations == NULL) {
 359     return false;
 360   }
 361 
 362   const AnnotationIterator annotation_iterator(ik, class_annotations);
 363   while (annotation_iterator.has_next()) {
 364     annotation_iterator.move_to_next();
 365     if (annotation_iterator.type() == annotation_type) {
 366       // target annotation found
 367       static const Symbol* value_symbol =
 368         SymbolTable::lookup_only(value_name, sizeof value_name - 1, unused_hash);
 369       assert(value_symbol != NULL, "invariant");
 370       const AnnotationElementIterator element_iterator = annotation_iterator.elements();
 371       while (element_iterator.has_next()) {
 372         element_iterator.move_to_next();
 373         if (value_symbol == element_iterator.name()) {
 374           // "value" element
 375           assert('Z' == element_iterator.value_type(), "invariant");
 376           value = element_iterator.read_bool();
 377           return true;
 378         }
 379       }
 380     }
 381   }
 382   return false;
 383 }
 384 
 385 static bool registered_annotation_value(const InstanceKlass* ik, const Symbol* const registered_symbol) {
 386   assert(registered_symbol != NULL, "invariant");
 387   assert(ik != NULL, "invariant");
 388   assert(JdkJfrEvent::is_a(ik), "invariant");
 389   bool registered_value = false;
 390   if (has_registered_annotation(ik, registered_symbol, registered_value)) {
 391     return registered_value;
 392   }
 393   InstanceKlass* super = InstanceKlass::cast(ik->super());
 394   return registered_annotation_value(super, registered_symbol);
 395 }
 396 
 397 static const char registered_constant[] = "Ljdk/jfr/Registered;";
 398 
 399 // Evaluate to the value of the first found "Ljdk/jfr/Registered;" annotation.
 400 // Searching moves upwards in the klass hierarchy in order to support
 401 // inherited annotations in addition to the ability to override.
 402 static bool should_register_klass(const InstanceKlass* ik) {
 403   static const Symbol* const registered_symbol = SymbolTable::lookup_only(registered_constant,
 404                                                                           sizeof registered_constant - 1,
 405                                                                           unused_hash);
 406   assert(registered_symbol != NULL, "invariant");
 407   return registered_annotation_value(ik, registered_symbol);
 408 }
 409 /*
 410  * Map an utf8 constant back to its CONSTANT_UTF8_INFO
 411  */
 412 static u2 utf8_info_index(const InstanceKlass* ik, const Symbol* const target, TRAPS) {
 413   assert(target != NULL, "invariant");
 414   ConstantPool* cp = ik->constants();
 415   const int cp_len = cp->length();
 416   for (u2 index = 1; index < cp_len; ++index) {
 417     const constantTag tag = cp->tag_at(index);
 418     if (tag.is_utf8()) {
 419       const Symbol* const utf8_sym = cp->symbol_at(index);
 420       assert(utf8_sym != NULL, "invariant");
 421       if (utf8_sym == target) {
 422         return index;
 423       }
 424     }
 425   }
 426   // not in constant pool
 427   return invalid_cp_index;
 428 }
 429 
 430 #ifdef ASSERT
 431 static bool is_index_within_range(u2 index, u2 orig_cp_len, u2 new_cp_entries_len) {
 432   return index > 0 && index < orig_cp_len + new_cp_entries_len;
 433 }
 434 #endif
 435 
 436 static u2 add_utf8_info(JfrBigEndianWriter& writer, const char* utf8_constant, u2 orig_cp_len, u2& new_cp_entries_len) {
 437   assert(utf8_constant != NULL, "invariant");
 438   writer.write<u1>(JVM_CONSTANT_Utf8);
 439   writer.write_utf8_u2_len(utf8_constant);
 440   assert(writer.is_valid(), "invariant");
 441   // return index for the added utf8 info
 442   return orig_cp_len + new_cp_entries_len++;
 443 }
 444 
 445 static u2 add_method_ref_info(JfrBigEndianWriter& writer,
 446                               u2 cls_name_index,
 447                               u2 method_index,
 448                               u2 desc_index,
 449                               u2 orig_cp_len,
 450                               u2& number_of_new_constants,
 451                               TRAPS) {
 452   assert(is_index_within_range(cls_name_index, orig_cp_len, number_of_new_constants), "invariant");
 453   assert(is_index_within_range(method_index, orig_cp_len, number_of_new_constants), "invariant");
 454   assert(is_index_within_range(desc_index, orig_cp_len, number_of_new_constants), "invariant");
 455   writer.write<u1>(JVM_CONSTANT_Class);
 456   writer.write<u2>(cls_name_index);
 457   const u2 cls_entry_index = orig_cp_len + number_of_new_constants;
 458   ++number_of_new_constants;
 459   writer.write<u1>(JVM_CONSTANT_NameAndType);
 460   writer.write<u2>(method_index);
 461   writer.write<u2>(desc_index);
 462   const u2 nat_entry_index = orig_cp_len + number_of_new_constants;
 463   ++number_of_new_constants;
 464   writer.write<u1>(JVM_CONSTANT_Methodref);
 465   writer.write<u2>(cls_entry_index);
 466   writer.write<u2>(nat_entry_index);
 467   // post-increment number_of_new_constants
 468   // value returned is the index to the added method_ref
 469   return orig_cp_len + number_of_new_constants++;
 470 }
 471 
 472 static u2 add_flr_register_method_constants(JfrBigEndianWriter& writer,
 473                                             const u2* utf8_indexes,
 474                                             u2 orig_cp_len,
 475                                             u2& number_of_new_constants,
 476                                             TRAPS) {
 477   assert(utf8_indexes != NULL, "invariant");
 478   return add_method_ref_info(writer,
 479                              utf8_indexes[UTF8_REQ_FlightRecorder],
 480                              utf8_indexes[UTF8_REQ_register],
 481                              utf8_indexes[UTF8_REQ_CLASS_VOID_METHOD_DESC],
 482                              orig_cp_len,
 483                              number_of_new_constants,
 484                              THREAD);
 485 }
 486 
 487 /*
 488  * field_info {
 489  *   u2             access_flags;
 490  *   u2             name_index;
 491  *   u2             descriptor_index;
 492  *   u2             attributes_count;
 493  *   attribute_info attributes[attributes_count];
 494  * }
 495  */
 496 static jlong add_field_info(JfrBigEndianWriter& writer, u2 name_index, u2 desc_index, bool is_static = false) {
 497   assert(name_index > 0, "invariant");
 498   assert(desc_index > 0, "invariant");
 499   DEBUG_ONLY(const jlong start_offset = writer.current_offset();)
 500   writer.write<u2>(JVM_ACC_SYNTHETIC | JVM_ACC_PRIVATE | (is_static ? JVM_ACC_STATIC : JVM_ACC_TRANSIENT)); // flags
 501   writer.write(name_index);
 502   writer.write(desc_index);
 503   writer.write((u2)0x0); // attributes_count
 504   assert(writer.is_valid(), "invariant");
 505   DEBUG_ONLY(assert(start_offset + 8 == writer.current_offset(), "invariant");)
 506   return writer.current_offset();
 507 }
 508 
 509 static u2 add_field_infos(JfrBigEndianWriter& writer, const u2* utf8_indexes) {
 510   assert(utf8_indexes != NULL, "invariant");
 511   add_field_info(writer,
 512                  utf8_indexes[UTF8_REQ_eventHandler],
 513                  utf8_indexes[UTF8_REQ_eventHandler_FIELD_DESC],
 514                  true); // static
 515 
 516   add_field_info(writer,
 517                  utf8_indexes[UTF8_REQ_startTime],
 518                  utf8_indexes[UTF8_REQ_J_FIELD_DESC]);
 519 
 520   add_field_info(writer,
 521                  utf8_indexes[UTF8_REQ_duration],
 522                  utf8_indexes[UTF8_REQ_J_FIELD_DESC]);
 523 
 524   return number_of_new_fields;
 525 }
 526 
 527 /*
 528  * method_info {
 529  *  u2             access_flags;
 530  *  u2             name_index;
 531  *  u2             descriptor_index;
 532  *  u2             attributes_count;
 533  *  attribute_info attributes[attributes_count];
 534  * }
 535  *
 536  * Code_attribute {
 537  *   u2 attribute_name_index;
 538  *   u4 attribute_length;
 539  *   u2 max_stack;
 540  *   u2 max_locals;
 541  *   u4 code_length;
 542  *   u1 code[code_length];
 543  *   u2 exception_table_length;
 544  *   {   u2 start_pc;
 545  *       u2 end_pc;
 546  *       u2 handler_pc;
 547  *       u2 catch_type;
 548  *   } exception_table[exception_table_length];
 549  *   u2 attributes_count;
 550  *   attribute_info attributes[attributes_count];
 551  * }
 552  */
 553 
 554 static jlong add_method_info(JfrBigEndianWriter& writer,
 555                              u2 name_index,
 556                              u2 desc_index,
 557                              u2 code_index,
 558                              const u1* const code,
 559                              const size_t code_len) {
 560   assert(name_index > 0, "invariant");
 561   assert(desc_index > 0, "invariant");
 562   assert(code_index > 0, "invariant");
 563   DEBUG_ONLY(const jlong start_offset = writer.current_offset();)
 564   writer.write<u2>(JVM_ACC_SYNTHETIC | JVM_ACC_PUBLIC); // flags
 565   writer.write(name_index);
 566   writer.write(desc_index);
 567   writer.write<u2>(0x1); // attributes_count ; 1 for "Code" attribute
 568   assert(writer.is_valid(), "invariant");
 569   DEBUG_ONLY(assert(start_offset + 8 == writer.current_offset(), "invariant");)
 570   // Code attribute
 571   writer.write(code_index); // "Code"
 572   writer.bytes(code, code_len);
 573   DEBUG_ONLY(assert((start_offset + 8 + 2 + (jlong)code_len) == writer.current_offset(), "invariant");)
 574   return writer.current_offset();
 575 }
 576 
 577 /*
 578  * On return, the passed stream will be positioned
 579  * just after the constant pool section in the classfile
 580  * and the cp length is returned.
 581  *
 582  * Stream should come in at the start position.
 583  */
 584 static u2 position_stream_after_cp(ClassFileStream* stream) {
 585   assert(stream != NULL, "invariant");
 586   assert(stream->current_offset() == 0, "invariant");
 587   stream->skip_u4_fast(2);  // 8 bytes skipped
 588   const u2 cp_len = stream->get_u2_fast();
 589   assert(cp_len > 0, "invariant");
 590   // now spin the stream position to just after the constant pool
 591   for (u2 index = 1; index < cp_len; ++index) {
 592     const u1 tag = stream->get_u1_fast(); // cp tag
 593     switch (tag) {
 594       case JVM_CONSTANT_Class:
 595       case JVM_CONSTANT_String: {
 596         stream->skip_u2_fast(1); // skip 2 bytes
 597         continue;
 598       }
 599       case JVM_CONSTANT_Fieldref:
 600       case JVM_CONSTANT_Methodref:
 601       case JVM_CONSTANT_InterfaceMethodref:
 602       case JVM_CONSTANT_Integer:
 603       case JVM_CONSTANT_Float:
 604       case JVM_CONSTANT_NameAndType:
 605       case JVM_CONSTANT_InvokeDynamic: {
 606         stream->skip_u4_fast(1); // skip 4 bytes
 607         continue;
 608       }
 609       case JVM_CONSTANT_Long:
 610       case JVM_CONSTANT_Double: {
 611         stream->skip_u4_fast(2); // skip 8 bytes
 612         // Skip entry following eigth-byte constant, see JVM book p. 98
 613         ++index;
 614         continue;
 615       }
 616       case JVM_CONSTANT_Utf8: {
 617         u2 utf8_length = stream->get_u2_fast();
 618         stream->skip_u1_fast(utf8_length); // skip 2 + len bytes
 619         continue;
 620       }
 621       case JVM_CONSTANT_MethodHandle:
 622       case JVM_CONSTANT_MethodType: {
 623         if (tag == JVM_CONSTANT_MethodHandle) {
 624           stream->skip_u1_fast(1);
 625           stream->skip_u2_fast(1); // skip 3 bytes
 626         }
 627         else if (tag == JVM_CONSTANT_MethodType) {
 628           stream->skip_u2_fast(1); // skip 3 bytes
 629         }
 630       }
 631       continue;
 632       default:
 633         assert(false, "error in skip logic!");
 634         break;
 635     } // end switch(tag)
 636   }
 637   return cp_len;
 638 }
 639 
 640 /*
 641 * On return, the passed stream will be positioned
 642 * just after the fields section in the classfile
 643 * and the number of fields will be returned.
 644 *
 645 * Stream should come in positioned just before fields_count
 646 */
 647 static u2 position_stream_after_fields(ClassFileStream* stream) {
 648   assert(stream != NULL, "invariant");
 649   assert(stream->current_offset() > 0, "invariant");
 650   // fields len
 651   const u2 orig_fields_len = stream->get_u2_fast();
 652   // fields
 653   for (u2 i = 0; i < orig_fields_len; ++i) {
 654     stream->skip_u2_fast(3);
 655     const u2 attrib_info_len = stream->get_u2_fast();
 656     for (u2 j = 0; j < attrib_info_len; ++j) {
 657       stream->skip_u2_fast(1);
 658       const u4 attrib_len = stream->get_u4_fast();
 659       stream->skip_u1_fast(attrib_len);
 660     }
 661   }
 662   return orig_fields_len;
 663 }
 664 
 665 /*
 666 * On return, the passed stream will be positioned
 667 * just after the methods section in the classfile
 668 * and the number of methods will be returned.
 669 *
 670 * Stream should come in positioned just before methods_count
 671 */
 672 static u2 position_stream_after_methods(JfrBigEndianWriter& writer,
 673                                         ClassFileStream* stream,
 674                                         const u2* utf8_indexes,
 675                                         bool register_klass,
 676                                         const Method* clinit_method,
 677                                         u4& orig_method_len_offset) {
 678   assert(stream != NULL, "invariant");
 679   assert(stream->current_offset() > 0, "invariant");
 680   assert(utf8_indexes != NULL, "invariant");
 681   // We will come back to this location when we
 682   // know how many methods there will be.
 683   writer.reserve(sizeof(u2));
 684   const u2 orig_methods_len = stream->get_u2_fast();
 685   // Move copy position past original method_count
 686   // in order to not copy the original count
 687   orig_method_len_offset += sizeof(u2);
 688   for (u2 i = 0; i < orig_methods_len; ++i) {
 689     const u4 method_offset = stream->current_offset();
 690     stream->skip_u2_fast(1); // Access Flags
 691     const u2 name_index = stream->get_u2_fast(); // Name index
 692     stream->skip_u2_fast(1); // Descriptor index
 693     const u2 attributes_count = stream->get_u2_fast();
 694     for (u2 j = 0; j < attributes_count; ++j) {
 695       stream->skip_u2_fast(1);
 696       const u4 attrib_len = stream->get_u4_fast();
 697       stream->skip_u1_fast(attrib_len);
 698     }
 699     if (clinit_method != NULL && name_index == clinit_method->name_index()) {
 700       // The method just parsed is an existing <clinit> method.
 701       // If the class has the @Registered(false) annotation, i.e. marking a class
 702       // for opting out from automatic registration, then we do not need to do anything.
 703       if (!register_klass) {
 704         continue;
 705       }
 706       // Automatic registration with the jfr system is acccomplished
 707       // by pre-pending code to the <clinit> method of the class.
 708       // We will need to re-create a new <clinit> in a later step.
 709       // For now, ensure that this method is excluded from the methods
 710       // being copied.
 711       writer.bytes(stream->buffer() + orig_method_len_offset,
 712                    method_offset - orig_method_len_offset);
 713       assert(writer.is_valid(), "invariant");
 714 
 715       // Update copy position to skip copy of <clinit> method
 716       orig_method_len_offset = stream->current_offset();
 717     }
 718   }
 719   return orig_methods_len;
 720 }
 721 
 722 static u2 add_method_infos(JfrBigEndianWriter& writer, const u2* utf8_indexes) {
 723   assert(utf8_indexes != NULL, "invariant");
 724   add_method_info(writer,
 725                   utf8_indexes[UTF8_REQ_begin],
 726                   utf8_indexes[UTF8_REQ_EMPTY_VOID_METHOD_DESC],
 727                   utf8_indexes[UTF8_REQ_Code],
 728                   empty_void_method_code_attribute,
 729                   sizeof(empty_void_method_code_attribute));
 730 
 731   assert(writer.is_valid(), "invariant");
 732 
 733   add_method_info(writer,
 734                   utf8_indexes[UTF8_REQ_end],
 735                   utf8_indexes[UTF8_REQ_EMPTY_VOID_METHOD_DESC],
 736                   utf8_indexes[UTF8_REQ_Code],
 737                   empty_void_method_code_attribute,
 738                   sizeof(empty_void_method_code_attribute));
 739 
 740   assert(writer.is_valid(), "invariant");
 741 
 742   add_method_info(writer,
 743                   utf8_indexes[UTF8_REQ_commit],
 744                   utf8_indexes[UTF8_REQ_EMPTY_VOID_METHOD_DESC],
 745                   utf8_indexes[UTF8_REQ_Code],
 746                   empty_void_method_code_attribute,
 747                   sizeof(empty_void_method_code_attribute));
 748 
 749   assert(writer.is_valid(), "invariant");
 750 
 751   add_method_info(writer,
 752                   utf8_indexes[UTF8_REQ_isEnabled],
 753                   utf8_indexes[UTF8_REQ_EMPTY_BOOLEAN_METHOD_DESC],
 754                   utf8_indexes[UTF8_REQ_Code],
 755                   boolean_method_code_attribute,
 756                   sizeof(boolean_method_code_attribute));
 757 
 758   assert(writer.is_valid(), "invariant");
 759 
 760   add_method_info(writer,
 761                   utf8_indexes[UTF8_REQ_shouldCommit],
 762                   utf8_indexes[UTF8_REQ_EMPTY_BOOLEAN_METHOD_DESC],
 763                   utf8_indexes[UTF8_REQ_Code],
 764                   boolean_method_code_attribute,
 765                   sizeof(boolean_method_code_attribute));
 766   assert(writer.is_valid(), "invariant");
 767   return number_of_new_methods;
 768 }
 769 
 770 static void adjust_exception_table(JfrBigEndianWriter& writer, u2 bci_adjustment_offset, const Method* method, TRAPS) {
 771   const u2 ex_table_length = method != NULL ? (u2)method->exception_table_length() : 0;
 772   writer.write<u2>(ex_table_length); // Exception table length
 773   if (ex_table_length > 0) {
 774     assert(method != NULL, "invariant");
 775     const ExceptionTableElement* const ex_elements = method->exception_table_start();
 776     for (int i = 0; i < ex_table_length; ++i) {
 777       assert(ex_elements != NULL, "invariant");
 778       writer.write<u2>(ex_elements[i].start_pc + bci_adjustment_offset);
 779       writer.write<u2>(ex_elements[i].end_pc + bci_adjustment_offset);
 780       writer.write<u2>(ex_elements[i].handler_pc + bci_adjustment_offset);
 781       writer.write<u2>(ex_elements[i].catch_type_index); // no adjustment
 782     }
 783   }
 784 }
 785 
 786 enum StackMapFrameTypes {
 787   SAME_FRAME_BEGIN = 0,
 788   SAME_FRAME_END = 63,
 789   SAME_LOCALS_1_STACK_ITEM_FRAME_BEGIN = 64,
 790   SAME_LOCALS_1_STACK_ITEM_FRAME_END = 127,
 791   SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED = 247,
 792   CHOP_FRAME_BEGIN = 248,
 793   CHOP_FRAME_END = 250,
 794   SAME_FRAME_EXTENDED = 251,
 795   APPEND_FRAME_BEGIN = 252,
 796   APPEND_FRAME_END = 254,
 797   FULL_FRAME = 255
 798 };
 799 
 800 static void adjust_stack_map(JfrBigEndianWriter& writer,
 801                              Array<u1>* stack_map,
 802                              const u2* utf8_indexes,
 803                              u2 bci_adjustment_offset,
 804                              TRAPS) {
 805   assert(stack_map != NULL, "invariant");
 806   assert(utf8_indexes != NULL, "invariant");
 807   writer.write<u2>(utf8_indexes[UTF8_OPT_StackMapTable]);
 808   const jlong stack_map_attrib_len_offset = writer.current_offset();
 809   writer.reserve(sizeof(u4));
 810   StackMapStream stream(stack_map);
 811   const u2 stack_map_entries = stream.get_u2(THREAD);
 812   // number of entries
 813   writer.write<u2>(stack_map_entries); // new stack map entry added
 814   const u1 frame_type = stream.get_u1(THREAD);
 815   // SAME_FRAME and SAME_LOCALS_1_STACK_ITEM_FRAME encode
 816   // their offset_delta into the actual frame type itself.
 817   // If such a frame type is the first frame, then we transform
 818   // it to a SAME_FRAME_EXTENDED or a SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED frame.
 819   // This is done in order to not overflow frame types accidentally
 820   // when adjusting the offset_delta. In changing the frame types,
 821   // we can work with an explicit u2 offset_delta field (like the other frame types)
 822   if (frame_type <= SAME_FRAME_END) {
 823     writer.write<u1>(SAME_FRAME_EXTENDED);
 824     writer.write<u2>(frame_type + bci_adjustment_offset);
 825   } else if (frame_type >= SAME_LOCALS_1_STACK_ITEM_FRAME_BEGIN &&
 826              frame_type <= SAME_LOCALS_1_STACK_ITEM_FRAME_END) {
 827     writer.write<u1>(SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED);
 828     writer.write<u2>((frame_type - SAME_LOCALS_1_STACK_ITEM_FRAME_BEGIN) + bci_adjustment_offset);
 829   } else if (frame_type >= SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED) {
 830       // SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED to FULL_FRAME
 831       // has a u2 offset_delta field
 832       writer.write<u1>(frame_type);
 833       writer.write<u2>(stream.get_u2(THREAD) + bci_adjustment_offset);
 834   } else {
 835     assert(false, "stackMapFrame type is invalid");
 836   }
 837 
 838   while (!stream.at_end()) {
 839     writer.write<u1>(stream.get_u1(THREAD));
 840   }
 841 
 842   u4 stack_map_attrib_len = writer.current_offset() - stack_map_attrib_len_offset;
 843   // the stack_map_table_attributes_length value is exclusive
 844   stack_map_attrib_len -= sizeof(u4);
 845   writer.write_at_offset(stack_map_attrib_len, stack_map_attrib_len_offset);
 846 }
 847 
 848 static void adjust_line_number_table(JfrBigEndianWriter& writer,
 849                                      const u2* utf8_indexes,
 850                                      u4 bci_adjustement_offset,
 851                                      const Method* method,
 852                                      TRAPS) {
 853   assert(utf8_indexes != NULL, "invariant");
 854   assert(method != NULL, "invariant");
 855   assert(method->has_linenumber_table(), "invariant");
 856   writer.write(utf8_indexes[UTF8_OPT_LineNumberTable]);
 857   const jlong lnt_attributes_length_offset = writer.current_offset();
 858   writer.reserve(sizeof(u4));
 859   const jlong lnt_attributes_entries_offset = writer.current_offset();
 860   writer.reserve(sizeof(u2));
 861   u1* lnt = method->compressed_linenumber_table();
 862   CompressedLineNumberReadStream lnt_stream(lnt);
 863   u2 line_number_table_entries = 0;
 864   while (lnt_stream.read_pair()) {
 865     ++line_number_table_entries;
 866     const u2 bci = (u2)lnt_stream.bci();
 867     writer.write<u2>(bci + (u2)bci_adjustement_offset);
 868     writer.write<u2>((u2)lnt_stream.line());
 869   }
 870   writer.write_at_offset(line_number_table_entries, lnt_attributes_entries_offset);
 871   u4 lnt_table_attributes_len = writer.current_offset() - lnt_attributes_length_offset;
 872   // the line_number_table_attributes_length value is exclusive
 873   lnt_table_attributes_len -= sizeof(u4);
 874   writer.write_at_offset(lnt_table_attributes_len, lnt_attributes_length_offset);
 875 }
 876 
 877 // returns the number of lvtt entries
 878 static u2 adjust_local_variable_table(JfrBigEndianWriter& writer,
 879                                      const u2* utf8_indexes,
 880                                      u2 bci_adjustment_offset,
 881                                      const Method* method,
 882                                      TRAPS) {
 883  assert(utf8_indexes != NULL, "invariant");
 884  assert(method != NULL, "invariant");
 885  assert(method->has_localvariable_table(), "invariant");
 886  writer.write<u2>(utf8_indexes[UTF8_OPT_LocalVariableTable]);
 887  const jlong lvt_attributes_length_offset = writer.current_offset();
 888  writer.reserve(sizeof(u4));
 889  const int lvt_len = method->localvariable_table_length();
 890  writer.write<u2>((u2)lvt_len);
 891  const LocalVariableTableElement* table = method->localvariable_table_start();
 892  assert(table != NULL, "invariant");
 893  u2 num_lvtt_entries = 0;
 894  for (int i = 0; i < lvt_len; ++i) {
 895    writer.write<u2>(table[i].start_bci + bci_adjustment_offset);
 896    writer.write<u2>(table[i].length);
 897    writer.write<u2>(table[i].name_cp_index);
 898    writer.write<u2>(table[i].descriptor_cp_index);
 899    writer.write<u2>(table[i].slot);
 900    if (table[i].signature_cp_index > 0) {
 901      ++num_lvtt_entries;
 902    }
 903  }
 904  u4 lvt_table_attributes_len = writer.current_offset() - lvt_attributes_length_offset;
 905  // the lvt_table_attributes_length value is exclusive
 906  lvt_table_attributes_len -= sizeof(u4);
 907  writer.write_at_offset(lvt_table_attributes_len, lvt_attributes_length_offset);
 908  return num_lvtt_entries;
 909 }
 910 
 911 static void adjust_local_variable_type_table(JfrBigEndianWriter& writer,
 912                                            const u2* utf8_indexes,
 913                                            u2 bci_adjustment_offset,
 914                                            u2 num_lvtt_entries,
 915                                            const Method* method,
 916                                            TRAPS) {
 917  assert(num_lvtt_entries > 0, "invariant");
 918  writer.write<u2>(utf8_indexes[UTF8_OPT_LocalVariableTypeTable]);
 919  const jlong lvtt_attributes_length_offset = writer.current_offset();
 920  writer.reserve(sizeof(u4));
 921  writer.write<u2>(num_lvtt_entries);
 922  const LocalVariableTableElement* table = method->localvariable_table_start();
 923  assert(table != NULL, "invariant");
 924  const int lvt_len = method->localvariable_table_length();
 925  for (int i = 0; i < lvt_len; ++i) {
 926    if (table[i].signature_cp_index > 0) {
 927      writer.write<u2>(table[i].start_bci + bci_adjustment_offset);
 928      writer.write<u2>(table[i].length);
 929      writer.write<u2>(table[i].name_cp_index);
 930      writer.write<u2>(table[i].signature_cp_index);
 931      writer.write<u2>(table[i].slot);
 932    }
 933  }
 934  u4 lvtt_table_attributes_len = writer.current_offset() - lvtt_attributes_length_offset;
 935  // the lvtt_table_attributes_length value is exclusive
 936  lvtt_table_attributes_len -= sizeof(u4);
 937  writer.write_at_offset(lvtt_table_attributes_len, lvtt_attributes_length_offset);
 938 }
 939 
 940 static void adjust_code_attributes(JfrBigEndianWriter& writer,
 941                                   const u2* utf8_indexes,
 942                                   u2 bci_adjustment_offset,
 943                                   const Method* clinit_method,
 944                                   TRAPS) {
 945  // "Code" attributes
 946  assert(utf8_indexes != NULL, "invariant");
 947  const jlong code_attributes_offset = writer.current_offset();
 948  writer.reserve(sizeof(u2));
 949  u2 number_of_code_attributes = 0;
 950  if (clinit_method != NULL) {
 951    Array<u1>* stack_map = clinit_method->stackmap_data();
 952    if (stack_map != NULL) {
 953      ++number_of_code_attributes;
 954      adjust_stack_map(writer, stack_map, utf8_indexes, bci_adjustment_offset, THREAD);
 955      assert(writer.is_valid(), "invariant");
 956    }
 957    if (clinit_method != NULL && clinit_method->has_linenumber_table()) {
 958      ++number_of_code_attributes;
 959      adjust_line_number_table(writer, utf8_indexes, bci_adjustment_offset, clinit_method, THREAD);
 960      assert(writer.is_valid(), "invariant");
 961    }
 962    if (clinit_method != NULL && clinit_method->has_localvariable_table()) {
 963      ++number_of_code_attributes;
 964      const u2 num_of_lvtt_entries = adjust_local_variable_table(writer, utf8_indexes, bci_adjustment_offset, clinit_method, THREAD);
 965      assert(writer.is_valid(), "invariant");
 966      if (num_of_lvtt_entries > 0) {
 967        ++number_of_code_attributes;
 968        adjust_local_variable_type_table(writer, utf8_indexes, bci_adjustment_offset, num_of_lvtt_entries, clinit_method, THREAD);
 969        assert(writer.is_valid(), "invariant");
 970      }
 971    }
 972  }
 973 
 974  // Store the number of code_attributes
 975  writer.write_at_offset(number_of_code_attributes, code_attributes_offset);
 976 }
 977 
 978 static jlong insert_clinit_method(const InstanceKlass* ik,
 979                                  ClassFileParser& parser,
 980                                  JfrBigEndianWriter& writer,
 981                                  u2 orig_constant_pool_len,
 982                                  const u2* utf8_indexes,
 983                                  const u2 register_method_ref_index,
 984                                  const Method* clinit_method,
 985                                  TRAPS) {
 986  assert(utf8_indexes != NULL, "invariant");
 987  // The injected code length is always this value.
 988  // This is to ensure that padding can be done
 989  // where needed and to simplify size calculations.
 990  static const u2 injected_code_length = 8;
 991  const u2 name_index = utf8_indexes[UTF8_REQ_clinit];
 992  const u2 desc_index = utf8_indexes[UTF8_REQ_EMPTY_VOID_METHOD_DESC];
 993  const u2 max_stack = MAX2(clinit_method != NULL ? clinit_method->verifier_max_stack() : 1, 1);
 994  const u2 max_locals = MAX2(clinit_method != NULL ? clinit_method->max_locals() : 0, 0);
 995  const u2 orig_bytecodes_length = clinit_method != NULL ? (u2)clinit_method->code_size() : 0;
 996  const address orig_bytecodes = clinit_method != NULL ? clinit_method->code_base() : NULL;
 997  const u2 new_code_length = injected_code_length + orig_bytecodes_length;
 998  DEBUG_ONLY(const jlong start_offset = writer.current_offset();)
 999  writer.write<u2>(JVM_ACC_STATIC); // flags
1000  writer.write<u2>(name_index);
1001  writer.write<u2>(desc_index);
1002  writer.write<u2>((u2)0x1); // attributes_count // "Code"
1003  assert(writer.is_valid(), "invariant");
1004  DEBUG_ONLY(assert(start_offset + 8 == writer.current_offset(), "invariant");)
1005  // "Code" attribute
1006  writer.write<u2>(utf8_indexes[UTF8_REQ_Code]); // "Code"
1007  const jlong code_attribute_length_offset = writer.current_offset();
1008  writer.reserve(sizeof(u4));
1009  writer.write<u2>(max_stack); // max stack
1010  writer.write<u2>(max_locals); // max locals
1011  writer.write<u4>((u4)new_code_length); // code length
1012 
1013  /* BEGIN CLINIT CODE */
1014 
1015  // Note the use of ldc_w here instead of ldc.
1016  // This is to handle all values of "this_class_index"
1017  writer.write<u1>((u1)Bytecodes::_ldc_w);
1018  writer.write<u2>((u2)parser.this_class_index()); // load constant "this class"
1019  writer.write<u1>((u1)Bytecodes::_invokestatic);
1020  // invoke "FlightRecorder.register(Ljava/lang/Class;")
1021  writer.write<u2>(register_method_ref_index);
1022  if (clinit_method == NULL) {
1023    writer.write<u1>((u1)Bytecodes::_nop);
1024    writer.write<u1>((u1)Bytecodes::_return);
1025  } else {
1026    // If we are pre-pending to original code,
1027    // do padding to minimize disruption to the original.
1028    // It might have dependencies on 4-byte boundaries
1029    // i.e. lookupswitch and tableswitch instructions
1030    writer.write<u1>((u1)Bytecodes::_nop);
1031    writer.write<u1>((u1)Bytecodes::_nop);
1032    // insert original clinit code
1033    writer.bytes(orig_bytecodes, orig_bytecodes_length);
1034  }
1035 
1036  /* END CLINIT CODE */
1037 
1038  assert(writer.is_valid(), "invariant");
1039  adjust_exception_table(writer, injected_code_length, clinit_method, THREAD);
1040  assert(writer.is_valid(), "invariant");
1041  adjust_code_attributes(writer, utf8_indexes, injected_code_length, clinit_method, THREAD);
1042  assert(writer.is_valid(), "invariant");
1043  u4 code_attribute_len = writer.current_offset() - code_attribute_length_offset;
1044  // the code_attribute_length value is exclusive
1045  code_attribute_len -= sizeof(u4);
1046  writer.write_at_offset(code_attribute_len, code_attribute_length_offset);
1047  return writer.current_offset();
1048 }
1049 
1050 // Caller needs ResourceMark
1051 static ClassFileStream* create_new_bytes_for_event_klass(const InstanceKlass* ik, const ClassFileParser& parser, TRAPS) {
1052  DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(THREAD));
1053  static const u2 public_final_flag_mask = JVM_ACC_PUBLIC | JVM_ACC_FINAL;
1054  ClassFileStream* const orig_stream = parser.clone_stream();
1055  const int orig_stream_length = orig_stream->length();
1056  // allocate an identically sized buffer
1057  u1* const new_buffer = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, u1, orig_stream_length);
1058  if (new_buffer == NULL) {
1059    return NULL;
1060  }
1061  assert(new_buffer != NULL, "invariant");
1062  // memcpy the entire [B
1063  memcpy(new_buffer, orig_stream->buffer(), orig_stream_length);
1064  const u2 orig_cp_len = position_stream_after_cp(orig_stream);
1065  assert(orig_cp_len > 0, "invariant");
1066  assert(orig_stream->current_offset() > 0, "invariant");
1067  orig_stream->skip_u2_fast(3); // access_flags, this_class_index, super_class_index
1068  const u2 iface_len = orig_stream->get_u2_fast();
1069  orig_stream->skip_u2_fast(iface_len);
1070  // fields len
1071  const u2 orig_fields_len = orig_stream->get_u2_fast();
1072  // fields
1073  for (u2 i = 0; i < orig_fields_len; ++i) {
1074    orig_stream->skip_u2_fast(3);
1075    const u2 attrib_info_len = orig_stream->get_u2_fast();
1076    for (u2 j = 0; j < attrib_info_len; ++j) {
1077      orig_stream->skip_u2_fast(1);
1078      const u4 attrib_len = orig_stream->get_u4_fast();
1079      orig_stream->skip_u1_fast(attrib_len);
1080    }
1081  }
1082  // methods
1083  const u2 orig_methods_len = orig_stream->get_u2_fast();
1084  for (u2 i = 0; i < orig_methods_len; ++i) {
1085    const u4 access_flag_offset = orig_stream->current_offset();
1086    const u2 flags = orig_stream->get_u2_fast();
1087    // Rewrite JVM_ACC_FINAL -> JVM_ACC_PUBLIC
1088    if (public_final_flag_mask == flags) {
1089      JfrBigEndianWriter accessflagsrewriter(new_buffer + access_flag_offset, sizeof(u2));
1090      accessflagsrewriter.write<u2>(JVM_ACC_PUBLIC);
1091      assert(accessflagsrewriter.is_valid(), "invariant");
1092    }
1093    orig_stream->skip_u2_fast(2);
1094    const u2 attributes_count = orig_stream->get_u2_fast();
1095    for (u2 j = 0; j < attributes_count; ++j) {
1096      orig_stream->skip_u2_fast(1);
1097      const u4 attrib_len = orig_stream->get_u4_fast();
1098      orig_stream->skip_u1_fast(attrib_len);
1099    }
1100  }
1101  return new ClassFileStream(new_buffer, orig_stream_length, NULL);
1102 }
1103 
1104 // Attempt to locate an existing UTF8_INFO mapping the utf8_constant.
1105 // If no UTF8_INFO exists, add (append) a new one to the constant pool.
1106 static u2 find_or_add_utf8_info(JfrBigEndianWriter& writer,
1107                                const InstanceKlass* ik,
1108                                const char* const utf8_constant,
1109                                u2 orig_cp_len,
1110                                u2& added_cp_entries,
1111                                TRAPS) {
1112  assert(utf8_constant != NULL, "invariant");
1113  TempNewSymbol utf8_sym = SymbolTable::new_symbol(utf8_constant, THREAD);
1114  // lookup existing
1115  const int utf8_orig_idx = utf8_info_index(ik, utf8_sym, THREAD);
1116  if (utf8_orig_idx != invalid_cp_index) {
1117    // existing constant pool entry found
1118    return utf8_orig_idx;
1119  }
1120  // no existing match, need to add a new utf8 cp entry
1121  assert(invalid_cp_index == utf8_orig_idx, "invariant");
1122  // add / append new
1123  return add_utf8_info(writer, utf8_constant, orig_cp_len, added_cp_entries);
1124 }
1125 
1126 /*
1127  * This routine will resolve the required utf8_constants array
1128  * to their constant pool indexes (mapping to their UTF8_INFO's)
1129  * Only if a constant is actually needed and does not already exist
1130  * will it be added.
1131  *
1132  * The passed in indexes array will be populated with the resolved indexes.
1133  * The number of newly added constant pool entries is returned.
1134  */
1135 static u2 resolve_utf8_indexes(JfrBigEndianWriter& writer,
1136                               const InstanceKlass* ik,
1137                               u2* const utf8_indexes,
1138                               u2 orig_cp_len,
1139                               const Method* clinit_method,
1140                               TRAPS) {
1141  assert(utf8_indexes != NULL, "invariant");
1142  u2 added_cp_entries = 0;
1143  // resolve all required symbols
1144  for (u2 index = 0; index < NOF_UTF8_REQ_SYMBOLS; ++index) {
1145    utf8_indexes[index] = find_or_add_utf8_info(writer,
1146                                                ik,
1147                                                utf8_constants[index],
1148                                                orig_cp_len,
1149                                                added_cp_entries,
1150                                                THREAD);
1151  }
1152  // Now determine optional constants (mainly "Code" attributes)
1153  if (clinit_method != NULL && clinit_method->has_stackmap_table()) {
1154    utf8_indexes[UTF8_OPT_StackMapTable] =
1155      find_or_add_utf8_info(writer,
1156                            ik,
1157                            utf8_constants[UTF8_OPT_StackMapTable],
1158                            orig_cp_len,
1159                            added_cp_entries,
1160                            THREAD);
1161  } else {
1162    utf8_indexes[UTF8_OPT_StackMapTable] = invalid_cp_index;
1163  }
1164 
1165  if (clinit_method != NULL && clinit_method->has_linenumber_table()) {
1166    utf8_indexes[UTF8_OPT_LineNumberTable] =
1167      find_or_add_utf8_info(writer,
1168                            ik,
1169                            utf8_constants[UTF8_OPT_LineNumberTable],
1170                            orig_cp_len,
1171                            added_cp_entries,
1172                            THREAD);
1173  } else {
1174    utf8_indexes[UTF8_OPT_LineNumberTable] = invalid_cp_index;
1175  }
1176 
1177  if (clinit_method != NULL && clinit_method->has_localvariable_table()) {
1178    utf8_indexes[UTF8_OPT_LocalVariableTable] =
1179      find_or_add_utf8_info(writer,
1180                            ik,
1181                            utf8_constants[UTF8_OPT_LocalVariableTable],
1182                            orig_cp_len,
1183                            added_cp_entries,
1184                            THREAD);
1185 
1186    utf8_indexes[UTF8_OPT_LocalVariableTypeTable] =
1187      find_or_add_utf8_info(writer,
1188                            ik,
1189                            utf8_constants[UTF8_OPT_LocalVariableTypeTable],
1190                            orig_cp_len,
1191                            added_cp_entries,
1192                            THREAD);
1193  } else {
1194    utf8_indexes[UTF8_OPT_LocalVariableTable] = invalid_cp_index;
1195    utf8_indexes[UTF8_OPT_LocalVariableTypeTable] = invalid_cp_index;
1196  }
1197 
1198  return added_cp_entries;
1199 }
1200 
1201 static u1* new_bytes_for_lazy_instrumentation(InstanceKlass* ik,
1202                                              ClassFileParser& parser,
1203                                              jint& size_of_new_bytes,
1204                                              TRAPS) {
1205  assert(ik != NULL, "invariant");
1206  // If the class already has a clinit method
1207  // we need to take that into account
1208  const Method* clinit_method = ik->class_initializer();
1209  const bool register_klass = should_register_klass(ik);
1210  ClassFileStream* const orig_stream = parser.clone_stream();
1211  const int orig_stream_size = orig_stream->length();
1212  assert(orig_stream->current_offset() == 0, "invariant");
1213  const u2 orig_cp_len = position_stream_after_cp(orig_stream);
1214  assert(orig_cp_len > 0, "invariant");
1215  assert(orig_stream->current_offset() > 0, "invariant");
1216  // Dimension and allocate a working byte buffer
1217  // to be used in building up a modified class [B.
1218  const jint new_buffer_size = extra_stream_bytes + orig_stream_size;
1219  u1* const new_buffer = NEW_RESOURCE_ARRAY_IN_THREAD_RETURN_NULL(THREAD, u1, new_buffer_size);
1220  if (new_buffer == NULL) {
1221    if (true) tty->print_cr ("Thread local allocation (native) for " SIZE_FORMAT
1222      " bytes failed in JfrClassAdapter::on_klass_creation", (size_t)new_buffer_size);
1223    return NULL;
1224  }
1225  assert(new_buffer != NULL, "invariant");
1226  // [B wrapped in a big endian writer
1227  JfrBigEndianWriter writer(new_buffer, new_buffer_size);
1228  assert(writer.current_offset() == 0, "invariant");
1229  const u4 orig_access_flag_offset = orig_stream->current_offset();
1230  // Copy original stream from the beginning up to AccessFlags
1231  // This means the original constant pool contents are copied unmodified
1232  writer.bytes(orig_stream->buffer(), orig_access_flag_offset);
1233  assert(writer.is_valid(), "invariant");
1234  assert(writer.current_offset() == (intptr_t)orig_access_flag_offset, "invariant"); // same positions
1235  // Our writer now sits just after the last original constant pool entry.
1236  // I.e. we are in a good position to append new constant pool entries
1237  // This array will contain the resolved indexes
1238  // in order to reference UTF8_INFO's needed
1239  u2 utf8_indexes[NOF_UTF8_SYMBOLS];
1240  // Resolve_utf8_indexes will be conservative in attempting to
1241  // locate an existing UTF8_INFO; it will only append constants
1242  // that is absolutely required
1243  u2 number_of_new_constants = resolve_utf8_indexes(writer, ik, utf8_indexes, orig_cp_len, clinit_method, THREAD);
1244  // UTF8_INFO entries now added to the constant pool
1245  // In order to invoke a method we would need additional
1246  // constants, JVM_CONSTANT_Class, JVM_CONSTANT_NameAndType
1247  // and JVM_CONSTANT_Methodref.
1248  const u2 flr_register_method_ref_index =
1249    register_klass ?
1250      add_flr_register_method_constants(writer,
1251                                        utf8_indexes,
1252                                        orig_cp_len,
1253                                        number_of_new_constants,
1254                                        THREAD) :  invalid_cp_index;
1255 
1256  // New constant pool entries added and all UTF8_INFO indexes resolved
1257  // Now update the class file constant_pool_count with an updated count
1258  writer.write_at_offset<u2>(orig_cp_len + number_of_new_constants, 8);
1259  assert(writer.is_valid(), "invariant");
1260  orig_stream->skip_u2_fast(3); // access_flags, this_class_index, super_class_index
1261  const u2 iface_len = orig_stream->get_u2_fast(); // interfaces
1262  orig_stream->skip_u2_fast(iface_len);
1263  const u4 orig_fields_len_offset = orig_stream->current_offset();
1264  // Copy from AccessFlags up to and including interfaces
1265  writer.bytes(orig_stream->buffer() + orig_access_flag_offset,
1266               orig_fields_len_offset - orig_access_flag_offset);
1267  assert(writer.is_valid(), "invariant");
1268  const jlong new_fields_len_offset = writer.current_offset();
1269  const u2 orig_fields_len = position_stream_after_fields(orig_stream);
1270  u4 orig_method_len_offset = orig_stream->current_offset();
1271  // Copy up to and including fields
1272  writer.bytes(orig_stream->buffer() + orig_fields_len_offset, orig_method_len_offset - orig_fields_len_offset);
1273  assert(writer.is_valid(), "invariant");
1274  // We are sitting just after the original number of field_infos
1275  // so this is a position where we can add (append) new field_infos
1276  const u2 number_of_new_fields = add_field_infos(writer, utf8_indexes);
1277  assert(writer.is_valid(), "invariant");
1278  const jlong new_method_len_offset = writer.current_offset();
1279  // Additional field_infos added, update classfile fields_count
1280  writer.write_at_offset<u2>(orig_fields_len + number_of_new_fields, new_fields_len_offset);
1281  assert(writer.is_valid(), "invariant");
1282  // Our current location is now at classfile methods_count
1283  const u2 orig_methods_len = position_stream_after_methods(writer,
1284                                                            orig_stream,
1285                                                            utf8_indexes,
1286                                                            register_klass,
1287                                                            clinit_method,
1288                                                            orig_method_len_offset);
1289  const u4 orig_attributes_count_offset = orig_stream->current_offset();
1290  // Copy existing methods
1291  writer.bytes(orig_stream->buffer() + orig_method_len_offset, orig_attributes_count_offset - orig_method_len_offset);
1292  assert(writer.is_valid(), "invariant");
1293  // We are sitting just after the original number of method_infos
1294  // so this is a position where we can add (append) new method_infos
1295  u2 number_of_new_methods = add_method_infos(writer, utf8_indexes);
1296 
1297  // We have just added the new methods.
1298  //
1299  // What about the state of <clinit>?
1300  // We would need to do:
1301  // 1. Nothing (@Registered(false) annotation)
1302  // 2. Build up a new <clinit> - and if the original class already contains a <clinit>,
1303  //                              merging will be neccessary.
1304  //
1305  if (register_klass) {
1306    insert_clinit_method(ik, parser, writer, orig_cp_len, utf8_indexes, flr_register_method_ref_index, clinit_method, THREAD);
1307  }
1308  number_of_new_methods += clinit_method != NULL ? 0 : register_klass ? 1 : 0;
1309  // Update classfile methods_count
1310  writer.write_at_offset<u2>(orig_methods_len + number_of_new_methods, new_method_len_offset);
1311  assert(writer.is_valid(), "invariant");
1312  // Copy last remaining bytes
1313  writer.bytes(orig_stream->buffer() + orig_attributes_count_offset, orig_stream_size - orig_attributes_count_offset);
1314  assert(writer.is_valid(), "invariant");
1315  assert(writer.current_offset() > orig_stream->length(), "invariant");
1316  size_of_new_bytes = (jint)writer.current_offset();
1317  return new_buffer;
1318 }
1319 
1320 static void log_pending_exception(oop throwable) {
1321  assert(throwable != NULL, "invariant");
1322  oop msg = java_lang_Throwable::message(throwable);
1323  if (msg != NULL) {
1324    char* text = java_lang_String::as_utf8_string(msg);
1325    if (text != NULL) {
1326      if (true) tty->print_cr ("%s", text);
1327    }
1328  }
1329 }
1330 
1331 static bool should_force_instrumentation() {
1332  return !JfrOptionSet::allow_event_retransforms() || JfrEventClassTransformer::is_force_instrumentation();
1333 }
1334 
1335 static ClassFileStream* create_new_bytes_for_subklass(InstanceKlass* ik, ClassFileParser& parser, Thread* t) {
1336  assert(JdkJfrEvent::is_a(ik), "invariant");
1337  DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(t));
1338  jint size_of_new_bytes = 0;
1339  u1* new_bytes = new_bytes_for_lazy_instrumentation(ik, parser, size_of_new_bytes, t);
1340  if (new_bytes == NULL) {
1341    return NULL;
1342  }
1343  assert(new_bytes != NULL, "invariant");
1344  assert(size_of_new_bytes > 0, "invariant");
1345 
1346  bool force_instrumentation = should_force_instrumentation();
1347  if (Jfr::is_recording() || force_instrumentation) {
1348    jint size_instrumented_data = 0;
1349    unsigned char* instrumented_data = NULL;
1350    const jclass super = (jclass)JNIHandles::make_local(ik->super()->java_mirror());
1351    JfrUpcalls::new_bytes_eager_instrumentation(TRACE_ID(ik),
1352                                                force_instrumentation,
1353                                                super,
1354                                                size_of_new_bytes,
1355                                                new_bytes,
1356                                                &size_instrumented_data,
1357                                                &instrumented_data,
1358                                                t);
1359    if (t->has_pending_exception()) {
1360      log_pending_exception(t->pending_exception());
1361      t->clear_pending_exception();
1362      return NULL;
1363    }
1364    assert(instrumented_data != NULL, "invariant");
1365    assert(size_instrumented_data > 0, "invariant");
1366    return new ClassFileStream(instrumented_data, size_instrumented_data, NULL);
1367  }
1368  return new ClassFileStream(new_bytes, size_of_new_bytes, NULL);
1369 }
1370 
1371 static bool cache_bytes(InstanceKlass* ik, ClassFileStream* new_stream, InstanceKlass* new_ik, TRAPS) {
1372  assert(ik != NULL, "invariant");
1373  assert(new_ik != NULL, "invariant");
1374  assert(new_ik->name() != NULL, "invariant");
1375  assert(new_stream != NULL, "invariant");
1376  assert(!HAS_PENDING_EXCEPTION, "invariant");
1377  static const bool can_retransform = JfrOptionSet::allow_retransforms();
1378  if (!can_retransform) {
1379    return true;
1380  }
1381  const jint stream_len = new_stream->length();
1382  JvmtiCachedClassFileData* p =
1383    (JvmtiCachedClassFileData*)NEW_C_HEAP_ARRAY_RETURN_NULL(u1, offset_of(JvmtiCachedClassFileData, data) + stream_len, mtInternal);
1384  if (p == NULL) {
1385    if (true) tty->print_cr("Allocation using C_HEAP_ARRAY for " SIZE_FORMAT
1386      " bytes failed in JfrClassAdapter::on_klass_creation", (size_t)offset_of(JvmtiCachedClassFileData, data) + stream_len);
1387    return false;
1388  }
1389  p->length = stream_len;
1390  memcpy(p->data, new_stream->buffer(), stream_len);
1391  new_ik->set_cached_class_file(p);
1392  JvmtiCachedClassFileData* const cached_class_data = ik->get_cached_class_file();
1393  if (cached_class_data != NULL) {
1394    os::free(cached_class_data);
1395    ik->set_cached_class_file(NULL);
1396  }
1397  return true;
1398 }
1399 
1400 static InstanceKlass* create_new_instance_klass(InstanceKlass* ik, ClassFileStream* stream, TRAPS) {
1401  assert(stream != NULL, "invariant");
1402  ResourceMark rm(THREAD);
1403 TempNewSymbol parsed_name = NULL;
1404  ClassLoaderData* const cld = ik->class_loader_data();
1405  Handle pd(THREAD, ik->protection_domain());
1406  Symbol* const class_name = ik->name();
1407  const char* const klass_name = class_name != NULL ? class_name->as_C_string() : "";
1408  InstanceKlass* const new_ik = ClassFileParser(stream).parseClassFile(
1409                             class_name,
1410                             cld,
1411                             pd,
1412                             NULL, // host klass
1413                             NULL, // cp_patches
1414                             parsed_name,
1415                             true, // need_verify
1416                             THREAD)();
1417  if (HAS_PENDING_EXCEPTION) {
1418    log_pending_exception(PENDING_EXCEPTION);
1419    CLEAR_PENDING_EXCEPTION;
1420    return NULL;
1421  }
1422  assert(new_ik != NULL, "invariant");
1423  assert(new_ik->name() != NULL, "invariant");
1424  assert(strncmp(ik->name()->as_C_string(), new_ik->name()->as_C_string(), strlen(ik->name()->as_C_string())) == 0, "invariant");
1425  return cache_bytes(ik, stream, new_ik, THREAD) ? new_ik : NULL;
1426 }
1427 
1428 static void rewrite_klass_pointer(InstanceKlass*& ik, InstanceKlass* new_ik, ClassFileParser& parser, TRAPS) {
1429  assert(ik != NULL, "invariant");
1430  assert(new_ik != NULL, "invariant");
1431  assert(new_ik->name() != NULL, "invariant");
1432  assert(JdkJfrEvent::is(new_ik) || JdkJfrEvent::is_subklass(new_ik), "invariant");
1433  assert(!HAS_PENDING_EXCEPTION, "invariant");
1434  // assign original InstanceKlass* back onto "its" parser object for proper destruction
1435  parser.set_klass_to_deallocate(ik);
1436  // now rewrite original pointer to newly created InstanceKlass
1437  ik = new_ik;
1438 }
1439 
1440 // During retransform/redefine, copy the Method specific trace flags
1441 // from the previous ik ("the original klass") to the new ik ("the scratch_klass").
1442 // The open code for retransform/redefine does not know about these.
1443 // In doing this migration here, we ensure the new Methods (defined in scratch klass)
1444 // will carry over trace tags from the old Methods being replaced,
1445 // ensuring flag/tag continuity while being transparent to open code.
1446 static void copy_method_trace_flags(const InstanceKlass* the_original_klass, const InstanceKlass* the_scratch_klass) {
1447   assert(the_original_klass != NULL, "invariant");
1448   assert(the_scratch_klass != NULL, "invariant");
1449   assert(the_original_klass->name() == the_scratch_klass->name(), "invariant");
1450   const Array<Method*>* old_methods = the_original_klass->methods();
1451   const Array<Method*>* new_methods = the_scratch_klass->methods();
1452   const bool equal_array_length = old_methods->length() == new_methods->length();
1453   // The Method array has the property of being sorted.
1454   // If they are the same length, there is a one-to-one mapping.
1455   // If they are unequal, there was a method added (currently only
1456   // private static methods allowed to be added), use lookup.
1457   for (int i = 0; i < old_methods->length(); ++i) {
1458     const Method* const old_method = old_methods->at(i);
1459     Method* const new_method = equal_array_length ? new_methods->at(i) :
1460       the_scratch_klass->find_method(old_method->name(), old_method->signature());
1461     assert(new_method != NULL, "invariant");
1462     assert(new_method->name() == old_method->name(), "invariant");
1463     assert(new_method->signature() == old_method->signature(), "invariant");
1464     *new_method->trace_flags_addr() = old_method->trace_flags();
1465     assert(new_method->trace_flags() == old_method->trace_flags(), "invariant");
1466   }
1467 }
1468 
1469 static bool is_retransforming(const InstanceKlass* ik, TRAPS) {
1470   assert(ik != NULL, "invariant");
1471   assert(JdkJfrEvent::is_a(ik), "invariant");
1472   Symbol* const name = ik->name();
1473   assert(name != NULL, "invariant");
1474   Handle class_loader(THREAD, ik->class_loader());
1475   Handle protection_domain(THREAD, ik->protection_domain());
1476   // nota bene: use lock-free dictionary lookup
1477   const InstanceKlass* prev_ik = (const InstanceKlass*)SystemDictionary::find(name, class_loader, protection_domain, THREAD);
1478   if (prev_ik == NULL) {
1479     return false;
1480   }
1481   // an existing ik implies a retransform/redefine
1482   assert(prev_ik != NULL, "invariant");
1483   assert(JdkJfrEvent::is_a(prev_ik), "invariant");
1484   copy_method_trace_flags(prev_ik, ik);
1485   return true;
1486 }
1487 
1488 // target for JFR_ON_KLASS_CREATION hook
1489 void JfrEventClassTransformer::on_klass_creation(InstanceKlass*& ik, ClassFileParser& parser, TRAPS) {
1490  assert(ik != NULL, "invariant");
1491  if (JdkJfrEvent::is(ik)) {
1492    ResourceMark rm(THREAD);
1493    HandleMark hm(THREAD);
1494    ClassFileStream* new_stream = create_new_bytes_for_event_klass(ik, parser, THREAD);
1495    if (new_stream == NULL) {
1496      if (true) tty->print_cr("JfrClassAdapter: unable to create ClassFileStream");
1497      return;
1498    }
1499    assert(new_stream != NULL, "invariant");
1500    InstanceKlass* new_ik = create_new_instance_klass(ik, new_stream, THREAD);
1501    if (new_ik == NULL) {
1502      if (true) tty->print_cr("JfrClassAdapter: unable to create InstanceKlass");
1503      return;
1504    }
1505    assert(new_ik != NULL, "invariant");
1506    // We now need to explicitly tag the replaced klass as the jdk.jfr.Event klass
1507    assert(!JdkJfrEvent::is(new_ik), "invariant");
1508    JdkJfrEvent::tag_as(new_ik);
1509    assert(JdkJfrEvent::is(new_ik), "invariant");
1510    rewrite_klass_pointer(ik, new_ik, parser, THREAD);
1511    return;
1512  }
1513  assert(JdkJfrEvent::is_subklass(ik), "invariant");
1514  if (is_retransforming(ik, THREAD)) {
1515    // not the initial klass load
1516    return;
1517  }
1518  if (ik->is_abstract()) {
1519    // abstract classes are not instrumented
1520    return;
1521  }
1522  ResourceMark rm(THREAD);
1523  HandleMark hm(THREAD);
1524  ClassFileStream* const new_stream = create_new_bytes_for_subklass(ik, parser, THREAD);
1525  if (NULL == new_stream) {
1526    if (true) tty->print_cr("JfrClassAdapter: unable to create ClassFileStream");
1527    return;
1528  }
1529  assert(new_stream != NULL, "invariant");
1530  InstanceKlass* new_ik = create_new_instance_klass(ik, new_stream, THREAD);
1531  if (new_ik == NULL) {
1532    if (true) tty->print_cr("JfrClassAdapter: unable to create InstanceKlass");
1533    return;
1534  }
1535  assert(new_ik != NULL, "invariant");
1536  // would have been tagged already as a subklass during the normal process of traceid assignment
1537  assert(JdkJfrEvent::is_subklass(new_ik), "invariant");
1538  traceid id = ik->trace_id();
1539  ik->set_trace_id(0);
1540  new_ik->set_trace_id(id);
1541  rewrite_klass_pointer(ik, new_ik, parser, THREAD);
1542 }
1543 
1544 static bool _force_instrumentation = false;
1545 void JfrEventClassTransformer::set_force_instrumentation(bool force_instrumentation) {
1546   _force_instrumentation = force_instrumentation;
1547 }
1548 
1549 bool JfrEventClassTransformer::is_force_instrumentation() {
1550   return _force_instrumentation;
1551 }