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