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