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