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