1 /*
   2  * Copyright (c) 1997, 2017, 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 #include "precompiled.hpp"
  25 #include "jvm.h"
  26 #include "aot/aotLoader.hpp"
  27 #include "classfile/classFileParser.hpp"
  28 #include "classfile/classFileStream.hpp"
  29 #include "classfile/classLoader.hpp"
  30 #include "classfile/classLoaderData.inline.hpp"
  31 #include "classfile/defaultMethods.hpp"
  32 #include "classfile/dictionary.hpp"
  33 #include "classfile/javaClasses.inline.hpp"
  34 #include "classfile/moduleEntry.hpp"
  35 #include "classfile/symbolTable.hpp"
  36 #include "classfile/systemDictionary.hpp"
  37 #include "classfile/verificationType.hpp"
  38 #include "classfile/verifier.hpp"
  39 #include "classfile/vmSymbols.hpp"
  40 #include "gc/shared/gcLocker.hpp"
  41 #include "logging/log.hpp"
  42 #include "logging/logStream.hpp"
  43 #include "memory/allocation.hpp"
  44 #include "memory/metadataFactory.hpp"
  45 #include "memory/oopFactory.hpp"
  46 #include "memory/resourceArea.hpp"
  47 #include "memory/universe.inline.hpp"
  48 #include "oops/annotations.hpp"
  49 #include "oops/fieldStreams.hpp"
  50 #include "oops/instanceKlass.hpp"
  51 #include "oops/instanceMirrorKlass.hpp"
  52 #include "oops/klass.inline.hpp"
  53 #include "oops/klassVtable.hpp"
  54 #include "oops/metadata.hpp"
  55 #include "oops/method.hpp"
  56 #include "oops/oop.inline.hpp"
  57 #include "oops/symbol.hpp"
  58 #include "prims/jvmtiExport.hpp"
  59 #include "prims/jvmtiThreadState.hpp"
  60 #include "runtime/javaCalls.hpp"
  61 #include "runtime/perfData.hpp"
  62 #include "runtime/reflection.hpp"
  63 #include "runtime/signature.hpp"
  64 #include "runtime/timer.hpp"
  65 #include "services/classLoadingService.hpp"
  66 #include "services/threadService.hpp"
  67 #include "trace/traceMacros.hpp"
  68 #include "utilities/align.hpp"
  69 #include "utilities/bitMap.inline.hpp"
  70 #include "utilities/exceptions.hpp"
  71 #include "utilities/globalDefinitions.hpp"
  72 #include "utilities/growableArray.hpp"
  73 #include "utilities/macros.hpp"
  74 #include "utilities/ostream.hpp"
  75 #include "utilities/resourceHash.hpp"
  76 #if INCLUDE_CDS
  77 #include "classfile/systemDictionaryShared.hpp"
  78 #endif
  79 
  80 // We generally try to create the oops directly when parsing, rather than
  81 // allocating temporary data structures and copying the bytes twice. A
  82 // temporary area is only needed when parsing utf8 entries in the constant
  83 // pool and when parsing line number tables.
  84 
  85 // We add assert in debug mode when class format is not checked.
  86 
  87 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
  88 #define JAVA_MIN_SUPPORTED_VERSION        45
  89 
  90 // Used for two backward compatibility reasons:
  91 // - to check for new additions to the class file format in JDK1.5
  92 // - to check for bug fixes in the format checker in JDK1.5
  93 #define JAVA_1_5_VERSION                  49
  94 
  95 // Used for backward compatibility reasons:
  96 // - to check for javac bug fixes that happened after 1.5
  97 // - also used as the max version when running in jdk6
  98 #define JAVA_6_VERSION                    50
  99 
 100 // Used for backward compatibility reasons:
 101 // - to disallow argument and require ACC_STATIC for <clinit> methods
 102 #define JAVA_7_VERSION                    51
 103 
 104 // Extension method support.
 105 #define JAVA_8_VERSION                    52
 106 
 107 #define JAVA_9_VERSION                    53
 108 
 109 #define JAVA_10_VERSION                   54
 110 
 111 #define JAVA_11_VERSION                   55
 112 
 113 void ClassFileParser::set_class_bad_constant_seen(short bad_constant) {
 114   assert((bad_constant == 19 || bad_constant == 20) && _major_version >= JAVA_9_VERSION,
 115          "Unexpected bad constant pool entry");
 116   if (_bad_constant_seen == 0) _bad_constant_seen = bad_constant;
 117 }
 118 
 119 void ClassFileParser::parse_constant_pool_entries(const ClassFileStream* const stream,
 120                                                   ConstantPool* cp,
 121                                                   const int length,
 122                                                   TRAPS) {
 123   assert(stream != NULL, "invariant");
 124   assert(cp != NULL, "invariant");
 125 
 126   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
 127   // this function (_current can be allocated in a register, with scalar
 128   // replacement of aggregates). The _current pointer is copied back to
 129   // stream() when this function returns. DON'T call another method within
 130   // this method that uses stream().
 131   const ClassFileStream cfs1 = *stream;
 132   const ClassFileStream* const cfs = &cfs1;
 133 
 134   assert(cfs->allocated_on_stack(), "should be local");
 135   debug_only(const u1* const old_current = stream->current();)
 136 
 137   // Used for batching symbol allocations.
 138   const char* names[SymbolTable::symbol_alloc_batch_size];
 139   int lengths[SymbolTable::symbol_alloc_batch_size];
 140   int indices[SymbolTable::symbol_alloc_batch_size];
 141   unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
 142   int names_count = 0;
 143 
 144   // parsing  Index 0 is unused
 145   for (int index = 1; index < length; index++) {
 146     // Each of the following case guarantees one more byte in the stream
 147     // for the following tag or the access_flags following constant pool,
 148     // so we don't need bounds-check for reading tag.
 149     const u1 tag = cfs->get_u1_fast();
 150     switch (tag) {
 151       case JVM_CONSTANT_Class : {
 152         cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
 153         const u2 name_index = cfs->get_u2_fast();
 154         cp->klass_index_at_put(index, name_index);
 155         break;
 156       }
 157       case JVM_CONSTANT_Fieldref: {
 158         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 159         const u2 class_index = cfs->get_u2_fast();
 160         const u2 name_and_type_index = cfs->get_u2_fast();
 161         cp->field_at_put(index, class_index, name_and_type_index);
 162         break;
 163       }
 164       case JVM_CONSTANT_Methodref: {
 165         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 166         const u2 class_index = cfs->get_u2_fast();
 167         const u2 name_and_type_index = cfs->get_u2_fast();
 168         cp->method_at_put(index, class_index, name_and_type_index);
 169         break;
 170       }
 171       case JVM_CONSTANT_InterfaceMethodref: {
 172         cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 173         const u2 class_index = cfs->get_u2_fast();
 174         const u2 name_and_type_index = cfs->get_u2_fast();
 175         cp->interface_method_at_put(index, class_index, name_and_type_index);
 176         break;
 177       }
 178       case JVM_CONSTANT_String : {
 179         cfs->guarantee_more(3, CHECK);  // string_index, tag/access_flags
 180         const u2 string_index = cfs->get_u2_fast();
 181         cp->string_index_at_put(index, string_index);
 182         break;
 183       }
 184       case JVM_CONSTANT_MethodHandle :
 185       case JVM_CONSTANT_MethodType: {
 186         if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
 187           classfile_parse_error(
 188             "Class file version does not support constant tag %u in class file %s",
 189             tag, CHECK);
 190         }
 191         if (tag == JVM_CONSTANT_MethodHandle) {
 192           cfs->guarantee_more(4, CHECK);  // ref_kind, method_index, tag/access_flags
 193           const u1 ref_kind = cfs->get_u1_fast();
 194           const u2 method_index = cfs->get_u2_fast();
 195           cp->method_handle_index_at_put(index, ref_kind, method_index);
 196         }
 197         else if (tag == JVM_CONSTANT_MethodType) {
 198           cfs->guarantee_more(3, CHECK);  // signature_index, tag/access_flags
 199           const u2 signature_index = cfs->get_u2_fast();
 200           cp->method_type_index_at_put(index, signature_index);
 201         }
 202         else {
 203           ShouldNotReachHere();
 204         }
 205         break;
 206       }
 207       case JVM_CONSTANT_InvokeDynamic : {
 208         if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
 209           classfile_parse_error(
 210               "Class file version does not support constant tag %u in class file %s",
 211               tag, CHECK);
 212         }
 213         cfs->guarantee_more(5, CHECK);  // bsm_index, nt, tag/access_flags
 214         const u2 bootstrap_specifier_index = cfs->get_u2_fast();
 215         const u2 name_and_type_index = cfs->get_u2_fast();
 216         if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index) {
 217           _max_bootstrap_specifier_index = (int) bootstrap_specifier_index;  // collect for later
 218         }
 219         cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);
 220         break;
 221       }
 222       case JVM_CONSTANT_Integer: {
 223         cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
 224         const u4 bytes = cfs->get_u4_fast();
 225         cp->int_at_put(index, (jint)bytes);
 226         break;
 227       }
 228       case JVM_CONSTANT_Float: {
 229         cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
 230         const u4 bytes = cfs->get_u4_fast();
 231         cp->float_at_put(index, *(jfloat*)&bytes);
 232         break;
 233       }
 234       case JVM_CONSTANT_Long: {
 235         // A mangled type might cause you to overrun allocated memory
 236         guarantee_property(index + 1 < length,
 237                            "Invalid constant pool entry %u in class file %s",
 238                            index,
 239                            CHECK);
 240         cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
 241         const u8 bytes = cfs->get_u8_fast();
 242         cp->long_at_put(index, bytes);
 243         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
 244         break;
 245       }
 246       case JVM_CONSTANT_Double: {
 247         // A mangled type might cause you to overrun allocated memory
 248         guarantee_property(index+1 < length,
 249                            "Invalid constant pool entry %u in class file %s",
 250                            index,
 251                            CHECK);
 252         cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
 253         const u8 bytes = cfs->get_u8_fast();
 254         cp->double_at_put(index, *(jdouble*)&bytes);
 255         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
 256         break;
 257       }
 258       case JVM_CONSTANT_NameAndType: {
 259         cfs->guarantee_more(5, CHECK);  // name_index, signature_index, tag/access_flags
 260         const u2 name_index = cfs->get_u2_fast();
 261         const u2 signature_index = cfs->get_u2_fast();
 262         cp->name_and_type_at_put(index, name_index, signature_index);
 263         break;
 264       }
 265       case JVM_CONSTANT_Utf8 : {
 266         cfs->guarantee_more(2, CHECK);  // utf8_length
 267         u2  utf8_length = cfs->get_u2_fast();
 268         const u1* utf8_buffer = cfs->current();
 269         assert(utf8_buffer != NULL, "null utf8 buffer");
 270         // Got utf8 string, guarantee utf8_length+1 bytes, set stream position forward.
 271         cfs->guarantee_more(utf8_length+1, CHECK);  // utf8 string, tag/access_flags
 272         cfs->skip_u1_fast(utf8_length);
 273 
 274         // Before storing the symbol, make sure it's legal
 275         if (_need_verify) {
 276           verify_legal_utf8(utf8_buffer, utf8_length, CHECK);
 277         }
 278 
 279         if (has_cp_patch_at(index)) {
 280           Handle patch = clear_cp_patch_at(index);
 281           guarantee_property(java_lang_String::is_instance(patch()),
 282                              "Illegal utf8 patch at %d in class file %s",
 283                              index,
 284                              CHECK);
 285           const char* const str = java_lang_String::as_utf8_string(patch());
 286           // (could use java_lang_String::as_symbol instead, but might as well batch them)
 287           utf8_buffer = (const u1*) str;
 288           utf8_length = (int) strlen(str);
 289         }
 290 
 291         unsigned int hash;
 292         Symbol* const result = SymbolTable::lookup_only((const char*)utf8_buffer,
 293                                                         utf8_length,
 294                                                         hash);
 295         if (result == NULL) {
 296           names[names_count] = (const char*)utf8_buffer;
 297           lengths[names_count] = utf8_length;
 298           indices[names_count] = index;
 299           hashValues[names_count++] = hash;
 300           if (names_count == SymbolTable::symbol_alloc_batch_size) {
 301             SymbolTable::new_symbols(_loader_data,
 302                                      cp,
 303                                      names_count,
 304                                      names,
 305                                      lengths,
 306                                      indices,
 307                                      hashValues,
 308                                      CHECK);
 309             names_count = 0;
 310           }
 311         } else {
 312           cp->symbol_at_put(index, result);
 313         }
 314         break;
 315       }
 316       case 19:
 317       case 20: {
 318         // Record that an error occurred in these two cases but keep parsing so
 319         // that ACC_Module can be checked for in the access_flags.  Need to
 320         // throw NoClassDefFoundError in that case.
 321         if (_major_version >= JAVA_9_VERSION) {
 322           cfs->guarantee_more(3, CHECK);
 323           cfs->get_u2_fast();
 324           set_class_bad_constant_seen(tag);
 325           break;
 326         }
 327       }
 328       default: {
 329         classfile_parse_error("Unknown constant tag %u in class file %s",
 330                               tag,
 331                               CHECK);
 332         break;
 333       }
 334     } // end of switch(tag)
 335   } // end of for
 336 
 337   // Allocate the remaining symbols
 338   if (names_count > 0) {
 339     SymbolTable::new_symbols(_loader_data,
 340                              cp,
 341                              names_count,
 342                              names,
 343                              lengths,
 344                              indices,
 345                              hashValues,
 346                              CHECK);
 347   }
 348 
 349   // Copy _current pointer of local copy back to stream.
 350   assert(stream->current() == old_current, "non-exclusive use of stream");
 351   stream->set_current(cfs1.current());
 352 
 353 }
 354 
 355 static inline bool valid_cp_range(int index, int length) {
 356   return (index > 0 && index < length);
 357 }
 358 
 359 static inline Symbol* check_symbol_at(const ConstantPool* cp, int index) {
 360   assert(cp != NULL, "invariant");
 361   if (valid_cp_range(index, cp->length()) && cp->tag_at(index).is_utf8()) {
 362     return cp->symbol_at(index);
 363   }
 364   return NULL;
 365 }
 366 
 367 #ifdef ASSERT
 368 PRAGMA_DIAG_PUSH
 369 PRAGMA_FORMAT_NONLITERAL_IGNORED
 370 void ClassFileParser::report_assert_property_failure(const char* msg, TRAPS) const {
 371   ResourceMark rm(THREAD);
 372   fatal(msg, _class_name->as_C_string());
 373 }
 374 
 375 void ClassFileParser::report_assert_property_failure(const char* msg,
 376                                                      int index,
 377                                                      TRAPS) const {
 378   ResourceMark rm(THREAD);
 379   fatal(msg, index, _class_name->as_C_string());
 380 }
 381 PRAGMA_DIAG_POP
 382 #endif
 383 
 384 void ClassFileParser::parse_constant_pool(const ClassFileStream* const stream,
 385                                          ConstantPool* const cp,
 386                                          const int length,
 387                                          TRAPS) {
 388   assert(cp != NULL, "invariant");
 389   assert(stream != NULL, "invariant");
 390 
 391   // parsing constant pool entries
 392   parse_constant_pool_entries(stream, cp, length, CHECK);
 393   if (class_bad_constant_seen() != 0) {
 394     // a bad CP entry has been detected previously so stop parsing and just return.
 395     return;
 396   }
 397 
 398   int index = 1;  // declared outside of loops for portability
 399   int num_klasses = 0;
 400 
 401   // first verification pass - validate cross references
 402   // and fixup class and string constants
 403   for (index = 1; index < length; index++) {          // Index 0 is unused
 404     const jbyte tag = cp->tag_at(index).value();
 405     switch (tag) {
 406       case JVM_CONSTANT_Class: {
 407         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 408         break;
 409       }
 410       case JVM_CONSTANT_Fieldref:
 411         // fall through
 412       case JVM_CONSTANT_Methodref:
 413         // fall through
 414       case JVM_CONSTANT_InterfaceMethodref: {
 415         if (!_need_verify) break;
 416         const int klass_ref_index = cp->klass_ref_index_at(index);
 417         const int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
 418         check_property(valid_klass_reference_at(klass_ref_index),
 419                        "Invalid constant pool index %u in class file %s",
 420                        klass_ref_index, CHECK);
 421         check_property(valid_cp_range(name_and_type_ref_index, length) &&
 422           cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 423           "Invalid constant pool index %u in class file %s",
 424           name_and_type_ref_index, CHECK);
 425         break;
 426       }
 427       case JVM_CONSTANT_String: {
 428         ShouldNotReachHere();     // Only JVM_CONSTANT_StringIndex should be present
 429         break;
 430       }
 431       case JVM_CONSTANT_Integer:
 432         break;
 433       case JVM_CONSTANT_Float:
 434         break;
 435       case JVM_CONSTANT_Long:
 436       case JVM_CONSTANT_Double: {
 437         index++;
 438         check_property(
 439           (index < length && cp->tag_at(index).is_invalid()),
 440           "Improper constant pool long/double index %u in class file %s",
 441           index, CHECK);
 442         break;
 443       }
 444       case JVM_CONSTANT_NameAndType: {
 445         if (!_need_verify) break;
 446         const int name_ref_index = cp->name_ref_index_at(index);
 447         const int signature_ref_index = cp->signature_ref_index_at(index);
 448         check_property(valid_symbol_at(name_ref_index),
 449           "Invalid constant pool index %u in class file %s",
 450           name_ref_index, CHECK);
 451         check_property(valid_symbol_at(signature_ref_index),
 452           "Invalid constant pool index %u in class file %s",
 453           signature_ref_index, CHECK);
 454         break;
 455       }
 456       case JVM_CONSTANT_Utf8:
 457         break;
 458       case JVM_CONSTANT_UnresolvedClass:         // fall-through
 459       case JVM_CONSTANT_UnresolvedClassInError: {
 460         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 461         break;
 462       }
 463       case JVM_CONSTANT_ClassIndex: {
 464         const int class_index = cp->klass_index_at(index);
 465         check_property(valid_symbol_at(class_index),
 466           "Invalid constant pool index %u in class file %s",
 467           class_index, CHECK);
 468         cp->unresolved_klass_at_put(index, class_index, num_klasses++);
 469         break;
 470       }
 471       case JVM_CONSTANT_StringIndex: {
 472         const int string_index = cp->string_index_at(index);
 473         check_property(valid_symbol_at(string_index),
 474           "Invalid constant pool index %u in class file %s",
 475           string_index, CHECK);
 476         Symbol* const sym = cp->symbol_at(string_index);
 477         cp->unresolved_string_at_put(index, sym);
 478         break;
 479       }
 480       case JVM_CONSTANT_MethodHandle: {
 481         const int ref_index = cp->method_handle_index_at(index);
 482         check_property(valid_cp_range(ref_index, length),
 483           "Invalid constant pool index %u in class file %s",
 484           ref_index, CHECK);
 485         const constantTag tag = cp->tag_at(ref_index);
 486         const int ref_kind = cp->method_handle_ref_kind_at(index);
 487 
 488         switch (ref_kind) {
 489           case JVM_REF_getField:
 490           case JVM_REF_getStatic:
 491           case JVM_REF_putField:
 492           case JVM_REF_putStatic: {
 493             check_property(
 494               tag.is_field(),
 495               "Invalid constant pool index %u in class file %s (not a field)",
 496               ref_index, CHECK);
 497             break;
 498           }
 499           case JVM_REF_invokeVirtual:
 500           case JVM_REF_newInvokeSpecial: {
 501             check_property(
 502               tag.is_method(),
 503               "Invalid constant pool index %u in class file %s (not a method)",
 504               ref_index, CHECK);
 505             break;
 506           }
 507           case JVM_REF_invokeStatic:
 508           case JVM_REF_invokeSpecial: {
 509             check_property(
 510               tag.is_method() ||
 511               ((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()),
 512               "Invalid constant pool index %u in class file %s (not a method)",
 513               ref_index, CHECK);
 514             break;
 515           }
 516           case JVM_REF_invokeInterface: {
 517             check_property(
 518               tag.is_interface_method(),
 519               "Invalid constant pool index %u in class file %s (not an interface method)",
 520               ref_index, CHECK);
 521             break;
 522           }
 523           default: {
 524             classfile_parse_error(
 525               "Bad method handle kind at constant pool index %u in class file %s",
 526               index, CHECK);
 527           }
 528         } // switch(refkind)
 529         // Keep the ref_index unchanged.  It will be indirected at link-time.
 530         break;
 531       } // case MethodHandle
 532       case JVM_CONSTANT_MethodType: {
 533         const int ref_index = cp->method_type_index_at(index);
 534         check_property(valid_symbol_at(ref_index),
 535           "Invalid constant pool index %u in class file %s",
 536           ref_index, CHECK);
 537         break;
 538       }
 539       case JVM_CONSTANT_InvokeDynamic: {
 540         const int name_and_type_ref_index =
 541           cp->invoke_dynamic_name_and_type_ref_index_at(index);
 542 
 543         check_property(valid_cp_range(name_and_type_ref_index, length) &&
 544           cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 545           "Invalid constant pool index %u in class file %s",
 546           name_and_type_ref_index, CHECK);
 547         // bootstrap specifier index must be checked later,
 548         // when BootstrapMethods attr is available
 549         break;
 550       }
 551       default: {
 552         fatal("bad constant pool tag value %u", cp->tag_at(index).value());
 553         ShouldNotReachHere();
 554         break;
 555       }
 556     } // switch(tag)
 557   } // end of for
 558 
 559   _first_patched_klass_resolved_index = num_klasses;
 560   cp->allocate_resolved_klasses(_loader_data, num_klasses + _max_num_patched_klasses, CHECK);
 561 
 562   if (_cp_patches != NULL) {
 563     // need to treat this_class specially...
 564 
 565     // Add dummy utf8 entries in the space reserved for names of patched classes. We'll use "*"
 566     // for now. These will be replaced with actual names of the patched classes in patch_class().
 567     Symbol* s = vmSymbols::star_name();
 568     for (int n=_orig_cp_size; n<cp->length(); n++) {
 569       cp->symbol_at_put(n, s);
 570     }
 571 
 572     int this_class_index;
 573     {
 574       stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
 575       const u1* const mark = stream->current();
 576       stream->skip_u2_fast(1); // skip flags
 577       this_class_index = stream->get_u2_fast();
 578       stream->set_current(mark);  // revert to mark
 579     }
 580 
 581     for (index = 1; index < length; index++) {          // Index 0 is unused
 582       if (has_cp_patch_at(index)) {
 583         guarantee_property(index != this_class_index,
 584           "Illegal constant pool patch to self at %d in class file %s",
 585           index, CHECK);
 586         patch_constant_pool(cp, index, cp_patch_at(index), CHECK);
 587       }
 588     }
 589   }
 590 
 591   if (!_need_verify) {
 592     return;
 593   }
 594 
 595   // second verification pass - checks the strings are of the right format.
 596   // but not yet to the other entries
 597   for (index = 1; index < length; index++) {
 598     const jbyte tag = cp->tag_at(index).value();
 599     switch (tag) {
 600       case JVM_CONSTANT_UnresolvedClass: {
 601         const Symbol* const class_name = cp->klass_name_at(index);
 602         // check the name, even if _cp_patches will overwrite it
 603         verify_legal_class_name(class_name, CHECK);
 604         break;
 605       }
 606       case JVM_CONSTANT_NameAndType: {
 607         if (_need_verify) {
 608           const int sig_index = cp->signature_ref_index_at(index);
 609           const int name_index = cp->name_ref_index_at(index);
 610           const Symbol* const name = cp->symbol_at(name_index);
 611           const Symbol* const sig = cp->symbol_at(sig_index);
 612           guarantee_property(sig->utf8_length() != 0,
 613             "Illegal zero length constant pool entry at %d in class %s",
 614             sig_index, CHECK);
 615           guarantee_property(name->utf8_length() != 0,
 616             "Illegal zero length constant pool entry at %d in class %s",
 617             name_index, CHECK);
 618 
 619           if (sig->byte_at(0) == JVM_SIGNATURE_FUNC) {
 620             // Format check method name and signature
 621             verify_legal_method_name(name, CHECK);
 622             verify_legal_method_signature(name, sig, CHECK);
 623           } else {
 624             // Format check field name and signature
 625             verify_legal_field_name(name, CHECK);
 626             verify_legal_field_signature(name, sig, CHECK);
 627           }
 628         }
 629         break;
 630       }
 631       case JVM_CONSTANT_InvokeDynamic:
 632       case JVM_CONSTANT_Fieldref:
 633       case JVM_CONSTANT_Methodref:
 634       case JVM_CONSTANT_InterfaceMethodref: {
 635         const int name_and_type_ref_index =
 636           cp->name_and_type_ref_index_at(index);
 637         // already verified to be utf8
 638         const int name_ref_index =
 639           cp->name_ref_index_at(name_and_type_ref_index);
 640         // already verified to be utf8
 641         const int signature_ref_index =
 642           cp->signature_ref_index_at(name_and_type_ref_index);
 643         const Symbol* const name = cp->symbol_at(name_ref_index);
 644         const Symbol* const signature = cp->symbol_at(signature_ref_index);
 645         if (tag == JVM_CONSTANT_Fieldref) {
 646           if (_need_verify) {
 647             // Field name and signature are verified above, when iterating NameAndType_info.
 648             // Need only to be sure signature is non-zero length and the right type.
 649             if (signature->utf8_length() == 0 ||
 650                 signature->byte_at(0) == JVM_SIGNATURE_FUNC) {
 651               throwIllegalSignature("Field", name, signature, CHECK);
 652             }
 653           }
 654         } else {
 655           if (_need_verify) {
 656             // Method name and signature are verified above, when iterating NameAndType_info.
 657             // Need only to be sure signature is non-zero length and the right type.
 658             if (signature->utf8_length() == 0 ||
 659                 signature->byte_at(0) != JVM_SIGNATURE_FUNC) {
 660               throwIllegalSignature("Method", name, signature, CHECK);
 661             }
 662           }
 663           // 4509014: If a class method name begins with '<', it must be "<init>"
 664           const unsigned int name_len = name->utf8_length();
 665           if (tag == JVM_CONSTANT_Methodref &&
 666               name_len != 0 &&
 667               name->byte_at(0) == '<' &&
 668               name != vmSymbols::object_initializer_name()) {
 669             classfile_parse_error(
 670               "Bad method name at constant pool index %u in class file %s",
 671               name_ref_index, CHECK);
 672           }
 673         }
 674         break;
 675       }
 676       case JVM_CONSTANT_MethodHandle: {
 677         const int ref_index = cp->method_handle_index_at(index);
 678         const int ref_kind = cp->method_handle_ref_kind_at(index);
 679         switch (ref_kind) {
 680           case JVM_REF_invokeVirtual:
 681           case JVM_REF_invokeStatic:
 682           case JVM_REF_invokeSpecial:
 683           case JVM_REF_newInvokeSpecial: {
 684             const int name_and_type_ref_index =
 685               cp->name_and_type_ref_index_at(ref_index);
 686             const int name_ref_index =
 687               cp->name_ref_index_at(name_and_type_ref_index);
 688             const Symbol* const name = cp->symbol_at(name_ref_index);
 689             if (ref_kind == JVM_REF_newInvokeSpecial) {
 690               if (name != vmSymbols::object_initializer_name()) {
 691                 classfile_parse_error(
 692                   "Bad constructor name at constant pool index %u in class file %s",
 693                     name_ref_index, CHECK);
 694               }
 695             } else {
 696               if (name == vmSymbols::object_initializer_name()) {
 697                 classfile_parse_error(
 698                   "Bad method name at constant pool index %u in class file %s",
 699                   name_ref_index, CHECK);
 700               }
 701             }
 702             break;
 703           }
 704           // Other ref_kinds are already fully checked in previous pass.
 705         } // switch(ref_kind)
 706         break;
 707       }
 708       case JVM_CONSTANT_MethodType: {
 709         const Symbol* const no_name = vmSymbols::type_name(); // place holder
 710         const Symbol* const signature = cp->method_type_signature_at(index);
 711         verify_legal_method_signature(no_name, signature, CHECK);
 712         break;
 713       }
 714       case JVM_CONSTANT_Utf8: {
 715         assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
 716       }
 717     }  // switch(tag)
 718   }  // end of for
 719 }
 720 
 721 void ClassFileParser::patch_class(ConstantPool* cp, int class_index, Klass* k, Symbol* name) {
 722   int name_index = _orig_cp_size + _num_patched_klasses;
 723   int resolved_klass_index = _first_patched_klass_resolved_index + _num_patched_klasses;
 724 
 725   cp->klass_at_put(class_index, name_index, resolved_klass_index, k, name);
 726   _num_patched_klasses ++;
 727 }
 728 
 729 void ClassFileParser::patch_constant_pool(ConstantPool* cp,
 730                                           int index,
 731                                           Handle patch,
 732                                           TRAPS) {
 733   assert(cp != NULL, "invariant");
 734 
 735   BasicType patch_type = T_VOID;
 736 
 737   switch (cp->tag_at(index).value()) {
 738 
 739     case JVM_CONSTANT_UnresolvedClass: {
 740       // Patching a class means pre-resolving it.
 741       // The name in the constant pool is ignored.
 742       if (java_lang_Class::is_instance(patch())) {
 743         guarantee_property(!java_lang_Class::is_primitive(patch()),
 744                            "Illegal class patch at %d in class file %s",
 745                            index, CHECK);
 746         Klass* k = java_lang_Class::as_Klass(patch());
 747         patch_class(cp, index, k, k->name());
 748       } else {
 749         guarantee_property(java_lang_String::is_instance(patch()),
 750                            "Illegal class patch at %d in class file %s",
 751                            index, CHECK);
 752         Symbol* const name = java_lang_String::as_symbol(patch(), CHECK);
 753         patch_class(cp, index, NULL, name);
 754       }
 755       break;
 756     }
 757 
 758     case JVM_CONSTANT_String: {
 759       // skip this patch and don't clear it.  Needs the oop array for resolved
 760       // references to be created first.
 761       return;
 762     }
 763     case JVM_CONSTANT_Integer: patch_type = T_INT;    goto patch_prim;
 764     case JVM_CONSTANT_Float:   patch_type = T_FLOAT;  goto patch_prim;
 765     case JVM_CONSTANT_Long:    patch_type = T_LONG;   goto patch_prim;
 766     case JVM_CONSTANT_Double:  patch_type = T_DOUBLE; goto patch_prim;
 767     patch_prim:
 768     {
 769       jvalue value;
 770       BasicType value_type = java_lang_boxing_object::get_value(patch(), &value);
 771       guarantee_property(value_type == patch_type,
 772                          "Illegal primitive patch at %d in class file %s",
 773                          index, CHECK);
 774       switch (value_type) {
 775         case T_INT:    cp->int_at_put(index,   value.i); break;
 776         case T_FLOAT:  cp->float_at_put(index, value.f); break;
 777         case T_LONG:   cp->long_at_put(index,  value.j); break;
 778         case T_DOUBLE: cp->double_at_put(index, value.d); break;
 779         default:       assert(false, "");
 780       }
 781     } // end patch_prim label
 782     break;
 783 
 784     default: {
 785       // %%% TODO: put method handles into CONSTANT_InterfaceMethodref, etc.
 786       guarantee_property(!has_cp_patch_at(index),
 787                          "Illegal unexpected patch at %d in class file %s",
 788                          index, CHECK);
 789       return;
 790     }
 791   } // end of switch(tag)
 792 
 793   // On fall-through, mark the patch as used.
 794   clear_cp_patch_at(index);
 795 }
 796 class NameSigHash: public ResourceObj {
 797  public:
 798   const Symbol*       _name;       // name
 799   const Symbol*       _sig;        // signature
 800   NameSigHash*  _next;             // Next entry in hash table
 801 };
 802 
 803 static const int HASH_ROW_SIZE = 256;
 804 
 805 static unsigned int hash(const Symbol* name, const Symbol* sig) {
 806   unsigned int raw_hash = 0;
 807   raw_hash += ((unsigned int)(uintptr_t)name) >> (LogHeapWordSize + 2);
 808   raw_hash += ((unsigned int)(uintptr_t)sig) >> LogHeapWordSize;
 809 
 810   return (raw_hash + (unsigned int)(uintptr_t)name) % HASH_ROW_SIZE;
 811 }
 812 
 813 
 814 static void initialize_hashtable(NameSigHash** table) {
 815   memset((void*)table, 0, sizeof(NameSigHash*) * HASH_ROW_SIZE);
 816 }
 817 // Return false if the name/sig combination is found in table.
 818 // Return true if no duplicate is found. And name/sig is added as a new entry in table.
 819 // The old format checker uses heap sort to find duplicates.
 820 // NOTE: caller should guarantee that GC doesn't happen during the life cycle
 821 // of table since we don't expect Symbol*'s to move.
 822 static bool put_after_lookup(const Symbol* name, const Symbol* sig, NameSigHash** table) {
 823   assert(name != NULL, "name in constant pool is NULL");
 824 
 825   // First lookup for duplicates
 826   int index = hash(name, sig);
 827   NameSigHash* entry = table[index];
 828   while (entry != NULL) {
 829     if (entry->_name == name && entry->_sig == sig) {
 830       return false;
 831     }
 832     entry = entry->_next;
 833   }
 834 
 835   // No duplicate is found, allocate a new entry and fill it.
 836   entry = new NameSigHash();
 837   entry->_name = name;
 838   entry->_sig = sig;
 839 
 840   // Insert into hash table
 841   entry->_next = table[index];
 842   table[index] = entry;
 843 
 844   return true;
 845 }
 846 
 847 // Side-effects: populates the _local_interfaces field
 848 void ClassFileParser::parse_interfaces(const ClassFileStream* const stream,
 849                                        const int itfs_len,
 850                                        ConstantPool* const cp,
 851                                        bool* const has_nonstatic_concrete_methods,
 852                                        TRAPS) {
 853   assert(stream != NULL, "invariant");
 854   assert(cp != NULL, "invariant");
 855   assert(has_nonstatic_concrete_methods != NULL, "invariant");
 856 
 857   if (itfs_len == 0) {
 858     _local_interfaces = Universe::the_empty_klass_array();
 859   } else {
 860     assert(itfs_len > 0, "only called for len>0");
 861     _local_interfaces = MetadataFactory::new_array<Klass*>(_loader_data, itfs_len, NULL, CHECK);
 862 
 863     int index;
 864     for (index = 0; index < itfs_len; index++) {
 865       const u2 interface_index = stream->get_u2(CHECK);
 866       Klass* interf;
 867       check_property(
 868         valid_klass_reference_at(interface_index),
 869         "Interface name has bad constant pool index %u in class file %s",
 870         interface_index, CHECK);
 871       if (cp->tag_at(interface_index).is_klass()) {
 872         interf = cp->resolved_klass_at(interface_index);
 873       } else {
 874         Symbol* const unresolved_klass  = cp->klass_name_at(interface_index);
 875 
 876         // Don't need to check legal name because it's checked when parsing constant pool.
 877         // But need to make sure it's not an array type.
 878         guarantee_property(unresolved_klass->byte_at(0) != JVM_SIGNATURE_ARRAY,
 879                            "Bad interface name in class file %s", CHECK);
 880 
 881         // Call resolve_super so classcircularity is checked
 882         interf = SystemDictionary::resolve_super_or_fail(
 883                                                   _class_name,
 884                                                   unresolved_klass,
 885                                                   Handle(THREAD, _loader_data->class_loader()),
 886                                                   _protection_domain,
 887                                                   false,
 888                                                   CHECK);
 889       }
 890 
 891       if (!interf->is_interface()) {
 892         THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
 893                    "Implementing class");
 894       }
 895 
 896       if (InstanceKlass::cast(interf)->has_nonstatic_concrete_methods()) {
 897         *has_nonstatic_concrete_methods = true;
 898       }
 899       _local_interfaces->at_put(index, interf);
 900     }
 901 
 902     if (!_need_verify || itfs_len <= 1) {
 903       return;
 904     }
 905 
 906     // Check if there's any duplicates in interfaces
 907     ResourceMark rm(THREAD);
 908     NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
 909                                                                  NameSigHash*,
 910                                                                  HASH_ROW_SIZE);
 911     initialize_hashtable(interface_names);
 912     bool dup = false;
 913     const Symbol* name = NULL;
 914     {
 915       debug_only(NoSafepointVerifier nsv;)
 916       for (index = 0; index < itfs_len; index++) {
 917         const Klass* const k = _local_interfaces->at(index);
 918         name = InstanceKlass::cast(k)->name();
 919         // If no duplicates, add (name, NULL) in hashtable interface_names.
 920         if (!put_after_lookup(name, NULL, interface_names)) {
 921           dup = true;
 922           break;
 923         }
 924       }
 925     }
 926     if (dup) {
 927       classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
 928                              name->as_C_string(), CHECK);
 929     }
 930   }
 931 }
 932 
 933 void ClassFileParser::verify_constantvalue(const ConstantPool* const cp,
 934                                            int constantvalue_index,
 935                                            int signature_index,
 936                                            TRAPS) const {
 937   // Make sure the constant pool entry is of a type appropriate to this field
 938   guarantee_property(
 939     (constantvalue_index > 0 &&
 940       constantvalue_index < cp->length()),
 941     "Bad initial value index %u in ConstantValue attribute in class file %s",
 942     constantvalue_index, CHECK);
 943 
 944   const constantTag value_type = cp->tag_at(constantvalue_index);
 945   switch(cp->basic_type_for_signature_at(signature_index)) {
 946     case T_LONG: {
 947       guarantee_property(value_type.is_long(),
 948                          "Inconsistent constant value type in class file %s",
 949                          CHECK);
 950       break;
 951     }
 952     case T_FLOAT: {
 953       guarantee_property(value_type.is_float(),
 954                          "Inconsistent constant value type in class file %s",
 955                          CHECK);
 956       break;
 957     }
 958     case T_DOUBLE: {
 959       guarantee_property(value_type.is_double(),
 960                          "Inconsistent constant value type in class file %s",
 961                          CHECK);
 962       break;
 963     }
 964     case T_BYTE:
 965     case T_CHAR:
 966     case T_SHORT:
 967     case T_BOOLEAN:
 968     case T_INT: {
 969       guarantee_property(value_type.is_int(),
 970                          "Inconsistent constant value type in class file %s",
 971                          CHECK);
 972       break;
 973     }
 974     case T_OBJECT: {
 975       guarantee_property((cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
 976                          && value_type.is_string()),
 977                          "Bad string initial value in class file %s",
 978                          CHECK);
 979       break;
 980     }
 981     default: {
 982       classfile_parse_error("Unable to set initial value %u in class file %s",
 983                              constantvalue_index,
 984                              CHECK);
 985     }
 986   }
 987 }
 988 
 989 class AnnotationCollector : public ResourceObj{
 990 public:
 991   enum Location { _in_field, _in_method, _in_class };
 992   enum ID {
 993     _unknown = 0,
 994     _method_CallerSensitive,
 995     _method_ForceInline,
 996     _method_DontInline,
 997     _method_InjectedProfile,
 998     _method_LambdaForm_Compiled,
 999     _method_LambdaForm_Hidden,
1000     _method_HotSpotIntrinsicCandidate,
1001     _jdk_internal_vm_annotation_Contended,
1002     _field_Stable,
1003     _jdk_internal_vm_annotation_ReservedStackAccess,
1004     _annotation_LIMIT
1005   };
1006   const Location _location;
1007   int _annotations_present;
1008   u2 _contended_group;
1009 
1010   AnnotationCollector(Location location)
1011     : _location(location), _annotations_present(0)
1012   {
1013     assert((int)_annotation_LIMIT <= (int)sizeof(_annotations_present) * BitsPerByte, "");
1014   }
1015   // If this annotation name has an ID, report it (or _none).
1016   ID annotation_index(const ClassLoaderData* loader_data, const Symbol* name);
1017   // Set the annotation name:
1018   void set_annotation(ID id) {
1019     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
1020     _annotations_present |= nth_bit((int)id);
1021   }
1022 
1023   void remove_annotation(ID id) {
1024     assert((int)id >= 0 && (int)id < (int)_annotation_LIMIT, "oob");
1025     _annotations_present &= ~nth_bit((int)id);
1026   }
1027 
1028   // Report if the annotation is present.
1029   bool has_any_annotations() const { return _annotations_present != 0; }
1030   bool has_annotation(ID id) const { return (nth_bit((int)id) & _annotations_present) != 0; }
1031 
1032   void set_contended_group(u2 group) { _contended_group = group; }
1033   u2 contended_group() const { return _contended_group; }
1034 
1035   bool is_contended() const { return has_annotation(_jdk_internal_vm_annotation_Contended); }
1036 
1037   void set_stable(bool stable) { set_annotation(_field_Stable); }
1038   bool is_stable() const { return has_annotation(_field_Stable); }
1039 };
1040 
1041 // This class also doubles as a holder for metadata cleanup.
1042 class ClassFileParser::FieldAnnotationCollector : public AnnotationCollector {
1043 private:
1044   ClassLoaderData* _loader_data;
1045   AnnotationArray* _field_annotations;
1046   AnnotationArray* _field_type_annotations;
1047 public:
1048   FieldAnnotationCollector(ClassLoaderData* loader_data) :
1049     AnnotationCollector(_in_field),
1050     _loader_data(loader_data),
1051     _field_annotations(NULL),
1052     _field_type_annotations(NULL) {}
1053   ~FieldAnnotationCollector();
1054   void apply_to(FieldInfo* f);
1055   AnnotationArray* field_annotations()      { return _field_annotations; }
1056   AnnotationArray* field_type_annotations() { return _field_type_annotations; }
1057 
1058   void set_field_annotations(AnnotationArray* a)      { _field_annotations = a; }
1059   void set_field_type_annotations(AnnotationArray* a) { _field_type_annotations = a; }
1060 };
1061 
1062 class MethodAnnotationCollector : public AnnotationCollector{
1063 public:
1064   MethodAnnotationCollector() : AnnotationCollector(_in_method) { }
1065   void apply_to(const methodHandle& m);
1066 };
1067 
1068 class ClassFileParser::ClassAnnotationCollector : public AnnotationCollector{
1069 public:
1070   ClassAnnotationCollector() : AnnotationCollector(_in_class) { }
1071   void apply_to(InstanceKlass* ik);
1072 };
1073 
1074 
1075 static int skip_annotation_value(const u1*, int, int); // fwd decl
1076 
1077 // Safely increment index by val if does not pass limit
1078 #define SAFE_ADD(index, limit, val) \
1079 if (index >= limit - val) return limit; \
1080 index += val;
1081 
1082 // Skip an annotation.  Return >=limit if there is any problem.
1083 static int skip_annotation(const u1* buffer, int limit, int index) {
1084   assert(buffer != NULL, "invariant");
1085   // annotation := atype:u2 do(nmem:u2) {member:u2 value}
1086   // value := switch (tag:u1) { ... }
1087   SAFE_ADD(index, limit, 4); // skip atype and read nmem
1088   int nmem = Bytes::get_Java_u2((address)buffer + index - 2);
1089   while (--nmem >= 0 && index < limit) {
1090     SAFE_ADD(index, limit, 2); // skip member
1091     index = skip_annotation_value(buffer, limit, index);
1092   }
1093   return index;
1094 }
1095 
1096 // Skip an annotation value.  Return >=limit if there is any problem.
1097 static int skip_annotation_value(const u1* buffer, int limit, int index) {
1098   assert(buffer != NULL, "invariant");
1099 
1100   // value := switch (tag:u1) {
1101   //   case B, C, I, S, Z, D, F, J, c: con:u2;
1102   //   case e: e_class:u2 e_name:u2;
1103   //   case s: s_con:u2;
1104   //   case [: do(nval:u2) {value};
1105   //   case @: annotation;
1106   //   case s: s_con:u2;
1107   // }
1108   SAFE_ADD(index, limit, 1); // read tag
1109   const u1 tag = buffer[index - 1];
1110   switch (tag) {
1111     case 'B':
1112     case 'C':
1113     case 'I':
1114     case 'S':
1115     case 'Z':
1116     case 'D':
1117     case 'F':
1118     case 'J':
1119     case 'c':
1120     case 's':
1121       SAFE_ADD(index, limit, 2);  // skip con or s_con
1122       break;
1123     case 'e':
1124       SAFE_ADD(index, limit, 4);  // skip e_class, e_name
1125       break;
1126     case '[':
1127     {
1128       SAFE_ADD(index, limit, 2); // read nval
1129       int nval = Bytes::get_Java_u2((address)buffer + index - 2);
1130       while (--nval >= 0 && index < limit) {
1131         index = skip_annotation_value(buffer, limit, index);
1132       }
1133     }
1134     break;
1135     case '@':
1136       index = skip_annotation(buffer, limit, index);
1137       break;
1138     default:
1139       return limit;  //  bad tag byte
1140   }
1141   return index;
1142 }
1143 
1144 // Sift through annotations, looking for those significant to the VM:
1145 static void parse_annotations(const ConstantPool* const cp,
1146                               const u1* buffer, int limit,
1147                               AnnotationCollector* coll,
1148                               ClassLoaderData* loader_data,
1149                               TRAPS) {
1150 
1151   assert(cp != NULL, "invariant");
1152   assert(buffer != NULL, "invariant");
1153   assert(coll != NULL, "invariant");
1154   assert(loader_data != NULL, "invariant");
1155 
1156   // annotations := do(nann:u2) {annotation}
1157   int index = 2; // read nann
1158   if (index >= limit)  return;
1159   int nann = Bytes::get_Java_u2((address)buffer + index - 2);
1160   enum {  // initial annotation layout
1161     atype_off = 0,      // utf8 such as 'Ljava/lang/annotation/Retention;'
1162     count_off = 2,      // u2   such as 1 (one value)
1163     member_off = 4,     // utf8 such as 'value'
1164     tag_off = 6,        // u1   such as 'c' (type) or 'e' (enum)
1165     e_tag_val = 'e',
1166     e_type_off = 7,   // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'
1167     e_con_off = 9,    // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'
1168     e_size = 11,     // end of 'e' annotation
1169     c_tag_val = 'c',    // payload is type
1170     c_con_off = 7,    // utf8 payload, such as 'I'
1171     c_size = 9,       // end of 'c' annotation
1172     s_tag_val = 's',    // payload is String
1173     s_con_off = 7,    // utf8 payload, such as 'Ljava/lang/String;'
1174     s_size = 9,
1175     min_size = 6        // smallest possible size (zero members)
1176   };
1177   // Cannot add min_size to index in case of overflow MAX_INT
1178   while ((--nann) >= 0 && (index - 2 <= limit - min_size)) {
1179     int index0 = index;
1180     index = skip_annotation(buffer, limit, index);
1181     const u1* const abase = buffer + index0;
1182     const int atype = Bytes::get_Java_u2((address)abase + atype_off);
1183     const int count = Bytes::get_Java_u2((address)abase + count_off);
1184     const Symbol* const aname = check_symbol_at(cp, atype);
1185     if (aname == NULL)  break;  // invalid annotation name
1186     const Symbol* member = NULL;
1187     if (count >= 1) {
1188       const int member_index = Bytes::get_Java_u2((address)abase + member_off);
1189       member = check_symbol_at(cp, member_index);
1190       if (member == NULL)  break;  // invalid member name
1191     }
1192 
1193     // Here is where parsing particular annotations will take place.
1194     AnnotationCollector::ID id = coll->annotation_index(loader_data, aname);
1195     if (AnnotationCollector::_unknown == id)  continue;
1196     coll->set_annotation(id);
1197 
1198     if (AnnotationCollector::_jdk_internal_vm_annotation_Contended == id) {
1199       // @Contended can optionally specify the contention group.
1200       //
1201       // Contended group defines the equivalence class over the fields:
1202       // the fields within the same contended group are not treated distinct.
1203       // The only exception is default group, which does not incur the
1204       // equivalence. Naturally, contention group for classes is meaningless.
1205       //
1206       // While the contention group is specified as String, annotation
1207       // values are already interned, and we might as well use the constant
1208       // pool index as the group tag.
1209       //
1210       u2 group_index = 0; // default contended group
1211       if (count == 1
1212         && s_size == (index - index0)  // match size
1213         && s_tag_val == *(abase + tag_off)
1214         && member == vmSymbols::value_name()) {
1215         group_index = Bytes::get_Java_u2((address)abase + s_con_off);
1216         if (cp->symbol_at(group_index)->utf8_length() == 0) {
1217           group_index = 0; // default contended group
1218         }
1219       }
1220       coll->set_contended_group(group_index);
1221     }
1222   }
1223 }
1224 
1225 
1226 // Parse attributes for a field.
1227 void ClassFileParser::parse_field_attributes(const ClassFileStream* const cfs,
1228                                              u2 attributes_count,
1229                                              bool is_static, u2 signature_index,
1230                                              u2* const constantvalue_index_addr,
1231                                              bool* const is_synthetic_addr,
1232                                              u2* const generic_signature_index_addr,
1233                                              ClassFileParser::FieldAnnotationCollector* parsed_annotations,
1234                                              TRAPS) {
1235   assert(cfs != NULL, "invariant");
1236   assert(constantvalue_index_addr != NULL, "invariant");
1237   assert(is_synthetic_addr != NULL, "invariant");
1238   assert(generic_signature_index_addr != NULL, "invariant");
1239   assert(parsed_annotations != NULL, "invariant");
1240   assert(attributes_count > 0, "attributes_count should be greater than 0");
1241 
1242   u2 constantvalue_index = 0;
1243   u2 generic_signature_index = 0;
1244   bool is_synthetic = false;
1245   const u1* runtime_visible_annotations = NULL;
1246   int runtime_visible_annotations_length = 0;
1247   const u1* runtime_invisible_annotations = NULL;
1248   int runtime_invisible_annotations_length = 0;
1249   const u1* runtime_visible_type_annotations = NULL;
1250   int runtime_visible_type_annotations_length = 0;
1251   const u1* runtime_invisible_type_annotations = NULL;
1252   int runtime_invisible_type_annotations_length = 0;
1253   bool runtime_invisible_annotations_exists = false;
1254   bool runtime_invisible_type_annotations_exists = false;
1255   const ConstantPool* const cp = _cp;
1256 
1257   while (attributes_count--) {
1258     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
1259     const u2 attribute_name_index = cfs->get_u2_fast();
1260     const u4 attribute_length = cfs->get_u4_fast();
1261     check_property(valid_symbol_at(attribute_name_index),
1262                    "Invalid field attribute index %u in class file %s",
1263                    attribute_name_index,
1264                    CHECK);
1265 
1266     const Symbol* const attribute_name = cp->symbol_at(attribute_name_index);
1267     if (is_static && attribute_name == vmSymbols::tag_constant_value()) {
1268       // ignore if non-static
1269       if (constantvalue_index != 0) {
1270         classfile_parse_error("Duplicate ConstantValue attribute in class file %s", CHECK);
1271       }
1272       check_property(
1273         attribute_length == 2,
1274         "Invalid ConstantValue field attribute length %u in class file %s",
1275         attribute_length, CHECK);
1276 
1277       constantvalue_index = cfs->get_u2(CHECK);
1278       if (_need_verify) {
1279         verify_constantvalue(cp, constantvalue_index, signature_index, CHECK);
1280       }
1281     } else if (attribute_name == vmSymbols::tag_synthetic()) {
1282       if (attribute_length != 0) {
1283         classfile_parse_error(
1284           "Invalid Synthetic field attribute length %u in class file %s",
1285           attribute_length, CHECK);
1286       }
1287       is_synthetic = true;
1288     } else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120
1289       if (attribute_length != 0) {
1290         classfile_parse_error(
1291           "Invalid Deprecated field attribute length %u in class file %s",
1292           attribute_length, CHECK);
1293       }
1294     } else if (_major_version >= JAVA_1_5_VERSION) {
1295       if (attribute_name == vmSymbols::tag_signature()) {
1296         if (generic_signature_index != 0) {
1297           classfile_parse_error(
1298             "Multiple Signature attributes for field in class file %s", CHECK);
1299         }
1300         if (attribute_length != 2) {
1301           classfile_parse_error(
1302             "Wrong size %u for field's Signature attribute in class file %s",
1303             attribute_length, CHECK);
1304         }
1305         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK);
1306       } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
1307         if (runtime_visible_annotations != NULL) {
1308           classfile_parse_error(
1309             "Multiple RuntimeVisibleAnnotations attributes for field in class file %s", CHECK);
1310         }
1311         runtime_visible_annotations_length = attribute_length;
1312         runtime_visible_annotations = cfs->current();
1313         assert(runtime_visible_annotations != NULL, "null visible annotations");
1314         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
1315         parse_annotations(cp,
1316                           runtime_visible_annotations,
1317                           runtime_visible_annotations_length,
1318                           parsed_annotations,
1319                           _loader_data,
1320                           CHECK);
1321         cfs->skip_u1_fast(runtime_visible_annotations_length);
1322       } else if (attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
1323         if (runtime_invisible_annotations_exists) {
1324           classfile_parse_error(
1325             "Multiple RuntimeInvisibleAnnotations attributes for field in class file %s", CHECK);
1326         }
1327         runtime_invisible_annotations_exists = true;
1328         if (PreserveAllAnnotations) {
1329           runtime_invisible_annotations_length = attribute_length;
1330           runtime_invisible_annotations = cfs->current();
1331           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
1332         }
1333         cfs->skip_u1(attribute_length, CHECK);
1334       } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
1335         if (runtime_visible_type_annotations != NULL) {
1336           classfile_parse_error(
1337             "Multiple RuntimeVisibleTypeAnnotations attributes for field in class file %s", CHECK);
1338         }
1339         runtime_visible_type_annotations_length = attribute_length;
1340         runtime_visible_type_annotations = cfs->current();
1341         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
1342         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
1343       } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
1344         if (runtime_invisible_type_annotations_exists) {
1345           classfile_parse_error(
1346             "Multiple RuntimeInvisibleTypeAnnotations attributes for field in class file %s", CHECK);
1347         } else {
1348           runtime_invisible_type_annotations_exists = true;
1349         }
1350         if (PreserveAllAnnotations) {
1351           runtime_invisible_type_annotations_length = attribute_length;
1352           runtime_invisible_type_annotations = cfs->current();
1353           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
1354         }
1355         cfs->skip_u1(attribute_length, CHECK);
1356       } else {
1357         cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
1358       }
1359     } else {
1360       cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
1361     }
1362   }
1363 
1364   *constantvalue_index_addr = constantvalue_index;
1365   *is_synthetic_addr = is_synthetic;
1366   *generic_signature_index_addr = generic_signature_index;
1367   AnnotationArray* a = assemble_annotations(runtime_visible_annotations,
1368                                             runtime_visible_annotations_length,
1369                                             runtime_invisible_annotations,
1370                                             runtime_invisible_annotations_length,
1371                                             CHECK);
1372   parsed_annotations->set_field_annotations(a);
1373   a = assemble_annotations(runtime_visible_type_annotations,
1374                            runtime_visible_type_annotations_length,
1375                            runtime_invisible_type_annotations,
1376                            runtime_invisible_type_annotations_length,
1377                            CHECK);
1378   parsed_annotations->set_field_type_annotations(a);
1379   return;
1380 }
1381 
1382 
1383 // Field allocation types. Used for computing field offsets.
1384 
1385 enum FieldAllocationType {
1386   STATIC_OOP,           // Oops
1387   STATIC_BYTE,          // Boolean, Byte, char
1388   STATIC_SHORT,         // shorts
1389   STATIC_WORD,          // ints
1390   STATIC_DOUBLE,        // aligned long or double
1391   NONSTATIC_OOP,
1392   NONSTATIC_BYTE,
1393   NONSTATIC_SHORT,
1394   NONSTATIC_WORD,
1395   NONSTATIC_DOUBLE,
1396   MAX_FIELD_ALLOCATION_TYPE,
1397   BAD_ALLOCATION_TYPE = -1
1398 };
1399 
1400 static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
1401   BAD_ALLOCATION_TYPE, // 0
1402   BAD_ALLOCATION_TYPE, // 1
1403   BAD_ALLOCATION_TYPE, // 2
1404   BAD_ALLOCATION_TYPE, // 3
1405   NONSTATIC_BYTE ,     // T_BOOLEAN     =  4,
1406   NONSTATIC_SHORT,     // T_CHAR        =  5,
1407   NONSTATIC_WORD,      // T_FLOAT       =  6,
1408   NONSTATIC_DOUBLE,    // T_DOUBLE      =  7,
1409   NONSTATIC_BYTE,      // T_BYTE        =  8,
1410   NONSTATIC_SHORT,     // T_SHORT       =  9,
1411   NONSTATIC_WORD,      // T_INT         = 10,
1412   NONSTATIC_DOUBLE,    // T_LONG        = 11,
1413   NONSTATIC_OOP,       // T_OBJECT      = 12,
1414   NONSTATIC_OOP,       // T_ARRAY       = 13,
1415   BAD_ALLOCATION_TYPE, // T_VOID        = 14,
1416   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
1417   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
1418   BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
1419   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1420   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,
1421   BAD_ALLOCATION_TYPE, // 0
1422   BAD_ALLOCATION_TYPE, // 1
1423   BAD_ALLOCATION_TYPE, // 2
1424   BAD_ALLOCATION_TYPE, // 3
1425   STATIC_BYTE ,        // T_BOOLEAN     =  4,
1426   STATIC_SHORT,        // T_CHAR        =  5,
1427   STATIC_WORD,         // T_FLOAT       =  6,
1428   STATIC_DOUBLE,       // T_DOUBLE      =  7,
1429   STATIC_BYTE,         // T_BYTE        =  8,
1430   STATIC_SHORT,        // T_SHORT       =  9,
1431   STATIC_WORD,         // T_INT         = 10,
1432   STATIC_DOUBLE,       // T_LONG        = 11,
1433   STATIC_OOP,          // T_OBJECT      = 12,
1434   STATIC_OOP,          // T_ARRAY       = 13,
1435   BAD_ALLOCATION_TYPE, // T_VOID        = 14,
1436   BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
1437   BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
1438   BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
1439   BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
1440   BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,
1441 };
1442 
1443 static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type) {
1444   assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
1445   FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
1446   assert(result != BAD_ALLOCATION_TYPE, "bad type");
1447   return result;
1448 }
1449 
1450 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1451  public:
1452   u2 count[MAX_FIELD_ALLOCATION_TYPE];
1453 
1454   FieldAllocationCount() {
1455     for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1456       count[i] = 0;
1457     }
1458   }
1459 
1460   FieldAllocationType update(bool is_static, BasicType type) {
1461     FieldAllocationType atype = basic_type_to_atype(is_static, type);
1462     if (atype != BAD_ALLOCATION_TYPE) {
1463       // Make sure there is no overflow with injected fields.
1464       assert(count[atype] < 0xFFFF, "More than 65535 fields");
1465       count[atype]++;
1466     }
1467     return atype;
1468   }
1469 };
1470 
1471 // Side-effects: populates the _fields, _fields_annotations,
1472 // _fields_type_annotations fields
1473 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1474                                    bool is_interface,
1475                                    FieldAllocationCount* const fac,
1476                                    ConstantPool* cp,
1477                                    const int cp_size,
1478                                    u2* const java_fields_count_ptr,
1479                                    TRAPS) {
1480 
1481   assert(cfs != NULL, "invariant");
1482   assert(fac != NULL, "invariant");
1483   assert(cp != NULL, "invariant");
1484   assert(java_fields_count_ptr != NULL, "invariant");
1485 
1486   assert(NULL == _fields, "invariant");
1487   assert(NULL == _fields_annotations, "invariant");
1488   assert(NULL == _fields_type_annotations, "invariant");
1489 
1490   cfs->guarantee_more(2, CHECK);  // length
1491   const u2 length = cfs->get_u2_fast();
1492   *java_fields_count_ptr = length;
1493 
1494   int num_injected = 0;
1495   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1496                                                                   &num_injected);
1497   const int total_fields = length + num_injected;
1498 
1499   // The field array starts with tuples of shorts
1500   // [access, name index, sig index, initial value index, byte offset].
1501   // A generic signature slot only exists for field with generic
1502   // signature attribute. And the access flag is set with
1503   // JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE for that field. The generic
1504   // signature slots are at the end of the field array and after all
1505   // other fields data.
1506   //
1507   //   f1: [access, name index, sig index, initial value index, low_offset, high_offset]
1508   //   f2: [access, name index, sig index, initial value index, low_offset, high_offset]
1509   //       ...
1510   //   fn: [access, name index, sig index, initial value index, low_offset, high_offset]
1511   //       [generic signature index]
1512   //       [generic signature index]
1513   //       ...
1514   //
1515   // Allocate a temporary resource array for field data. For each field,
1516   // a slot is reserved in the temporary array for the generic signature
1517   // index. After parsing all fields, the data are copied to a permanent
1518   // array and any unused slots will be discarded.
1519   ResourceMark rm(THREAD);
1520   u2* const fa = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
1521                                               u2,
1522                                               total_fields * (FieldInfo::field_slots + 1));
1523 
1524   // The generic signature slots start after all other fields' data.
1525   int generic_signature_slot = total_fields * FieldInfo::field_slots;
1526   int num_generic_signature = 0;
1527   for (int n = 0; n < length; n++) {
1528     // access_flags, name_index, descriptor_index, attributes_count
1529     cfs->guarantee_more(8, CHECK);
1530 
1531     AccessFlags access_flags;
1532     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1533     verify_legal_field_modifiers(flags, is_interface, CHECK);
1534     access_flags.set_flags(flags);
1535 
1536     const u2 name_index = cfs->get_u2_fast();
1537     check_property(valid_symbol_at(name_index),
1538       "Invalid constant pool index %u for field name in class file %s",
1539       name_index, CHECK);
1540     const Symbol* const name = cp->symbol_at(name_index);
1541     verify_legal_field_name(name, CHECK);
1542 
1543     const u2 signature_index = cfs->get_u2_fast();
1544     check_property(valid_symbol_at(signature_index),
1545       "Invalid constant pool index %u for field signature in class file %s",
1546       signature_index, CHECK);
1547     const Symbol* const sig = cp->symbol_at(signature_index);
1548     verify_legal_field_signature(name, sig, CHECK);
1549 
1550     u2 constantvalue_index = 0;
1551     bool is_synthetic = false;
1552     u2 generic_signature_index = 0;
1553     const bool is_static = access_flags.is_static();
1554     FieldAnnotationCollector parsed_annotations(_loader_data);
1555 
1556     const u2 attributes_count = cfs->get_u2_fast();
1557     if (attributes_count > 0) {
1558       parse_field_attributes(cfs,
1559                              attributes_count,
1560                              is_static,
1561                              signature_index,
1562                              &constantvalue_index,
1563                              &is_synthetic,
1564                              &generic_signature_index,
1565                              &parsed_annotations,
1566                              CHECK);
1567 
1568       if (parsed_annotations.field_annotations() != NULL) {
1569         if (_fields_annotations == NULL) {
1570           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1571                                              _loader_data, length, NULL,
1572                                              CHECK);
1573         }
1574         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1575         parsed_annotations.set_field_annotations(NULL);
1576       }
1577       if (parsed_annotations.field_type_annotations() != NULL) {
1578         if (_fields_type_annotations == NULL) {
1579           _fields_type_annotations =
1580             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1581                                                          length,
1582                                                          NULL,
1583                                                          CHECK);
1584         }
1585         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1586         parsed_annotations.set_field_type_annotations(NULL);
1587       }
1588 
1589       if (is_synthetic) {
1590         access_flags.set_is_synthetic();
1591       }
1592       if (generic_signature_index != 0) {
1593         access_flags.set_field_has_generic_signature();
1594         fa[generic_signature_slot] = generic_signature_index;
1595         generic_signature_slot ++;
1596         num_generic_signature ++;
1597       }
1598     }
1599 
1600     FieldInfo* const field = FieldInfo::from_field_array(fa, n);
1601     field->initialize(access_flags.as_short(),
1602                       name_index,
1603                       signature_index,
1604                       constantvalue_index);
1605     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1606 
1607     // Remember how many oops we encountered and compute allocation type
1608     const FieldAllocationType atype = fac->update(is_static, type);
1609     field->set_allocation_type(atype);
1610 
1611     // After field is initialized with type, we can augment it with aux info
1612     if (parsed_annotations.has_any_annotations())
1613       parsed_annotations.apply_to(field);
1614   }
1615 
1616   int index = length;
1617   if (num_injected != 0) {
1618     for (int n = 0; n < num_injected; n++) {
1619       // Check for duplicates
1620       if (injected[n].may_be_java) {
1621         const Symbol* const name      = injected[n].name();
1622         const Symbol* const signature = injected[n].signature();
1623         bool duplicate = false;
1624         for (int i = 0; i < length; i++) {
1625           const FieldInfo* const f = FieldInfo::from_field_array(fa, i);
1626           if (name      == cp->symbol_at(f->name_index()) &&
1627               signature == cp->symbol_at(f->signature_index())) {
1628             // Symbol is desclared in Java so skip this one
1629             duplicate = true;
1630             break;
1631           }
1632         }
1633         if (duplicate) {
1634           // These will be removed from the field array at the end
1635           continue;
1636         }
1637       }
1638 
1639       // Injected field
1640       FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1641       field->initialize(JVM_ACC_FIELD_INTERNAL,
1642                         injected[n].name_index,
1643                         injected[n].signature_index,
1644                         0);
1645 
1646       const BasicType type = FieldType::basic_type(injected[n].signature());
1647 
1648       // Remember how many oops we encountered and compute allocation type
1649       const FieldAllocationType atype = fac->update(false, type);
1650       field->set_allocation_type(atype);
1651       index++;
1652     }
1653   }
1654 
1655   assert(NULL == _fields, "invariant");
1656 
1657   _fields =
1658     MetadataFactory::new_array<u2>(_loader_data,
1659                                    index * FieldInfo::field_slots + num_generic_signature,
1660                                    CHECK);
1661   // Sometimes injected fields already exist in the Java source so
1662   // the fields array could be too long.  In that case the
1663   // fields array is trimed. Also unused slots that were reserved
1664   // for generic signature indexes are discarded.
1665   {
1666     int i = 0;
1667     for (; i < index * FieldInfo::field_slots; i++) {
1668       _fields->at_put(i, fa[i]);
1669     }
1670     for (int j = total_fields * FieldInfo::field_slots;
1671          j < generic_signature_slot; j++) {
1672       _fields->at_put(i++, fa[j]);
1673     }
1674     assert(_fields->length() == i, "");
1675   }
1676 
1677   if (_need_verify && length > 1) {
1678     // Check duplicated fields
1679     ResourceMark rm(THREAD);
1680     NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
1681       THREAD, NameSigHash*, HASH_ROW_SIZE);
1682     initialize_hashtable(names_and_sigs);
1683     bool dup = false;
1684     const Symbol* name = NULL;
1685     const Symbol* sig = NULL;
1686     {
1687       debug_only(NoSafepointVerifier nsv;)
1688       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
1689         name = fs.name();
1690         sig = fs.signature();
1691         // If no duplicates, add name/signature in hashtable names_and_sigs.
1692         if (!put_after_lookup(name, sig, names_and_sigs)) {
1693           dup = true;
1694           break;
1695         }
1696       }
1697     }
1698     if (dup) {
1699       classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1700                              name->as_C_string(), sig->as_klass_external_name(), CHECK);
1701     }
1702   }
1703 }
1704 
1705 
1706 const ClassFileParser::unsafe_u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs,
1707                                                                          u4 code_length,
1708                                                                          u4 exception_table_length,
1709                                                                          TRAPS) {
1710   assert(cfs != NULL, "invariant");
1711 
1712   const unsafe_u2* const exception_table_start = cfs->current();
1713   assert(exception_table_start != NULL, "null exception table");
1714 
1715   cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc,
1716                                                                // end_pc,
1717                                                                // handler_pc,
1718                                                                // catch_type_index
1719 
1720   // Will check legal target after parsing code array in verifier.
1721   if (_need_verify) {
1722     for (unsigned int i = 0; i < exception_table_length; i++) {
1723       const u2 start_pc = cfs->get_u2_fast();
1724       const u2 end_pc = cfs->get_u2_fast();
1725       const u2 handler_pc = cfs->get_u2_fast();
1726       const u2 catch_type_index = cfs->get_u2_fast();
1727       guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1728                          "Illegal exception table range in class file %s",
1729                          CHECK_NULL);
1730       guarantee_property(handler_pc < code_length,
1731                          "Illegal exception table handler in class file %s",
1732                          CHECK_NULL);
1733       if (catch_type_index != 0) {
1734         guarantee_property(valid_klass_reference_at(catch_type_index),
1735                            "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
1736       }
1737     }
1738   } else {
1739     cfs->skip_u2_fast(exception_table_length * 4);
1740   }
1741   return exception_table_start;
1742 }
1743 
1744 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length,
1745                                              u4 code_length,
1746                                              CompressedLineNumberWriteStream**const write_stream,
1747                                              TRAPS) {
1748 
1749   const ClassFileStream* const cfs = _stream;
1750   unsigned int num_entries = cfs->get_u2(CHECK);
1751 
1752   // Each entry is a u2 start_pc, and a u2 line_number
1753   const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2);
1754 
1755   // Verify line number attribute and table length
1756   check_property(
1757     code_attribute_length == sizeof(u2) + length_in_bytes,
1758     "LineNumberTable attribute has wrong length in class file %s", CHECK);
1759 
1760   cfs->guarantee_more(length_in_bytes, CHECK);
1761 
1762   if ((*write_stream) == NULL) {
1763     if (length_in_bytes > fixed_buffer_size) {
1764       (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1765     } else {
1766       (*write_stream) = new CompressedLineNumberWriteStream(
1767         _linenumbertable_buffer, fixed_buffer_size);
1768     }
1769   }
1770 
1771   while (num_entries-- > 0) {
1772     const u2 bci  = cfs->get_u2_fast(); // start_pc
1773     const u2 line = cfs->get_u2_fast(); // line_number
1774     guarantee_property(bci < code_length,
1775         "Invalid pc in LineNumberTable in class file %s", CHECK);
1776     (*write_stream)->write_pair(bci, line);
1777   }
1778 }
1779 
1780 
1781 class LVT_Hash : public AllStatic {
1782  public:
1783 
1784   static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) {
1785   /*
1786    * 3-tuple start_bci/length/slot has to be unique key,
1787    * so the following comparison seems to be redundant:
1788    *       && elem->name_cp_index == entry->_elem->name_cp_index
1789    */
1790     return (e0.start_bci     == e1.start_bci &&
1791             e0.length        == e1.length &&
1792             e0.name_cp_index == e1.name_cp_index &&
1793             e0.slot          == e1.slot);
1794   }
1795 
1796   static unsigned int hash(LocalVariableTableElement const& e0) {
1797     unsigned int raw_hash = e0.start_bci;
1798 
1799     raw_hash = e0.length        + raw_hash * 37;
1800     raw_hash = e0.name_cp_index + raw_hash * 37;
1801     raw_hash = e0.slot          + raw_hash * 37;
1802 
1803     return raw_hash;
1804   }
1805 };
1806 
1807 
1808 // Class file LocalVariableTable elements.
1809 class Classfile_LVT_Element VALUE_OBJ_CLASS_SPEC {
1810  public:
1811   u2 start_bci;
1812   u2 length;
1813   u2 name_cp_index;
1814   u2 descriptor_cp_index;
1815   u2 slot;
1816 };
1817 
1818 static void copy_lvt_element(const Classfile_LVT_Element* const src,
1819                              LocalVariableTableElement* const lvt) {
1820   lvt->start_bci           = Bytes::get_Java_u2((u1*) &src->start_bci);
1821   lvt->length              = Bytes::get_Java_u2((u1*) &src->length);
1822   lvt->name_cp_index       = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1823   lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1824   lvt->signature_cp_index  = 0;
1825   lvt->slot                = Bytes::get_Java_u2((u1*) &src->slot);
1826 }
1827 
1828 // Function is used to parse both attributes:
1829 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1830 const ClassFileParser::unsafe_u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs,
1831                                                                              u4 code_length,
1832                                                                              u2 max_locals,
1833                                                                              u4 code_attribute_length,
1834                                                                              u2* const localvariable_table_length,
1835                                                                              bool isLVTT,
1836                                                                              TRAPS) {
1837   const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1838   *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1839   const unsigned int size =
1840     (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);
1841 
1842   const ConstantPool* const cp = _cp;
1843 
1844   // Verify local variable table attribute has right length
1845   if (_need_verify) {
1846     guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1847                        "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1848   }
1849 
1850   const unsafe_u2* const localvariable_table_start = cfs->current();
1851   assert(localvariable_table_start != NULL, "null local variable table");
1852   if (!_need_verify) {
1853     cfs->skip_u2_fast(size);
1854   } else {
1855     cfs->guarantee_more(size * 2, CHECK_NULL);
1856     for(int i = 0; i < (*localvariable_table_length); i++) {
1857       const u2 start_pc = cfs->get_u2_fast();
1858       const u2 length = cfs->get_u2_fast();
1859       const u2 name_index = cfs->get_u2_fast();
1860       const u2 descriptor_index = cfs->get_u2_fast();
1861       const u2 index = cfs->get_u2_fast();
1862       // Assign to a u4 to avoid overflow
1863       const u4 end_pc = (u4)start_pc + (u4)length;
1864 
1865       if (start_pc >= code_length) {
1866         classfile_parse_error(
1867           "Invalid start_pc %u in %s in class file %s",
1868           start_pc, tbl_name, CHECK_NULL);
1869       }
1870       if (end_pc > code_length) {
1871         classfile_parse_error(
1872           "Invalid length %u in %s in class file %s",
1873           length, tbl_name, CHECK_NULL);
1874       }
1875       const int cp_size = cp->length();
1876       guarantee_property(valid_symbol_at(name_index),
1877         "Name index %u in %s has bad constant type in class file %s",
1878         name_index, tbl_name, CHECK_NULL);
1879       guarantee_property(valid_symbol_at(descriptor_index),
1880         "Signature index %u in %s has bad constant type in class file %s",
1881         descriptor_index, tbl_name, CHECK_NULL);
1882 
1883       const Symbol* const name = cp->symbol_at(name_index);
1884       const Symbol* const sig = cp->symbol_at(descriptor_index);
1885       verify_legal_field_name(name, CHECK_NULL);
1886       u2 extra_slot = 0;
1887       if (!isLVTT) {
1888         verify_legal_field_signature(name, sig, CHECK_NULL);
1889 
1890         // 4894874: check special cases for double and long local variables
1891         if (sig == vmSymbols::type_signature(T_DOUBLE) ||
1892             sig == vmSymbols::type_signature(T_LONG)) {
1893           extra_slot = 1;
1894         }
1895       }
1896       guarantee_property((index + extra_slot) < max_locals,
1897                           "Invalid index %u in %s in class file %s",
1898                           index, tbl_name, CHECK_NULL);
1899     }
1900   }
1901   return localvariable_table_start;
1902 }
1903 
1904 
1905 void ClassFileParser::parse_type_array(u2 array_length,
1906                                        u4 code_length,
1907                                        u4* const u1_index,
1908                                        u4* const u2_index,
1909                                        u1* const u1_array,
1910                                        u2* const u2_array,
1911                                        TRAPS) {
1912   const ClassFileStream* const cfs = _stream;
1913   u2 index = 0; // index in the array with long/double occupying two slots
1914   u4 i1 = *u1_index;
1915   u4 i2 = *u2_index + 1;
1916   for(int i = 0; i < array_length; i++) {
1917     const u1 tag = u1_array[i1++] = cfs->get_u1(CHECK);
1918     index++;
1919     if (tag == ITEM_Long || tag == ITEM_Double) {
1920       index++;
1921     } else if (tag == ITEM_Object) {
1922       const u2 class_index = u2_array[i2++] = cfs->get_u2(CHECK);
1923       guarantee_property(valid_klass_reference_at(class_index),
1924                          "Bad class index %u in StackMap in class file %s",
1925                          class_index, CHECK);
1926     } else if (tag == ITEM_Uninitialized) {
1927       const u2 offset = u2_array[i2++] = cfs->get_u2(CHECK);
1928       guarantee_property(
1929         offset < code_length,
1930         "Bad uninitialized type offset %u in StackMap in class file %s",
1931         offset, CHECK);
1932     } else {
1933       guarantee_property(
1934         tag <= (u1)ITEM_Uninitialized,
1935         "Unknown variable type %u in StackMap in class file %s",
1936         tag, CHECK);
1937     }
1938   }
1939   u2_array[*u2_index] = index;
1940   *u1_index = i1;
1941   *u2_index = i2;
1942 }
1943 
1944 static const u1* parse_stackmap_table(const ClassFileStream* const cfs,
1945                                       u4 code_attribute_length,
1946                                       bool need_verify,
1947                                       TRAPS) {
1948   assert(cfs != NULL, "invariant");
1949 
1950   if (0 == code_attribute_length) {
1951     return NULL;
1952   }
1953 
1954   const u1* const stackmap_table_start = cfs->current();
1955   assert(stackmap_table_start != NULL, "null stackmap table");
1956 
1957   // check code_attribute_length first
1958   cfs->skip_u1(code_attribute_length, CHECK_NULL);
1959 
1960   if (!need_verify && !DumpSharedSpaces) {
1961     return NULL;
1962   }
1963   return stackmap_table_start;
1964 }
1965 
1966 const ClassFileParser::unsafe_u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs,
1967                                                                             u2* const checked_exceptions_length,
1968                                                                             u4 method_attribute_length,
1969                                                                             TRAPS) {
1970   assert(cfs != NULL, "invariant");
1971   assert(checked_exceptions_length != NULL, "invariant");
1972 
1973   cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
1974   *checked_exceptions_length = cfs->get_u2_fast();
1975   const unsigned int size =
1976     (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
1977   const unsafe_u2* const checked_exceptions_start = cfs->current();
1978   assert(checked_exceptions_start != NULL, "null checked exceptions");
1979   if (!_need_verify) {
1980     cfs->skip_u2_fast(size);
1981   } else {
1982     // Verify each value in the checked exception table
1983     u2 checked_exception;
1984     const u2 len = *checked_exceptions_length;
1985     cfs->guarantee_more(2 * len, CHECK_NULL);
1986     for (int i = 0; i < len; i++) {
1987       checked_exception = cfs->get_u2_fast();
1988       check_property(
1989         valid_klass_reference_at(checked_exception),
1990         "Exception name has bad type at constant pool %u in class file %s",
1991         checked_exception, CHECK_NULL);
1992     }
1993   }
1994   // check exceptions attribute length
1995   if (_need_verify) {
1996     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
1997                                                    sizeof(u2) * size),
1998                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
1999   }
2000   return checked_exceptions_start;
2001 }
2002 
2003 void ClassFileParser::throwIllegalSignature(const char* type,
2004                                             const Symbol* name,
2005                                             const Symbol* sig,
2006                                             TRAPS) const {
2007   assert(name != NULL, "invariant");
2008   assert(sig != NULL, "invariant");
2009 
2010   ResourceMark rm(THREAD);
2011   Exceptions::fthrow(THREAD_AND_LOCATION,
2012       vmSymbols::java_lang_ClassFormatError(),
2013       "%s \"%s\" in class %s has illegal signature \"%s\"", type,
2014       name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
2015 }
2016 
2017 AnnotationCollector::ID
2018 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
2019                                       const Symbol* name) {
2020   const vmSymbols::SID sid = vmSymbols::find_sid(name);
2021   // Privileged code can use all annotations.  Other code silently drops some.
2022   const bool privileged = loader_data->is_the_null_class_loader_data() ||
2023                           loader_data->is_platform_class_loader_data() ||
2024                           loader_data->is_anonymous();
2025   switch (sid) {
2026     case vmSymbols::VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
2027       if (_location != _in_method)  break;  // only allow for methods
2028       if (!privileged)              break;  // only allow in privileged code
2029       return _method_CallerSensitive;
2030     }
2031     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
2032       if (_location != _in_method)  break;  // only allow for methods
2033       if (!privileged)              break;  // only allow in privileged code
2034       return _method_ForceInline;
2035     }
2036     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): {
2037       if (_location != _in_method)  break;  // only allow for methods
2038       if (!privileged)              break;  // only allow in privileged code
2039       return _method_DontInline;
2040     }
2041     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): {
2042       if (_location != _in_method)  break;  // only allow for methods
2043       if (!privileged)              break;  // only allow in privileged code
2044       return _method_InjectedProfile;
2045     }
2046     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): {
2047       if (_location != _in_method)  break;  // only allow for methods
2048       if (!privileged)              break;  // only allow in privileged code
2049       return _method_LambdaForm_Compiled;
2050     }
2051     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Hidden_signature): {
2052       if (_location != _in_method)  break;  // only allow for methods
2053       if (!privileged)              break;  // only allow in privileged code
2054       return _method_LambdaForm_Hidden;
2055     }
2056     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_HotSpotIntrinsicCandidate_signature): {
2057       if (_location != _in_method)  break;  // only allow for methods
2058       if (!privileged)              break;  // only allow in privileged code
2059       return _method_HotSpotIntrinsicCandidate;
2060     }
2061     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): {
2062       if (_location != _in_field)   break;  // only allow for fields
2063       if (!privileged)              break;  // only allow in privileged code
2064       return _field_Stable;
2065     }
2066     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
2067       if (_location != _in_field && _location != _in_class) {
2068         break;  // only allow for fields and classes
2069       }
2070       if (!EnableContended || (RestrictContended && !privileged)) {
2071         break;  // honor privileges
2072       }
2073       return _jdk_internal_vm_annotation_Contended;
2074     }
2075     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
2076       if (_location != _in_method)  break;  // only allow for methods
2077       if (RestrictReservedStack && !privileged) break; // honor privileges
2078       return _jdk_internal_vm_annotation_ReservedStackAccess;
2079     }
2080     default: {
2081       break;
2082     }
2083   }
2084   return AnnotationCollector::_unknown;
2085 }
2086 
2087 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2088   if (is_contended())
2089     f->set_contended_group(contended_group());
2090   if (is_stable())
2091     f->set_stable(true);
2092 }
2093 
2094 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2095   // If there's an error deallocate metadata for field annotations
2096   MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
2097   MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
2098 }
2099 
2100 void MethodAnnotationCollector::apply_to(const methodHandle& m) {
2101   if (has_annotation(_method_CallerSensitive))
2102     m->set_caller_sensitive(true);
2103   if (has_annotation(_method_ForceInline))
2104     m->set_force_inline(true);
2105   if (has_annotation(_method_DontInline))
2106     m->set_dont_inline(true);
2107   if (has_annotation(_method_InjectedProfile))
2108     m->set_has_injected_profile(true);
2109   if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
2110     m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
2111   if (has_annotation(_method_LambdaForm_Hidden))
2112     m->set_hidden(true);
2113   if (has_annotation(_method_HotSpotIntrinsicCandidate) && !m->is_synthetic())
2114     m->set_intrinsic_candidate(true);
2115   if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess))
2116     m->set_has_reserved_stack_access(true);
2117 }
2118 
2119 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) {
2120   assert(ik != NULL, "invariant");
2121   ik->set_is_contended(is_contended());
2122 }
2123 
2124 #define MAX_ARGS_SIZE 255
2125 #define MAX_CODE_SIZE 65535
2126 #define INITIAL_MAX_LVT_NUMBER 256
2127 
2128 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2129  *
2130  * Rules for LVT's and LVTT's are:
2131  *   - There can be any number of LVT's and LVTT's.
2132  *   - If there are n LVT's, it is the same as if there was just
2133  *     one LVT containing all the entries from the n LVT's.
2134  *   - There may be no more than one LVT entry per local variable.
2135  *     Two LVT entries are 'equal' if these fields are the same:
2136  *        start_pc, length, name, slot
2137  *   - There may be no more than one LVTT entry per each LVT entry.
2138  *     Each LVTT entry has to match some LVT entry.
2139  *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
2140  */
2141 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm,
2142                                                int lvt_cnt,
2143                                                u2* const localvariable_table_length,
2144                                                const unsafe_u2** const localvariable_table_start,
2145                                                int lvtt_cnt,
2146                                                u2* const localvariable_type_table_length,
2147                                                const unsafe_u2** const localvariable_type_table_start,
2148                                                TRAPS) {
2149 
2150   ResourceMark rm(THREAD);
2151 
2152   typedef ResourceHashtable<LocalVariableTableElement, LocalVariableTableElement*,
2153                             &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable;
2154 
2155   LVT_HashTable* const table = new LVT_HashTable();
2156 
2157   // To fill LocalVariableTable in
2158   const Classfile_LVT_Element* cf_lvt;
2159   LocalVariableTableElement* lvt = cm->localvariable_table_start();
2160 
2161   for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
2162     cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
2163     for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
2164       copy_lvt_element(&cf_lvt[idx], lvt);
2165       // If no duplicates, add LVT elem in hashtable.
2166       if (table->put(*lvt, lvt) == false
2167           && _need_verify
2168           && _major_version >= JAVA_1_5_VERSION) {
2169         classfile_parse_error("Duplicated LocalVariableTable attribute "
2170                               "entry for '%s' in class file %s",
2171                                _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
2172                                CHECK);
2173       }
2174     }
2175   }
2176 
2177   // To merge LocalVariableTable and LocalVariableTypeTable
2178   const Classfile_LVT_Element* cf_lvtt;
2179   LocalVariableTableElement lvtt_elem;
2180 
2181   for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2182     cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2183     for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2184       copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2185       LocalVariableTableElement** entry = table->get(lvtt_elem);
2186       if (entry == NULL) {
2187         if (_need_verify) {
2188           classfile_parse_error("LVTT entry for '%s' in class file %s "
2189                                 "does not match any LVT entry",
2190                                  _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2191                                  CHECK);
2192         }
2193       } else if ((*entry)->signature_cp_index != 0 && _need_verify) {
2194         classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2195                               "entry for '%s' in class file %s",
2196                                _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2197                                CHECK);
2198       } else {
2199         // to add generic signatures into LocalVariableTable
2200         (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index;
2201       }
2202     }
2203   }
2204 }
2205 
2206 
2207 void ClassFileParser::copy_method_annotations(ConstMethod* cm,
2208                                        const u1* runtime_visible_annotations,
2209                                        int runtime_visible_annotations_length,
2210                                        const u1* runtime_invisible_annotations,
2211                                        int runtime_invisible_annotations_length,
2212                                        const u1* runtime_visible_parameter_annotations,
2213                                        int runtime_visible_parameter_annotations_length,
2214                                        const u1* runtime_invisible_parameter_annotations,
2215                                        int runtime_invisible_parameter_annotations_length,
2216                                        const u1* runtime_visible_type_annotations,
2217                                        int runtime_visible_type_annotations_length,
2218                                        const u1* runtime_invisible_type_annotations,
2219                                        int runtime_invisible_type_annotations_length,
2220                                        const u1* annotation_default,
2221                                        int annotation_default_length,
2222                                        TRAPS) {
2223 
2224   AnnotationArray* a;
2225 
2226   if (runtime_visible_annotations_length +
2227       runtime_invisible_annotations_length > 0) {
2228      a = assemble_annotations(runtime_visible_annotations,
2229                               runtime_visible_annotations_length,
2230                               runtime_invisible_annotations,
2231                               runtime_invisible_annotations_length,
2232                               CHECK);
2233      cm->set_method_annotations(a);
2234   }
2235 
2236   if (runtime_visible_parameter_annotations_length +
2237       runtime_invisible_parameter_annotations_length > 0) {
2238     a = assemble_annotations(runtime_visible_parameter_annotations,
2239                              runtime_visible_parameter_annotations_length,
2240                              runtime_invisible_parameter_annotations,
2241                              runtime_invisible_parameter_annotations_length,
2242                              CHECK);
2243     cm->set_parameter_annotations(a);
2244   }
2245 
2246   if (annotation_default_length > 0) {
2247     a = assemble_annotations(annotation_default,
2248                              annotation_default_length,
2249                              NULL,
2250                              0,
2251                              CHECK);
2252     cm->set_default_annotations(a);
2253   }
2254 
2255   if (runtime_visible_type_annotations_length +
2256       runtime_invisible_type_annotations_length > 0) {
2257     a = assemble_annotations(runtime_visible_type_annotations,
2258                              runtime_visible_type_annotations_length,
2259                              runtime_invisible_type_annotations,
2260                              runtime_invisible_type_annotations_length,
2261                              CHECK);
2262     cm->set_type_annotations(a);
2263   }
2264 }
2265 
2266 
2267 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2268 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2269 // Method* to save footprint, so we only know the size of the resulting Method* when the
2270 // entire method attribute is parsed.
2271 //
2272 // The promoted_flags parameter is used to pass relevant access_flags
2273 // from the method back up to the containing klass. These flag values
2274 // are added to klass's access_flags.
2275 
2276 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2277                                       bool is_interface,
2278                                       const ConstantPool* cp,
2279                                       AccessFlags* const promoted_flags,
2280                                       TRAPS) {
2281   assert(cfs != NULL, "invariant");
2282   assert(cp != NULL, "invariant");
2283   assert(promoted_flags != NULL, "invariant");
2284 
2285   ResourceMark rm(THREAD);
2286   // Parse fixed parts:
2287   // access_flags, name_index, descriptor_index, attributes_count
2288   cfs->guarantee_more(8, CHECK_NULL);
2289 
2290   int flags = cfs->get_u2_fast();
2291   const u2 name_index = cfs->get_u2_fast();
2292   const int cp_size = cp->length();
2293   check_property(
2294     valid_symbol_at(name_index),
2295     "Illegal constant pool index %u for method name in class file %s",
2296     name_index, CHECK_NULL);
2297   const Symbol* const name = cp->symbol_at(name_index);
2298   verify_legal_method_name(name, CHECK_NULL);
2299 
2300   const u2 signature_index = cfs->get_u2_fast();
2301   guarantee_property(
2302     valid_symbol_at(signature_index),
2303     "Illegal constant pool index %u for method signature in class file %s",
2304     signature_index, CHECK_NULL);
2305   const Symbol* const signature = cp->symbol_at(signature_index);
2306 
2307   if (name == vmSymbols::class_initializer_name()) {
2308     // We ignore the other access flags for a valid class initializer.
2309     // (JVM Spec 2nd ed., chapter 4.6)
2310     if (_major_version < 51) { // backward compatibility
2311       flags = JVM_ACC_STATIC;
2312     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2313       flags &= JVM_ACC_STATIC | JVM_ACC_STRICT;
2314     } else {
2315       classfile_parse_error("Method <clinit> is not static in class file %s", CHECK_NULL);
2316     }
2317   } else {
2318     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2319   }
2320 
2321   if (name == vmSymbols::object_initializer_name() && is_interface) {
2322     classfile_parse_error("Interface cannot have a method named <init>, class file %s", CHECK_NULL);
2323   }
2324 
2325   int args_size = -1;  // only used when _need_verify is true
2326   if (_need_verify) {
2327     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2328                  verify_legal_method_signature(name, signature, CHECK_NULL);
2329     if (args_size > MAX_ARGS_SIZE) {
2330       classfile_parse_error("Too many arguments in method signature in class file %s", CHECK_NULL);
2331     }
2332   }
2333 
2334   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2335 
2336   // Default values for code and exceptions attribute elements
2337   u2 max_stack = 0;
2338   u2 max_locals = 0;
2339   u4 code_length = 0;
2340   const u1* code_start = 0;
2341   u2 exception_table_length = 0;
2342   const unsafe_u2* exception_table_start = NULL; // (potentially unaligned) pointer to array of u2 elements
2343   Array<int>* exception_handlers = Universe::the_empty_int_array();
2344   u2 checked_exceptions_length = 0;
2345   const unsafe_u2* checked_exceptions_start = NULL; // (potentially unaligned) pointer to array of u2 elements
2346   CompressedLineNumberWriteStream* linenumber_table = NULL;
2347   int linenumber_table_length = 0;
2348   int total_lvt_length = 0;
2349   u2 lvt_cnt = 0;
2350   u2 lvtt_cnt = 0;
2351   bool lvt_allocated = false;
2352   u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
2353   u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
2354   u2* localvariable_table_length = NULL;
2355   const unsafe_u2** localvariable_table_start = NULL; // (potentially unaligned) pointer to array of LVT attributes
2356   u2* localvariable_type_table_length = NULL;
2357   const unsafe_u2** localvariable_type_table_start = NULL; // (potentially unaligned) pointer to LVTT attributes
2358   int method_parameters_length = -1;
2359   const u1* method_parameters_data = NULL;
2360   bool method_parameters_seen = false;
2361   bool parsed_code_attribute = false;
2362   bool parsed_checked_exceptions_attribute = false;
2363   bool parsed_stackmap_attribute = false;
2364   // stackmap attribute - JDK1.5
2365   const u1* stackmap_data = NULL;
2366   int stackmap_data_length = 0;
2367   u2 generic_signature_index = 0;
2368   MethodAnnotationCollector parsed_annotations;
2369   const u1* runtime_visible_annotations = NULL;
2370   int runtime_visible_annotations_length = 0;
2371   const u1* runtime_invisible_annotations = NULL;
2372   int runtime_invisible_annotations_length = 0;
2373   const u1* runtime_visible_parameter_annotations = NULL;
2374   int runtime_visible_parameter_annotations_length = 0;
2375   const u1* runtime_invisible_parameter_annotations = NULL;
2376   int runtime_invisible_parameter_annotations_length = 0;
2377   const u1* runtime_visible_type_annotations = NULL;
2378   int runtime_visible_type_annotations_length = 0;
2379   const u1* runtime_invisible_type_annotations = NULL;
2380   int runtime_invisible_type_annotations_length = 0;
2381   bool runtime_invisible_annotations_exists = false;
2382   bool runtime_invisible_type_annotations_exists = false;
2383   bool runtime_invisible_parameter_annotations_exists = false;
2384   const u1* annotation_default = NULL;
2385   int annotation_default_length = 0;
2386 
2387   // Parse code and exceptions attribute
2388   u2 method_attributes_count = cfs->get_u2_fast();
2389   while (method_attributes_count--) {
2390     cfs->guarantee_more(6, CHECK_NULL);  // method_attribute_name_index, method_attribute_length
2391     const u2 method_attribute_name_index = cfs->get_u2_fast();
2392     const u4 method_attribute_length = cfs->get_u4_fast();
2393     check_property(
2394       valid_symbol_at(method_attribute_name_index),
2395       "Invalid method attribute name index %u in class file %s",
2396       method_attribute_name_index, CHECK_NULL);
2397 
2398     const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index);
2399     if (method_attribute_name == vmSymbols::tag_code()) {
2400       // Parse Code attribute
2401       if (_need_verify) {
2402         guarantee_property(
2403             !access_flags.is_native() && !access_flags.is_abstract(),
2404                         "Code attribute in native or abstract methods in class file %s",
2405                          CHECK_NULL);
2406       }
2407       if (parsed_code_attribute) {
2408         classfile_parse_error("Multiple Code attributes in class file %s",
2409                               CHECK_NULL);
2410       }
2411       parsed_code_attribute = true;
2412 
2413       // Stack size, locals size, and code size
2414       if (_major_version == 45 && _minor_version <= 2) {
2415         cfs->guarantee_more(4, CHECK_NULL);
2416         max_stack = cfs->get_u1_fast();
2417         max_locals = cfs->get_u1_fast();
2418         code_length = cfs->get_u2_fast();
2419       } else {
2420         cfs->guarantee_more(8, CHECK_NULL);
2421         max_stack = cfs->get_u2_fast();
2422         max_locals = cfs->get_u2_fast();
2423         code_length = cfs->get_u4_fast();
2424       }
2425       if (_need_verify) {
2426         guarantee_property(args_size <= max_locals,
2427                            "Arguments can't fit into locals in class file %s",
2428                            CHECK_NULL);
2429         guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
2430                            "Invalid method Code length %u in class file %s",
2431                            code_length, CHECK_NULL);
2432       }
2433       // Code pointer
2434       code_start = cfs->current();
2435       assert(code_start != NULL, "null code start");
2436       cfs->guarantee_more(code_length, CHECK_NULL);
2437       cfs->skip_u1_fast(code_length);
2438 
2439       // Exception handler table
2440       cfs->guarantee_more(2, CHECK_NULL);  // exception_table_length
2441       exception_table_length = cfs->get_u2_fast();
2442       if (exception_table_length > 0) {
2443         exception_table_start = parse_exception_table(cfs,
2444                                                       code_length,
2445                                                       exception_table_length,
2446                                                       CHECK_NULL);
2447       }
2448 
2449       // Parse additional attributes in code attribute
2450       cfs->guarantee_more(2, CHECK_NULL);  // code_attributes_count
2451       u2 code_attributes_count = cfs->get_u2_fast();
2452 
2453       unsigned int calculated_attribute_length = 0;
2454 
2455       if (_major_version > 45 || (_major_version == 45 && _minor_version > 2)) {
2456         calculated_attribute_length =
2457             sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
2458       } else {
2459         // max_stack, locals and length are smaller in pre-version 45.2 classes
2460         calculated_attribute_length = sizeof(u1) + sizeof(u1) + sizeof(u2);
2461       }
2462       calculated_attribute_length +=
2463         code_length +
2464         sizeof(exception_table_length) +
2465         sizeof(code_attributes_count) +
2466         exception_table_length *
2467             ( sizeof(u2) +   // start_pc
2468               sizeof(u2) +   // end_pc
2469               sizeof(u2) +   // handler_pc
2470               sizeof(u2) );  // catch_type_index
2471 
2472       while (code_attributes_count--) {
2473         cfs->guarantee_more(6, CHECK_NULL);  // code_attribute_name_index, code_attribute_length
2474         const u2 code_attribute_name_index = cfs->get_u2_fast();
2475         const u4 code_attribute_length = cfs->get_u4_fast();
2476         calculated_attribute_length += code_attribute_length +
2477                                        sizeof(code_attribute_name_index) +
2478                                        sizeof(code_attribute_length);
2479         check_property(valid_symbol_at(code_attribute_name_index),
2480                        "Invalid code attribute name index %u in class file %s",
2481                        code_attribute_name_index,
2482                        CHECK_NULL);
2483         if (LoadLineNumberTables &&
2484             cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
2485           // Parse and compress line number table
2486           parse_linenumber_table(code_attribute_length,
2487                                  code_length,
2488                                  &linenumber_table,
2489                                  CHECK_NULL);
2490 
2491         } else if (LoadLocalVariableTables &&
2492                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
2493           // Parse local variable table
2494           if (!lvt_allocated) {
2495             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2496               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2497             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2498               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2499             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2500               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2501             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2502               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2503             lvt_allocated = true;
2504           }
2505           if (lvt_cnt == max_lvt_cnt) {
2506             max_lvt_cnt <<= 1;
2507             localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
2508             localvariable_table_start  = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
2509           }
2510           localvariable_table_start[lvt_cnt] =
2511             parse_localvariable_table(cfs,
2512                                       code_length,
2513                                       max_locals,
2514                                       code_attribute_length,
2515                                       &localvariable_table_length[lvt_cnt],
2516                                       false,    // is not LVTT
2517                                       CHECK_NULL);
2518           total_lvt_length += localvariable_table_length[lvt_cnt];
2519           lvt_cnt++;
2520         } else if (LoadLocalVariableTypeTables &&
2521                    _major_version >= JAVA_1_5_VERSION &&
2522                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
2523           if (!lvt_allocated) {
2524             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2525               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2526             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2527               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2528             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2529               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2530             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2531               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2532             lvt_allocated = true;
2533           }
2534           // Parse local variable type table
2535           if (lvtt_cnt == max_lvtt_cnt) {
2536             max_lvtt_cnt <<= 1;
2537             localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
2538             localvariable_type_table_start  = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
2539           }
2540           localvariable_type_table_start[lvtt_cnt] =
2541             parse_localvariable_table(cfs,
2542                                       code_length,
2543                                       max_locals,
2544                                       code_attribute_length,
2545                                       &localvariable_type_table_length[lvtt_cnt],
2546                                       true,     // is LVTT
2547                                       CHECK_NULL);
2548           lvtt_cnt++;
2549         } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2550                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
2551           // Stack map is only needed by the new verifier in JDK1.5.
2552           if (parsed_stackmap_attribute) {
2553             classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_NULL);
2554           }
2555           stackmap_data = parse_stackmap_table(cfs, code_attribute_length, _need_verify, CHECK_NULL);
2556           stackmap_data_length = code_attribute_length;
2557           parsed_stackmap_attribute = true;
2558         } else {
2559           // Skip unknown attributes
2560           cfs->skip_u1(code_attribute_length, CHECK_NULL);
2561         }
2562       }
2563       // check method attribute length
2564       if (_need_verify) {
2565         guarantee_property(method_attribute_length == calculated_attribute_length,
2566                            "Code segment has wrong length in class file %s",
2567                            CHECK_NULL);
2568       }
2569     } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
2570       // Parse Exceptions attribute
2571       if (parsed_checked_exceptions_attribute) {
2572         classfile_parse_error("Multiple Exceptions attributes in class file %s",
2573                               CHECK_NULL);
2574       }
2575       parsed_checked_exceptions_attribute = true;
2576       checked_exceptions_start =
2577             parse_checked_exceptions(cfs,
2578                                      &checked_exceptions_length,
2579                                      method_attribute_length,
2580                                      CHECK_NULL);
2581     } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2582       // reject multiple method parameters
2583       if (method_parameters_seen) {
2584         classfile_parse_error("Multiple MethodParameters attributes in class file %s",
2585                               CHECK_NULL);
2586       }
2587       method_parameters_seen = true;
2588       method_parameters_length = cfs->get_u1_fast();
2589       const u2 real_length = (method_parameters_length * 4u) + 1u;
2590       if (method_attribute_length != real_length) {
2591         classfile_parse_error(
2592           "Invalid MethodParameters method attribute length %u in class file",
2593           method_attribute_length, CHECK_NULL);
2594       }
2595       method_parameters_data = cfs->current();
2596       cfs->skip_u2_fast(method_parameters_length);
2597       cfs->skip_u2_fast(method_parameters_length);
2598       // ignore this attribute if it cannot be reflected
2599       if (!SystemDictionary::Parameter_klass_loaded())
2600         method_parameters_length = -1;
2601     } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
2602       if (method_attribute_length != 0) {
2603         classfile_parse_error(
2604           "Invalid Synthetic method attribute length %u in class file %s",
2605           method_attribute_length, CHECK_NULL);
2606       }
2607       // Should we check that there hasn't already been a synthetic attribute?
2608       access_flags.set_is_synthetic();
2609     } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
2610       if (method_attribute_length != 0) {
2611         classfile_parse_error(
2612           "Invalid Deprecated method attribute length %u in class file %s",
2613           method_attribute_length, CHECK_NULL);
2614       }
2615     } else if (_major_version >= JAVA_1_5_VERSION) {
2616       if (method_attribute_name == vmSymbols::tag_signature()) {
2617         if (generic_signature_index != 0) {
2618           classfile_parse_error(
2619             "Multiple Signature attributes for method in class file %s",
2620             CHECK_NULL);
2621         }
2622         if (method_attribute_length != 2) {
2623           classfile_parse_error(
2624             "Invalid Signature attribute length %u in class file %s",
2625             method_attribute_length, CHECK_NULL);
2626         }
2627         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL);
2628       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
2629         if (runtime_visible_annotations != NULL) {
2630           classfile_parse_error(
2631             "Multiple RuntimeVisibleAnnotations attributes for method in class file %s",
2632             CHECK_NULL);
2633         }
2634         runtime_visible_annotations_length = method_attribute_length;
2635         runtime_visible_annotations = cfs->current();
2636         assert(runtime_visible_annotations != NULL, "null visible annotations");
2637         cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL);
2638         parse_annotations(cp,
2639                           runtime_visible_annotations,
2640                           runtime_visible_annotations_length,
2641                           &parsed_annotations,
2642                           _loader_data,
2643                           CHECK_NULL);
2644         cfs->skip_u1_fast(runtime_visible_annotations_length);
2645       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
2646         if (runtime_invisible_annotations_exists) {
2647           classfile_parse_error(
2648             "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s",
2649             CHECK_NULL);
2650         }
2651         runtime_invisible_annotations_exists = true;
2652         if (PreserveAllAnnotations) {
2653           runtime_invisible_annotations_length = method_attribute_length;
2654           runtime_invisible_annotations = cfs->current();
2655           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
2656         }
2657         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2658       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
2659         if (runtime_visible_parameter_annotations != NULL) {
2660           classfile_parse_error(
2661             "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s",
2662             CHECK_NULL);
2663         }
2664         runtime_visible_parameter_annotations_length = method_attribute_length;
2665         runtime_visible_parameter_annotations = cfs->current();
2666         assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");
2667         cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL);
2668       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
2669         if (runtime_invisible_parameter_annotations_exists) {
2670           classfile_parse_error(
2671             "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s",
2672             CHECK_NULL);
2673         }
2674         runtime_invisible_parameter_annotations_exists = true;
2675         if (PreserveAllAnnotations) {
2676           runtime_invisible_parameter_annotations_length = method_attribute_length;
2677           runtime_invisible_parameter_annotations = cfs->current();
2678           assert(runtime_invisible_parameter_annotations != NULL,
2679             "null invisible parameter annotations");
2680         }
2681         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2682       } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
2683         if (annotation_default != NULL) {
2684           classfile_parse_error(
2685             "Multiple AnnotationDefault attributes for method in class file %s",
2686             CHECK_NULL);
2687         }
2688         annotation_default_length = method_attribute_length;
2689         annotation_default = cfs->current();
2690         assert(annotation_default != NULL, "null annotation default");
2691         cfs->skip_u1(annotation_default_length, CHECK_NULL);
2692       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2693         if (runtime_visible_type_annotations != NULL) {
2694           classfile_parse_error(
2695             "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
2696             CHECK_NULL);
2697         }
2698         runtime_visible_type_annotations_length = method_attribute_length;
2699         runtime_visible_type_annotations = cfs->current();
2700         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
2701         // No need for the VM to parse Type annotations
2702         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL);
2703       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
2704         if (runtime_invisible_type_annotations_exists) {
2705           classfile_parse_error(
2706             "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
2707             CHECK_NULL);
2708         } else {
2709           runtime_invisible_type_annotations_exists = true;
2710         }
2711         if (PreserveAllAnnotations) {
2712           runtime_invisible_type_annotations_length = method_attribute_length;
2713           runtime_invisible_type_annotations = cfs->current();
2714           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
2715         }
2716         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2717       } else {
2718         // Skip unknown attributes
2719         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2720       }
2721     } else {
2722       // Skip unknown attributes
2723       cfs->skip_u1(method_attribute_length, CHECK_NULL);
2724     }
2725   }
2726 
2727   if (linenumber_table != NULL) {
2728     linenumber_table->write_terminator();
2729     linenumber_table_length = linenumber_table->position();
2730   }
2731 
2732   // Make sure there's at least one Code attribute in non-native/non-abstract method
2733   if (_need_verify) {
2734     guarantee_property(access_flags.is_native() ||
2735                        access_flags.is_abstract() ||
2736                        parsed_code_attribute,
2737                        "Absent Code attribute in method that is not native or abstract in class file %s",
2738                        CHECK_NULL);
2739   }
2740 
2741   // All sizing information for a Method* is finally available, now create it
2742   InlineTableSizes sizes(
2743       total_lvt_length,
2744       linenumber_table_length,
2745       exception_table_length,
2746       checked_exceptions_length,
2747       method_parameters_length,
2748       generic_signature_index,
2749       runtime_visible_annotations_length +
2750            runtime_invisible_annotations_length,
2751       runtime_visible_parameter_annotations_length +
2752            runtime_invisible_parameter_annotations_length,
2753       runtime_visible_type_annotations_length +
2754            runtime_invisible_type_annotations_length,
2755       annotation_default_length,
2756       0);
2757 
2758   Method* const m = Method::allocate(_loader_data,
2759                                      code_length,
2760                                      access_flags,
2761                                      &sizes,
2762                                      ConstMethod::NORMAL,
2763                                      CHECK_NULL);
2764 
2765   ClassLoadingService::add_class_method_size(m->size()*wordSize);
2766 
2767   // Fill in information from fixed part (access_flags already set)
2768   m->set_constants(_cp);
2769   m->set_name_index(name_index);
2770   m->set_signature_index(signature_index);
2771 
2772   ResultTypeFinder rtf(cp->symbol_at(signature_index));
2773   m->constMethod()->set_result_type(rtf.type());
2774 
2775   if (args_size >= 0) {
2776     m->set_size_of_parameters(args_size);
2777   } else {
2778     m->compute_size_of_parameters(THREAD);
2779   }
2780 #ifdef ASSERT
2781   if (args_size >= 0) {
2782     m->compute_size_of_parameters(THREAD);
2783     assert(args_size == m->size_of_parameters(), "");
2784   }
2785 #endif
2786 
2787   // Fill in code attribute information
2788   m->set_max_stack(max_stack);
2789   m->set_max_locals(max_locals);
2790   if (stackmap_data != NULL) {
2791     m->constMethod()->copy_stackmap_data(_loader_data,
2792                                          (u1*)stackmap_data,
2793                                          stackmap_data_length,
2794                                          CHECK_NULL);
2795   }
2796 
2797   // Copy byte codes
2798   m->set_code((u1*)code_start);
2799 
2800   // Copy line number table
2801   if (linenumber_table != NULL) {
2802     memcpy(m->compressed_linenumber_table(),
2803            linenumber_table->buffer(),
2804            linenumber_table_length);
2805   }
2806 
2807   // Copy exception table
2808   if (exception_table_length > 0) {
2809     Copy::conjoint_swap_if_needed<Endian::JAVA>(exception_table_start,
2810                                                 m->exception_table_start(),
2811                                                 exception_table_length * sizeof(ExceptionTableElement),
2812                                                 sizeof(u2));
2813   }
2814 
2815   // Copy method parameters
2816   if (method_parameters_length > 0) {
2817     MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2818     for (int i = 0; i < method_parameters_length; i++) {
2819       elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data);
2820       method_parameters_data += 2;
2821       elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data);
2822       method_parameters_data += 2;
2823     }
2824   }
2825 
2826   // Copy checked exceptions
2827   if (checked_exceptions_length > 0) {
2828     Copy::conjoint_swap_if_needed<Endian::JAVA>(checked_exceptions_start,
2829                                                 m->checked_exceptions_start(),
2830                                                 checked_exceptions_length * sizeof(CheckedExceptionElement),
2831                                                 sizeof(u2));
2832   }
2833 
2834   // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2835   if (total_lvt_length > 0) {
2836     promoted_flags->set_has_localvariable_table();
2837     copy_localvariable_table(m->constMethod(),
2838                              lvt_cnt,
2839                              localvariable_table_length,
2840                              localvariable_table_start,
2841                              lvtt_cnt,
2842                              localvariable_type_table_length,
2843                              localvariable_type_table_start,
2844                              CHECK_NULL);
2845   }
2846 
2847   if (parsed_annotations.has_any_annotations())
2848     parsed_annotations.apply_to(m);
2849 
2850   // Copy annotations
2851   copy_method_annotations(m->constMethod(),
2852                           runtime_visible_annotations,
2853                           runtime_visible_annotations_length,
2854                           runtime_invisible_annotations,
2855                           runtime_invisible_annotations_length,
2856                           runtime_visible_parameter_annotations,
2857                           runtime_visible_parameter_annotations_length,
2858                           runtime_invisible_parameter_annotations,
2859                           runtime_invisible_parameter_annotations_length,
2860                           runtime_visible_type_annotations,
2861                           runtime_visible_type_annotations_length,
2862                           runtime_invisible_type_annotations,
2863                           runtime_invisible_type_annotations_length,
2864                           annotation_default,
2865                           annotation_default_length,
2866                           CHECK_NULL);
2867 
2868   if (name == vmSymbols::finalize_method_name() &&
2869       signature == vmSymbols::void_method_signature()) {
2870     if (m->is_empty_method()) {
2871       _has_empty_finalizer = true;
2872     } else {
2873       _has_finalizer = true;
2874     }
2875   }
2876   if (name == vmSymbols::object_initializer_name() &&
2877       signature == vmSymbols::void_method_signature() &&
2878       m->is_vanilla_constructor()) {
2879     _has_vanilla_constructor = true;
2880   }
2881 
2882   NOT_PRODUCT(m->verify());
2883   return m;
2884 }
2885 
2886 
2887 // The promoted_flags parameter is used to pass relevant access_flags
2888 // from the methods back up to the containing klass. These flag values
2889 // are added to klass's access_flags.
2890 // Side-effects: populates the _methods field in the parser
2891 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2892                                     bool is_interface,
2893                                     AccessFlags* promoted_flags,
2894                                     bool* has_final_method,
2895                                     bool* declares_nonstatic_concrete_methods,
2896                                     TRAPS) {
2897   assert(cfs != NULL, "invariant");
2898   assert(promoted_flags != NULL, "invariant");
2899   assert(has_final_method != NULL, "invariant");
2900   assert(declares_nonstatic_concrete_methods != NULL, "invariant");
2901 
2902   assert(NULL == _methods, "invariant");
2903 
2904   cfs->guarantee_more(2, CHECK);  // length
2905   const u2 length = cfs->get_u2_fast();
2906   if (length == 0) {
2907     _methods = Universe::the_empty_method_array();
2908   } else {
2909     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2910                                                    length,
2911                                                    NULL,
2912                                                    CHECK);
2913 
2914     for (int index = 0; index < length; index++) {
2915       Method* method = parse_method(cfs,
2916                                     is_interface,
2917                                     _cp,
2918                                     promoted_flags,
2919                                     CHECK);
2920 
2921       if (method->is_final()) {
2922         *has_final_method = true;
2923       }
2924       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2925       // used for interface initialization, and default method inheritance analysis
2926       if (is_interface && !(*declares_nonstatic_concrete_methods)
2927         && !method->is_abstract() && !method->is_static()) {
2928         *declares_nonstatic_concrete_methods = true;
2929       }
2930       _methods->at_put(index, method);
2931     }
2932 
2933     if (_need_verify && length > 1) {
2934       // Check duplicated methods
2935       ResourceMark rm(THREAD);
2936       NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
2937         THREAD, NameSigHash*, HASH_ROW_SIZE);
2938       initialize_hashtable(names_and_sigs);
2939       bool dup = false;
2940       const Symbol* name = NULL;
2941       const Symbol* sig = NULL;
2942       {
2943         debug_only(NoSafepointVerifier nsv;)
2944         for (int i = 0; i < length; i++) {
2945           const Method* const m = _methods->at(i);
2946           name = m->name();
2947           sig = m->signature();
2948           // If no duplicates, add name/signature in hashtable names_and_sigs.
2949           if (!put_after_lookup(name, sig, names_and_sigs)) {
2950             dup = true;
2951             break;
2952           }
2953         }
2954       }
2955       if (dup) {
2956         classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
2957                                name->as_C_string(), sig->as_klass_external_name(), CHECK);
2958       }
2959     }
2960   }
2961 }
2962 
2963 static const intArray* sort_methods(Array<Method*>* methods) {
2964   const int length = methods->length();
2965   // If JVMTI original method ordering or sharing is enabled we have to
2966   // remember the original class file ordering.
2967   // We temporarily use the vtable_index field in the Method* to store the
2968   // class file index, so we can read in after calling qsort.
2969   // Put the method ordering in the shared archive.
2970   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
2971     for (int index = 0; index < length; index++) {
2972       Method* const m = methods->at(index);
2973       assert(!m->valid_vtable_index(), "vtable index should not be set");
2974       m->set_vtable_index(index);
2975     }
2976   }
2977   // Sort method array by ascending method name (for faster lookups & vtable construction)
2978   // Note that the ordering is not alphabetical, see Symbol::fast_compare
2979   Method::sort_methods(methods);
2980 
2981   intArray* method_ordering = NULL;
2982   // If JVMTI original method ordering or sharing is enabled construct int
2983   // array remembering the original ordering
2984   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
2985     method_ordering = new intArray(length, length, -1);
2986     for (int index = 0; index < length; index++) {
2987       Method* const m = methods->at(index);
2988       const int old_index = m->vtable_index();
2989       assert(old_index >= 0 && old_index < length, "invalid method index");
2990       method_ordering->at_put(index, old_index);
2991       m->set_vtable_index(Method::invalid_vtable_index);
2992     }
2993   }
2994   return method_ordering;
2995 }
2996 
2997 // Parse generic_signature attribute for methods and fields
2998 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs,
2999                                                       TRAPS) {
3000   assert(cfs != NULL, "invariant");
3001 
3002   cfs->guarantee_more(2, CHECK_0);  // generic_signature_index
3003   const u2 generic_signature_index = cfs->get_u2_fast();
3004   check_property(
3005     valid_symbol_at(generic_signature_index),
3006     "Invalid Signature attribute at constant pool index %u in class file %s",
3007     generic_signature_index, CHECK_0);
3008   return generic_signature_index;
3009 }
3010 
3011 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs,
3012                                                            TRAPS) {
3013 
3014   assert(cfs != NULL, "invariant");
3015 
3016   cfs->guarantee_more(2, CHECK);  // sourcefile_index
3017   const u2 sourcefile_index = cfs->get_u2_fast();
3018   check_property(
3019     valid_symbol_at(sourcefile_index),
3020     "Invalid SourceFile attribute at constant pool index %u in class file %s",
3021     sourcefile_index, CHECK);
3022   set_class_sourcefile_index(sourcefile_index);
3023 }
3024 
3025 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
3026                                                                        int length,
3027                                                                        TRAPS) {
3028   assert(cfs != NULL, "invariant");
3029 
3030   const u1* const sde_buffer = cfs->current();
3031   assert(sde_buffer != NULL, "null sde buffer");
3032 
3033   // Don't bother storing it if there is no way to retrieve it
3034   if (JvmtiExport::can_get_source_debug_extension()) {
3035     assert((length+1) > length, "Overflow checking");
3036     u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
3037     for (int i = 0; i < length; i++) {
3038       sde[i] = sde_buffer[i];
3039     }
3040     sde[length] = '\0';
3041     set_class_sde_buffer((const char*)sde, length);
3042   }
3043   // Got utf8 string, set stream position forward
3044   cfs->skip_u1(length, CHECK);
3045 }
3046 
3047 
3048 // Inner classes can be static, private or protected (classic VM does this)
3049 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \
3050                                            JVM_ACC_PRIVATE |                \
3051                                            JVM_ACC_PROTECTED |              \
3052                                            JVM_ACC_STATIC                   \
3053                                          )
3054 
3055 // Return number of classes in the inner classes attribute table
3056 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
3057                                                             const u1* const inner_classes_attribute_start,
3058                                                             bool parsed_enclosingmethod_attribute,
3059                                                             u2 enclosing_method_class_index,
3060                                                             u2 enclosing_method_method_index,
3061                                                             TRAPS) {
3062   const u1* const current_mark = cfs->current();
3063   u2 length = 0;
3064   if (inner_classes_attribute_start != NULL) {
3065     cfs->set_current(inner_classes_attribute_start);
3066     cfs->guarantee_more(2, CHECK_0);  // length
3067     length = cfs->get_u2_fast();
3068   }
3069 
3070   // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
3071   // method data:
3072   //   [inner_class_info_index,
3073   //    outer_class_info_index,
3074   //    inner_name_index,
3075   //    inner_class_access_flags,
3076   //    ...
3077   //    enclosing_method_class_index,
3078   //    enclosing_method_method_index]
3079   const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
3080   Array<u2>* const inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3081   _inner_classes = inner_classes;
3082 
3083   int index = 0;
3084   const int cp_size = _cp->length();
3085   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
3086   for (int n = 0; n < length; n++) {
3087     // Inner class index
3088     const u2 inner_class_info_index = cfs->get_u2_fast();
3089     check_property(
3090       valid_klass_reference_at(inner_class_info_index),
3091       "inner_class_info_index %u has bad constant type in class file %s",
3092       inner_class_info_index, CHECK_0);
3093     // Outer class index
3094     const u2 outer_class_info_index = cfs->get_u2_fast();
3095     check_property(
3096       outer_class_info_index == 0 ||
3097         valid_klass_reference_at(outer_class_info_index),
3098       "outer_class_info_index %u has bad constant type in class file %s",
3099       outer_class_info_index, CHECK_0);
3100     // Inner class name
3101     const u2 inner_name_index = cfs->get_u2_fast();
3102     check_property(
3103       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3104       "inner_name_index %u has bad constant type in class file %s",
3105       inner_name_index, CHECK_0);
3106     if (_need_verify) {
3107       guarantee_property(inner_class_info_index != outer_class_info_index,
3108                          "Class is both outer and inner class in class file %s", CHECK_0);
3109     }
3110     // Access flags
3111     jint flags;
3112     // JVM_ACC_MODULE is defined in JDK-9 and later.
3113     if (_major_version >= JAVA_9_VERSION) {
3114       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3115     } else {
3116       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3117     }
3118     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3119       // Set abstract bit for old class files for backward compatibility
3120       flags |= JVM_ACC_ABSTRACT;
3121     }
3122     verify_legal_class_modifiers(flags, CHECK_0);
3123     AccessFlags inner_access_flags(flags);
3124 
3125     inner_classes->at_put(index++, inner_class_info_index);
3126     inner_classes->at_put(index++, outer_class_info_index);
3127     inner_classes->at_put(index++, inner_name_index);
3128     inner_classes->at_put(index++, inner_access_flags.as_short());
3129   }
3130 
3131   // 4347400: make sure there's no duplicate entry in the classes array
3132   if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
3133     for(int i = 0; i < length * 4; i += 4) {
3134       for(int j = i + 4; j < length * 4; j += 4) {
3135         guarantee_property((inner_classes->at(i)   != inner_classes->at(j) ||
3136                             inner_classes->at(i+1) != inner_classes->at(j+1) ||
3137                             inner_classes->at(i+2) != inner_classes->at(j+2) ||
3138                             inner_classes->at(i+3) != inner_classes->at(j+3)),
3139                             "Duplicate entry in InnerClasses in class file %s",
3140                             CHECK_0);
3141       }
3142     }
3143   }
3144 
3145   // Set EnclosingMethod class and method indexes.
3146   if (parsed_enclosingmethod_attribute) {
3147     inner_classes->at_put(index++, enclosing_method_class_index);
3148     inner_classes->at_put(index++, enclosing_method_method_index);
3149   }
3150   assert(index == size, "wrong size");
3151 
3152   // Restore buffer's current position.
3153   cfs->set_current(current_mark);
3154 
3155   return length;
3156 }
3157 
3158 void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
3159   set_class_synthetic_flag(true);
3160 }
3161 
3162 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3163   assert(cfs != NULL, "invariant");
3164 
3165   const u2 signature_index = cfs->get_u2(CHECK);
3166   check_property(
3167     valid_symbol_at(signature_index),
3168     "Invalid constant pool index %u in Signature attribute in class file %s",
3169     signature_index, CHECK);
3170   set_class_generic_signature_index(signature_index);
3171 }
3172 
3173 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3174                                                                   ConstantPool* cp,
3175                                                                   u4 attribute_byte_length,
3176                                                                   TRAPS) {
3177   assert(cfs != NULL, "invariant");
3178   assert(cp != NULL, "invariant");
3179 
3180   const u1* const current_start = cfs->current();
3181 
3182   guarantee_property(attribute_byte_length >= sizeof(u2),
3183                      "Invalid BootstrapMethods attribute length %u in class file %s",
3184                      attribute_byte_length,
3185                      CHECK);
3186 
3187   cfs->guarantee_more(attribute_byte_length, CHECK);
3188 
3189   const int attribute_array_length = cfs->get_u2_fast();
3190 
3191   guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
3192                      "Short length on BootstrapMethods in class file %s",
3193                      CHECK);
3194 
3195 
3196   // The attribute contains a counted array of counted tuples of shorts,
3197   // represending bootstrap specifiers:
3198   //    length*{bootstrap_method_index, argument_count*{argument_index}}
3199   const int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3200   // operand_count = number of shorts in attr, except for leading length
3201 
3202   // The attribute is copied into a short[] array.
3203   // The array begins with a series of short[2] pairs, one for each tuple.
3204   const int index_size = (attribute_array_length * 2);
3205 
3206   Array<u2>* const operands =
3207     MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
3208 
3209   // Eagerly assign operands so they will be deallocated with the constant
3210   // pool if there is an error.
3211   cp->set_operands(operands);
3212 
3213   int operand_fill_index = index_size;
3214   const int cp_size = cp->length();
3215 
3216   for (int n = 0; n < attribute_array_length; n++) {
3217     // Store a 32-bit offset into the header of the operand array.
3218     ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
3219 
3220     // Read a bootstrap specifier.
3221     cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
3222     const u2 bootstrap_method_index = cfs->get_u2_fast();
3223     const u2 argument_count = cfs->get_u2_fast();
3224     check_property(
3225       valid_cp_range(bootstrap_method_index, cp_size) &&
3226       cp->tag_at(bootstrap_method_index).is_method_handle(),
3227       "bootstrap_method_index %u has bad constant type in class file %s",
3228       bootstrap_method_index,
3229       CHECK);
3230 
3231     guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
3232       "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
3233       CHECK);
3234 
3235     operands->at_put(operand_fill_index++, bootstrap_method_index);
3236     operands->at_put(operand_fill_index++, argument_count);
3237 
3238     cfs->guarantee_more(sizeof(u2) * argument_count, CHECK);  // argv[argc]
3239     for (int j = 0; j < argument_count; j++) {
3240       const u2 argument_index = cfs->get_u2_fast();
3241       check_property(
3242         valid_cp_range(argument_index, cp_size) &&
3243         cp->tag_at(argument_index).is_loadable_constant(),
3244         "argument_index %u has bad constant type in class file %s",
3245         argument_index,
3246         CHECK);
3247       operands->at_put(operand_fill_index++, argument_index);
3248     }
3249   }
3250   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3251                      "Bad length on BootstrapMethods in class file %s",
3252                      CHECK);
3253 }
3254 
3255 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3256                                                  ConstantPool* cp,
3257                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3258                                                  TRAPS) {
3259   assert(cfs != NULL, "invariant");
3260   assert(cp != NULL, "invariant");
3261   assert(parsed_annotations != NULL, "invariant");
3262 
3263   // Set inner classes attribute to default sentinel
3264   _inner_classes = Universe::the_empty_short_array();
3265   cfs->guarantee_more(2, CHECK);  // attributes_count
3266   u2 attributes_count = cfs->get_u2_fast();
3267   bool parsed_sourcefile_attribute = false;
3268   bool parsed_innerclasses_attribute = false;
3269   bool parsed_enclosingmethod_attribute = false;
3270   bool parsed_bootstrap_methods_attribute = false;
3271   const u1* runtime_visible_annotations = NULL;
3272   int runtime_visible_annotations_length = 0;
3273   const u1* runtime_invisible_annotations = NULL;
3274   int runtime_invisible_annotations_length = 0;
3275   const u1* runtime_visible_type_annotations = NULL;
3276   int runtime_visible_type_annotations_length = 0;
3277   const u1* runtime_invisible_type_annotations = NULL;
3278   int runtime_invisible_type_annotations_length = 0;
3279   bool runtime_invisible_type_annotations_exists = false;
3280   bool runtime_invisible_annotations_exists = false;
3281   bool parsed_source_debug_ext_annotations_exist = false;
3282   const u1* inner_classes_attribute_start = NULL;
3283   u4  inner_classes_attribute_length = 0;
3284   u2  enclosing_method_class_index = 0;
3285   u2  enclosing_method_method_index = 0;
3286   // Iterate over attributes
3287   while (attributes_count--) {
3288     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3289     const u2 attribute_name_index = cfs->get_u2_fast();
3290     const u4 attribute_length = cfs->get_u4_fast();
3291     check_property(
3292       valid_symbol_at(attribute_name_index),
3293       "Attribute name has bad constant pool index %u in class file %s",
3294       attribute_name_index, CHECK);
3295     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3296     if (tag == vmSymbols::tag_source_file()) {
3297       // Check for SourceFile tag
3298       if (_need_verify) {
3299         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3300       }
3301       if (parsed_sourcefile_attribute) {
3302         classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
3303       } else {
3304         parsed_sourcefile_attribute = true;
3305       }
3306       parse_classfile_sourcefile_attribute(cfs, CHECK);
3307     } else if (tag == vmSymbols::tag_source_debug_extension()) {
3308       // Check for SourceDebugExtension tag
3309       if (parsed_source_debug_ext_annotations_exist) {
3310           classfile_parse_error(
3311             "Multiple SourceDebugExtension attributes in class file %s", CHECK);
3312       }
3313       parsed_source_debug_ext_annotations_exist = true;
3314       parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3315     } else if (tag == vmSymbols::tag_inner_classes()) {
3316       // Check for InnerClasses tag
3317       if (parsed_innerclasses_attribute) {
3318         classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
3319       } else {
3320         parsed_innerclasses_attribute = true;
3321       }
3322       inner_classes_attribute_start = cfs->current();
3323       inner_classes_attribute_length = attribute_length;
3324       cfs->skip_u1(inner_classes_attribute_length, CHECK);
3325     } else if (tag == vmSymbols::tag_synthetic()) {
3326       // Check for Synthetic tag
3327       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3328       if (attribute_length != 0) {
3329         classfile_parse_error(
3330           "Invalid Synthetic classfile attribute length %u in class file %s",
3331           attribute_length, CHECK);
3332       }
3333       parse_classfile_synthetic_attribute(CHECK);
3334     } else if (tag == vmSymbols::tag_deprecated()) {
3335       // Check for Deprecatd tag - 4276120
3336       if (attribute_length != 0) {
3337         classfile_parse_error(
3338           "Invalid Deprecated classfile attribute length %u in class file %s",
3339           attribute_length, CHECK);
3340       }
3341     } else if (_major_version >= JAVA_1_5_VERSION) {
3342       if (tag == vmSymbols::tag_signature()) {
3343         if (_generic_signature_index != 0) {
3344           classfile_parse_error(
3345             "Multiple Signature attributes in class file %s", CHECK);
3346         }
3347         if (attribute_length != 2) {
3348           classfile_parse_error(
3349             "Wrong Signature attribute length %u in class file %s",
3350             attribute_length, CHECK);
3351         }
3352         parse_classfile_signature_attribute(cfs, CHECK);
3353       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3354         if (runtime_visible_annotations != NULL) {
3355           classfile_parse_error(
3356             "Multiple RuntimeVisibleAnnotations attributes in class file %s", CHECK);
3357         }
3358         runtime_visible_annotations_length = attribute_length;
3359         runtime_visible_annotations = cfs->current();
3360         assert(runtime_visible_annotations != NULL, "null visible annotations");
3361         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3362         parse_annotations(cp,
3363                           runtime_visible_annotations,
3364                           runtime_visible_annotations_length,
3365                           parsed_annotations,
3366                           _loader_data,
3367                           CHECK);
3368         cfs->skip_u1_fast(runtime_visible_annotations_length);
3369       } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3370         if (runtime_invisible_annotations_exists) {
3371           classfile_parse_error(
3372             "Multiple RuntimeInvisibleAnnotations attributes in class file %s", CHECK);
3373         }
3374         runtime_invisible_annotations_exists = true;
3375         if (PreserveAllAnnotations) {
3376           runtime_invisible_annotations_length = attribute_length;
3377           runtime_invisible_annotations = cfs->current();
3378           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
3379         }
3380         cfs->skip_u1(attribute_length, CHECK);
3381       } else if (tag == vmSymbols::tag_enclosing_method()) {
3382         if (parsed_enclosingmethod_attribute) {
3383           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
3384         } else {
3385           parsed_enclosingmethod_attribute = true;
3386         }
3387         guarantee_property(attribute_length == 4,
3388           "Wrong EnclosingMethod attribute length %u in class file %s",
3389           attribute_length, CHECK);
3390         cfs->guarantee_more(4, CHECK);  // class_index, method_index
3391         enclosing_method_class_index  = cfs->get_u2_fast();
3392         enclosing_method_method_index = cfs->get_u2_fast();
3393         if (enclosing_method_class_index == 0) {
3394           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
3395         }
3396         // Validate the constant pool indices and types
3397         check_property(valid_klass_reference_at(enclosing_method_class_index),
3398           "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3399         if (enclosing_method_method_index != 0 &&
3400             (!cp->is_within_bounds(enclosing_method_method_index) ||
3401              !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3402           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
3403         }
3404       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3405                  _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3406         if (parsed_bootstrap_methods_attribute) {
3407           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
3408         }
3409         parsed_bootstrap_methods_attribute = true;
3410         parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3411       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3412         if (runtime_visible_type_annotations != NULL) {
3413           classfile_parse_error(
3414             "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);
3415         }
3416         runtime_visible_type_annotations_length = attribute_length;
3417         runtime_visible_type_annotations = cfs->current();
3418         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
3419         // No need for the VM to parse Type annotations
3420         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3421       } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3422         if (runtime_invisible_type_annotations_exists) {
3423           classfile_parse_error(
3424             "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);
3425         } else {
3426           runtime_invisible_type_annotations_exists = true;
3427         }
3428         if (PreserveAllAnnotations) {
3429           runtime_invisible_type_annotations_length = attribute_length;
3430           runtime_invisible_type_annotations = cfs->current();
3431           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
3432         }
3433         cfs->skip_u1(attribute_length, CHECK);
3434       } else {
3435         // Unknown attribute
3436         cfs->skip_u1(attribute_length, CHECK);
3437       }
3438     } else {
3439       // Unknown attribute
3440       cfs->skip_u1(attribute_length, CHECK);
3441     }
3442   }
3443   _annotations = assemble_annotations(runtime_visible_annotations,
3444                                       runtime_visible_annotations_length,
3445                                       runtime_invisible_annotations,
3446                                       runtime_invisible_annotations_length,
3447                                       CHECK);
3448   _type_annotations = assemble_annotations(runtime_visible_type_annotations,
3449                                            runtime_visible_type_annotations_length,
3450                                            runtime_invisible_type_annotations,
3451                                            runtime_invisible_type_annotations_length,
3452                                            CHECK);
3453 
3454   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3455     const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3456                             cfs,
3457                             inner_classes_attribute_start,
3458                             parsed_innerclasses_attribute,
3459                             enclosing_method_class_index,
3460                             enclosing_method_method_index,
3461                             CHECK);
3462     if (parsed_innerclasses_attribute &&_need_verify && _major_version >= JAVA_1_5_VERSION) {
3463       guarantee_property(
3464         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3465         "Wrong InnerClasses attribute length in class file %s", CHECK);
3466     }
3467   }
3468 
3469   if (_max_bootstrap_specifier_index >= 0) {
3470     guarantee_property(parsed_bootstrap_methods_attribute,
3471                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3472   }
3473 }
3474 
3475 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3476   assert(k != NULL, "invariant");
3477 
3478   if (_synthetic_flag)
3479     k->set_is_synthetic();
3480   if (_sourcefile_index != 0) {
3481     k->set_source_file_name_index(_sourcefile_index);
3482   }
3483   if (_generic_signature_index != 0) {
3484     k->set_generic_signature_index(_generic_signature_index);
3485   }
3486   if (_sde_buffer != NULL) {
3487     k->set_source_debug_extension(_sde_buffer, _sde_length);
3488   }
3489 }
3490 
3491 // Create the Annotations object that will
3492 // hold the annotations array for the Klass.
3493 void ClassFileParser::create_combined_annotations(TRAPS) {
3494     if (_annotations == NULL &&
3495         _type_annotations == NULL &&
3496         _fields_annotations == NULL &&
3497         _fields_type_annotations == NULL) {
3498       // Don't create the Annotations object unnecessarily.
3499       return;
3500     }
3501 
3502     Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3503     annotations->set_class_annotations(_annotations);
3504     annotations->set_class_type_annotations(_type_annotations);
3505     annotations->set_fields_annotations(_fields_annotations);
3506     annotations->set_fields_type_annotations(_fields_type_annotations);
3507 
3508     // This is the Annotations object that will be
3509     // assigned to InstanceKlass being constructed.
3510     _combined_annotations = annotations;
3511 
3512     // The annotations arrays below has been transfered the
3513     // _combined_annotations so these fields can now be cleared.
3514     _annotations             = NULL;
3515     _type_annotations        = NULL;
3516     _fields_annotations      = NULL;
3517     _fields_type_annotations = NULL;
3518 }
3519 
3520 // Transfer ownership of metadata allocated to the InstanceKlass.
3521 void ClassFileParser::apply_parsed_class_metadata(
3522                                             InstanceKlass* this_klass,
3523                                             int java_fields_count, TRAPS) {
3524   assert(this_klass != NULL, "invariant");
3525 
3526   _cp->set_pool_holder(this_klass);
3527   this_klass->set_constants(_cp);
3528   this_klass->set_fields(_fields, java_fields_count);
3529   this_klass->set_methods(_methods);
3530   this_klass->set_inner_classes(_inner_classes);
3531   this_klass->set_local_interfaces(_local_interfaces);
3532   this_klass->set_transitive_interfaces(_transitive_interfaces);
3533   this_klass->set_annotations(_combined_annotations);
3534 
3535   // Clear out these fields so they don't get deallocated by the destructor
3536   clear_class_metadata();
3537 }
3538 
3539 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3540                                                        int runtime_visible_annotations_length,
3541                                                        const u1* const runtime_invisible_annotations,
3542                                                        int runtime_invisible_annotations_length,
3543                                                        TRAPS) {
3544   AnnotationArray* annotations = NULL;
3545   if (runtime_visible_annotations != NULL ||
3546       runtime_invisible_annotations != NULL) {
3547     annotations = MetadataFactory::new_array<u1>(_loader_data,
3548                                           runtime_visible_annotations_length +
3549                                           runtime_invisible_annotations_length,
3550                                           CHECK_(annotations));
3551     if (runtime_visible_annotations != NULL) {
3552       for (int i = 0; i < runtime_visible_annotations_length; i++) {
3553         annotations->at_put(i, runtime_visible_annotations[i]);
3554       }
3555     }
3556     if (runtime_invisible_annotations != NULL) {
3557       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3558         int append = runtime_visible_annotations_length+i;
3559         annotations->at_put(append, runtime_invisible_annotations[i]);
3560       }
3561     }
3562   }
3563   return annotations;
3564 }
3565 
3566 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3567                                                         const int super_class_index,
3568                                                         const bool need_verify,
3569                                                         TRAPS) {
3570   assert(cp != NULL, "invariant");
3571   const InstanceKlass* super_klass = NULL;
3572 
3573   if (super_class_index == 0) {
3574     check_property(_class_name == vmSymbols::java_lang_Object(),
3575                    "Invalid superclass index %u in class file %s",
3576                    super_class_index,
3577                    CHECK_NULL);
3578   } else {
3579     check_property(valid_klass_reference_at(super_class_index),
3580                    "Invalid superclass index %u in class file %s",
3581                    super_class_index,
3582                    CHECK_NULL);
3583     // The class name should be legal because it is checked when parsing constant pool.
3584     // However, make sure it is not an array type.
3585     bool is_array = false;
3586     if (cp->tag_at(super_class_index).is_klass()) {
3587       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3588       if (need_verify)
3589         is_array = super_klass->is_array_klass();
3590     } else if (need_verify) {
3591       is_array = (cp->klass_name_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
3592     }
3593     if (need_verify) {
3594       guarantee_property(!is_array,
3595                         "Bad superclass name in class file %s", CHECK_NULL);
3596     }
3597   }
3598   return super_klass;
3599 }
3600 
3601 static unsigned int compute_oop_map_count(const InstanceKlass* super,
3602                                           unsigned int nonstatic_oop_map_count,
3603                                           int first_nonstatic_oop_offset) {
3604 
3605   unsigned int map_count =
3606     NULL == super ? 0 : super->nonstatic_oop_map_count();
3607   if (nonstatic_oop_map_count > 0) {
3608     // We have oops to add to map
3609     if (map_count == 0) {
3610       map_count = nonstatic_oop_map_count;
3611     }
3612     else {
3613       // Check whether we should add a new map block or whether the last one can
3614       // be extended
3615       const OopMapBlock* const first_map = super->start_of_nonstatic_oop_maps();
3616       const OopMapBlock* const last_map = first_map + map_count - 1;
3617 
3618       const int next_offset = last_map->offset() + last_map->count() * heapOopSize;
3619       if (next_offset == first_nonstatic_oop_offset) {
3620         // There is no gap bettwen superklass's last oop field and first
3621         // local oop field, merge maps.
3622         nonstatic_oop_map_count -= 1;
3623       }
3624       else {
3625         // Superklass didn't end with a oop field, add extra maps
3626         assert(next_offset < first_nonstatic_oop_offset, "just checking");
3627       }
3628       map_count += nonstatic_oop_map_count;
3629     }
3630   }
3631   return map_count;
3632 }
3633 
3634 #ifndef PRODUCT
3635 static void print_field_layout(const Symbol* name,
3636                                Array<u2>* fields,
3637                                const constantPoolHandle& cp,
3638                                int instance_size,
3639                                int instance_fields_start,
3640                                int instance_fields_end,
3641                                int static_fields_end) {
3642 
3643   assert(name != NULL, "invariant");
3644 
3645   tty->print("%s: field layout\n", name->as_klass_external_name());
3646   tty->print("  @%3d %s\n", instance_fields_start, "--- instance fields start ---");
3647   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3648     if (!fs.access_flags().is_static()) {
3649       tty->print("  @%3d \"%s\" %s\n",
3650         fs.offset(),
3651         fs.name()->as_klass_external_name(),
3652         fs.signature()->as_klass_external_name());
3653     }
3654   }
3655   tty->print("  @%3d %s\n", instance_fields_end, "--- instance fields end ---");
3656   tty->print("  @%3d %s\n", instance_size * wordSize, "--- instance ends ---");
3657   tty->print("  @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");
3658   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3659     if (fs.access_flags().is_static()) {
3660       tty->print("  @%3d \"%s\" %s\n",
3661         fs.offset(),
3662         fs.name()->as_klass_external_name(),
3663         fs.signature()->as_klass_external_name());
3664     }
3665   }
3666   tty->print("  @%3d %s\n", static_fields_end, "--- static fields end ---");
3667   tty->print("\n");
3668 }
3669 #endif
3670 
3671 // Values needed for oopmap and InstanceKlass creation
3672 class ClassFileParser::FieldLayoutInfo : public ResourceObj {
3673  public:
3674   int*          nonstatic_oop_offsets;
3675   unsigned int* nonstatic_oop_counts;
3676   unsigned int  nonstatic_oop_map_count;
3677   unsigned int  total_oop_map_count;
3678   int           instance_size;
3679   int           nonstatic_field_size;
3680   int           static_field_size;
3681   bool          has_nonstatic_fields;
3682 };
3683 
3684 // Layout fields and fill in FieldLayoutInfo.  Could use more refactoring!
3685 void ClassFileParser::layout_fields(ConstantPool* cp,
3686                                     const FieldAllocationCount* fac,
3687                                     const ClassAnnotationCollector* parsed_annotations,
3688                                     FieldLayoutInfo* info,
3689                                     TRAPS) {
3690 
3691   assert(cp != NULL, "invariant");
3692 
3693   // Field size and offset computation
3694   int nonstatic_field_size = _super_klass == NULL ? 0 :
3695                                _super_klass->nonstatic_field_size();
3696 
3697   // Count the contended fields by type.
3698   //
3699   // We ignore static fields, because @Contended is not supported for them.
3700   // The layout code below will also ignore the static fields.
3701   int nonstatic_contended_count = 0;
3702   FieldAllocationCount fac_contended;
3703   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
3704     FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
3705     if (fs.is_contended()) {
3706       fac_contended.count[atype]++;
3707       if (!fs.access_flags().is_static()) {
3708         nonstatic_contended_count++;
3709       }
3710     }
3711   }
3712 
3713 
3714   // Calculate the starting byte offsets
3715   int next_static_oop_offset    = InstanceMirrorKlass::offset_of_static_fields();
3716   int next_static_double_offset = next_static_oop_offset +
3717                                       ((fac->count[STATIC_OOP]) * heapOopSize);
3718   if ( fac->count[STATIC_DOUBLE] &&
3719        (Universe::field_type_should_be_aligned(T_DOUBLE) ||
3720         Universe::field_type_should_be_aligned(T_LONG)) ) {
3721     next_static_double_offset = align_up(next_static_double_offset, BytesPerLong);
3722   }
3723 
3724   int next_static_word_offset   = next_static_double_offset +
3725                                     ((fac->count[STATIC_DOUBLE]) * BytesPerLong);
3726   int next_static_short_offset  = next_static_word_offset +
3727                                     ((fac->count[STATIC_WORD]) * BytesPerInt);
3728   int next_static_byte_offset   = next_static_short_offset +
3729                                   ((fac->count[STATIC_SHORT]) * BytesPerShort);
3730 
3731   int nonstatic_fields_start  = instanceOopDesc::base_offset_in_bytes() +
3732                                 nonstatic_field_size * heapOopSize;
3733 
3734   int next_nonstatic_field_offset = nonstatic_fields_start;
3735 
3736   const bool is_contended_class     = parsed_annotations->is_contended();
3737 
3738   // Class is contended, pad before all the fields
3739   if (is_contended_class) {
3740     next_nonstatic_field_offset += ContendedPaddingWidth;
3741   }
3742 
3743   // Compute the non-contended fields count.
3744   // The packing code below relies on these counts to determine if some field
3745   // can be squeezed into the alignment gap. Contended fields are obviously
3746   // exempt from that.
3747   unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
3748   unsigned int nonstatic_word_count   = fac->count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
3749   unsigned int nonstatic_short_count  = fac->count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
3750   unsigned int nonstatic_byte_count   = fac->count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
3751   unsigned int nonstatic_oop_count    = fac->count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];
3752 
3753   // Total non-static fields count, including every contended field
3754   unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +
3755                                         fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +
3756                                         fac->count[NONSTATIC_OOP];
3757 
3758   const bool super_has_nonstatic_fields =
3759           (_super_klass != NULL && _super_klass->has_nonstatic_fields());
3760   const bool has_nonstatic_fields =
3761     super_has_nonstatic_fields || (nonstatic_fields_count != 0);
3762 
3763 
3764   // Prepare list of oops for oop map generation.
3765   //
3766   // "offset" and "count" lists are describing the set of contiguous oop
3767   // regions. offset[i] is the start of the i-th region, which then has
3768   // count[i] oops following. Before we know how many regions are required,
3769   // we pessimistically allocate the maps to fit all the oops into the
3770   // distinct regions.
3771   //
3772   // TODO: We add +1 to always allocate non-zero resource arrays; we need
3773   // to figure out if we still need to do this.
3774   unsigned int nonstatic_oop_map_count = 0;
3775   unsigned int max_nonstatic_oop_maps  = fac->count[NONSTATIC_OOP] + 1;
3776 
3777   int* nonstatic_oop_offsets = NEW_RESOURCE_ARRAY_IN_THREAD(
3778             THREAD, int, max_nonstatic_oop_maps);
3779   unsigned int* const nonstatic_oop_counts  = NEW_RESOURCE_ARRAY_IN_THREAD(
3780             THREAD, unsigned int, max_nonstatic_oop_maps);
3781 
3782   int first_nonstatic_oop_offset = 0; // will be set for first oop field
3783 
3784   bool compact_fields   = CompactFields;
3785   int allocation_style = FieldsAllocationStyle;
3786   if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
3787     assert(false, "0 <= FieldsAllocationStyle <= 2");
3788     allocation_style = 1; // Optimistic
3789   }
3790 
3791   // The next classes have predefined hard-coded fields offsets
3792   // (see in JavaClasses::compute_hard_coded_offsets()).
3793   // Use default fields allocation order for them.
3794   if( (allocation_style != 0 || compact_fields ) && _loader_data->class_loader() == NULL &&
3795       (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
3796        _class_name == vmSymbols::java_lang_Class() ||
3797        _class_name == vmSymbols::java_lang_ClassLoader() ||
3798        _class_name == vmSymbols::java_lang_ref_Reference() ||
3799        _class_name == vmSymbols::java_lang_ref_SoftReference() ||
3800        _class_name == vmSymbols::java_lang_StackTraceElement() ||
3801        _class_name == vmSymbols::java_lang_String() ||
3802        _class_name == vmSymbols::java_lang_Throwable() ||
3803        _class_name == vmSymbols::java_lang_Boolean() ||
3804        _class_name == vmSymbols::java_lang_Character() ||
3805        _class_name == vmSymbols::java_lang_Float() ||
3806        _class_name == vmSymbols::java_lang_Double() ||
3807        _class_name == vmSymbols::java_lang_Byte() ||
3808        _class_name == vmSymbols::java_lang_Short() ||
3809        _class_name == vmSymbols::java_lang_Integer() ||
3810        _class_name == vmSymbols::java_lang_Long())) {
3811     allocation_style = 0;     // Allocate oops first
3812     compact_fields   = false; // Don't compact fields
3813   }
3814 
3815   int next_nonstatic_oop_offset = 0;
3816   int next_nonstatic_double_offset = 0;
3817 
3818   // Rearrange fields for a given allocation style
3819   if( allocation_style == 0 ) {
3820     // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
3821     next_nonstatic_oop_offset    = next_nonstatic_field_offset;
3822     next_nonstatic_double_offset = next_nonstatic_oop_offset +
3823                                     (nonstatic_oop_count * heapOopSize);
3824   } else if( allocation_style == 1 ) {
3825     // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
3826     next_nonstatic_double_offset = next_nonstatic_field_offset;
3827   } else if( allocation_style == 2 ) {
3828     // Fields allocation: oops fields in super and sub classes are together.
3829     if( nonstatic_field_size > 0 && _super_klass != NULL &&
3830         _super_klass->nonstatic_oop_map_size() > 0 ) {
3831       const unsigned int map_count = _super_klass->nonstatic_oop_map_count();
3832       const OopMapBlock* const first_map = _super_klass->start_of_nonstatic_oop_maps();
3833       const OopMapBlock* const last_map = first_map + map_count - 1;
3834       const int next_offset = last_map->offset() + (last_map->count() * heapOopSize);
3835       if (next_offset == next_nonstatic_field_offset) {
3836         allocation_style = 0;   // allocate oops first
3837         next_nonstatic_oop_offset    = next_nonstatic_field_offset;
3838         next_nonstatic_double_offset = next_nonstatic_oop_offset +
3839                                        (nonstatic_oop_count * heapOopSize);
3840       }
3841     }
3842     if( allocation_style == 2 ) {
3843       allocation_style = 1;     // allocate oops last
3844       next_nonstatic_double_offset = next_nonstatic_field_offset;
3845     }
3846   } else {
3847     ShouldNotReachHere();
3848   }
3849 
3850   int nonstatic_oop_space_count   = 0;
3851   int nonstatic_word_space_count  = 0;
3852   int nonstatic_short_space_count = 0;
3853   int nonstatic_byte_space_count  = 0;
3854   int nonstatic_oop_space_offset = 0;
3855   int nonstatic_word_space_offset = 0;
3856   int nonstatic_short_space_offset = 0;
3857   int nonstatic_byte_space_offset = 0;
3858 
3859   // Try to squeeze some of the fields into the gaps due to
3860   // long/double alignment.
3861   if (nonstatic_double_count > 0) {
3862     int offset = next_nonstatic_double_offset;
3863     next_nonstatic_double_offset = align_up(offset, BytesPerLong);
3864     if (compact_fields && offset != next_nonstatic_double_offset) {
3865       // Allocate available fields into the gap before double field.
3866       int length = next_nonstatic_double_offset - offset;
3867       assert(length == BytesPerInt, "");
3868       nonstatic_word_space_offset = offset;
3869       if (nonstatic_word_count > 0) {
3870         nonstatic_word_count      -= 1;
3871         nonstatic_word_space_count = 1; // Only one will fit
3872         length -= BytesPerInt;
3873         offset += BytesPerInt;
3874       }
3875       nonstatic_short_space_offset = offset;
3876       while (length >= BytesPerShort && nonstatic_short_count > 0) {
3877         nonstatic_short_count       -= 1;
3878         nonstatic_short_space_count += 1;
3879         length -= BytesPerShort;
3880         offset += BytesPerShort;
3881       }
3882       nonstatic_byte_space_offset = offset;
3883       while (length > 0 && nonstatic_byte_count > 0) {
3884         nonstatic_byte_count       -= 1;
3885         nonstatic_byte_space_count += 1;
3886         length -= 1;
3887       }
3888       // Allocate oop field in the gap if there are no other fields for that.
3889       nonstatic_oop_space_offset = offset;
3890       if (length >= heapOopSize && nonstatic_oop_count > 0 &&
3891           allocation_style != 0) { // when oop fields not first
3892         nonstatic_oop_count      -= 1;
3893         nonstatic_oop_space_count = 1; // Only one will fit
3894         length -= heapOopSize;
3895         offset += heapOopSize;
3896       }
3897     }
3898   }
3899 
3900   int next_nonstatic_word_offset = next_nonstatic_double_offset +
3901                                      (nonstatic_double_count * BytesPerLong);
3902   int next_nonstatic_short_offset = next_nonstatic_word_offset +
3903                                       (nonstatic_word_count * BytesPerInt);
3904   int next_nonstatic_byte_offset = next_nonstatic_short_offset +
3905                                      (nonstatic_short_count * BytesPerShort);
3906   int next_nonstatic_padded_offset = next_nonstatic_byte_offset +
3907                                        nonstatic_byte_count;
3908 
3909   // let oops jump before padding with this allocation style
3910   if( allocation_style == 1 ) {
3911     next_nonstatic_oop_offset = next_nonstatic_padded_offset;
3912     if( nonstatic_oop_count > 0 ) {
3913       next_nonstatic_oop_offset = align_up(next_nonstatic_oop_offset, heapOopSize);
3914     }
3915     next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
3916   }
3917 
3918   // Iterate over fields again and compute correct offsets.
3919   // The field allocation type was temporarily stored in the offset slot.
3920   // oop fields are located before non-oop fields (static and non-static).
3921   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
3922 
3923     // skip already laid out fields
3924     if (fs.is_offset_set()) continue;
3925 
3926     // contended instance fields are handled below
3927     if (fs.is_contended() && !fs.access_flags().is_static()) continue;
3928 
3929     int real_offset = 0;
3930     const FieldAllocationType atype = (const FieldAllocationType) fs.allocation_type();
3931 
3932     // pack the rest of the fields
3933     switch (atype) {
3934       case STATIC_OOP:
3935         real_offset = next_static_oop_offset;
3936         next_static_oop_offset += heapOopSize;
3937         break;
3938       case STATIC_BYTE:
3939         real_offset = next_static_byte_offset;
3940         next_static_byte_offset += 1;
3941         break;
3942       case STATIC_SHORT:
3943         real_offset = next_static_short_offset;
3944         next_static_short_offset += BytesPerShort;
3945         break;
3946       case STATIC_WORD:
3947         real_offset = next_static_word_offset;
3948         next_static_word_offset += BytesPerInt;
3949         break;
3950       case STATIC_DOUBLE:
3951         real_offset = next_static_double_offset;
3952         next_static_double_offset += BytesPerLong;
3953         break;
3954       case NONSTATIC_OOP:
3955         if( nonstatic_oop_space_count > 0 ) {
3956           real_offset = nonstatic_oop_space_offset;
3957           nonstatic_oop_space_offset += heapOopSize;
3958           nonstatic_oop_space_count  -= 1;
3959         } else {
3960           real_offset = next_nonstatic_oop_offset;
3961           next_nonstatic_oop_offset += heapOopSize;
3962         }
3963 
3964         // Record this oop in the oop maps
3965         if( nonstatic_oop_map_count > 0 &&
3966             nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
3967             real_offset -
3968             int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
3969             heapOopSize ) {
3970           // This oop is adjacent to the previous one, add to current oop map
3971           assert(nonstatic_oop_map_count - 1 < max_nonstatic_oop_maps, "range check");
3972           nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
3973         } else {
3974           // This oop is not adjacent to the previous one, create new oop map
3975           assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");
3976           nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
3977           nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
3978           nonstatic_oop_map_count += 1;
3979           if( first_nonstatic_oop_offset == 0 ) { // Undefined
3980             first_nonstatic_oop_offset = real_offset;
3981           }
3982         }
3983         break;
3984       case NONSTATIC_BYTE:
3985         if( nonstatic_byte_space_count > 0 ) {
3986           real_offset = nonstatic_byte_space_offset;
3987           nonstatic_byte_space_offset += 1;
3988           nonstatic_byte_space_count  -= 1;
3989         } else {
3990           real_offset = next_nonstatic_byte_offset;
3991           next_nonstatic_byte_offset += 1;
3992         }
3993         break;
3994       case NONSTATIC_SHORT:
3995         if( nonstatic_short_space_count > 0 ) {
3996           real_offset = nonstatic_short_space_offset;
3997           nonstatic_short_space_offset += BytesPerShort;
3998           nonstatic_short_space_count  -= 1;
3999         } else {
4000           real_offset = next_nonstatic_short_offset;
4001           next_nonstatic_short_offset += BytesPerShort;
4002         }
4003         break;
4004       case NONSTATIC_WORD:
4005         if( nonstatic_word_space_count > 0 ) {
4006           real_offset = nonstatic_word_space_offset;
4007           nonstatic_word_space_offset += BytesPerInt;
4008           nonstatic_word_space_count  -= 1;
4009         } else {
4010           real_offset = next_nonstatic_word_offset;
4011           next_nonstatic_word_offset += BytesPerInt;
4012         }
4013         break;
4014       case NONSTATIC_DOUBLE:
4015         real_offset = next_nonstatic_double_offset;
4016         next_nonstatic_double_offset += BytesPerLong;
4017         break;
4018       default:
4019         ShouldNotReachHere();
4020     }
4021     fs.set_offset(real_offset);
4022   }
4023 
4024 
4025   // Handle the contended cases.
4026   //
4027   // Each contended field should not intersect the cache line with another contended field.
4028   // In the absence of alignment information, we end up with pessimistically separating
4029   // the fields with full-width padding.
4030   //
4031   // Additionally, this should not break alignment for the fields, so we round the alignment up
4032   // for each field.
4033   if (nonstatic_contended_count > 0) {
4034 
4035     // if there is at least one contended field, we need to have pre-padding for them
4036     next_nonstatic_padded_offset += ContendedPaddingWidth;
4037 
4038     // collect all contended groups
4039     ResourceBitMap bm(cp->size());
4040     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4041       // skip already laid out fields
4042       if (fs.is_offset_set()) continue;
4043 
4044       if (fs.is_contended()) {
4045         bm.set_bit(fs.contended_group());
4046       }
4047     }
4048 
4049     int current_group = -1;
4050     while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
4051 
4052       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4053 
4054         // skip already laid out fields
4055         if (fs.is_offset_set()) continue;
4056 
4057         // skip non-contended fields and fields from different group
4058         if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
4059 
4060         // handle statics below
4061         if (fs.access_flags().is_static()) continue;
4062 
4063         int real_offset = 0;
4064         FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
4065 
4066         switch (atype) {
4067           case NONSTATIC_BYTE:
4068             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, 1);
4069             real_offset = next_nonstatic_padded_offset;
4070             next_nonstatic_padded_offset += 1;
4071             break;
4072 
4073           case NONSTATIC_SHORT:
4074             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerShort);
4075             real_offset = next_nonstatic_padded_offset;
4076             next_nonstatic_padded_offset += BytesPerShort;
4077             break;
4078 
4079           case NONSTATIC_WORD:
4080             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerInt);
4081             real_offset = next_nonstatic_padded_offset;
4082             next_nonstatic_padded_offset += BytesPerInt;
4083             break;
4084 
4085           case NONSTATIC_DOUBLE:
4086             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4087             real_offset = next_nonstatic_padded_offset;
4088             next_nonstatic_padded_offset += BytesPerLong;
4089             break;
4090 
4091           case NONSTATIC_OOP:
4092             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, heapOopSize);
4093             real_offset = next_nonstatic_padded_offset;
4094             next_nonstatic_padded_offset += heapOopSize;
4095 
4096             // Record this oop in the oop maps
4097             if( nonstatic_oop_map_count > 0 &&
4098                 nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
4099                 real_offset -
4100                 int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
4101                 heapOopSize ) {
4102               // This oop is adjacent to the previous one, add to current oop map
4103               assert(nonstatic_oop_map_count - 1 < max_nonstatic_oop_maps, "range check");
4104               nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
4105             } else {
4106               // This oop is not adjacent to the previous one, create new oop map
4107               assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");
4108               nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
4109               nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
4110               nonstatic_oop_map_count += 1;
4111               if( first_nonstatic_oop_offset == 0 ) { // Undefined
4112                 first_nonstatic_oop_offset = real_offset;
4113               }
4114             }
4115             break;
4116 
4117           default:
4118             ShouldNotReachHere();
4119         }
4120 
4121         if (fs.contended_group() == 0) {
4122           // Contended group defines the equivalence class over the fields:
4123           // the fields within the same contended group are not inter-padded.
4124           // The only exception is default group, which does not incur the
4125           // equivalence, and so requires intra-padding.
4126           next_nonstatic_padded_offset += ContendedPaddingWidth;
4127         }
4128 
4129         fs.set_offset(real_offset);
4130       } // for
4131 
4132       // Start laying out the next group.
4133       // Note that this will effectively pad the last group in the back;
4134       // this is expected to alleviate memory contention effects for
4135       // subclass fields and/or adjacent object.
4136       // If this was the default group, the padding is already in place.
4137       if (current_group != 0) {
4138         next_nonstatic_padded_offset += ContendedPaddingWidth;
4139       }
4140     }
4141 
4142     // handle static fields
4143   }
4144 
4145   // Entire class is contended, pad in the back.
4146   // This helps to alleviate memory contention effects for subclass fields
4147   // and/or adjacent object.
4148   if (is_contended_class) {
4149     next_nonstatic_padded_offset += ContendedPaddingWidth;
4150   }
4151 
4152   int notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;
4153 
4154   int nonstatic_fields_end      = align_up(notaligned_nonstatic_fields_end, heapOopSize);
4155   int instance_end              = align_up(notaligned_nonstatic_fields_end, wordSize);
4156   int static_fields_end         = align_up(next_static_byte_offset, wordSize);
4157 
4158   int static_field_size         = (static_fields_end -
4159                                    InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
4160   nonstatic_field_size          = nonstatic_field_size +
4161                                   (nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
4162 
4163   int instance_size             = align_object_size(instance_end / wordSize);
4164 
4165   assert(instance_size == align_object_size(align_up(
4166          (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize),
4167           wordSize) / wordSize), "consistent layout helper value");
4168 
4169   // Invariant: nonstatic_field end/start should only change if there are
4170   // nonstatic fields in the class, or if the class is contended. We compare
4171   // against the non-aligned value, so that end alignment will not fail the
4172   // assert without actually having the fields.
4173   assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
4174          is_contended_class ||
4175          (nonstatic_fields_count > 0), "double-check nonstatic start/end");
4176 
4177   // Number of non-static oop map blocks allocated at end of klass.
4178   const unsigned int total_oop_map_count =
4179     compute_oop_map_count(_super_klass, nonstatic_oop_map_count,
4180                           first_nonstatic_oop_offset);
4181 
4182 #ifndef PRODUCT
4183   if (PrintFieldLayout) {
4184     print_field_layout(_class_name,
4185           _fields,
4186           cp,
4187           instance_size,
4188           nonstatic_fields_start,
4189           nonstatic_fields_end,
4190           static_fields_end);
4191   }
4192 
4193 #endif
4194   // Pass back information needed for InstanceKlass creation
4195   info->nonstatic_oop_offsets = nonstatic_oop_offsets;
4196   info->nonstatic_oop_counts = nonstatic_oop_counts;
4197   info->nonstatic_oop_map_count = nonstatic_oop_map_count;
4198   info->total_oop_map_count = total_oop_map_count;
4199   info->instance_size = instance_size;
4200   info->static_field_size = static_field_size;
4201   info->nonstatic_field_size = nonstatic_field_size;
4202   info->has_nonstatic_fields = has_nonstatic_fields;
4203 }
4204 
4205 static void fill_oop_maps(const InstanceKlass* k,
4206                           unsigned int nonstatic_oop_map_count,
4207                           const int* nonstatic_oop_offsets,
4208                           const unsigned int* nonstatic_oop_counts) {
4209 
4210   assert(k != NULL, "invariant");
4211 
4212   OopMapBlock* this_oop_map = k->start_of_nonstatic_oop_maps();
4213   const InstanceKlass* const super = k->superklass();
4214   const unsigned int super_count = super ? super->nonstatic_oop_map_count() : 0;
4215   if (super_count > 0) {
4216     // Copy maps from superklass
4217     OopMapBlock* super_oop_map = super->start_of_nonstatic_oop_maps();
4218     for (unsigned int i = 0; i < super_count; ++i) {
4219       *this_oop_map++ = *super_oop_map++;
4220     }
4221   }
4222 
4223   if (nonstatic_oop_map_count > 0) {
4224     if (super_count + nonstatic_oop_map_count > k->nonstatic_oop_map_count()) {
4225       // The counts differ because there is no gap between superklass's last oop
4226       // field and the first local oop field.  Extend the last oop map copied
4227       // from the superklass instead of creating new one.
4228       nonstatic_oop_map_count--;
4229       nonstatic_oop_offsets++;
4230       this_oop_map--;
4231       this_oop_map->set_count(this_oop_map->count() + *nonstatic_oop_counts++);
4232       this_oop_map++;
4233     }
4234 
4235     // Add new map blocks, fill them
4236     while (nonstatic_oop_map_count-- > 0) {
4237       this_oop_map->set_offset(*nonstatic_oop_offsets++);
4238       this_oop_map->set_count(*nonstatic_oop_counts++);
4239       this_oop_map++;
4240     }
4241     assert(k->start_of_nonstatic_oop_maps() + k->nonstatic_oop_map_count() ==
4242            this_oop_map, "sanity");
4243   }
4244 }
4245 
4246 
4247 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4248   assert(ik != NULL, "invariant");
4249 
4250   const Klass* const super = ik->super();
4251 
4252   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4253   // in which case we don't have to register objects as finalizable
4254   if (!_has_empty_finalizer) {
4255     if (_has_finalizer ||
4256         (super != NULL && super->has_finalizer())) {
4257       ik->set_has_finalizer();
4258     }
4259   }
4260 
4261 #ifdef ASSERT
4262   bool f = false;
4263   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4264                                            vmSymbols::void_method_signature());
4265   if (m != NULL && !m->is_empty_method()) {
4266       f = true;
4267   }
4268 
4269   // Spec doesn't prevent agent from redefinition of empty finalizer.
4270   // Despite the fact that it's generally bad idea and redefined finalizer
4271   // will not work as expected we shouldn't abort vm in this case
4272   if (!ik->has_redefined_this_or_super()) {
4273     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4274   }
4275 #endif
4276 
4277   // Check if this klass supports the java.lang.Cloneable interface
4278   if (SystemDictionary::Cloneable_klass_loaded()) {
4279     if (ik->is_subtype_of(SystemDictionary::Cloneable_klass())) {
4280       ik->set_is_cloneable();
4281     }
4282   }
4283 
4284   // Check if this klass has a vanilla default constructor
4285   if (super == NULL) {
4286     // java.lang.Object has empty default constructor
4287     ik->set_has_vanilla_constructor();
4288   } else {
4289     if (super->has_vanilla_constructor() &&
4290         _has_vanilla_constructor) {
4291       ik->set_has_vanilla_constructor();
4292     }
4293 #ifdef ASSERT
4294     bool v = false;
4295     if (super->has_vanilla_constructor()) {
4296       const Method* const constructor =
4297         ik->find_method(vmSymbols::object_initializer_name(),
4298                        vmSymbols::void_method_signature());
4299       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4300         v = true;
4301       }
4302     }
4303     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4304 #endif
4305   }
4306 
4307   // If it cannot be fast-path allocated, set a bit in the layout helper.
4308   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4309   assert(ik->size_helper() > 0, "layout_helper is initialized");
4310   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4311       || ik->is_abstract() || ik->is_interface()
4312       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4313       || ik->size_helper() >= FastAllocateSizeLimit) {
4314     // Forbid fast-path allocation.
4315     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4316     ik->set_layout_helper(lh);
4317   }
4318 }
4319 
4320 // Attach super classes and interface classes to class loader data
4321 static void record_defined_class_dependencies(const InstanceKlass* defined_klass,
4322                                               TRAPS) {
4323   assert(defined_klass != NULL, "invariant");
4324 
4325   ClassLoaderData* const defining_loader_data = defined_klass->class_loader_data();
4326   if (defining_loader_data->is_the_null_class_loader_data()) {
4327       // Dependencies to null class loader data are implicit.
4328       return;
4329   } else {
4330     // add super class dependency
4331     Klass* const super = defined_klass->super();
4332     if (super != NULL) {
4333       defining_loader_data->record_dependency(super, CHECK);
4334     }
4335 
4336     // add super interface dependencies
4337     const Array<Klass*>* const local_interfaces = defined_klass->local_interfaces();
4338     if (local_interfaces != NULL) {
4339       const int length = local_interfaces->length();
4340       for (int i = 0; i < length; i++) {
4341         defining_loader_data->record_dependency(local_interfaces->at(i), CHECK);
4342       }
4343     }
4344   }
4345 }
4346 
4347 // utility methods for appending an array with check for duplicates
4348 
4349 static void append_interfaces(GrowableArray<Klass*>* result,
4350                               const Array<Klass*>* const ifs) {
4351   // iterate over new interfaces
4352   for (int i = 0; i < ifs->length(); i++) {
4353     Klass* const e = ifs->at(i);
4354     assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");
4355     // add new interface
4356     result->append_if_missing(e);
4357   }
4358 }
4359 
4360 static Array<Klass*>* compute_transitive_interfaces(const InstanceKlass* super,
4361                                                     Array<Klass*>* local_ifs,
4362                                                     ClassLoaderData* loader_data,
4363                                                     TRAPS) {
4364   assert(local_ifs != NULL, "invariant");
4365   assert(loader_data != NULL, "invariant");
4366 
4367   // Compute maximum size for transitive interfaces
4368   int max_transitive_size = 0;
4369   int super_size = 0;
4370   // Add superclass transitive interfaces size
4371   if (super != NULL) {
4372     super_size = super->transitive_interfaces()->length();
4373     max_transitive_size += super_size;
4374   }
4375   // Add local interfaces' super interfaces
4376   const int local_size = local_ifs->length();
4377   for (int i = 0; i < local_size; i++) {
4378     Klass* const l = local_ifs->at(i);
4379     max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();
4380   }
4381   // Finally add local interfaces
4382   max_transitive_size += local_size;
4383   // Construct array
4384   if (max_transitive_size == 0) {
4385     // no interfaces, use canonicalized array
4386     return Universe::the_empty_klass_array();
4387   } else if (max_transitive_size == super_size) {
4388     // no new local interfaces added, share superklass' transitive interface array
4389     return super->transitive_interfaces();
4390   } else if (max_transitive_size == local_size) {
4391     // only local interfaces added, share local interface array
4392     return local_ifs;
4393   } else {
4394     ResourceMark rm;
4395     GrowableArray<Klass*>* const result = new GrowableArray<Klass*>(max_transitive_size);
4396 
4397     // Copy down from superclass
4398     if (super != NULL) {
4399       append_interfaces(result, super->transitive_interfaces());
4400     }
4401 
4402     // Copy down from local interfaces' superinterfaces
4403     for (int i = 0; i < local_size; i++) {
4404       Klass* const l = local_ifs->at(i);
4405       append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());
4406     }
4407     // Finally add local interfaces
4408     append_interfaces(result, local_ifs);
4409 
4410     // length will be less than the max_transitive_size if duplicates were removed
4411     const int length = result->length();
4412     assert(length <= max_transitive_size, "just checking");
4413     Array<Klass*>* const new_result =
4414       MetadataFactory::new_array<Klass*>(loader_data, length, CHECK_NULL);
4415     for (int i = 0; i < length; i++) {
4416       Klass* const e = result->at(i);
4417       assert(e != NULL, "just checking");
4418       new_result->at_put(i, e);
4419     }
4420     return new_result;
4421   }
4422 }
4423 
4424 static void check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4425   assert(this_klass != NULL, "invariant");
4426   const Klass* const super = this_klass->super();
4427   if (super != NULL) {
4428 
4429     // If the loader is not the boot loader then throw an exception if its
4430     // superclass is in package jdk.internal.reflect and its loader is not a
4431     // special reflection class loader
4432     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4433       assert(super->is_instance_klass(), "super is not instance klass");
4434       PackageEntry* super_package = super->package();
4435       if (super_package != NULL &&
4436           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4437           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4438         ResourceMark rm(THREAD);
4439         Exceptions::fthrow(
4440           THREAD_AND_LOCATION,
4441           vmSymbols::java_lang_IllegalAccessError(),
4442           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4443           this_klass->external_name(),
4444           this_klass->class_loader_data()->loader_name(),
4445           super->external_name());
4446         return;
4447       }
4448     }
4449 
4450     Reflection::VerifyClassAccessResults vca_result =
4451       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4452     if (vca_result != Reflection::ACCESS_OK) {
4453       ResourceMark rm(THREAD);
4454       char* msg = Reflection::verify_class_access_msg(this_klass,
4455                                                       InstanceKlass::cast(super),
4456                                                       vca_result);
4457       if (msg == NULL) {
4458         Exceptions::fthrow(
4459           THREAD_AND_LOCATION,
4460           vmSymbols::java_lang_IllegalAccessError(),
4461           "class %s cannot access its superclass %s",
4462           this_klass->external_name(),
4463           super->external_name());
4464       } else {
4465         // Add additional message content.
4466         Exceptions::fthrow(
4467           THREAD_AND_LOCATION,
4468           vmSymbols::java_lang_IllegalAccessError(),
4469           "superclass access check failed: %s",
4470           msg);
4471       }
4472     }
4473   }
4474 }
4475 
4476 
4477 static void check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4478   assert(this_klass != NULL, "invariant");
4479   const Array<Klass*>* const local_interfaces = this_klass->local_interfaces();
4480   const int lng = local_interfaces->length();
4481   for (int i = lng - 1; i >= 0; i--) {
4482     Klass* const k = local_interfaces->at(i);
4483     assert (k != NULL && k->is_interface(), "invalid interface");
4484     Reflection::VerifyClassAccessResults vca_result =
4485       Reflection::verify_class_access(this_klass, InstanceKlass::cast(k), false);
4486     if (vca_result != Reflection::ACCESS_OK) {
4487       ResourceMark rm(THREAD);
4488       char* msg = Reflection::verify_class_access_msg(this_klass,
4489                                                       InstanceKlass::cast(k),
4490                                                       vca_result);
4491       if (msg == NULL) {
4492         Exceptions::fthrow(
4493           THREAD_AND_LOCATION,
4494           vmSymbols::java_lang_IllegalAccessError(),
4495           "class %s cannot access its superinterface %s",
4496           this_klass->external_name(),
4497           k->external_name());
4498       } else {
4499         // Add additional message content.
4500         Exceptions::fthrow(
4501           THREAD_AND_LOCATION,
4502           vmSymbols::java_lang_IllegalAccessError(),
4503           "superinterface check failed: %s",
4504           msg);
4505       }
4506     }
4507   }
4508 }
4509 
4510 
4511 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4512   assert(this_klass != NULL, "invariant");
4513   const Array<Method*>* const methods = this_klass->methods();
4514   const int num_methods = methods->length();
4515 
4516   // go thru each method and check if it overrides a final method
4517   for (int index = 0; index < num_methods; index++) {
4518     const Method* const m = methods->at(index);
4519 
4520     // skip private, static, and <init> methods
4521     if ((!m->is_private() && !m->is_static()) &&
4522         (m->name() != vmSymbols::object_initializer_name())) {
4523 
4524       const Symbol* const name = m->name();
4525       const Symbol* const signature = m->signature();
4526       const Klass* k = this_klass->super();
4527       const Method* super_m = NULL;
4528       while (k != NULL) {
4529         // skip supers that don't have final methods.
4530         if (k->has_final_method()) {
4531           // lookup a matching method in the super class hierarchy
4532           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4533           if (super_m == NULL) {
4534             break; // didn't find any match; get out
4535           }
4536 
4537           if (super_m->is_final() && !super_m->is_static() &&
4538               // matching method in super is final, and not static
4539               (Reflection::verify_field_access(this_klass,
4540                                                super_m->method_holder(),
4541                                                super_m->method_holder(),
4542                                                super_m->access_flags(), false))
4543             // this class can access super final method and therefore override
4544             ) {
4545             ResourceMark rm(THREAD);
4546             Exceptions::fthrow(
4547               THREAD_AND_LOCATION,
4548               vmSymbols::java_lang_VerifyError(),
4549               "class %s overrides final method %s.%s%s",
4550               this_klass->external_name(),
4551               super_m->method_holder()->external_name(),
4552               name->as_C_string(),
4553               signature->as_C_string()
4554             );
4555             return;
4556           }
4557 
4558           // continue to look from super_m's holder's super.
4559           k = super_m->method_holder()->super();
4560           continue;
4561         }
4562 
4563         k = k->super();
4564       }
4565     }
4566   }
4567 }
4568 
4569 
4570 // assumes that this_klass is an interface
4571 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4572   assert(this_klass != NULL, "invariant");
4573   assert(this_klass->is_interface(), "not an interface");
4574   const Array<Method*>* methods = this_klass->methods();
4575   const int num_methods = methods->length();
4576 
4577   for (int index = 0; index < num_methods; index++) {
4578     const Method* const m = methods->at(index);
4579     // if m is static and not the init method, throw a verify error
4580     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4581       ResourceMark rm(THREAD);
4582       Exceptions::fthrow(
4583         THREAD_AND_LOCATION,
4584         vmSymbols::java_lang_VerifyError(),
4585         "Illegal static method %s in interface %s",
4586         m->name()->as_C_string(),
4587         this_klass->external_name()
4588       );
4589       return;
4590     }
4591   }
4592 }
4593 
4594 // utility methods for format checking
4595 
4596 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4597   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4598   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4599   if (is_module) {
4600     ResourceMark rm(THREAD);
4601     Exceptions::fthrow(
4602       THREAD_AND_LOCATION,
4603       vmSymbols::java_lang_NoClassDefFoundError(),
4604       "%s is not a class because access_flag ACC_MODULE is set",
4605       _class_name->as_C_string());
4606     return;
4607   }
4608 
4609   if (!_need_verify) { return; }
4610 
4611   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4612   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4613   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4614   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4615   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4616   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4617   const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;
4618 
4619   if ((is_abstract && is_final) ||
4620       (is_interface && !is_abstract) ||
4621       (is_interface && major_gte_15 && (is_super || is_enum)) ||
4622       (!is_interface && major_gte_15 && is_annotation)) {
4623     ResourceMark rm(THREAD);
4624     Exceptions::fthrow(
4625       THREAD_AND_LOCATION,
4626       vmSymbols::java_lang_ClassFormatError(),
4627       "Illegal class modifiers in class %s: 0x%X",
4628       _class_name->as_C_string(), flags
4629     );
4630     return;
4631   }
4632 }
4633 
4634 static bool has_illegal_visibility(jint flags) {
4635   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4636   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4637   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4638 
4639   return ((is_public && is_protected) ||
4640           (is_public && is_private) ||
4641           (is_protected && is_private));
4642 }
4643 
4644 static bool is_supported_version(u2 major, u2 minor){
4645   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
4646   return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
4647          (major <= max_version) &&
4648          ((major != max_version) ||
4649           (minor <= JVM_CLASSFILE_MINOR_VERSION));
4650 }
4651 
4652 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4653                                                    bool is_interface,
4654                                                    TRAPS) const {
4655   if (!_need_verify) { return; }
4656 
4657   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4658   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4659   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4660   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4661   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4662   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4663   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4664   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4665   const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
4666 
4667   bool is_illegal = false;
4668 
4669   if (is_interface) {
4670     if (!is_public || !is_static || !is_final || is_private ||
4671         is_protected || is_volatile || is_transient ||
4672         (major_gte_15 && is_enum)) {
4673       is_illegal = true;
4674     }
4675   } else { // not interface
4676     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4677       is_illegal = true;
4678     }
4679   }
4680 
4681   if (is_illegal) {
4682     ResourceMark rm(THREAD);
4683     Exceptions::fthrow(
4684       THREAD_AND_LOCATION,
4685       vmSymbols::java_lang_ClassFormatError(),
4686       "Illegal field modifiers in class %s: 0x%X",
4687       _class_name->as_C_string(), flags);
4688     return;
4689   }
4690 }
4691 
4692 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4693                                                     bool is_interface,
4694                                                     const Symbol* name,
4695                                                     TRAPS) const {
4696   if (!_need_verify) { return; }
4697 
4698   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4699   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4700   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4701   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4702   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4703   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4704   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4705   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4706   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4707   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4708   const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
4709   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4710   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4711 
4712   bool is_illegal = false;
4713 
4714   if (is_interface) {
4715     if (major_gte_8) {
4716       // Class file version is JAVA_8_VERSION or later Methods of
4717       // interfaces may set any of the flags except ACC_PROTECTED,
4718       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4719       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4720       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4721           (is_native || is_protected || is_final || is_synchronized) ||
4722           // If a specific method of a class or interface has its
4723           // ACC_ABSTRACT flag set, it must not have any of its
4724           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4725           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4726           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4727           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4728           (is_abstract && (is_private || is_static || is_strict))) {
4729         is_illegal = true;
4730       }
4731     } else if (major_gte_15) {
4732       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4733       if (!is_public || is_private || is_protected || is_static || is_final ||
4734           is_synchronized || is_native || !is_abstract || is_strict) {
4735         is_illegal = true;
4736       }
4737     } else {
4738       // Class file version is pre-JAVA_1_5_VERSION
4739       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4740         is_illegal = true;
4741       }
4742     }
4743   } else { // not interface
4744     if (has_illegal_visibility(flags)) {
4745       is_illegal = true;
4746     } else {
4747       if (is_initializer) {
4748         if (is_static || is_final || is_synchronized || is_native ||
4749             is_abstract || (major_gte_15 && is_bridge)) {
4750           is_illegal = true;
4751         }
4752       } else { // not initializer
4753         if (is_abstract) {
4754           if ((is_final || is_native || is_private || is_static ||
4755               (major_gte_15 && (is_synchronized || is_strict)))) {
4756             is_illegal = true;
4757           }
4758         }
4759       }
4760     }
4761   }
4762 
4763   if (is_illegal) {
4764     ResourceMark rm(THREAD);
4765     Exceptions::fthrow(
4766       THREAD_AND_LOCATION,
4767       vmSymbols::java_lang_ClassFormatError(),
4768       "Method %s in class %s has illegal modifiers: 0x%X",
4769       name->as_C_string(), _class_name->as_C_string(), flags);
4770     return;
4771   }
4772 }
4773 
4774 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4775                                         int length,
4776                                         TRAPS) const {
4777   assert(_need_verify, "only called when _need_verify is true");
4778   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4779     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
4780   }
4781 }
4782 
4783 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4784 // In class names, '/' separates unqualified names.  This is verified in this function also.
4785 // Method names also may not contain the characters '<' or '>', unless <init>
4786 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4787 // method.  Because these names have been checked as special cases before
4788 // calling this method in verify_legal_method_name.
4789 //
4790 // This method is also called from the modular system APIs in modules.cpp
4791 // to verify the validity of module and package names.
4792 bool ClassFileParser::verify_unqualified_name(const char* name,
4793                                               unsigned int length,
4794                                               int type) {
4795   for (const char* p = name; p != name + length;) {
4796     jchar ch = *p;
4797     if (ch < 128) {
4798       if (ch == '.' || ch == ';' || ch == '[' ) {
4799         return false;   // do not permit '.', ';', or '['
4800       }
4801       if (ch == '/') {
4802         // check for '//' or leading or trailing '/' which are not legal
4803         // unqualified name must not be empty
4804         if (type == ClassFileParser::LegalClass) {
4805           if (p == name || p+1 >= name+length || *(p+1) == '/') {
4806            return false;
4807           }
4808         } else {
4809           return false;   // do not permit '/' unless it's class name
4810         }
4811       }
4812       if (type == ClassFileParser::LegalMethod && (ch == '<' || ch == '>')) {
4813         return false;   // do not permit '<' or '>' in method names
4814       }
4815       p++;
4816     } else {
4817       char* tmp_p = UTF8::next(p, &ch);
4818       p = tmp_p;
4819     }
4820   }
4821   return true;
4822 }
4823 
4824 // Take pointer to a string. Skip over the longest part of the string that could
4825 // be taken as a fieldname. Allow '/' if slash_ok is true.
4826 // Return a pointer to just past the fieldname.
4827 // Return NULL if no fieldname at all was found, or in the case of slash_ok
4828 // being true, we saw consecutive slashes (meaning we were looking for a
4829 // qualified path but found something that was badly-formed).
4830 static const char* skip_over_field_name(const char* name,
4831                                         bool slash_ok,
4832                                         unsigned int length) {
4833   const char* p;
4834   jboolean last_is_slash = false;
4835   jboolean not_first_ch = false;
4836 
4837   for (p = name; p != name + length; not_first_ch = true) {
4838     const char* old_p = p;
4839     jchar ch = *p;
4840     if (ch < 128) {
4841       p++;
4842       // quick check for ascii
4843       if ((ch >= 'a' && ch <= 'z') ||
4844         (ch >= 'A' && ch <= 'Z') ||
4845         (ch == '_' || ch == '$') ||
4846         (not_first_ch && ch >= '0' && ch <= '9')) {
4847         last_is_slash = false;
4848         continue;
4849       }
4850       if (slash_ok && ch == '/') {
4851         if (last_is_slash) {
4852           return NULL;  // Don't permit consecutive slashes
4853         }
4854         last_is_slash = true;
4855         continue;
4856       }
4857     }
4858     else {
4859       jint unicode_ch;
4860       char* tmp_p = UTF8::next_character(p, &unicode_ch);
4861       p = tmp_p;
4862       last_is_slash = false;
4863       // Check if ch is Java identifier start or is Java identifier part
4864       // 4672820: call java.lang.Character methods directly without generating separate tables.
4865       EXCEPTION_MARK;
4866 
4867       // return value
4868       JavaValue result(T_BOOLEAN);
4869       // Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart
4870       JavaCallArguments args;
4871       args.push_int(unicode_ch);
4872 
4873       // public static boolean isJavaIdentifierStart(char ch);
4874       JavaCalls::call_static(&result,
4875         SystemDictionary::Character_klass(),
4876         vmSymbols::isJavaIdentifierStart_name(),
4877         vmSymbols::int_bool_signature(),
4878         &args,
4879         THREAD);
4880 
4881       if (HAS_PENDING_EXCEPTION) {
4882         CLEAR_PENDING_EXCEPTION;
4883         return 0;
4884       }
4885       if (result.get_jboolean()) {
4886         continue;
4887       }
4888 
4889       if (not_first_ch) {
4890         // public static boolean isJavaIdentifierPart(char ch);
4891         JavaCalls::call_static(&result,
4892           SystemDictionary::Character_klass(),
4893           vmSymbols::isJavaIdentifierPart_name(),
4894           vmSymbols::int_bool_signature(),
4895           &args,
4896           THREAD);
4897 
4898         if (HAS_PENDING_EXCEPTION) {
4899           CLEAR_PENDING_EXCEPTION;
4900           return 0;
4901         }
4902 
4903         if (result.get_jboolean()) {
4904           continue;
4905         }
4906       }
4907     }
4908     return (not_first_ch) ? old_p : NULL;
4909   }
4910   return (not_first_ch) ? p : NULL;
4911 }
4912 
4913 // Take pointer to a string. Skip over the longest part of the string that could
4914 // be taken as a field signature. Allow "void" if void_ok.
4915 // Return a pointer to just past the signature.
4916 // Return NULL if no legal signature is found.
4917 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4918                                                        bool void_ok,
4919                                                        unsigned int length,
4920                                                        TRAPS) const {
4921   unsigned int array_dim = 0;
4922   while (length > 0) {
4923     switch (signature[0]) {
4924     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
4925     case JVM_SIGNATURE_BOOLEAN:
4926     case JVM_SIGNATURE_BYTE:
4927     case JVM_SIGNATURE_CHAR:
4928     case JVM_SIGNATURE_SHORT:
4929     case JVM_SIGNATURE_INT:
4930     case JVM_SIGNATURE_FLOAT:
4931     case JVM_SIGNATURE_LONG:
4932     case JVM_SIGNATURE_DOUBLE:
4933       return signature + 1;
4934     case JVM_SIGNATURE_CLASS: {
4935       if (_major_version < JAVA_1_5_VERSION) {
4936         // Skip over the class name if one is there
4937         const char* const p = skip_over_field_name(signature + 1, true, --length);
4938 
4939         // The next character better be a semicolon
4940         if (p && (p - signature) > 1 && p[0] == ';') {
4941           return p + 1;
4942         }
4943       }
4944       else {
4945         // Skip leading 'L' and ignore first appearance of ';'
4946         length--;
4947         signature++;
4948         char* c = strchr((char*) signature, ';');
4949         // Format check signature
4950         if (c != NULL) {
4951           ResourceMark rm(THREAD);
4952           int newlen = c - (char*) signature;
4953           char* sig = NEW_RESOURCE_ARRAY(char, newlen + 1);
4954           strncpy(sig, signature, newlen);
4955           sig[newlen] = '\0';
4956 
4957           bool legal = verify_unqualified_name(sig, newlen, LegalClass);
4958           if (!legal) {
4959             classfile_parse_error("Class name contains illegal character "
4960                                   "in descriptor in class file %s",
4961                                   CHECK_0);
4962             return NULL;
4963           }
4964           return signature + newlen + 1;
4965         }
4966       }
4967       return NULL;
4968     }
4969     case JVM_SIGNATURE_ARRAY:
4970       array_dim++;
4971       if (array_dim > 255) {
4972         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
4973         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
4974       }
4975       // The rest of what's there better be a legal signature
4976       signature++;
4977       length--;
4978       void_ok = false;
4979       break;
4980     default:
4981       return NULL;
4982     }
4983   }
4984   return NULL;
4985 }
4986 
4987 // Checks if name is a legal class name.
4988 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4989   if (!_need_verify || _relax_verify) { return; }
4990 
4991   char buf[fixed_buffer_size];
4992   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
4993   unsigned int length = name->utf8_length();
4994   bool legal = false;
4995 
4996   if (length > 0) {
4997     const char* p;
4998     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4999       p = skip_over_field_signature(bytes, false, length, CHECK);
5000       legal = (p != NULL) && ((p - bytes) == (int)length);
5001     } else if (_major_version < JAVA_1_5_VERSION) {
5002       if (bytes[0] != '<') {
5003         p = skip_over_field_name(bytes, true, length);
5004         legal = (p != NULL) && ((p - bytes) == (int)length);
5005       }
5006     } else {
5007       // 4900761: relax the constraints based on JSR202 spec
5008       // Class names may be drawn from the entire Unicode character set.
5009       // Identifiers between '/' must be unqualified names.
5010       // The utf8 string has been verified when parsing cpool entries.
5011       legal = verify_unqualified_name(bytes, length, LegalClass);
5012     }
5013   }
5014   if (!legal) {
5015     ResourceMark rm(THREAD);
5016     assert(_class_name != NULL, "invariant");
5017     Exceptions::fthrow(
5018       THREAD_AND_LOCATION,
5019       vmSymbols::java_lang_ClassFormatError(),
5020       "Illegal class name \"%s\" in class file %s", bytes,
5021       _class_name->as_C_string()
5022     );
5023     return;
5024   }
5025 }
5026 
5027 // Checks if name is a legal field name.
5028 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5029   if (!_need_verify || _relax_verify) { return; }
5030 
5031   char buf[fixed_buffer_size];
5032   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5033   unsigned int length = name->utf8_length();
5034   bool legal = false;
5035 
5036   if (length > 0) {
5037     if (_major_version < JAVA_1_5_VERSION) {
5038       if (bytes[0] != '<') {
5039         const char* p = skip_over_field_name(bytes, false, length);
5040         legal = (p != NULL) && ((p - bytes) == (int)length);
5041       }
5042     } else {
5043       // 4881221: relax the constraints based on JSR202 spec
5044       legal = verify_unqualified_name(bytes, length, LegalField);
5045     }
5046   }
5047 
5048   if (!legal) {
5049     ResourceMark rm(THREAD);
5050     assert(_class_name != NULL, "invariant");
5051     Exceptions::fthrow(
5052       THREAD_AND_LOCATION,
5053       vmSymbols::java_lang_ClassFormatError(),
5054       "Illegal field name \"%s\" in class %s", bytes,
5055       _class_name->as_C_string()
5056     );
5057     return;
5058   }
5059 }
5060 
5061 // Checks if name is a legal method name.
5062 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5063   if (!_need_verify || _relax_verify) { return; }
5064 
5065   assert(name != NULL, "method name is null");
5066   char buf[fixed_buffer_size];
5067   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5068   unsigned int length = name->utf8_length();
5069   bool legal = false;
5070 
5071   if (length > 0) {
5072     if (bytes[0] == '<') {
5073       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5074         legal = true;
5075       }
5076     } else if (_major_version < JAVA_1_5_VERSION) {
5077       const char* p;
5078       p = skip_over_field_name(bytes, false, length);
5079       legal = (p != NULL) && ((p - bytes) == (int)length);
5080     } else {
5081       // 4881221: relax the constraints based on JSR202 spec
5082       legal = verify_unqualified_name(bytes, length, LegalMethod);
5083     }
5084   }
5085 
5086   if (!legal) {
5087     ResourceMark rm(THREAD);
5088     assert(_class_name != NULL, "invariant");
5089     Exceptions::fthrow(
5090       THREAD_AND_LOCATION,
5091       vmSymbols::java_lang_ClassFormatError(),
5092       "Illegal method name \"%s\" in class %s", bytes,
5093       _class_name->as_C_string()
5094     );
5095     return;
5096   }
5097 }
5098 
5099 
5100 // Checks if signature is a legal field signature.
5101 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5102                                                    const Symbol* signature,
5103                                                    TRAPS) const {
5104   if (!_need_verify) { return; }
5105 
5106   char buf[fixed_buffer_size];
5107   const char* const bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5108   const unsigned int length = signature->utf8_length();
5109   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5110 
5111   if (p == NULL || (p - bytes) != (int)length) {
5112     throwIllegalSignature("Field", name, signature, CHECK);
5113   }
5114 }
5115 
5116 // Checks if signature is a legal method signature.
5117 // Returns number of parameters
5118 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5119                                                    const Symbol* signature,
5120                                                    TRAPS) const {
5121   if (!_need_verify) {
5122     // make sure caller's args_size will be less than 0 even for non-static
5123     // method so it will be recomputed in compute_size_of_parameters().
5124     return -2;
5125   }
5126 
5127   // Class initializers cannot have args for class format version >= 51.
5128   if (name == vmSymbols::class_initializer_name() &&
5129       signature != vmSymbols::void_method_signature() &&
5130       _major_version >= JAVA_7_VERSION) {
5131     throwIllegalSignature("Method", name, signature, CHECK_0);
5132     return 0;
5133   }
5134 
5135   unsigned int args_size = 0;
5136   char buf[fixed_buffer_size];
5137   const char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5138   unsigned int length = signature->utf8_length();
5139   const char* nextp;
5140 
5141   // The first character must be a '('
5142   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5143     length--;
5144     // Skip over legal field signatures
5145     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5146     while ((length > 0) && (nextp != NULL)) {
5147       args_size++;
5148       if (p[0] == 'J' || p[0] == 'D') {
5149         args_size++;
5150       }
5151       length -= nextp - p;
5152       p = nextp;
5153       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5154     }
5155     // The first non-signature thing better be a ')'
5156     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5157       length--;
5158       if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
5159         // All internal methods must return void
5160         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
5161           return args_size;
5162         }
5163       } else {
5164         // Now we better just have a return value
5165         nextp = skip_over_field_signature(p, true, length, CHECK_0);
5166         if (nextp && ((int)length == (nextp - p))) {
5167           return args_size;
5168         }
5169       }
5170     }
5171   }
5172   // Report error
5173   throwIllegalSignature("Method", name, signature, CHECK_0);
5174   return 0;
5175 }
5176 
5177 int ClassFileParser::static_field_size() const {
5178   assert(_field_info != NULL, "invariant");
5179   return _field_info->static_field_size;
5180 }
5181 
5182 int ClassFileParser::total_oop_map_count() const {
5183   assert(_field_info != NULL, "invariant");
5184   return _field_info->total_oop_map_count;
5185 }
5186 
5187 jint ClassFileParser::layout_size() const {
5188   assert(_field_info != NULL, "invariant");
5189   return _field_info->instance_size;
5190 }
5191 
5192 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5193                                          const Array<Method*>* methods) {
5194   assert(ik != NULL, "invariant");
5195   assert(methods != NULL, "invariant");
5196 
5197   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5198   // (We used to do this lazily, but now we query it in Rewriter,
5199   // which is eagerly done for every method, so we might as well do it now,
5200   // when everything is fresh in memory.)
5201   const vmSymbols::SID klass_id = Method::klass_id_for_intrinsics(ik);
5202 
5203   if (klass_id != vmSymbols::NO_SID) {
5204     for (int j = 0; j < methods->length(); ++j) {
5205       Method* method = methods->at(j);
5206       method->init_intrinsic_id();
5207 
5208       if (CheckIntrinsics) {
5209         // Check if an intrinsic is defined for method 'method',
5210         // but the method is not annotated with @HotSpotIntrinsicCandidate.
5211         if (method->intrinsic_id() != vmIntrinsics::_none &&
5212             !method->intrinsic_candidate()) {
5213               tty->print("Compiler intrinsic is defined for method [%s], "
5214               "but the method is not annotated with @HotSpotIntrinsicCandidate.%s",
5215               method->name_and_sig_as_C_string(),
5216               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5217             );
5218           tty->cr();
5219           DEBUG_ONLY(vm_exit(1));
5220         }
5221         // Check is the method 'method' is annotated with @HotSpotIntrinsicCandidate,
5222         // but there is no intrinsic available for it.
5223         if (method->intrinsic_candidate() &&
5224           method->intrinsic_id() == vmIntrinsics::_none) {
5225             tty->print("Method [%s] is annotated with @HotSpotIntrinsicCandidate, "
5226               "but no compiler intrinsic is defined for the method.%s",
5227               method->name_and_sig_as_C_string(),
5228               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5229             );
5230           tty->cr();
5231           DEBUG_ONLY(vm_exit(1));
5232         }
5233       }
5234     } // end for
5235 
5236 #ifdef ASSERT
5237     if (CheckIntrinsics) {
5238       // Check for orphan methods in the current class. A method m
5239       // of a class C is orphan if an intrinsic is defined for method m,
5240       // but class C does not declare m.
5241       // The check is potentially expensive, therefore it is available
5242       // only in debug builds.
5243 
5244       for (int id = vmIntrinsics::FIRST_ID; id < (int)vmIntrinsics::ID_LIMIT; ++id) {
5245         if (vmIntrinsics::_compiledLambdaForm == id) {
5246           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5247           // generated for the JVM from a LambdaForm and therefore no method
5248           // is defined for it.
5249           continue;
5250         }
5251 
5252         if (vmIntrinsics::class_for(vmIntrinsics::ID_from(id)) == klass_id) {
5253           // Check if the current class contains a method with the same
5254           // name, flags, signature.
5255           bool match = false;
5256           for (int j = 0; j < methods->length(); ++j) {
5257             const Method* method = methods->at(j);
5258             if (method->intrinsic_id() == id) {
5259               match = true;
5260               break;
5261             }
5262           }
5263 
5264           if (!match) {
5265             char buf[1000];
5266             tty->print("Compiler intrinsic is defined for method [%s], "
5267                        "but the method is not available in class [%s].%s",
5268                         vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID_from(id),
5269                                                              buf, sizeof(buf)),
5270                         ik->name()->as_C_string(),
5271                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5272             );
5273             tty->cr();
5274             DEBUG_ONLY(vm_exit(1));
5275           }
5276         }
5277       } // end for
5278     } // CheckIntrinsics
5279 #endif // ASSERT
5280   }
5281 }
5282 
5283 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook, TRAPS) {
5284   if (_klass != NULL) {
5285     return _klass;
5286   }
5287 
5288   InstanceKlass* const ik =
5289     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5290 
5291   fill_instance_klass(ik, changed_by_loadhook, CHECK_NULL);
5292 
5293   assert(_klass == ik, "invariant");
5294 
5295   ik->set_has_passed_fingerprint_check(false);
5296   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
5297     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
5298     if (aot_fp != 0 && aot_fp == _stream->compute_fingerprint()) {
5299       // This class matches with a class saved in an AOT library
5300       ik->set_has_passed_fingerprint_check(true);
5301     } else {
5302       ResourceMark rm;
5303       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT,
5304                                  ik->external_name(), aot_fp, _stream->compute_fingerprint());
5305     }
5306   }
5307 
5308   return ik;
5309 }
5310 
5311 void ClassFileParser::fill_instance_klass(InstanceKlass* ik, bool changed_by_loadhook, TRAPS) {
5312   assert(ik != NULL, "invariant");
5313 
5314   set_klass_to_deallocate(ik);
5315 
5316   assert(_field_info != NULL, "invariant");
5317   assert(ik->static_field_size() == _field_info->static_field_size, "sanity");
5318   assert(ik->nonstatic_oop_map_count() == _field_info->total_oop_map_count,
5319     "sanity");
5320 
5321   assert(ik->is_instance_klass(), "sanity");
5322   assert(ik->size_helper() == _field_info->instance_size, "sanity");
5323 
5324   // Fill in information already parsed
5325   ik->set_should_verify_class(_need_verify);
5326 
5327   // Not yet: supers are done below to support the new subtype-checking fields
5328   ik->set_class_loader_data(_loader_data);
5329   ik->set_nonstatic_field_size(_field_info->nonstatic_field_size);
5330   ik->set_has_nonstatic_fields(_field_info->has_nonstatic_fields);
5331   assert(_fac != NULL, "invariant");
5332   ik->set_static_oop_field_count(_fac->count[STATIC_OOP]);
5333 
5334   // this transfers ownership of a lot of arrays from
5335   // the parser onto the InstanceKlass*
5336   apply_parsed_class_metadata(ik, _java_fields_count, CHECK);
5337 
5338   // note that is not safe to use the fields in the parser from this point on
5339   assert(NULL == _cp, "invariant");
5340   assert(NULL == _fields, "invariant");
5341   assert(NULL == _methods, "invariant");
5342   assert(NULL == _inner_classes, "invariant");
5343   assert(NULL == _local_interfaces, "invariant");
5344   assert(NULL == _transitive_interfaces, "invariant");
5345   assert(NULL == _combined_annotations, "invariant");
5346 
5347   if (_has_final_method) {
5348     ik->set_has_final_method();
5349   }
5350 
5351   ik->copy_method_ordering(_method_ordering, CHECK);
5352   // The InstanceKlass::_methods_jmethod_ids cache
5353   // is managed on the assumption that the initial cache
5354   // size is equal to the number of methods in the class. If
5355   // that changes, then InstanceKlass::idnum_can_increment()
5356   // has to be changed accordingly.
5357   ik->set_initial_method_idnum(ik->methods()->length());
5358 
5359   ik->set_name(_class_name);
5360 
5361   if (is_anonymous()) {
5362     // _this_class_index is a CONSTANT_Class entry that refers to this
5363     // anonymous class itself. If this class needs to refer to its own methods or
5364     // fields, it would use a CONSTANT_MethodRef, etc, which would reference
5365     // _this_class_index. However, because this class is anonymous (it's
5366     // not stored in SystemDictionary), _this_class_index cannot be resolved
5367     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5368     // Therefore, we must eagerly resolve _this_class_index now.
5369     ik->constants()->klass_at_put(_this_class_index, ik);
5370   }
5371 
5372   ik->set_minor_version(_minor_version);
5373   ik->set_major_version(_major_version);
5374   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5375   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5376 
5377   if (_host_klass != NULL) {
5378     assert (ik->is_anonymous(), "should be the same");
5379     ik->set_host_klass(_host_klass);
5380   }
5381 
5382   // Set PackageEntry for this_klass
5383   oop cl = ik->class_loader();
5384   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5385   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5386   ik->set_package(cld, CHECK);
5387 
5388   const Array<Method*>* const methods = ik->methods();
5389   assert(methods != NULL, "invariant");
5390   const int methods_len = methods->length();
5391 
5392   check_methods_for_intrinsics(ik, methods);
5393 
5394   // Fill in field values obtained by parse_classfile_attributes
5395   if (_parsed_annotations->has_any_annotations()) {
5396     _parsed_annotations->apply_to(ik);
5397   }
5398 
5399   apply_parsed_class_attributes(ik);
5400 
5401   // Miranda methods
5402   if ((_num_miranda_methods > 0) ||
5403       // if this class introduced new miranda methods or
5404       (_super_klass != NULL && _super_klass->has_miranda_methods())
5405         // super class exists and this class inherited miranda methods
5406      ) {
5407        ik->set_has_miranda_methods(); // then set a flag
5408   }
5409 
5410   // Fill in information needed to compute superclasses.
5411   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), CHECK);
5412 
5413   // Initialize itable offset tables
5414   klassItable::setup_itable_offset_table(ik);
5415 
5416   // Compute transitive closure of interfaces this class implements
5417   // Do final class setup
5418   fill_oop_maps(ik,
5419                 _field_info->nonstatic_oop_map_count,
5420                 _field_info->nonstatic_oop_offsets,
5421                 _field_info->nonstatic_oop_counts);
5422 
5423   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5424   set_precomputed_flags(ik);
5425 
5426   // check if this class can access its super class
5427   check_super_class_access(ik, CHECK);
5428 
5429   // check if this class can access its superinterfaces
5430   check_super_interface_access(ik, CHECK);
5431 
5432   // check if this class overrides any final method
5433   check_final_method_override(ik, CHECK);
5434 
5435   // reject static interface methods prior to Java 8
5436   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5437     check_illegal_static_method(ik, CHECK);
5438   }
5439 
5440   // Obtain this_klass' module entry
5441   ModuleEntry* module_entry = ik->module();
5442   assert(module_entry != NULL, "module_entry should always be set");
5443 
5444   // Obtain java.lang.Module
5445   Handle module_handle(THREAD, module_entry->module());
5446 
5447   // Allocate mirror and initialize static fields
5448   // The create_mirror() call will also call compute_modifiers()
5449   java_lang_Class::create_mirror(ik,
5450                                  Handle(THREAD, _loader_data->class_loader()),
5451                                  module_handle,
5452                                  _protection_domain,
5453                                  CHECK);
5454 
5455   assert(_all_mirandas != NULL, "invariant");
5456 
5457   // Generate any default methods - default methods are public interface methods
5458   // that have a default implementation.  This is new with Java 8.
5459   if (_has_nonstatic_concrete_methods) {
5460     DefaultMethods::generate_default_methods(ik,
5461                                              _all_mirandas,
5462                                              CHECK);
5463   }
5464 
5465   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5466   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5467       !module_entry->has_default_read_edges()) {
5468     if (!module_entry->set_has_default_read_edges()) {
5469       // We won a potential race
5470       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5471     }
5472   }
5473 
5474   // Update the loader_data graph.
5475   record_defined_class_dependencies(ik, CHECK);
5476 
5477   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5478 
5479   if (!is_internal()) {
5480     if (log_is_enabled(Info, class, load)) {
5481       ResourceMark rm;
5482       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
5483       ik->print_class_load_logging(_loader_data, module_name, _stream);
5484     }
5485 
5486     if (log_is_enabled(Debug, class, resolve))  {
5487       ResourceMark rm;
5488       // print out the superclass.
5489       const char * from = ik->external_name();
5490       if (ik->java_super() != NULL) {
5491         log_debug(class, resolve)("%s %s (super)",
5492                    from,
5493                    ik->java_super()->external_name());
5494       }
5495       // print out each of the interface classes referred to by this class.
5496       const Array<Klass*>* const local_interfaces = ik->local_interfaces();
5497       if (local_interfaces != NULL) {
5498         const int length = local_interfaces->length();
5499         for (int i = 0; i < length; i++) {
5500           const Klass* const k = local_interfaces->at(i);
5501           const char * to = k->external_name();
5502           log_debug(class, resolve)("%s %s (interface)", from, to);
5503         }
5504       }
5505     }
5506   }
5507 
5508   TRACE_INIT_ID(ik);
5509 
5510   // If we reach here, all is well.
5511   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5512   // in order for it to not be destroyed in the ClassFileParser destructor.
5513   set_klass_to_deallocate(NULL);
5514 
5515   // it's official
5516   set_klass(ik);
5517 
5518   debug_only(ik->verify();)
5519 }
5520 
5521 // For an anonymous class that is in the unnamed package, move it to its host class's
5522 // package by prepending its host class's package name to its class name and setting
5523 // its _class_name field.
5524 void ClassFileParser::prepend_host_package_name(const InstanceKlass* host_klass, TRAPS) {
5525   ResourceMark rm(THREAD);
5526   assert(strrchr(_class_name->as_C_string(), '/') == NULL,
5527          "Anonymous class should not be in a package");
5528   const char* host_pkg_name =
5529     ClassLoader::package_from_name(host_klass->name()->as_C_string(), NULL);
5530 
5531   if (host_pkg_name != NULL) {
5532     size_t host_pkg_len = strlen(host_pkg_name);
5533     int class_name_len = _class_name->utf8_length();
5534     char* new_anon_name =
5535       NEW_RESOURCE_ARRAY(char, host_pkg_len + 1 + class_name_len);
5536     // Copy host package name and trailing /.
5537     strncpy(new_anon_name, host_pkg_name, host_pkg_len);
5538     new_anon_name[host_pkg_len] = '/';
5539     // Append anonymous class name. The anonymous class name can contain odd
5540     // characters.  So, do a strncpy instead of using sprintf("%s...").
5541     strncpy(new_anon_name + host_pkg_len + 1, (char *)_class_name->base(), class_name_len);
5542 
5543     // Create a symbol and update the anonymous class name.
5544     _class_name = SymbolTable::new_symbol(new_anon_name,
5545                                           (int)host_pkg_len + 1 + class_name_len,
5546                                           CHECK);
5547   }
5548 }
5549 
5550 // If the host class and the anonymous class are in the same package then do
5551 // nothing.  If the anonymous class is in the unnamed package then move it to its
5552 // host's package.  If the classes are in different packages then throw an IAE
5553 // exception.
5554 void ClassFileParser::fix_anonymous_class_name(TRAPS) {
5555   assert(_host_klass != NULL, "Expected an anonymous class");
5556 
5557   const jbyte* anon_last_slash = UTF8::strrchr(_class_name->base(),
5558                                                _class_name->utf8_length(), '/');
5559   if (anon_last_slash == NULL) {  // Unnamed package
5560     prepend_host_package_name(_host_klass, CHECK);
5561   } else {
5562     if (!_host_klass->is_same_class_package(_host_klass->class_loader(), _class_name)) {
5563       ResourceMark rm(THREAD);
5564       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
5565         err_msg("Host class %s and anonymous class %s are in different packages",
5566         _host_klass->name()->as_C_string(), _class_name->as_C_string()));
5567     }
5568   }
5569 }
5570 
5571 static bool relax_format_check_for(ClassLoaderData* loader_data) {
5572   bool trusted = (loader_data->is_the_null_class_loader_data() ||
5573                   SystemDictionary::is_platform_class_loader(loader_data->class_loader()));
5574   bool need_verify =
5575     // verifyAll
5576     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
5577     // verifyRemote
5578     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
5579   return !need_verify;
5580 }
5581 
5582 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5583                                  Symbol* name,
5584                                  ClassLoaderData* loader_data,
5585                                  Handle protection_domain,
5586                                  const InstanceKlass* host_klass,
5587                                  GrowableArray<Handle>* cp_patches,
5588                                  Publicity pub_level,
5589                                  TRAPS) :
5590   _stream(stream),
5591   _requested_name(name),
5592   _loader_data(loader_data),
5593   _host_klass(host_klass),
5594   _cp_patches(cp_patches),
5595   _num_patched_klasses(0),
5596   _max_num_patched_klasses(0),
5597   _orig_cp_size(0),
5598   _first_patched_klass_resolved_index(0),
5599   _super_klass(),
5600   _cp(NULL),
5601   _fields(NULL),
5602   _methods(NULL),
5603   _inner_classes(NULL),
5604   _local_interfaces(NULL),
5605   _transitive_interfaces(NULL),
5606   _combined_annotations(NULL),
5607   _annotations(NULL),
5608   _type_annotations(NULL),
5609   _fields_annotations(NULL),
5610   _fields_type_annotations(NULL),
5611   _klass(NULL),
5612   _klass_to_deallocate(NULL),
5613   _parsed_annotations(NULL),
5614   _fac(NULL),
5615   _field_info(NULL),
5616   _method_ordering(NULL),
5617   _all_mirandas(NULL),
5618   _vtable_size(0),
5619   _itable_size(0),
5620   _num_miranda_methods(0),
5621   _rt(REF_NONE),
5622   _protection_domain(protection_domain),
5623   _access_flags(),
5624   _pub_level(pub_level),
5625   _bad_constant_seen(0),
5626   _synthetic_flag(false),
5627   _sde_length(false),
5628   _sde_buffer(NULL),
5629   _sourcefile_index(0),
5630   _generic_signature_index(0),
5631   _major_version(0),
5632   _minor_version(0),
5633   _this_class_index(0),
5634   _super_class_index(0),
5635   _itfs_len(0),
5636   _java_fields_count(0),
5637   _need_verify(false),
5638   _relax_verify(false),
5639   _has_nonstatic_concrete_methods(false),
5640   _declares_nonstatic_concrete_methods(false),
5641   _has_final_method(false),
5642   _has_finalizer(false),
5643   _has_empty_finalizer(false),
5644   _has_vanilla_constructor(false),
5645   _max_bootstrap_specifier_index(-1) {
5646 
5647   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5648 
5649   assert(THREAD->is_Java_thread(), "invariant");
5650   assert(_loader_data != NULL, "invariant");
5651   assert(stream != NULL, "invariant");
5652   assert(_stream != NULL, "invariant");
5653   assert(_stream->buffer() == _stream->current(), "invariant");
5654   assert(_class_name != NULL, "invariant");
5655   assert(0 == _access_flags.as_int(), "invariant");
5656 
5657   // Figure out whether we can skip format checking (matching classic VM behavior)
5658   if (DumpSharedSpaces) {
5659     // verify == true means it's a 'remote' class (i.e., non-boot class)
5660     // Verification decision is based on BytecodeVerificationRemote flag
5661     // for those classes.
5662     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
5663                                               BytecodeVerificationLocal;
5664   }
5665   else {
5666     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
5667                                                stream->need_verify());
5668   }
5669   if (_cp_patches != NULL) {
5670     int len = _cp_patches->length();
5671     for (int i=0; i<len; i++) {
5672       if (has_cp_patch_at(i)) {
5673         Handle patch = cp_patch_at(i);
5674         if (java_lang_String::is_instance(patch()) || java_lang_Class::is_instance(patch())) {
5675           // We need to append the names of the patched classes to the end of the constant pool,
5676           // because a patched class may have a Utf8 name that's not already included in the
5677           // original constant pool. These class names are used when patch_constant_pool()
5678           // calls patch_class().
5679           //
5680           // Note that a String in cp_patch_at(i) may be used to patch a Utf8, a String, or a Class.
5681           // At this point, we don't know the tag for index i yet, because we haven't parsed the
5682           // constant pool. So we can only assume the worst -- every String is used to patch a Class.
5683           _max_num_patched_klasses++;
5684         }
5685       }
5686     }
5687   }
5688 
5689   // synch back verification state to stream
5690   stream->set_verify(_need_verify);
5691 
5692   // Check if verification needs to be relaxed for this class file
5693   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5694   _relax_verify = relax_format_check_for(_loader_data);
5695 
5696   parse_stream(stream, CHECK);
5697 
5698   post_process_parsed_stream(stream, _cp, CHECK);
5699 }
5700 
5701 void ClassFileParser::clear_class_metadata() {
5702   // metadata created before the instance klass is created.  Must be
5703   // deallocated if classfile parsing returns an error.
5704   _cp = NULL;
5705   _fields = NULL;
5706   _methods = NULL;
5707   _inner_classes = NULL;
5708   _local_interfaces = NULL;
5709   _transitive_interfaces = NULL;
5710   _combined_annotations = NULL;
5711   _annotations = _type_annotations = NULL;
5712   _fields_annotations = _fields_type_annotations = NULL;
5713 }
5714 
5715 // Destructor to clean up
5716 ClassFileParser::~ClassFileParser() {
5717   if (_cp != NULL) {
5718     MetadataFactory::free_metadata(_loader_data, _cp);
5719   }
5720   if (_fields != NULL) {
5721     MetadataFactory::free_array<u2>(_loader_data, _fields);
5722   }
5723 
5724   if (_methods != NULL) {
5725     // Free methods
5726     InstanceKlass::deallocate_methods(_loader_data, _methods);
5727   }
5728 
5729   // beware of the Universe::empty_blah_array!!
5730   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
5731     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5732   }
5733 
5734   // Free interfaces
5735   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5736                                        _local_interfaces, _transitive_interfaces);
5737 
5738   if (_combined_annotations != NULL) {
5739     // After all annotations arrays have been created, they are installed into the
5740     // Annotations object that will be assigned to the InstanceKlass being created.
5741 
5742     // Deallocate the Annotations object and the installed annotations arrays.
5743     _combined_annotations->deallocate_contents(_loader_data);
5744 
5745     // If the _combined_annotations pointer is non-NULL,
5746     // then the other annotations fields should have been cleared.
5747     assert(_annotations             == NULL, "Should have been cleared");
5748     assert(_type_annotations        == NULL, "Should have been cleared");
5749     assert(_fields_annotations      == NULL, "Should have been cleared");
5750     assert(_fields_type_annotations == NULL, "Should have been cleared");
5751   } else {
5752     // If the annotations arrays were not installed into the Annotations object,
5753     // then they have to be deallocated explicitly.
5754     MetadataFactory::free_array<u1>(_loader_data, _annotations);
5755     MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
5756     Annotations::free_contents(_loader_data, _fields_annotations);
5757     Annotations::free_contents(_loader_data, _fields_type_annotations);
5758   }
5759 
5760   clear_class_metadata();
5761 
5762   // deallocate the klass if already created.  Don't directly deallocate, but add
5763   // to the deallocate list so that the klass is removed from the CLD::_klasses list
5764   // at a safepoint.
5765   if (_klass_to_deallocate != NULL) {
5766     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
5767   }
5768 }
5769 
5770 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
5771                                    TRAPS) {
5772 
5773   assert(stream != NULL, "invariant");
5774   assert(_class_name != NULL, "invariant");
5775 
5776   // BEGIN STREAM PARSING
5777   stream->guarantee_more(8, CHECK);  // magic, major, minor
5778   // Magic value
5779   const u4 magic = stream->get_u4_fast();
5780   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
5781                      "Incompatible magic value %u in class file %s",
5782                      magic, CHECK);
5783 
5784   // Version numbers
5785   _minor_version = stream->get_u2_fast();
5786   _major_version = stream->get_u2_fast();
5787 
5788   if (DumpSharedSpaces && _major_version < JAVA_1_5_VERSION) {
5789     ResourceMark rm;
5790     warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
5791             _major_version,  _minor_version, _class_name->as_C_string());
5792     Exceptions::fthrow(
5793       THREAD_AND_LOCATION,
5794       vmSymbols::java_lang_UnsupportedClassVersionError(),
5795       "Unsupported major.minor version for dump time %u.%u",
5796       _major_version,
5797       _minor_version);
5798   }
5799 
5800   // Check version numbers - we check this even with verifier off
5801   if (!is_supported_version(_major_version, _minor_version)) {
5802     ResourceMark rm(THREAD);
5803     Exceptions::fthrow(
5804       THREAD_AND_LOCATION,
5805       vmSymbols::java_lang_UnsupportedClassVersionError(),
5806       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
5807       "this version of the Java Runtime only recognizes class file versions up to %u.%u",
5808       _class_name->as_C_string(),
5809       _major_version,
5810       _minor_version,
5811       JVM_CLASSFILE_MAJOR_VERSION,
5812       JVM_CLASSFILE_MINOR_VERSION);
5813     return;
5814   }
5815 
5816   stream->guarantee_more(3, CHECK); // length, first cp tag
5817   u2 cp_size = stream->get_u2_fast();
5818 
5819   guarantee_property(
5820     cp_size >= 1, "Illegal constant pool size %u in class file %s",
5821     cp_size, CHECK);
5822 
5823   _orig_cp_size = cp_size;
5824   if (int(cp_size) + _max_num_patched_klasses > 0xffff) {
5825     THROW_MSG(vmSymbols::java_lang_InternalError(), "not enough space for patched classes");
5826   }
5827   cp_size += _max_num_patched_klasses;
5828 
5829   _cp = ConstantPool::allocate(_loader_data,
5830                                cp_size,
5831                                CHECK);
5832 
5833   ConstantPool* const cp = _cp;
5834 
5835   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5836 
5837   assert(cp_size == (const u2)cp->length(), "invariant");
5838 
5839   // ACCESS FLAGS
5840   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5841 
5842   // Access flags
5843   jint flags;
5844   // JVM_ACC_MODULE is defined in JDK-9 and later.
5845   if (_major_version >= JAVA_9_VERSION) {
5846     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5847   } else {
5848     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5849   }
5850 
5851   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5852     // Set abstract bit for old class files for backward compatibility
5853     flags |= JVM_ACC_ABSTRACT;
5854   }
5855 
5856   verify_legal_class_modifiers(flags, CHECK);
5857 
5858   short bad_constant = class_bad_constant_seen();
5859   if (bad_constant != 0) {
5860     // Do not throw CFE until after the access_flags are checked because if
5861     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5862     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, CHECK);
5863   }
5864 
5865   _access_flags.set_flags(flags);
5866 
5867   // This class and superclass
5868   _this_class_index = stream->get_u2_fast();
5869   check_property(
5870     valid_cp_range(_this_class_index, cp_size) &&
5871       cp->tag_at(_this_class_index).is_unresolved_klass(),
5872     "Invalid this class index %u in constant pool in class file %s",
5873     _this_class_index, CHECK);
5874 
5875   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5876   assert(class_name_in_cp != NULL, "class_name can't be null");
5877 
5878   // Update _class_name which could be null previously
5879   // to reflect the name in the constant pool
5880   _class_name = class_name_in_cp;
5881 
5882   // Don't need to check whether this class name is legal or not.
5883   // It has been checked when constant pool is parsed.
5884   // However, make sure it is not an array type.
5885   if (_need_verify) {
5886     guarantee_property(_class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
5887                        "Bad class name in class file %s",
5888                        CHECK);
5889   }
5890 
5891   // Checks if name in class file matches requested name
5892   if (_requested_name != NULL && _requested_name != _class_name) {
5893     ResourceMark rm(THREAD);
5894     Exceptions::fthrow(
5895       THREAD_AND_LOCATION,
5896       vmSymbols::java_lang_NoClassDefFoundError(),
5897       "%s (wrong name: %s)",
5898       _class_name->as_C_string(),
5899       _requested_name != NULL ? _requested_name->as_C_string() : "NoName"
5900     );
5901     return;
5902   }
5903 
5904   // if this is an anonymous class fix up its name if it's in the unnamed
5905   // package.  Otherwise, throw IAE if it is in a different package than
5906   // its host class.
5907   if (_host_klass != NULL) {
5908     fix_anonymous_class_name(CHECK);
5909   }
5910 
5911   // Verification prevents us from creating names with dots in them, this
5912   // asserts that that's the case.
5913   assert(is_internal_format(_class_name), "external class name format used internally");
5914 
5915   if (!is_internal()) {
5916     LogTarget(Debug, class, preorder) lt;
5917     if (lt.is_enabled()){
5918       ResourceMark rm(THREAD);
5919       LogStream ls(lt);
5920       ls.print("%s", _class_name->as_klass_external_name());
5921       if (stream->source() != NULL) {
5922         ls.print(" source: %s", stream->source());
5923       }
5924       ls.cr();
5925     }
5926 
5927 #if INCLUDE_CDS
5928     if (DumpLoadedClassList != NULL && stream->source() != NULL && classlist_file->is_open()) {
5929       if (!ClassLoader::has_jrt_entry()) {
5930         warning("DumpLoadedClassList and CDS are not supported in exploded build");
5931         DumpLoadedClassList = NULL;
5932       } else if (SystemDictionaryShared::is_sharing_possible(_loader_data) &&
5933           _host_klass == NULL) {
5934         // Only dump the classes that can be stored into CDS archive.
5935         // Anonymous classes such as generated LambdaForm classes are also not included.
5936         oop class_loader = _loader_data->class_loader();
5937         ResourceMark rm(THREAD);
5938         bool skip = false;
5939         if (class_loader == NULL || SystemDictionary::is_platform_class_loader(class_loader)) {
5940           // For the boot and platform class loaders, skip classes that are not found in the
5941           // java runtime image, such as those found in the --patch-module entries.
5942           // These classes can't be loaded from the archive during runtime.
5943           if (!ClassLoader::is_modules_image(stream->source()) && strncmp(stream->source(), "jrt:", 4) != 0) {
5944             skip = true;
5945           }
5946 
5947           if (class_loader == NULL && ClassLoader::contains_append_entry(stream->source())) {
5948             // .. but don't skip the boot classes that are loaded from -Xbootclasspath/a
5949             // as they can be loaded from the archive during runtime.
5950             skip = false;
5951           }
5952         }
5953         if (skip) {
5954           tty->print_cr("skip writing class %s from source %s to classlist file",
5955             _class_name->as_C_string(), stream->source());
5956         } else {
5957           classlist_file->print_cr("%s", _class_name->as_C_string());
5958           classlist_file->flush();
5959         }
5960       }
5961     }
5962 #endif
5963   }
5964 
5965   // SUPERKLASS
5966   _super_class_index = stream->get_u2_fast();
5967   _super_klass = parse_super_class(cp,
5968                                    _super_class_index,
5969                                    _need_verify,
5970                                    CHECK);
5971 
5972   // Interfaces
5973   _itfs_len = stream->get_u2_fast();
5974   parse_interfaces(stream,
5975                    _itfs_len,
5976                    cp,
5977                    &_has_nonstatic_concrete_methods,
5978                    CHECK);
5979 
5980   assert(_local_interfaces != NULL, "invariant");
5981 
5982   // Fields (offsets are filled in later)
5983   _fac = new FieldAllocationCount();
5984   parse_fields(stream,
5985                _access_flags.is_interface(),
5986                _fac,
5987                cp,
5988                cp_size,
5989                &_java_fields_count,
5990                CHECK);
5991 
5992   assert(_fields != NULL, "invariant");
5993 
5994   // Methods
5995   AccessFlags promoted_flags;
5996   parse_methods(stream,
5997                 _access_flags.is_interface(),
5998                 &promoted_flags,
5999                 &_has_final_method,
6000                 &_declares_nonstatic_concrete_methods,
6001                 CHECK);
6002 
6003   assert(_methods != NULL, "invariant");
6004 
6005   // promote flags from parse_methods() to the klass' flags
6006   _access_flags.add_promoted_flags(promoted_flags.as_int());
6007 
6008   if (_declares_nonstatic_concrete_methods) {
6009     _has_nonstatic_concrete_methods = true;
6010   }
6011 
6012   // Additional attributes/annotations
6013   _parsed_annotations = new ClassAnnotationCollector();
6014   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6015 
6016   assert(_inner_classes != NULL, "invariant");
6017 
6018   // Finalize the Annotations metadata object,
6019   // now that all annotation arrays have been created.
6020   create_combined_annotations(CHECK);
6021 
6022   // Make sure this is the end of class file stream
6023   guarantee_property(stream->at_eos(),
6024                      "Extra bytes at the end of class file %s",
6025                      CHECK);
6026 
6027   // all bytes in stream read and parsed
6028 }
6029 
6030 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6031                                                  ConstantPool* cp,
6032                                                  TRAPS) {
6033   assert(stream != NULL, "invariant");
6034   assert(stream->at_eos(), "invariant");
6035   assert(cp != NULL, "invariant");
6036   assert(_loader_data != NULL, "invariant");
6037 
6038   if (_class_name == vmSymbols::java_lang_Object()) {
6039     check_property(_local_interfaces == Universe::the_empty_klass_array(),
6040                    "java.lang.Object cannot implement an interface in class file %s",
6041                    CHECK);
6042   }
6043   // We check super class after class file is parsed and format is checked
6044   if (_super_class_index > 0 && NULL ==_super_klass) {
6045     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6046     if (_access_flags.is_interface()) {
6047       // Before attempting to resolve the superclass, check for class format
6048       // errors not checked yet.
6049       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6050         "Interfaces must have java.lang.Object as superclass in class file %s",
6051         CHECK);
6052     }
6053     Handle loader(THREAD, _loader_data->class_loader());
6054     _super_klass = (const InstanceKlass*)
6055                        SystemDictionary::resolve_super_or_fail(_class_name,
6056                                                                super_class_name,
6057                                                                loader,
6058                                                                _protection_domain,
6059                                                                true,
6060                                                                CHECK);
6061   }
6062 
6063   if (_super_klass != NULL) {
6064     if (_super_klass->has_nonstatic_concrete_methods()) {
6065       _has_nonstatic_concrete_methods = true;
6066     }
6067 
6068     if (_super_klass->is_interface()) {
6069       ResourceMark rm(THREAD);
6070       Exceptions::fthrow(
6071         THREAD_AND_LOCATION,
6072         vmSymbols::java_lang_IncompatibleClassChangeError(),
6073         "class %s has interface %s as super class",
6074         _class_name->as_klass_external_name(),
6075         _super_klass->external_name()
6076       );
6077       return;
6078     }
6079     // Make sure super class is not final
6080     if (_super_klass->is_final()) {
6081       THROW_MSG(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class");
6082     }
6083   }
6084 
6085   // Compute the transitive list of all unique interfaces implemented by this class
6086   _transitive_interfaces =
6087     compute_transitive_interfaces(_super_klass,
6088                                   _local_interfaces,
6089                                   _loader_data,
6090                                   CHECK);
6091 
6092   assert(_transitive_interfaces != NULL, "invariant");
6093 
6094   // sort methods
6095   _method_ordering = sort_methods(_methods);
6096 
6097   _all_mirandas = new GrowableArray<Method*>(20);
6098 
6099   Handle loader(THREAD, _loader_data->class_loader());
6100   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6101                                                     &_num_miranda_methods,
6102                                                     _all_mirandas,
6103                                                     _super_klass,
6104                                                     _methods,
6105                                                     _access_flags,
6106                                                     _major_version,
6107                                                     loader,
6108                                                     _class_name,
6109                                                     _local_interfaces,
6110                                                     CHECK);
6111 
6112   // Size of Java itable (in words)
6113   _itable_size = _access_flags.is_interface() ? 0 :
6114     klassItable::compute_itable_size(_transitive_interfaces);
6115 
6116   assert(_fac != NULL, "invariant");
6117   assert(_parsed_annotations != NULL, "invariant");
6118 
6119   _field_info = new FieldLayoutInfo();
6120   layout_fields(cp, _fac, _parsed_annotations, _field_info, CHECK);
6121 
6122   // Compute reference typ
6123   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();
6124 
6125 }
6126 
6127 void ClassFileParser::set_klass(InstanceKlass* klass) {
6128 
6129 #ifdef ASSERT
6130   if (klass != NULL) {
6131     assert(NULL == _klass, "leaking?");
6132   }
6133 #endif
6134 
6135   _klass = klass;
6136 }
6137 
6138 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6139 
6140 #ifdef ASSERT
6141   if (klass != NULL) {
6142     assert(NULL == _klass_to_deallocate, "leaking?");
6143   }
6144 #endif
6145 
6146   _klass_to_deallocate = klass;
6147 }
6148 
6149 // Caller responsible for ResourceMark
6150 // clone stream with rewound position
6151 const ClassFileStream* ClassFileParser::clone_stream() const {
6152   assert(_stream != NULL, "invariant");
6153 
6154   return _stream->clone();
6155 }
6156 // ----------------------------------------------------------------------------
6157 // debugging
6158 
6159 #ifdef ASSERT
6160 
6161 // return true if class_name contains no '.' (internal format is '/')
6162 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6163   if (class_name != NULL) {
6164     ResourceMark rm;
6165     char* name = class_name->as_C_string();
6166     return strchr(name, '.') == NULL;
6167   } else {
6168     return true;
6169   }
6170 }
6171 
6172 #endif