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