1 /*
   2  * Copyright (c) 2005, 2019, 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/symbolTable.hpp"
  27 #include "interpreter/bytecodeStream.hpp"
  28 #include "memory/universe.hpp"
  29 #include "oops/fieldStreams.hpp"
  30 #include "prims/jvmtiClassFileReconstituter.hpp"
  31 #include "runtime/handles.inline.hpp"
  32 #include "runtime/signature.hpp"
  33 #include "utilities/bytes.hpp"
  34 
  35 // FIXME: add Deprecated attribute
  36 // FIXME: fix Synthetic attribute
  37 // FIXME: per Serguei, add error return handling for ConstantPool::copy_cpool_bytes()
  38 
  39 JvmtiConstantPoolReconstituter::JvmtiConstantPoolReconstituter(InstanceKlass* ik) {
  40   set_error(JVMTI_ERROR_NONE);
  41   _ik = ik;
  42   _cpool = constantPoolHandle(Thread::current(), ik->constants());
  43   _symmap = new SymbolHashMap();
  44   _classmap = new SymbolHashMap();
  45   _cpool_size = _cpool->hash_entries_to(_symmap, _classmap);
  46   if (_cpool_size == 0) {
  47     set_error(JVMTI_ERROR_OUT_OF_MEMORY);
  48   } else if (_cpool_size < 0) {
  49     set_error(JVMTI_ERROR_INTERNAL);
  50   }
  51 }
  52 
  53 // Write the field information portion of ClassFile structure
  54 // JVMSpec|     u2 fields_count;
  55 // JVMSpec|     field_info fields[fields_count];
  56 void JvmtiClassFileReconstituter::write_field_infos() {
  57   HandleMark hm(thread());
  58   Array<AnnotationArray*>* fields_anno = ik()->fields_annotations();
  59   Array<AnnotationArray*>* fields_type_anno = ik()->fields_type_annotations();
  60 
  61   // Compute the real number of Java fields
  62   int java_fields = ik()->java_fields_count();
  63 
  64   write_u2(java_fields);
  65   for (JavaFieldStream fs(ik()); !fs.done(); fs.next()) {
  66     AccessFlags access_flags = fs.access_flags();
  67     int name_index = fs.name_index();
  68     int signature_index = fs.signature_index();
  69     int initial_value_index = fs.initval_index();
  70     guarantee(name_index != 0 && signature_index != 0, "bad constant pool index for field");
  71     // int offset = ik()->field_offset( index );
  72     int generic_signature_index = fs.generic_signature_index();
  73     AnnotationArray* anno = fields_anno == NULL ? NULL : fields_anno->at(fs.index());
  74     AnnotationArray* type_anno = fields_type_anno == NULL ? NULL : fields_type_anno->at(fs.index());
  75 
  76     // JVMSpec|   field_info {
  77     // JVMSpec|         u2 access_flags;
  78     // JVMSpec|         u2 name_index;
  79     // JVMSpec|         u2 descriptor_index;
  80     // JVMSpec|         u2 attributes_count;
  81     // JVMSpec|         attribute_info attributes[attributes_count];
  82     // JVMSpec|   }
  83 
  84     write_u2(access_flags.as_int() & JVM_RECOGNIZED_FIELD_MODIFIERS);
  85     write_u2(name_index);
  86     write_u2(signature_index);
  87     int attr_count = 0;
  88     if (initial_value_index != 0) {
  89       ++attr_count;
  90     }
  91     if (access_flags.is_synthetic()) {
  92       // ++attr_count;
  93     }
  94     if (generic_signature_index != 0) {
  95       ++attr_count;
  96     }
  97     if (anno != NULL) {
  98       ++attr_count;     // has RuntimeVisibleAnnotations attribute
  99     }
 100     if (type_anno != NULL) {
 101       ++attr_count;     // has RuntimeVisibleTypeAnnotations attribute
 102     }
 103 
 104     write_u2(attr_count);
 105 
 106     if (initial_value_index != 0) {
 107       write_attribute_name_index("ConstantValue");
 108       write_u4(2); //length always 2
 109       write_u2(initial_value_index);
 110     }
 111     if (access_flags.is_synthetic()) {
 112       // write_synthetic_attribute();
 113     }
 114     if (generic_signature_index != 0) {
 115       write_signature_attribute(generic_signature_index);
 116     }
 117     if (anno != NULL) {
 118       write_annotations_attribute("RuntimeVisibleAnnotations", anno);
 119     }
 120     if (type_anno != NULL) {
 121       write_annotations_attribute("RuntimeVisibleTypeAnnotations", type_anno);
 122     }
 123   }
 124 }
 125 
 126 // Write Code attribute
 127 // JVMSpec|   Code_attribute {
 128 // JVMSpec|     u2 attribute_name_index;
 129 // JVMSpec|     u4 attribute_length;
 130 // JVMSpec|     u2 max_stack;
 131 // JVMSpec|     u2 max_locals;
 132 // JVMSpec|     u4 code_length;
 133 // JVMSpec|     u1 code[code_length];
 134 // JVMSpec|     u2 exception_table_length;
 135 // JVMSpec|     {       u2 start_pc;
 136 // JVMSpec|             u2 end_pc;
 137 // JVMSpec|             u2  handler_pc;
 138 // JVMSpec|             u2  catch_type;
 139 // JVMSpec|     }       exception_table[exception_table_length];
 140 // JVMSpec|     u2 attributes_count;
 141 // JVMSpec|     attribute_info attributes[attributes_count];
 142 // JVMSpec|   }
 143 void JvmtiClassFileReconstituter::write_code_attribute(const methodHandle& method) {
 144   ConstMethod* const_method = method->constMethod();
 145   u2 line_num_cnt = 0;
 146   int stackmap_len = 0;
 147   int local_variable_table_length = 0;
 148   int local_variable_type_table_length = 0;
 149 
 150   // compute number and length of attributes
 151   int attr_count = 0;
 152   int attr_size = 0;
 153   if (const_method->has_linenumber_table()) {
 154     line_num_cnt = line_number_table_entries(method);
 155     if (line_num_cnt != 0) {
 156       ++attr_count;
 157       // Compute the complete size of the line number table attribute:
 158       //      LineNumberTable_attribute {
 159       //        u2 attribute_name_index;
 160       //        u4 attribute_length;
 161       //        u2 line_number_table_length;
 162       //        {  u2 start_pc;
 163       //           u2 line_number;
 164       //        } line_number_table[line_number_table_length];
 165       //      }
 166       attr_size += 2 + 4 + 2 + line_num_cnt * (2 + 2);
 167     }
 168   }
 169   if (method->has_stackmap_table()) {
 170     stackmap_len = method->stackmap_data()->length();
 171     if (stackmap_len != 0) {
 172       ++attr_count;
 173       // Compute the  size of the stack map table attribute (VM stores raw):
 174       //      StackMapTable_attribute {
 175       //        u2 attribute_name_index;
 176       //        u4 attribute_length;
 177       //        u2 number_of_entries;
 178       //        stack_map_frame_entries[number_of_entries];
 179       //      }
 180       attr_size += 2 + 4 + stackmap_len;
 181     }
 182   }
 183   if (method->has_localvariable_table()) {
 184     local_variable_table_length = method->localvariable_table_length();
 185     if (local_variable_table_length != 0) {
 186       ++attr_count;
 187       // Compute the size of the local variable table attribute (VM stores raw):
 188       // LocalVariableTable_attribute {
 189       //   u2 attribute_name_index;
 190       //   u4 attribute_length;
 191       //   u2 local_variable_table_length;
 192       //   {
 193       //     u2 start_pc;
 194       //     u2 length;
 195       //     u2 name_index;
 196       //     u2 descriptor_index;
 197       //     u2 index;
 198       //   }
 199       attr_size += 2 + 4 + 2 + local_variable_table_length * (2 + 2 + 2 + 2 + 2);
 200 
 201       // Local variables with generic signatures must have LVTT entries
 202       LocalVariableTableElement *elem = method->localvariable_table_start();
 203       for (int idx = 0; idx < local_variable_table_length; idx++) {
 204         if (elem[idx].signature_cp_index != 0) {
 205           local_variable_type_table_length++;
 206         }
 207       }
 208 
 209       if (local_variable_type_table_length != 0) {
 210         ++attr_count;
 211         // Compute the size of the local variable type table attribute (VM stores raw):
 212         // LocalVariableTypeTable_attribute {
 213         //   u2 attribute_name_index;
 214         //   u4 attribute_length;
 215         //   u2 local_variable_type_table_length;
 216         //   {
 217         //     u2 start_pc;
 218         //     u2 length;
 219         //     u2 name_index;
 220         //     u2 signature_index;
 221         //     u2 index;
 222         //   }
 223         attr_size += 2 + 4 + 2 + local_variable_type_table_length * (2 + 2 + 2 + 2 + 2);
 224       }
 225     }
 226   }
 227 
 228   ExceptionTable exception_table(method());
 229   int exception_table_length = exception_table.length();
 230   int code_size = const_method->code_size();
 231   int size =
 232     2+2+4 +                                // max_stack, max_locals, code_length
 233     code_size +                            // code
 234     2 +                                    // exception_table_length
 235     (2+2+2+2) * exception_table_length +   // exception_table
 236     2 +                                    // attributes_count
 237     attr_size;                             // attributes
 238 
 239   write_attribute_name_index("Code");
 240   write_u4(size);
 241   write_u2(method->verifier_max_stack());
 242   write_u2(method->max_locals());
 243   write_u4(code_size);
 244   copy_bytecodes(method, (unsigned char*)writeable_address(code_size));
 245   write_u2(exception_table_length);
 246   for (int index = 0; index < exception_table_length; index++) {
 247     write_u2(exception_table.start_pc(index));
 248     write_u2(exception_table.end_pc(index));
 249     write_u2(exception_table.handler_pc(index));
 250     write_u2(exception_table.catch_type_index(index));
 251   }
 252   write_u2(attr_count);
 253   if (line_num_cnt != 0) {
 254     write_line_number_table_attribute(method, line_num_cnt);
 255   }
 256   if (stackmap_len != 0) {
 257     write_stackmap_table_attribute(method, stackmap_len);
 258   }
 259   if (local_variable_table_length != 0) {
 260     write_local_variable_table_attribute(method, local_variable_table_length);
 261   }
 262   if (local_variable_type_table_length != 0) {
 263     write_local_variable_type_table_attribute(method, local_variable_type_table_length);
 264   }
 265 }
 266 
 267 // Write Exceptions attribute
 268 // JVMSpec|   Exceptions_attribute {
 269 // JVMSpec|     u2 attribute_name_index;
 270 // JVMSpec|     u4 attribute_length;
 271 // JVMSpec|     u2 number_of_exceptions;
 272 // JVMSpec|     u2 exception_index_table[number_of_exceptions];
 273 // JVMSpec|   }
 274 void JvmtiClassFileReconstituter::write_exceptions_attribute(ConstMethod* const_method) {
 275   CheckedExceptionElement* checked_exceptions = const_method->checked_exceptions_start();
 276   int checked_exceptions_length = const_method->checked_exceptions_length();
 277   int size =
 278     2 +                                    // number_of_exceptions
 279     2 * checked_exceptions_length;         // exception_index_table
 280 
 281   write_attribute_name_index("Exceptions");
 282   write_u4(size);
 283   write_u2(checked_exceptions_length);
 284   for (int index = 0; index < checked_exceptions_length; index++) {
 285     write_u2(checked_exceptions[index].class_cp_index);
 286   }
 287 }
 288 
 289 // Write SourceFile attribute
 290 // JVMSpec|   SourceFile_attribute {
 291 // JVMSpec|     u2 attribute_name_index;
 292 // JVMSpec|     u4 attribute_length;
 293 // JVMSpec|     u2 sourcefile_index;
 294 // JVMSpec|   }
 295 void JvmtiClassFileReconstituter::write_source_file_attribute() {
 296   assert(ik()->source_file_name() != NULL, "caller must check");
 297 
 298   write_attribute_name_index("SourceFile");
 299   write_u4(2);  // always length 2
 300   write_u2(symbol_to_cpool_index(ik()->source_file_name()));
 301 }
 302 
 303 // Write SourceDebugExtension attribute
 304 // JSR45|   SourceDebugExtension_attribute {
 305 // JSR45|       u2 attribute_name_index;
 306 // JSR45|       u4 attribute_length;
 307 // JSR45|       u1 debug_extension[attribute_length];
 308 // JSR45|   }
 309 void JvmtiClassFileReconstituter::write_source_debug_extension_attribute() {
 310   assert(ik()->source_debug_extension() != NULL, "caller must check");
 311 
 312   write_attribute_name_index("SourceDebugExtension");
 313   int len = (int)strlen(ik()->source_debug_extension());
 314   write_u4(len);
 315   u1* ext = (u1*)ik()->source_debug_extension();
 316   for (int i=0; i<len; i++) {
 317     write_u1(ext[i]);
 318   }
 319 }
 320 
 321 // Write (generic) Signature attribute
 322 // JVMSpec|   Signature_attribute {
 323 // JVMSpec|     u2 attribute_name_index;
 324 // JVMSpec|     u4 attribute_length;
 325 // JVMSpec|     u2 signature_index;
 326 // JVMSpec|   }
 327 void JvmtiClassFileReconstituter::write_signature_attribute(u2 generic_signature_index) {
 328   write_attribute_name_index("Signature");
 329   write_u4(2);  // always length 2
 330   write_u2(generic_signature_index);
 331 }
 332 
 333 // Compute the number of entries in the InnerClasses attribute
 334 u2 JvmtiClassFileReconstituter::inner_classes_attribute_length() {
 335   InnerClassesIterator iter(ik());
 336   return iter.length();
 337 }
 338 
 339 // Write an annotation attribute.  The VM stores them in raw form, so all we need
 340 // to do is add the attrubute name and fill in the length.
 341 // JSR202|   *Annotations_attribute {
 342 // JSR202|     u2 attribute_name_index;
 343 // JSR202|     u4 attribute_length;
 344 // JSR202|     ...
 345 // JSR202|   }
 346 void JvmtiClassFileReconstituter::write_annotations_attribute(const char* attr_name,
 347                                                               AnnotationArray* annos) {
 348   u4 length = annos->length();
 349   write_attribute_name_index(attr_name);
 350   write_u4(length);
 351   memcpy(writeable_address(length), annos->adr_at(0), length);
 352 }
 353 
 354 //  BootstrapMethods_attribute {
 355 //    u2 attribute_name_index;
 356 //    u4 attribute_length;
 357 //    u2 num_bootstrap_methods;
 358 //    {   u2 bootstrap_method_ref;
 359 //        u2 num_bootstrap_arguments;
 360 //        u2 bootstrap_arguments[num_bootstrap_arguments];
 361 //    } bootstrap_methods[num_bootstrap_methods];
 362 //  }
 363 void JvmtiClassFileReconstituter::write_bootstrapmethod_attribute() {
 364   Array<u2>* operands = cpool()->operands();
 365   write_attribute_name_index("BootstrapMethods");
 366   int num_bootstrap_methods = ConstantPool::operand_array_length(operands);
 367 
 368   // calculate length of attribute
 369   int length = sizeof(u2); // num_bootstrap_methods
 370   for (int n = 0; n < num_bootstrap_methods; n++) {
 371     u2 num_bootstrap_arguments = cpool()->operand_argument_count_at(n);
 372     length += sizeof(u2); // bootstrap_method_ref
 373     length += sizeof(u2); // num_bootstrap_arguments
 374     length += sizeof(u2) * num_bootstrap_arguments; // bootstrap_arguments[num_bootstrap_arguments]
 375   }
 376   write_u4(length);
 377 
 378   // write attribute
 379   write_u2(num_bootstrap_methods);
 380   for (int n = 0; n < num_bootstrap_methods; n++) {
 381     u2 bootstrap_method_ref = cpool()->operand_bootstrap_method_ref_index_at(n);
 382     u2 num_bootstrap_arguments = cpool()->operand_argument_count_at(n);
 383     write_u2(bootstrap_method_ref);
 384     write_u2(num_bootstrap_arguments);
 385     for (int arg = 0; arg < num_bootstrap_arguments; arg++) {
 386       u2 bootstrap_argument = cpool()->operand_argument_index_at(n, arg);
 387       write_u2(bootstrap_argument);
 388     }
 389   }
 390 }
 391 
 392 //  NestHost_attribute {
 393 //    u2 attribute_name_index;
 394 //    u4 attribute_length;
 395 //    u2 host_class_index;
 396 //  }
 397 void JvmtiClassFileReconstituter::write_nest_host_attribute() {
 398   int length = sizeof(u2);
 399   int host_class_index = ik()->nest_host_index();
 400 
 401   write_attribute_name_index("NestHost");
 402   write_u4(length);
 403   write_u2(host_class_index);
 404 }
 405 
 406 //  NestMembers_attribute {
 407 //    u2 attribute_name_index;
 408 //    u4 attribute_length;
 409 //    u2 number_of_classes;
 410 //    u2 classes[number_of_classes];
 411 //  }
 412 void JvmtiClassFileReconstituter::write_nest_members_attribute() {
 413   Array<u2>* nest_members = ik()->nest_members();
 414   int number_of_classes = nest_members->length();
 415   int length = sizeof(u2) * (1 + number_of_classes);
 416 
 417   write_attribute_name_index("NestMembers");
 418   write_u4(length);
 419   write_u2(number_of_classes);
 420   for (int i = 0; i < number_of_classes; i++) {
 421     u2 class_cp_index = nest_members->at(i);
 422     write_u2(class_cp_index);
 423   }
 424 }
 425 
 426 //  PermittedSubtypes {
 427 //    u2 attribute_name_index;
 428 //    u4 attribute_length;
 429 //    u2 number_of_classes;
 430 //    u2 classes[number_of_classes];
 431 //  }
 432 void JvmtiClassFileReconstituter::write_permitted_subtypes_attribute() {
 433   Array<u2>* permitted_subtypes = ik()->permitted_subtypes();
 434   int number_of_classes = permitted_subtypes->length();
 435   int length = sizeof(u2) * (1 + number_of_classes);
 436 
 437   write_attribute_name_index("PermittedSubtypes");
 438   write_u4(length);
 439   write_u2(number_of_classes);
 440   for (int i = 0; i < number_of_classes; i++) {
 441     u2 class_cp_index = permitted_subtypes->at(i);
 442     write_u2(class_cp_index);
 443   }
 444 }
 445 
 446 
 447 // Write InnerClasses attribute
 448 // JVMSpec|   InnerClasses_attribute {
 449 // JVMSpec|     u2 attribute_name_index;
 450 // JVMSpec|     u4 attribute_length;
 451 // JVMSpec|     u2 number_of_classes;
 452 // JVMSpec|     {  u2 inner_class_info_index;
 453 // JVMSpec|        u2 outer_class_info_index;
 454 // JVMSpec|        u2 inner_name_index;
 455 // JVMSpec|        u2 inner_class_access_flags;
 456 // JVMSpec|     } classes[number_of_classes];
 457 // JVMSpec|   }
 458 void JvmtiClassFileReconstituter::write_inner_classes_attribute(int length) {
 459   InnerClassesIterator iter(ik());
 460   guarantee(iter.length() != 0 && iter.length() == length,
 461             "caller must check");
 462   u2 entry_count = length / InstanceKlass::inner_class_next_offset;
 463   u4 size = 2 + entry_count * (2+2+2+2);
 464 
 465   write_attribute_name_index("InnerClasses");
 466   write_u4(size);
 467   write_u2(entry_count);
 468   for (; !iter.done(); iter.next()) {
 469     write_u2(iter.inner_class_info_index());
 470     write_u2(iter.outer_class_info_index());
 471     write_u2(iter.inner_name_index());
 472     write_u2(iter.inner_access_flags());
 473   }
 474 }
 475 
 476 // Write Synthetic attribute
 477 // JVMSpec|   Synthetic_attribute {
 478 // JVMSpec|     u2 attribute_name_index;
 479 // JVMSpec|     u4 attribute_length;
 480 // JVMSpec|   }
 481 void JvmtiClassFileReconstituter::write_synthetic_attribute() {
 482   write_attribute_name_index("Synthetic");
 483   write_u4(0); //length always zero
 484 }
 485 
 486 // Compute size of LineNumberTable
 487 u2 JvmtiClassFileReconstituter::line_number_table_entries(const methodHandle& method) {
 488   // The line number table is compressed so we don't know how big it is until decompressed.
 489   // Decompression is really fast so we just do it twice.
 490   u2 num_entries = 0;
 491   CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
 492   while (stream.read_pair()) {
 493     num_entries++;
 494   }
 495   return num_entries;
 496 }
 497 
 498 // Write LineNumberTable attribute
 499 // JVMSpec|   LineNumberTable_attribute {
 500 // JVMSpec|     u2 attribute_name_index;
 501 // JVMSpec|     u4 attribute_length;
 502 // JVMSpec|     u2 line_number_table_length;
 503 // JVMSpec|     {  u2 start_pc;
 504 // JVMSpec|        u2 line_number;
 505 // JVMSpec|     } line_number_table[line_number_table_length];
 506 // JVMSpec|   }
 507 void JvmtiClassFileReconstituter::write_line_number_table_attribute(const methodHandle& method,
 508                                                                     u2 num_entries) {
 509 
 510   write_attribute_name_index("LineNumberTable");
 511   write_u4(2 + num_entries * (2 + 2));
 512   write_u2(num_entries);
 513 
 514   CompressedLineNumberReadStream stream(method->compressed_linenumber_table());
 515   while (stream.read_pair()) {
 516     write_u2(stream.bci());
 517     write_u2(stream.line());
 518   }
 519 }
 520 
 521 // Write LocalVariableTable attribute
 522 // JVMSpec|   LocalVariableTable_attribute {
 523 // JVMSpec|     u2 attribute_name_index;
 524 // JVMSpec|     u4 attribute_length;
 525 // JVMSpec|     u2 local_variable_table_length;
 526 // JVMSpec|     {  u2 start_pc;
 527 // JVMSpec|       u2 length;
 528 // JVMSpec|       u2 name_index;
 529 // JVMSpec|       u2 descriptor_index;
 530 // JVMSpec|       u2 index;
 531 // JVMSpec|     } local_variable_table[local_variable_table_length];
 532 // JVMSpec|   }
 533 void JvmtiClassFileReconstituter::write_local_variable_table_attribute(const methodHandle& method, u2 num_entries) {
 534     write_attribute_name_index("LocalVariableTable");
 535     write_u4(2 + num_entries * (2 + 2 + 2 + 2 + 2));
 536     write_u2(num_entries);
 537 
 538     assert(method->localvariable_table_length() == num_entries, "just checking");
 539 
 540     LocalVariableTableElement *elem = method->localvariable_table_start();
 541     for (int j=0; j<method->localvariable_table_length(); j++) {
 542       write_u2(elem->start_bci);
 543       write_u2(elem->length);
 544       write_u2(elem->name_cp_index);
 545       write_u2(elem->descriptor_cp_index);
 546       write_u2(elem->slot);
 547       elem++;
 548     }
 549 }
 550 
 551 // Write LocalVariableTypeTable attribute
 552 // JVMSpec|   LocalVariableTypeTable_attribute {
 553 // JVMSpec|     u2 attribute_name_index;
 554 // JVMSpec|     u4 attribute_length;
 555 // JVMSpec|     u2 local_variable_type_table_length;
 556 // JVMSpec|     { u2 start_pc;
 557 // JVMSpec|       u2 length;
 558 // JVMSpec|       u2 name_index;
 559 // JVMSpec|       u2 signature_index;
 560 // JVMSpec|       u2 index;
 561 // JVMSpec|     } local_variable_type_table[local_variable_type_table_length];
 562 // JVMSpec|   }
 563 void JvmtiClassFileReconstituter::write_local_variable_type_table_attribute(const methodHandle& method, u2 num_entries) {
 564     write_attribute_name_index("LocalVariableTypeTable");
 565     write_u4(2 + num_entries * (2 + 2 + 2 + 2 + 2));
 566     write_u2(num_entries);
 567 
 568     LocalVariableTableElement *elem = method->localvariable_table_start();
 569     for (int j=0; j<method->localvariable_table_length(); j++) {
 570       if (elem->signature_cp_index > 0) {
 571         // Local variable has a generic signature - write LVTT attribute entry
 572         write_u2(elem->start_bci);
 573         write_u2(elem->length);
 574         write_u2(elem->name_cp_index);
 575         write_u2(elem->signature_cp_index);
 576         write_u2(elem->slot);
 577         num_entries--;
 578       }
 579       elem++;
 580     }
 581     assert(num_entries == 0, "just checking");
 582 }
 583 
 584 // Write stack map table attribute
 585 // JSR-202|   StackMapTable_attribute {
 586 // JSR-202|     u2 attribute_name_index;
 587 // JSR-202|     u4 attribute_length;
 588 // JSR-202|     u2 number_of_entries;
 589 // JSR-202|     stack_map_frame_entries[number_of_entries];
 590 // JSR-202|   }
 591 void JvmtiClassFileReconstituter::write_stackmap_table_attribute(const methodHandle& method,
 592                                                                  int stackmap_len) {
 593 
 594   write_attribute_name_index("StackMapTable");
 595   write_u4(stackmap_len);
 596   memcpy(
 597     writeable_address(stackmap_len),
 598     (void*)(method->stackmap_data()->adr_at(0)),
 599     stackmap_len);
 600 }
 601 
 602 // Write one method_info structure
 603 // JVMSpec|   method_info {
 604 // JVMSpec|     u2 access_flags;
 605 // JVMSpec|     u2 name_index;
 606 // JVMSpec|     u2 descriptor_index;
 607 // JVMSpec|     u2 attributes_count;
 608 // JVMSpec|     attribute_info attributes[attributes_count];
 609 // JVMSpec|   }
 610 void JvmtiClassFileReconstituter::write_method_info(const methodHandle& method) {
 611   AccessFlags access_flags = method->access_flags();
 612   ConstMethod* const_method = method->constMethod();
 613   u2 generic_signature_index = const_method->generic_signature_index();
 614   AnnotationArray* anno = method->annotations();
 615   AnnotationArray* param_anno = method->parameter_annotations();
 616   AnnotationArray* default_anno = method->annotation_default();
 617   AnnotationArray* type_anno = method->type_annotations();
 618 
 619   // skip generated default interface methods
 620   if (method->is_overpass()) {
 621     return;
 622   }
 623 
 624   write_u2(access_flags.get_flags() & JVM_RECOGNIZED_METHOD_MODIFIERS);
 625   write_u2(const_method->name_index());
 626   write_u2(const_method->signature_index());
 627 
 628   // write attributes in the same order javac does, so we can test with byte for
 629   // byte comparison
 630   int attr_count = 0;
 631   if (const_method->code_size() != 0) {
 632     ++attr_count;     // has Code attribute
 633   }
 634   if (const_method->has_checked_exceptions()) {
 635     ++attr_count;     // has Exceptions attribute
 636   }
 637   if (default_anno != NULL) {
 638     ++attr_count;     // has AnnotationDefault attribute
 639   }
 640   // Deprecated attribute would go here
 641   if (access_flags.is_synthetic()) { // FIXME
 642     // ++attr_count;
 643   }
 644   if (generic_signature_index != 0) {
 645     ++attr_count;
 646   }
 647   if (anno != NULL) {
 648     ++attr_count;     // has RuntimeVisibleAnnotations attribute
 649   }
 650   if (param_anno != NULL) {
 651     ++attr_count;     // has RuntimeVisibleParameterAnnotations attribute
 652   }
 653   if (type_anno != NULL) {
 654     ++attr_count;     // has RuntimeVisibleTypeAnnotations attribute
 655   }
 656 
 657   write_u2(attr_count);
 658   if (const_method->code_size() > 0) {
 659     write_code_attribute(method);
 660   }
 661   if (const_method->has_checked_exceptions()) {
 662     write_exceptions_attribute(const_method);
 663   }
 664   if (default_anno != NULL) {
 665     write_annotations_attribute("AnnotationDefault", default_anno);
 666   }
 667   // Deprecated attribute would go here
 668   if (access_flags.is_synthetic()) {
 669     // write_synthetic_attribute();
 670   }
 671   if (generic_signature_index != 0) {
 672     write_signature_attribute(generic_signature_index);
 673   }
 674   if (anno != NULL) {
 675     write_annotations_attribute("RuntimeVisibleAnnotations", anno);
 676   }
 677   if (param_anno != NULL) {
 678     write_annotations_attribute("RuntimeVisibleParameterAnnotations", param_anno);
 679   }
 680   if (type_anno != NULL) {
 681     write_annotations_attribute("RuntimeVisibleTypeAnnotations", type_anno);
 682   }
 683 }
 684 
 685 // Write the class attributes portion of ClassFile structure
 686 // JVMSpec|     u2 attributes_count;
 687 // JVMSpec|     attribute_info attributes[attributes_count];
 688 void JvmtiClassFileReconstituter::write_class_attributes() {
 689   u2 inner_classes_length = inner_classes_attribute_length();
 690   Symbol* generic_signature = ik()->generic_signature();
 691   AnnotationArray* anno = ik()->class_annotations();
 692   AnnotationArray* type_anno = ik()->class_type_annotations();
 693 
 694   int attr_count = 0;
 695   if (generic_signature != NULL) {
 696     ++attr_count;
 697   }
 698   if (ik()->source_file_name() != NULL) {
 699     ++attr_count;
 700   }
 701   if (ik()->source_debug_extension() != NULL) {
 702     ++attr_count;
 703   }
 704   if (inner_classes_length > 0) {
 705     ++attr_count;
 706   }
 707   if (anno != NULL) {
 708     ++attr_count;     // has RuntimeVisibleAnnotations attribute
 709   }
 710   if (type_anno != NULL) {
 711     ++attr_count;     // has RuntimeVisibleTypeAnnotations attribute
 712   }
 713   if (cpool()->operands() != NULL) {
 714     ++attr_count;
 715   }
 716   if (ik()->nest_host_index() != 0) {
 717     ++attr_count;
 718   }
 719   if (ik()->nest_members() != Universe::the_empty_short_array()) {
 720     ++attr_count;
 721   }
 722   if (ik()->permitted_subtypes() != Universe::the_empty_short_array()) {
 723     ++attr_count;
 724   }
 725 
 726   write_u2(attr_count);
 727 
 728   if (generic_signature != NULL) {
 729     write_signature_attribute(symbol_to_cpool_index(generic_signature));
 730   }
 731   if (ik()->source_file_name() != NULL) {
 732     write_source_file_attribute();
 733   }
 734   if (ik()->source_debug_extension() != NULL) {
 735     write_source_debug_extension_attribute();
 736   }
 737   if (inner_classes_length > 0) {
 738     write_inner_classes_attribute(inner_classes_length);
 739   }
 740   if (anno != NULL) {
 741     write_annotations_attribute("RuntimeVisibleAnnotations", anno);
 742   }
 743   if (type_anno != NULL) {
 744     write_annotations_attribute("RuntimeVisibleTypeAnnotations", type_anno);
 745   }
 746   if (cpool()->operands() != NULL) {
 747     write_bootstrapmethod_attribute();
 748   }
 749   if (ik()->nest_host_index() != 0) {
 750     write_nest_host_attribute();
 751   }
 752   if (ik()->nest_members() != Universe::the_empty_short_array()) {
 753     write_nest_members_attribute();
 754   }
 755   if (ik()->permitted_subtypes() != Universe::the_empty_short_array()) {
 756     write_permitted_subtypes_attribute();
 757   }
 758 }
 759 
 760 // Write the method information portion of ClassFile structure
 761 // JVMSpec|     u2 methods_count;
 762 // JVMSpec|     method_info methods[methods_count];
 763 void JvmtiClassFileReconstituter::write_method_infos() {
 764   HandleMark hm(thread());
 765   Array<Method*>* methods = ik()->methods();
 766   int num_methods = methods->length();
 767   int num_overpass = 0;
 768 
 769   // count the generated default interface methods
 770   // these will not be re-created by write_method_info
 771   // and should not be included in the total count
 772   for (int index = 0; index < num_methods; index++) {
 773     Method* method = methods->at(index);
 774     if (method->is_overpass()) {
 775       num_overpass++;
 776     }
 777   }
 778 
 779   write_u2(num_methods - num_overpass);
 780   if (JvmtiExport::can_maintain_original_method_order()) {
 781     int index;
 782     int original_index;
 783     intArray method_order(num_methods, num_methods, 0);
 784 
 785     // invert the method order mapping
 786     for (index = 0; index < num_methods; index++) {
 787       original_index = ik()->method_ordering()->at(index);
 788       assert(original_index >= 0 && original_index < num_methods,
 789              "invalid original method index");
 790       method_order.at_put(original_index, index);
 791     }
 792 
 793     // write in original order
 794     for (original_index = 0; original_index < num_methods; original_index++) {
 795       index = method_order.at(original_index);
 796       methodHandle method(thread(), methods->at(index));
 797       write_method_info(method);
 798     }
 799   } else {
 800     // method order not preserved just dump the method infos
 801     for (int index = 0; index < num_methods; index++) {
 802       methodHandle method(thread(), methods->at(index));
 803       write_method_info(method);
 804     }
 805   }
 806 }
 807 
 808 void JvmtiClassFileReconstituter::write_class_file_format() {
 809   ReallocMark();
 810 
 811   // JVMSpec|   ClassFile {
 812   // JVMSpec|           u4 magic;
 813   write_u4(0xCAFEBABE);
 814 
 815   // JVMSpec|           u2 minor_version;
 816   // JVMSpec|           u2 major_version;
 817   write_u2(ik()->minor_version());
 818   u2 major = ik()->major_version();
 819   write_u2(major);
 820 
 821   // JVMSpec|           u2 constant_pool_count;
 822   // JVMSpec|           cp_info constant_pool[constant_pool_count-1];
 823   write_u2(cpool()->length());
 824   copy_cpool_bytes(writeable_address(cpool_size()));
 825 
 826   // JVMSpec|           u2 access_flags;
 827   write_u2(ik()->access_flags().get_flags() & JVM_RECOGNIZED_CLASS_MODIFIERS);
 828 
 829   // JVMSpec|           u2 this_class;
 830   // JVMSpec|           u2 super_class;
 831   write_u2(class_symbol_to_cpool_index(ik()->name()));
 832   Klass* super_class = ik()->super();
 833   write_u2(super_class == NULL? 0 :  // zero for java.lang.Object
 834                 class_symbol_to_cpool_index(super_class->name()));
 835 
 836   // JVMSpec|           u2 interfaces_count;
 837   // JVMSpec|           u2 interfaces[interfaces_count];
 838   Array<InstanceKlass*>* interfaces =  ik()->local_interfaces();
 839   int num_interfaces = interfaces->length();
 840   write_u2(num_interfaces);
 841   for (int index = 0; index < num_interfaces; index++) {
 842     HandleMark hm(thread());
 843     InstanceKlass* iik = interfaces->at(index);
 844     write_u2(class_symbol_to_cpool_index(iik->name()));
 845   }
 846 
 847   // JVMSpec|           u2 fields_count;
 848   // JVMSpec|           field_info fields[fields_count];
 849   write_field_infos();
 850 
 851   // JVMSpec|           u2 methods_count;
 852   // JVMSpec|           method_info methods[methods_count];
 853   write_method_infos();
 854 
 855   // JVMSpec|           u2 attributes_count;
 856   // JVMSpec|           attribute_info attributes[attributes_count];
 857   // JVMSpec|   } /* end ClassFile 8?
 858   write_class_attributes();
 859 }
 860 
 861 address JvmtiClassFileReconstituter::writeable_address(size_t size) {
 862   size_t used_size = _buffer_ptr - _buffer;
 863   if (size + used_size >= _buffer_size) {
 864     // compute the new buffer size: must be at least twice as big as before
 865     // plus whatever new is being used; then convert to nice clean block boundary
 866     size_t new_buffer_size = (size + _buffer_size*2 + 1) / initial_buffer_size
 867                                                          * initial_buffer_size;
 868 
 869     // VM goes belly-up if the memory isn't available, so cannot do OOM processing
 870     _buffer = REALLOC_RESOURCE_ARRAY(u1, _buffer, _buffer_size, new_buffer_size);
 871     _buffer_size = new_buffer_size;
 872     _buffer_ptr = _buffer + used_size;
 873   }
 874   u1* ret_ptr = _buffer_ptr;
 875   _buffer_ptr += size;
 876   return ret_ptr;
 877 }
 878 
 879 void JvmtiClassFileReconstituter::write_attribute_name_index(const char* name) {
 880   TempNewSymbol sym = SymbolTable::probe(name, (int)strlen(name));
 881   assert(sym != NULL, "attribute name symbol not found");
 882   u2 attr_name_index = symbol_to_cpool_index(sym);
 883   assert(attr_name_index != 0, "attribute name symbol not in constant pool");
 884   write_u2(attr_name_index);
 885 }
 886 
 887 void JvmtiClassFileReconstituter::write_u1(u1 x) {
 888   *writeable_address(1) = x;
 889 }
 890 
 891 void JvmtiClassFileReconstituter::write_u2(u2 x) {
 892   Bytes::put_Java_u2(writeable_address(2), x);
 893 }
 894 
 895 void JvmtiClassFileReconstituter::write_u4(u4 x) {
 896   Bytes::put_Java_u4(writeable_address(4), x);
 897 }
 898 
 899 void JvmtiClassFileReconstituter::write_u8(u8 x) {
 900   Bytes::put_Java_u8(writeable_address(8), x);
 901 }
 902 
 903 void JvmtiClassFileReconstituter::copy_bytecodes(const methodHandle& mh,
 904                                                  unsigned char* bytecodes) {
 905   // use a BytecodeStream to iterate over the bytecodes. JVM/fast bytecodes
 906   // and the breakpoint bytecode are converted to their original bytecodes.
 907 
 908   BytecodeStream bs(mh);
 909 
 910   unsigned char* p = bytecodes;
 911   Bytecodes::Code code;
 912   bool is_rewritten = mh->method_holder()->is_rewritten();
 913 
 914   while ((code = bs.next()) >= 0) {
 915     assert(Bytecodes::is_java_code(code), "sanity check");
 916     assert(code != Bytecodes::_breakpoint, "sanity check");
 917 
 918     // length of bytecode (mnemonic + operands)
 919     address bcp = bs.bcp();
 920     int     len = bs.instruction_size();
 921     assert(len > 0, "length must be > 0");
 922 
 923     // copy the bytecodes
 924     *p = (unsigned char) (bs.is_wide()? Bytecodes::_wide : code);
 925     if (len > 1) {
 926       memcpy(p+1, bcp+1, len-1);
 927     }
 928 
 929     // During linking the get/put and invoke instructions are rewritten
 930     // with an index into the constant pool cache. The original constant
 931     // pool index must be returned to caller.  Rewrite the index.
 932     if (is_rewritten && len > 1) {
 933       bool is_wide = false;
 934       switch (code) {
 935       case Bytecodes::_getstatic       :  // fall through
 936       case Bytecodes::_putstatic       :  // fall through
 937       case Bytecodes::_getfield        :  // fall through
 938       case Bytecodes::_putfield        :  // fall through
 939       case Bytecodes::_invokevirtual   :  // fall through
 940       case Bytecodes::_invokespecial   :  // fall through
 941       case Bytecodes::_invokestatic    :  // fall through
 942       case Bytecodes::_invokedynamic   :  // fall through
 943       case Bytecodes::_invokeinterface : {
 944         assert(len == 3 ||
 945                (code == Bytecodes::_invokeinterface && len == 5) ||
 946                (code == Bytecodes::_invokedynamic   && len == 5),
 947                "sanity check");
 948 
 949         int cpci = Bytes::get_native_u2(bcp+1);
 950         bool is_invokedynamic = (code == Bytecodes::_invokedynamic);
 951         ConstantPoolCacheEntry* entry;
 952         if (is_invokedynamic) {
 953           cpci = Bytes::get_native_u4(bcp+1);
 954           entry = mh->constants()->invokedynamic_cp_cache_entry_at(cpci);
 955         } else {
 956         // cache cannot be pre-fetched since some classes won't have it yet
 957           entry = mh->constants()->cache()->entry_at(cpci);
 958         }
 959         int i = entry->constant_pool_index();
 960         assert(i < mh->constants()->length(), "sanity check");
 961         Bytes::put_Java_u2((address)(p+1), (u2)i);     // java byte ordering
 962         if (is_invokedynamic)  *(p+3) = *(p+4) = 0;
 963         break;
 964       }
 965       case Bytecodes::_ldc_w:
 966         is_wide = true; // fall through
 967       case Bytecodes::_ldc: {
 968         if (bs.raw_code() == Bytecodes::_fast_aldc || bs.raw_code() == Bytecodes::_fast_aldc_w) {
 969           int cpci = is_wide ? Bytes::get_native_u2(bcp+1) : (u1)(*(bcp+1));
 970           int i = mh->constants()->object_to_cp_index(cpci);
 971           assert(i < mh->constants()->length(), "sanity check");
 972           if (is_wide) {
 973             Bytes::put_Java_u2((address)(p+1), (u2)i);     // java byte ordering
 974           } else {
 975             *(p+1) = (u1)i;
 976           }
 977         }
 978         break;
 979         }
 980       default:
 981         break;
 982       }
 983     }
 984 
 985     p += len;
 986   }
 987 }