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 "aot/aotLoader.hpp"
  26 #include "classfile/classFileParser.hpp"
  27 #include "classfile/classFileStream.hpp"
  28 #include "classfile/classLoader.hpp"
  29 #include "classfile/classLoaderData.inline.hpp"
  30 #include "classfile/defaultMethods.hpp"
  31 #include "classfile/dictionary.hpp"
  32 #include "classfile/javaClasses.inline.hpp"
  33 #include "classfile/moduleEntry.hpp"
  34 #include "classfile/symbolTable.hpp"
  35 #include "classfile/systemDictionary.hpp"
  36 #include "classfile/verificationType.hpp"
  37 #include "classfile/verifier.hpp"
  38 #include "classfile/vmSymbols.hpp"
  39 #include "gc/shared/gcLocker.hpp"
  40 #include "logging/log.hpp"
  41 #include "logging/logStream.hpp"
  42 #include "memory/allocation.hpp"
  43 #include "memory/metadataFactory.hpp"
  44 #include "memory/oopFactory.hpp"
  45 #include "memory/resourceArea.hpp"
  46 #include "memory/universe.inline.hpp"
  47 #include "oops/annotations.hpp"
  48 #include "oops/fieldStreams.hpp"
  49 #include "oops/instanceKlass.hpp"
  50 #include "oops/instanceMirrorKlass.hpp"
  51 #include "oops/klass.inline.hpp"
  52 #include "oops/klassVtable.hpp"
  53 #include "oops/metadata.hpp"
  54 #include "oops/method.hpp"
  55 #include "oops/oop.inline.hpp"
  56 #include "oops/symbol.hpp"
  57 #include "prims/jvm.h"
  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   if (_need_verify) {
3183     for (int i = 0; i < length; i++) {
3184       for (int j = i + 1; j < length; j++) {
3185         guarantee_property((nest_members->at(i) != nest_members->at(j)),
3186                            "Duplicate entry in NestMembers in class file %s",
3187                            CHECK_0);
3188       }
3189     }
3190   }
3191   assert(index == size, "wrong size");
3192 
3193   // Restore buffer's current position.
3194   cfs->set_current(current_mark);
3195 
3196   return length;
3197 }
3198 
3199 void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
3200   set_class_synthetic_flag(true);
3201 }
3202 
3203 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3204   assert(cfs != NULL, "invariant");
3205 
3206   const u2 signature_index = cfs->get_u2(CHECK);
3207   check_property(
3208     valid_symbol_at(signature_index),
3209     "Invalid constant pool index %u in Signature attribute in class file %s",
3210     signature_index, CHECK);
3211   set_class_generic_signature_index(signature_index);
3212 }
3213 
3214 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3215                                                                   ConstantPool* cp,
3216                                                                   u4 attribute_byte_length,
3217                                                                   TRAPS) {
3218   assert(cfs != NULL, "invariant");
3219   assert(cp != NULL, "invariant");
3220 
3221   const u1* const current_start = cfs->current();
3222 
3223   guarantee_property(attribute_byte_length >= sizeof(u2),
3224                      "Invalid BootstrapMethods attribute length %u in class file %s",
3225                      attribute_byte_length,
3226                      CHECK);
3227 
3228   cfs->guarantee_more(attribute_byte_length, CHECK);
3229 
3230   const int attribute_array_length = cfs->get_u2_fast();
3231 
3232   guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
3233                      "Short length on BootstrapMethods in class file %s",
3234                      CHECK);
3235 
3236 
3237   // The attribute contains a counted array of counted tuples of shorts,
3238   // represending bootstrap specifiers:
3239   //    length*{bootstrap_method_index, argument_count*{argument_index}}
3240   const int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3241   // operand_count = number of shorts in attr, except for leading length
3242 
3243   // The attribute is copied into a short[] array.
3244   // The array begins with a series of short[2] pairs, one for each tuple.
3245   const int index_size = (attribute_array_length * 2);
3246 
3247   Array<u2>* const operands =
3248     MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
3249 
3250   // Eagerly assign operands so they will be deallocated with the constant
3251   // pool if there is an error.
3252   cp->set_operands(operands);
3253 
3254   int operand_fill_index = index_size;
3255   const int cp_size = cp->length();
3256 
3257   for (int n = 0; n < attribute_array_length; n++) {
3258     // Store a 32-bit offset into the header of the operand array.
3259     ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
3260 
3261     // Read a bootstrap specifier.
3262     cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
3263     const u2 bootstrap_method_index = cfs->get_u2_fast();
3264     const u2 argument_count = cfs->get_u2_fast();
3265     check_property(
3266       valid_cp_range(bootstrap_method_index, cp_size) &&
3267       cp->tag_at(bootstrap_method_index).is_method_handle(),
3268       "bootstrap_method_index %u has bad constant type in class file %s",
3269       bootstrap_method_index,
3270       CHECK);
3271 
3272     guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
3273       "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
3274       CHECK);
3275 
3276     operands->at_put(operand_fill_index++, bootstrap_method_index);
3277     operands->at_put(operand_fill_index++, argument_count);
3278 
3279     cfs->guarantee_more(sizeof(u2) * argument_count, CHECK);  // argv[argc]
3280     for (int j = 0; j < argument_count; j++) {
3281       const u2 argument_index = cfs->get_u2_fast();
3282       check_property(
3283         valid_cp_range(argument_index, cp_size) &&
3284         cp->tag_at(argument_index).is_loadable_constant(),
3285         "argument_index %u has bad constant type in class file %s",
3286         argument_index,
3287         CHECK);
3288       operands->at_put(operand_fill_index++, argument_index);
3289     }
3290   }
3291   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3292                      "Bad length on BootstrapMethods in class file %s",
3293                      CHECK);
3294 }
3295 
3296 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3297                                                  ConstantPool* cp,
3298                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3299                                                  TRAPS) {
3300   assert(cfs != NULL, "invariant");
3301   assert(cp != NULL, "invariant");
3302   assert(parsed_annotations != NULL, "invariant");
3303 
3304   // Set inner classes attribute to default sentinel
3305   _inner_classes = Universe::the_empty_short_array();
3306   // Set nest members attribute to default sentinel
3307   _nest_members = Universe::the_empty_short_array();
3308   cfs->guarantee_more(2, CHECK);  // attributes_count
3309   u2 attributes_count = cfs->get_u2_fast();
3310   bool parsed_sourcefile_attribute = false;
3311   bool parsed_innerclasses_attribute = false;
3312   bool parsed_nest_members_attribute = false;
3313   bool parsed_member_of_nest_attribute = false;
3314   bool parsed_enclosingmethod_attribute = false;
3315   bool parsed_bootstrap_methods_attribute = false;
3316   const u1* runtime_visible_annotations = NULL;
3317   int runtime_visible_annotations_length = 0;
3318   const u1* runtime_invisible_annotations = NULL;
3319   int runtime_invisible_annotations_length = 0;
3320   const u1* runtime_visible_type_annotations = NULL;
3321   int runtime_visible_type_annotations_length = 0;
3322   const u1* runtime_invisible_type_annotations = NULL;
3323   int runtime_invisible_type_annotations_length = 0;
3324   bool runtime_invisible_type_annotations_exists = false;
3325   bool runtime_invisible_annotations_exists = false;
3326   bool parsed_source_debug_ext_annotations_exist = false;
3327   const u1* inner_classes_attribute_start = NULL;
3328   u4  inner_classes_attribute_length = 0;
3329   u2  enclosing_method_class_index = 0;
3330   u2  enclosing_method_method_index = 0;
3331   const u1* nest_members_attribute_start = NULL;
3332   u4  nest_members_attribute_length = 0;
3333 
3334   // Iterate over attributes
3335   while (attributes_count--) {
3336     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3337     const u2 attribute_name_index = cfs->get_u2_fast();
3338     const u4 attribute_length = cfs->get_u4_fast();
3339     check_property(
3340       valid_symbol_at(attribute_name_index),
3341       "Attribute name has bad constant pool index %u in class file %s",
3342       attribute_name_index, CHECK);
3343     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3344     if (tag == vmSymbols::tag_source_file()) {
3345       // Check for SourceFile tag
3346       if (_need_verify) {
3347         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3348       }
3349       if (parsed_sourcefile_attribute) {
3350         classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
3351       } else {
3352         parsed_sourcefile_attribute = true;
3353       }
3354       parse_classfile_sourcefile_attribute(cfs, CHECK);
3355     } else if (tag == vmSymbols::tag_source_debug_extension()) {
3356       // Check for SourceDebugExtension tag
3357       if (parsed_source_debug_ext_annotations_exist) {
3358           classfile_parse_error(
3359             "Multiple SourceDebugExtension attributes in class file %s", CHECK);
3360       }
3361       parsed_source_debug_ext_annotations_exist = true;
3362       parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3363     } else if (tag == vmSymbols::tag_inner_classes()) {
3364       // Check for InnerClasses tag
3365       if (parsed_innerclasses_attribute) {
3366         classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
3367       } else {
3368         parsed_innerclasses_attribute = true;
3369       }
3370       inner_classes_attribute_start = cfs->current();
3371       inner_classes_attribute_length = attribute_length;
3372       cfs->skip_u1(inner_classes_attribute_length, CHECK);
3373     } else if (tag == vmSymbols::tag_nest_members()) {
3374       // Check for NestMembers tag
3375       if (parsed_nest_members_attribute) {
3376         classfile_parse_error("Multiple NestMembers attributes in class file %s", CHECK);
3377       } else {
3378         parsed_nest_members_attribute = true;
3379       }
3380       if (parsed_member_of_nest_attribute) {
3381         classfile_parse_error("Conflicting MemberOfNest and NestMembers attributes in class file %s", CHECK);
3382       }
3383       nest_members_attribute_start = cfs->current();
3384       nest_members_attribute_length = attribute_length;
3385       cfs->skip_u1(nest_members_attribute_length, CHECK);
3386     } else if (tag == vmSymbols::tag_member_of_nest()) {
3387       if (parsed_member_of_nest_attribute) {
3388         classfile_parse_error("Multiple MemberOfNest attributes in class file %s", CHECK);
3389       } else {
3390         parsed_member_of_nest_attribute = true;
3391       }
3392       if (parsed_nest_members_attribute) {
3393         classfile_parse_error("Conflicting NestMembers and MemberOfNest attributes in class file %s", CHECK);
3394       }
3395       cfs->guarantee_more(2, CHECK);
3396       u2 class_info_index = cfs->get_u2_fast();
3397       check_property(
3398         valid_klass_reference_at(class_info_index),
3399         "Nest top class_info_index %u has bad constant type in class file %s",
3400         class_info_index, CHECK);
3401       _nest_top = class_info_index;
3402     } else if (tag == vmSymbols::tag_synthetic()) {
3403       // Check for Synthetic tag
3404       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3405       if (attribute_length != 0) {
3406         classfile_parse_error(
3407           "Invalid Synthetic classfile attribute length %u in class file %s",
3408           attribute_length, CHECK);
3409       }
3410       parse_classfile_synthetic_attribute(CHECK);
3411     } else if (tag == vmSymbols::tag_deprecated()) {
3412       // Check for Deprecatd tag - 4276120
3413       if (attribute_length != 0) {
3414         classfile_parse_error(
3415           "Invalid Deprecated classfile attribute length %u in class file %s",
3416           attribute_length, CHECK);
3417       }
3418     } else if (_major_version >= JAVA_1_5_VERSION) {
3419       if (tag == vmSymbols::tag_signature()) {
3420         if (_generic_signature_index != 0) {
3421           classfile_parse_error(
3422             "Multiple Signature attributes in class file %s", CHECK);
3423         }
3424         if (attribute_length != 2) {
3425           classfile_parse_error(
3426             "Wrong Signature attribute length %u in class file %s",
3427             attribute_length, CHECK);
3428         }
3429         parse_classfile_signature_attribute(cfs, CHECK);
3430       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3431         if (runtime_visible_annotations != NULL) {
3432           classfile_parse_error(
3433             "Multiple RuntimeVisibleAnnotations attributes in class file %s", CHECK);
3434         }
3435         runtime_visible_annotations_length = attribute_length;
3436         runtime_visible_annotations = cfs->current();
3437         assert(runtime_visible_annotations != NULL, "null visible annotations");
3438         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3439         parse_annotations(cp,
3440                           runtime_visible_annotations,
3441                           runtime_visible_annotations_length,
3442                           parsed_annotations,
3443                           _loader_data,
3444                           CHECK);
3445         cfs->skip_u1_fast(runtime_visible_annotations_length);
3446       } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3447         if (runtime_invisible_annotations_exists) {
3448           classfile_parse_error(
3449             "Multiple RuntimeInvisibleAnnotations attributes in class file %s", CHECK);
3450         }
3451         runtime_invisible_annotations_exists = true;
3452         if (PreserveAllAnnotations) {
3453           runtime_invisible_annotations_length = attribute_length;
3454           runtime_invisible_annotations = cfs->current();
3455           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
3456         }
3457         cfs->skip_u1(attribute_length, CHECK);
3458       } else if (tag == vmSymbols::tag_enclosing_method()) {
3459         if (parsed_enclosingmethod_attribute) {
3460           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
3461         } else {
3462           parsed_enclosingmethod_attribute = true;
3463         }
3464         guarantee_property(attribute_length == 4,
3465           "Wrong EnclosingMethod attribute length %u in class file %s",
3466           attribute_length, CHECK);
3467         cfs->guarantee_more(4, CHECK);  // class_index, method_index
3468         enclosing_method_class_index  = cfs->get_u2_fast();
3469         enclosing_method_method_index = cfs->get_u2_fast();
3470         if (enclosing_method_class_index == 0) {
3471           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
3472         }
3473         // Validate the constant pool indices and types
3474         check_property(valid_klass_reference_at(enclosing_method_class_index),
3475           "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3476         if (enclosing_method_method_index != 0 &&
3477             (!cp->is_within_bounds(enclosing_method_method_index) ||
3478              !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3479           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
3480         }
3481       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3482                  _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3483         if (parsed_bootstrap_methods_attribute) {
3484           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
3485         }
3486         parsed_bootstrap_methods_attribute = true;
3487         parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3488       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3489         if (runtime_visible_type_annotations != NULL) {
3490           classfile_parse_error(
3491             "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);
3492         }
3493         runtime_visible_type_annotations_length = attribute_length;
3494         runtime_visible_type_annotations = cfs->current();
3495         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
3496         // No need for the VM to parse Type annotations
3497         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3498       } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3499         if (runtime_invisible_type_annotations_exists) {
3500           classfile_parse_error(
3501             "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);
3502         } else {
3503           runtime_invisible_type_annotations_exists = true;
3504         }
3505         if (PreserveAllAnnotations) {
3506           runtime_invisible_type_annotations_length = attribute_length;
3507           runtime_invisible_type_annotations = cfs->current();
3508           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
3509         }
3510         cfs->skip_u1(attribute_length, CHECK);
3511       } else {
3512         // Unknown attribute
3513         cfs->skip_u1(attribute_length, CHECK);
3514       }
3515     } else {
3516       // Unknown attribute
3517       cfs->skip_u1(attribute_length, CHECK);
3518     }
3519   }
3520   _annotations = assemble_annotations(runtime_visible_annotations,
3521                                       runtime_visible_annotations_length,
3522                                       runtime_invisible_annotations,
3523                                       runtime_invisible_annotations_length,
3524                                       CHECK);
3525   _type_annotations = assemble_annotations(runtime_visible_type_annotations,
3526                                            runtime_visible_type_annotations_length,
3527                                            runtime_invisible_type_annotations,
3528                                            runtime_invisible_type_annotations_length,
3529                                            CHECK);
3530 
3531   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3532     const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3533                             cfs,
3534                             inner_classes_attribute_start,
3535                             parsed_innerclasses_attribute,
3536                             enclosing_method_class_index,
3537                             enclosing_method_method_index,
3538                             CHECK);
3539     if (parsed_innerclasses_attribute && _need_verify && _major_version >= JAVA_1_5_VERSION) {
3540       guarantee_property(
3541         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3542         "Wrong InnerClasses attribute length in class file %s", CHECK);
3543     }
3544   }
3545 
3546   if (parsed_nest_members_attribute) {
3547     const u2 num_of_classes = parse_classfile_nest_members_attribute(
3548                             cfs,
3549                             nest_members_attribute_start,
3550                             CHECK);
3551     if (_need_verify && _major_version >= JAVA_10_VERSION) {
3552       guarantee_property(
3553         nest_members_attribute_length == sizeof(num_of_classes) + sizeof(u2) * num_of_classes,
3554         "Wrong NestMembers attribute length in class file %s", CHECK);
3555     }
3556   }
3557 
3558   if (_max_bootstrap_specifier_index >= 0) {
3559     guarantee_property(parsed_bootstrap_methods_attribute,
3560                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3561   }
3562 }
3563 
3564 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3565   assert(k != NULL, "invariant");
3566 
3567   if (_synthetic_flag)
3568     k->set_is_synthetic();
3569   if (_sourcefile_index != 0) {
3570     k->set_source_file_name_index(_sourcefile_index);
3571   }
3572   if (_generic_signature_index != 0) {
3573     k->set_generic_signature_index(_generic_signature_index);
3574   }
3575   if (_sde_buffer != NULL) {
3576     k->set_source_debug_extension(_sde_buffer, _sde_length);
3577   }
3578 }
3579 
3580 // Create the Annotations object that will
3581 // hold the annotations array for the Klass.
3582 void ClassFileParser::create_combined_annotations(TRAPS) {
3583     if (_annotations == NULL &&
3584         _type_annotations == NULL &&
3585         _fields_annotations == NULL &&
3586         _fields_type_annotations == NULL) {
3587       // Don't create the Annotations object unnecessarily.
3588       return;
3589     }
3590 
3591     Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3592     annotations->set_class_annotations(_annotations);
3593     annotations->set_class_type_annotations(_type_annotations);
3594     annotations->set_fields_annotations(_fields_annotations);
3595     annotations->set_fields_type_annotations(_fields_type_annotations);
3596 
3597     // This is the Annotations object that will be
3598     // assigned to InstanceKlass being constructed.
3599     _combined_annotations = annotations;
3600 
3601     // The annotations arrays below has been transfered the
3602     // _combined_annotations so these fields can now be cleared.
3603     _annotations             = NULL;
3604     _type_annotations        = NULL;
3605     _fields_annotations      = NULL;
3606     _fields_type_annotations = NULL;
3607 }
3608 
3609 // Transfer ownership of metadata allocated to the InstanceKlass.
3610 void ClassFileParser::apply_parsed_class_metadata(
3611                                             InstanceKlass* this_klass,
3612                                             int java_fields_count, TRAPS) {
3613   assert(this_klass != NULL, "invariant");
3614 
3615   _cp->set_pool_holder(this_klass);
3616   this_klass->set_constants(_cp);
3617   this_klass->set_fields(_fields, java_fields_count);
3618   this_klass->set_methods(_methods);
3619   this_klass->set_inner_classes(_inner_classes);
3620   this_klass->set_nest_members(_nest_members);
3621   this_klass->set_nest_top_index(_nest_top);
3622   this_klass->set_local_interfaces(_local_interfaces);
3623   this_klass->set_transitive_interfaces(_transitive_interfaces);
3624   this_klass->set_annotations(_combined_annotations);
3625 
3626   // Clear out these fields so they don't get deallocated by the destructor
3627   clear_class_metadata();
3628 }
3629 
3630 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3631                                                        int runtime_visible_annotations_length,
3632                                                        const u1* const runtime_invisible_annotations,
3633                                                        int runtime_invisible_annotations_length,
3634                                                        TRAPS) {
3635   AnnotationArray* annotations = NULL;
3636   if (runtime_visible_annotations != NULL ||
3637       runtime_invisible_annotations != NULL) {
3638     annotations = MetadataFactory::new_array<u1>(_loader_data,
3639                                           runtime_visible_annotations_length +
3640                                           runtime_invisible_annotations_length,
3641                                           CHECK_(annotations));
3642     if (runtime_visible_annotations != NULL) {
3643       for (int i = 0; i < runtime_visible_annotations_length; i++) {
3644         annotations->at_put(i, runtime_visible_annotations[i]);
3645       }
3646     }
3647     if (runtime_invisible_annotations != NULL) {
3648       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3649         int append = runtime_visible_annotations_length+i;
3650         annotations->at_put(append, runtime_invisible_annotations[i]);
3651       }
3652     }
3653   }
3654   return annotations;
3655 }
3656 
3657 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3658                                                         const int super_class_index,
3659                                                         const bool need_verify,
3660                                                         TRAPS) {
3661   assert(cp != NULL, "invariant");
3662   const InstanceKlass* super_klass = NULL;
3663 
3664   if (super_class_index == 0) {
3665     check_property(_class_name == vmSymbols::java_lang_Object(),
3666                    "Invalid superclass index %u in class file %s",
3667                    super_class_index,
3668                    CHECK_NULL);
3669   } else {
3670     check_property(valid_klass_reference_at(super_class_index),
3671                    "Invalid superclass index %u in class file %s",
3672                    super_class_index,
3673                    CHECK_NULL);
3674     // The class name should be legal because it is checked when parsing constant pool.
3675     // However, make sure it is not an array type.
3676     bool is_array = false;
3677     if (cp->tag_at(super_class_index).is_klass()) {
3678       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3679       if (need_verify)
3680         is_array = super_klass->is_array_klass();
3681     } else if (need_verify) {
3682       is_array = (cp->klass_name_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
3683     }
3684     if (need_verify) {
3685       guarantee_property(!is_array,
3686                         "Bad superclass name in class file %s", CHECK_NULL);
3687     }
3688   }
3689   return super_klass;
3690 }
3691 
3692 static unsigned int compute_oop_map_count(const InstanceKlass* super,
3693                                           unsigned int nonstatic_oop_map_count,
3694                                           int first_nonstatic_oop_offset) {
3695 
3696   unsigned int map_count =
3697     NULL == super ? 0 : super->nonstatic_oop_map_count();
3698   if (nonstatic_oop_map_count > 0) {
3699     // We have oops to add to map
3700     if (map_count == 0) {
3701       map_count = nonstatic_oop_map_count;
3702     }
3703     else {
3704       // Check whether we should add a new map block or whether the last one can
3705       // be extended
3706       const OopMapBlock* const first_map = super->start_of_nonstatic_oop_maps();
3707       const OopMapBlock* const last_map = first_map + map_count - 1;
3708 
3709       const int next_offset = last_map->offset() + last_map->count() * heapOopSize;
3710       if (next_offset == first_nonstatic_oop_offset) {
3711         // There is no gap bettwen superklass's last oop field and first
3712         // local oop field, merge maps.
3713         nonstatic_oop_map_count -= 1;
3714       }
3715       else {
3716         // Superklass didn't end with a oop field, add extra maps
3717         assert(next_offset < first_nonstatic_oop_offset, "just checking");
3718       }
3719       map_count += nonstatic_oop_map_count;
3720     }
3721   }
3722   return map_count;
3723 }
3724 
3725 #ifndef PRODUCT
3726 static void print_field_layout(const Symbol* name,
3727                                Array<u2>* fields,
3728                                const constantPoolHandle& cp,
3729                                int instance_size,
3730                                int instance_fields_start,
3731                                int instance_fields_end,
3732                                int static_fields_end) {
3733 
3734   assert(name != NULL, "invariant");
3735 
3736   tty->print("%s: field layout\n", name->as_klass_external_name());
3737   tty->print("  @%3d %s\n", instance_fields_start, "--- instance fields start ---");
3738   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3739     if (!fs.access_flags().is_static()) {
3740       tty->print("  @%3d \"%s\" %s\n",
3741         fs.offset(),
3742         fs.name()->as_klass_external_name(),
3743         fs.signature()->as_klass_external_name());
3744     }
3745   }
3746   tty->print("  @%3d %s\n", instance_fields_end, "--- instance fields end ---");
3747   tty->print("  @%3d %s\n", instance_size * wordSize, "--- instance ends ---");
3748   tty->print("  @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");
3749   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3750     if (fs.access_flags().is_static()) {
3751       tty->print("  @%3d \"%s\" %s\n",
3752         fs.offset(),
3753         fs.name()->as_klass_external_name(),
3754         fs.signature()->as_klass_external_name());
3755     }
3756   }
3757   tty->print("  @%3d %s\n", static_fields_end, "--- static fields end ---");
3758   tty->print("\n");
3759 }
3760 #endif
3761 
3762 // Values needed for oopmap and InstanceKlass creation
3763 class ClassFileParser::FieldLayoutInfo : public ResourceObj {
3764  public:
3765   int*          nonstatic_oop_offsets;
3766   unsigned int* nonstatic_oop_counts;
3767   unsigned int  nonstatic_oop_map_count;
3768   unsigned int  total_oop_map_count;
3769   int           instance_size;
3770   int           nonstatic_field_size;
3771   int           static_field_size;
3772   bool          has_nonstatic_fields;
3773 };
3774 
3775 // Layout fields and fill in FieldLayoutInfo.  Could use more refactoring!
3776 void ClassFileParser::layout_fields(ConstantPool* cp,
3777                                     const FieldAllocationCount* fac,
3778                                     const ClassAnnotationCollector* parsed_annotations,
3779                                     FieldLayoutInfo* info,
3780                                     TRAPS) {
3781 
3782   assert(cp != NULL, "invariant");
3783 
3784   // Field size and offset computation
3785   int nonstatic_field_size = _super_klass == NULL ? 0 :
3786                                _super_klass->nonstatic_field_size();
3787 
3788   // Count the contended fields by type.
3789   //
3790   // We ignore static fields, because @Contended is not supported for them.
3791   // The layout code below will also ignore the static fields.
3792   int nonstatic_contended_count = 0;
3793   FieldAllocationCount fac_contended;
3794   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
3795     FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
3796     if (fs.is_contended()) {
3797       fac_contended.count[atype]++;
3798       if (!fs.access_flags().is_static()) {
3799         nonstatic_contended_count++;
3800       }
3801     }
3802   }
3803 
3804 
3805   // Calculate the starting byte offsets
3806   int next_static_oop_offset    = InstanceMirrorKlass::offset_of_static_fields();
3807   int next_static_double_offset = next_static_oop_offset +
3808                                       ((fac->count[STATIC_OOP]) * heapOopSize);
3809   if ( fac->count[STATIC_DOUBLE] &&
3810        (Universe::field_type_should_be_aligned(T_DOUBLE) ||
3811         Universe::field_type_should_be_aligned(T_LONG)) ) {
3812     next_static_double_offset = align_up(next_static_double_offset, BytesPerLong);
3813   }
3814 
3815   int next_static_word_offset   = next_static_double_offset +
3816                                     ((fac->count[STATIC_DOUBLE]) * BytesPerLong);
3817   int next_static_short_offset  = next_static_word_offset +
3818                                     ((fac->count[STATIC_WORD]) * BytesPerInt);
3819   int next_static_byte_offset   = next_static_short_offset +
3820                                   ((fac->count[STATIC_SHORT]) * BytesPerShort);
3821 
3822   int nonstatic_fields_start  = instanceOopDesc::base_offset_in_bytes() +
3823                                 nonstatic_field_size * heapOopSize;
3824 
3825   int next_nonstatic_field_offset = nonstatic_fields_start;
3826 
3827   const bool is_contended_class     = parsed_annotations->is_contended();
3828 
3829   // Class is contended, pad before all the fields
3830   if (is_contended_class) {
3831     next_nonstatic_field_offset += ContendedPaddingWidth;
3832   }
3833 
3834   // Compute the non-contended fields count.
3835   // The packing code below relies on these counts to determine if some field
3836   // can be squeezed into the alignment gap. Contended fields are obviously
3837   // exempt from that.
3838   unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
3839   unsigned int nonstatic_word_count   = fac->count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
3840   unsigned int nonstatic_short_count  = fac->count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
3841   unsigned int nonstatic_byte_count   = fac->count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
3842   unsigned int nonstatic_oop_count    = fac->count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];
3843 
3844   // Total non-static fields count, including every contended field
3845   unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +
3846                                         fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +
3847                                         fac->count[NONSTATIC_OOP];
3848 
3849   const bool super_has_nonstatic_fields =
3850           (_super_klass != NULL && _super_klass->has_nonstatic_fields());
3851   const bool has_nonstatic_fields =
3852     super_has_nonstatic_fields || (nonstatic_fields_count != 0);
3853 
3854 
3855   // Prepare list of oops for oop map generation.
3856   //
3857   // "offset" and "count" lists are describing the set of contiguous oop
3858   // regions. offset[i] is the start of the i-th region, which then has
3859   // count[i] oops following. Before we know how many regions are required,
3860   // we pessimistically allocate the maps to fit all the oops into the
3861   // distinct regions.
3862   //
3863   // TODO: We add +1 to always allocate non-zero resource arrays; we need
3864   // to figure out if we still need to do this.
3865   unsigned int nonstatic_oop_map_count = 0;
3866   unsigned int max_nonstatic_oop_maps  = fac->count[NONSTATIC_OOP] + 1;
3867 
3868   int* nonstatic_oop_offsets = NEW_RESOURCE_ARRAY_IN_THREAD(
3869             THREAD, int, max_nonstatic_oop_maps);
3870   unsigned int* const nonstatic_oop_counts  = NEW_RESOURCE_ARRAY_IN_THREAD(
3871             THREAD, unsigned int, max_nonstatic_oop_maps);
3872 
3873   int first_nonstatic_oop_offset = 0; // will be set for first oop field
3874 
3875   bool compact_fields   = CompactFields;
3876   int allocation_style = FieldsAllocationStyle;
3877   if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
3878     assert(false, "0 <= FieldsAllocationStyle <= 2");
3879     allocation_style = 1; // Optimistic
3880   }
3881 
3882   // The next classes have predefined hard-coded fields offsets
3883   // (see in JavaClasses::compute_hard_coded_offsets()).
3884   // Use default fields allocation order for them.
3885   if( (allocation_style != 0 || compact_fields ) && _loader_data->class_loader() == NULL &&
3886       (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
3887        _class_name == vmSymbols::java_lang_Class() ||
3888        _class_name == vmSymbols::java_lang_ClassLoader() ||
3889        _class_name == vmSymbols::java_lang_ref_Reference() ||
3890        _class_name == vmSymbols::java_lang_ref_SoftReference() ||
3891        _class_name == vmSymbols::java_lang_StackTraceElement() ||
3892        _class_name == vmSymbols::java_lang_String() ||
3893        _class_name == vmSymbols::java_lang_Throwable() ||
3894        _class_name == vmSymbols::java_lang_Boolean() ||
3895        _class_name == vmSymbols::java_lang_Character() ||
3896        _class_name == vmSymbols::java_lang_Float() ||
3897        _class_name == vmSymbols::java_lang_Double() ||
3898        _class_name == vmSymbols::java_lang_Byte() ||
3899        _class_name == vmSymbols::java_lang_Short() ||
3900        _class_name == vmSymbols::java_lang_Integer() ||
3901        _class_name == vmSymbols::java_lang_Long())) {
3902     allocation_style = 0;     // Allocate oops first
3903     compact_fields   = false; // Don't compact fields
3904   }
3905 
3906   int next_nonstatic_oop_offset = 0;
3907   int next_nonstatic_double_offset = 0;
3908 
3909   // Rearrange fields for a given allocation style
3910   if( allocation_style == 0 ) {
3911     // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
3912     next_nonstatic_oop_offset    = next_nonstatic_field_offset;
3913     next_nonstatic_double_offset = next_nonstatic_oop_offset +
3914                                     (nonstatic_oop_count * heapOopSize);
3915   } else if( allocation_style == 1 ) {
3916     // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
3917     next_nonstatic_double_offset = next_nonstatic_field_offset;
3918   } else if( allocation_style == 2 ) {
3919     // Fields allocation: oops fields in super and sub classes are together.
3920     if( nonstatic_field_size > 0 && _super_klass != NULL &&
3921         _super_klass->nonstatic_oop_map_size() > 0 ) {
3922       const unsigned int map_count = _super_klass->nonstatic_oop_map_count();
3923       const OopMapBlock* const first_map = _super_klass->start_of_nonstatic_oop_maps();
3924       const OopMapBlock* const last_map = first_map + map_count - 1;
3925       const int next_offset = last_map->offset() + (last_map->count() * heapOopSize);
3926       if (next_offset == next_nonstatic_field_offset) {
3927         allocation_style = 0;   // allocate oops first
3928         next_nonstatic_oop_offset    = next_nonstatic_field_offset;
3929         next_nonstatic_double_offset = next_nonstatic_oop_offset +
3930                                        (nonstatic_oop_count * heapOopSize);
3931       }
3932     }
3933     if( allocation_style == 2 ) {
3934       allocation_style = 1;     // allocate oops last
3935       next_nonstatic_double_offset = next_nonstatic_field_offset;
3936     }
3937   } else {
3938     ShouldNotReachHere();
3939   }
3940 
3941   int nonstatic_oop_space_count   = 0;
3942   int nonstatic_word_space_count  = 0;
3943   int nonstatic_short_space_count = 0;
3944   int nonstatic_byte_space_count  = 0;
3945   int nonstatic_oop_space_offset = 0;
3946   int nonstatic_word_space_offset = 0;
3947   int nonstatic_short_space_offset = 0;
3948   int nonstatic_byte_space_offset = 0;
3949 
3950   // Try to squeeze some of the fields into the gaps due to
3951   // long/double alignment.
3952   if (nonstatic_double_count > 0) {
3953     int offset = next_nonstatic_double_offset;
3954     next_nonstatic_double_offset = align_up(offset, BytesPerLong);
3955     if (compact_fields && offset != next_nonstatic_double_offset) {
3956       // Allocate available fields into the gap before double field.
3957       int length = next_nonstatic_double_offset - offset;
3958       assert(length == BytesPerInt, "");
3959       nonstatic_word_space_offset = offset;
3960       if (nonstatic_word_count > 0) {
3961         nonstatic_word_count      -= 1;
3962         nonstatic_word_space_count = 1; // Only one will fit
3963         length -= BytesPerInt;
3964         offset += BytesPerInt;
3965       }
3966       nonstatic_short_space_offset = offset;
3967       while (length >= BytesPerShort && nonstatic_short_count > 0) {
3968         nonstatic_short_count       -= 1;
3969         nonstatic_short_space_count += 1;
3970         length -= BytesPerShort;
3971         offset += BytesPerShort;
3972       }
3973       nonstatic_byte_space_offset = offset;
3974       while (length > 0 && nonstatic_byte_count > 0) {
3975         nonstatic_byte_count       -= 1;
3976         nonstatic_byte_space_count += 1;
3977         length -= 1;
3978       }
3979       // Allocate oop field in the gap if there are no other fields for that.
3980       nonstatic_oop_space_offset = offset;
3981       if (length >= heapOopSize && nonstatic_oop_count > 0 &&
3982           allocation_style != 0) { // when oop fields not first
3983         nonstatic_oop_count      -= 1;
3984         nonstatic_oop_space_count = 1; // Only one will fit
3985         length -= heapOopSize;
3986         offset += heapOopSize;
3987       }
3988     }
3989   }
3990 
3991   int next_nonstatic_word_offset = next_nonstatic_double_offset +
3992                                      (nonstatic_double_count * BytesPerLong);
3993   int next_nonstatic_short_offset = next_nonstatic_word_offset +
3994                                       (nonstatic_word_count * BytesPerInt);
3995   int next_nonstatic_byte_offset = next_nonstatic_short_offset +
3996                                      (nonstatic_short_count * BytesPerShort);
3997   int next_nonstatic_padded_offset = next_nonstatic_byte_offset +
3998                                        nonstatic_byte_count;
3999 
4000   // let oops jump before padding with this allocation style
4001   if( allocation_style == 1 ) {
4002     next_nonstatic_oop_offset = next_nonstatic_padded_offset;
4003     if( nonstatic_oop_count > 0 ) {
4004       next_nonstatic_oop_offset = align_up(next_nonstatic_oop_offset, heapOopSize);
4005     }
4006     next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
4007   }
4008 
4009   // Iterate over fields again and compute correct offsets.
4010   // The field allocation type was temporarily stored in the offset slot.
4011   // oop fields are located before non-oop fields (static and non-static).
4012   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4013 
4014     // skip already laid out fields
4015     if (fs.is_offset_set()) continue;
4016 
4017     // contended instance fields are handled below
4018     if (fs.is_contended() && !fs.access_flags().is_static()) continue;
4019 
4020     int real_offset = 0;
4021     const FieldAllocationType atype = (const FieldAllocationType) fs.allocation_type();
4022 
4023     // pack the rest of the fields
4024     switch (atype) {
4025       case STATIC_OOP:
4026         real_offset = next_static_oop_offset;
4027         next_static_oop_offset += heapOopSize;
4028         break;
4029       case STATIC_BYTE:
4030         real_offset = next_static_byte_offset;
4031         next_static_byte_offset += 1;
4032         break;
4033       case STATIC_SHORT:
4034         real_offset = next_static_short_offset;
4035         next_static_short_offset += BytesPerShort;
4036         break;
4037       case STATIC_WORD:
4038         real_offset = next_static_word_offset;
4039         next_static_word_offset += BytesPerInt;
4040         break;
4041       case STATIC_DOUBLE:
4042         real_offset = next_static_double_offset;
4043         next_static_double_offset += BytesPerLong;
4044         break;
4045       case NONSTATIC_OOP:
4046         if( nonstatic_oop_space_count > 0 ) {
4047           real_offset = nonstatic_oop_space_offset;
4048           nonstatic_oop_space_offset += heapOopSize;
4049           nonstatic_oop_space_count  -= 1;
4050         } else {
4051           real_offset = next_nonstatic_oop_offset;
4052           next_nonstatic_oop_offset += heapOopSize;
4053         }
4054 
4055         // Record this oop in the oop maps
4056         if( nonstatic_oop_map_count > 0 &&
4057             nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
4058             real_offset -
4059             int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
4060             heapOopSize ) {
4061           // This oop is adjacent to the previous one, add to current oop map
4062           assert(nonstatic_oop_map_count - 1 < max_nonstatic_oop_maps, "range check");
4063           nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
4064         } else {
4065           // This oop is not adjacent to the previous one, create new oop map
4066           assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");
4067           nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
4068           nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
4069           nonstatic_oop_map_count += 1;
4070           if( first_nonstatic_oop_offset == 0 ) { // Undefined
4071             first_nonstatic_oop_offset = real_offset;
4072           }
4073         }
4074         break;
4075       case NONSTATIC_BYTE:
4076         if( nonstatic_byte_space_count > 0 ) {
4077           real_offset = nonstatic_byte_space_offset;
4078           nonstatic_byte_space_offset += 1;
4079           nonstatic_byte_space_count  -= 1;
4080         } else {
4081           real_offset = next_nonstatic_byte_offset;
4082           next_nonstatic_byte_offset += 1;
4083         }
4084         break;
4085       case NONSTATIC_SHORT:
4086         if( nonstatic_short_space_count > 0 ) {
4087           real_offset = nonstatic_short_space_offset;
4088           nonstatic_short_space_offset += BytesPerShort;
4089           nonstatic_short_space_count  -= 1;
4090         } else {
4091           real_offset = next_nonstatic_short_offset;
4092           next_nonstatic_short_offset += BytesPerShort;
4093         }
4094         break;
4095       case NONSTATIC_WORD:
4096         if( nonstatic_word_space_count > 0 ) {
4097           real_offset = nonstatic_word_space_offset;
4098           nonstatic_word_space_offset += BytesPerInt;
4099           nonstatic_word_space_count  -= 1;
4100         } else {
4101           real_offset = next_nonstatic_word_offset;
4102           next_nonstatic_word_offset += BytesPerInt;
4103         }
4104         break;
4105       case NONSTATIC_DOUBLE:
4106         real_offset = next_nonstatic_double_offset;
4107         next_nonstatic_double_offset += BytesPerLong;
4108         break;
4109       default:
4110         ShouldNotReachHere();
4111     }
4112     fs.set_offset(real_offset);
4113   }
4114 
4115 
4116   // Handle the contended cases.
4117   //
4118   // Each contended field should not intersect the cache line with another contended field.
4119   // In the absence of alignment information, we end up with pessimistically separating
4120   // the fields with full-width padding.
4121   //
4122   // Additionally, this should not break alignment for the fields, so we round the alignment up
4123   // for each field.
4124   if (nonstatic_contended_count > 0) {
4125 
4126     // if there is at least one contended field, we need to have pre-padding for them
4127     next_nonstatic_padded_offset += ContendedPaddingWidth;
4128 
4129     // collect all contended groups
4130     ResourceBitMap bm(cp->size());
4131     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4132       // skip already laid out fields
4133       if (fs.is_offset_set()) continue;
4134 
4135       if (fs.is_contended()) {
4136         bm.set_bit(fs.contended_group());
4137       }
4138     }
4139 
4140     int current_group = -1;
4141     while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
4142 
4143       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4144 
4145         // skip already laid out fields
4146         if (fs.is_offset_set()) continue;
4147 
4148         // skip non-contended fields and fields from different group
4149         if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
4150 
4151         // handle statics below
4152         if (fs.access_flags().is_static()) continue;
4153 
4154         int real_offset = 0;
4155         FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
4156 
4157         switch (atype) {
4158           case NONSTATIC_BYTE:
4159             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, 1);
4160             real_offset = next_nonstatic_padded_offset;
4161             next_nonstatic_padded_offset += 1;
4162             break;
4163 
4164           case NONSTATIC_SHORT:
4165             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerShort);
4166             real_offset = next_nonstatic_padded_offset;
4167             next_nonstatic_padded_offset += BytesPerShort;
4168             break;
4169 
4170           case NONSTATIC_WORD:
4171             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerInt);
4172             real_offset = next_nonstatic_padded_offset;
4173             next_nonstatic_padded_offset += BytesPerInt;
4174             break;
4175 
4176           case NONSTATIC_DOUBLE:
4177             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4178             real_offset = next_nonstatic_padded_offset;
4179             next_nonstatic_padded_offset += BytesPerLong;
4180             break;
4181 
4182           case NONSTATIC_OOP:
4183             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, heapOopSize);
4184             real_offset = next_nonstatic_padded_offset;
4185             next_nonstatic_padded_offset += heapOopSize;
4186 
4187             // Record this oop in the oop maps
4188             if( nonstatic_oop_map_count > 0 &&
4189                 nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
4190                 real_offset -
4191                 int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
4192                 heapOopSize ) {
4193               // This oop is adjacent to the previous one, add to current oop map
4194               assert(nonstatic_oop_map_count - 1 < max_nonstatic_oop_maps, "range check");
4195               nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
4196             } else {
4197               // This oop is not adjacent to the previous one, create new oop map
4198               assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");
4199               nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
4200               nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
4201               nonstatic_oop_map_count += 1;
4202               if( first_nonstatic_oop_offset == 0 ) { // Undefined
4203                 first_nonstatic_oop_offset = real_offset;
4204               }
4205             }
4206             break;
4207 
4208           default:
4209             ShouldNotReachHere();
4210         }
4211 
4212         if (fs.contended_group() == 0) {
4213           // Contended group defines the equivalence class over the fields:
4214           // the fields within the same contended group are not inter-padded.
4215           // The only exception is default group, which does not incur the
4216           // equivalence, and so requires intra-padding.
4217           next_nonstatic_padded_offset += ContendedPaddingWidth;
4218         }
4219 
4220         fs.set_offset(real_offset);
4221       } // for
4222 
4223       // Start laying out the next group.
4224       // Note that this will effectively pad the last group in the back;
4225       // this is expected to alleviate memory contention effects for
4226       // subclass fields and/or adjacent object.
4227       // If this was the default group, the padding is already in place.
4228       if (current_group != 0) {
4229         next_nonstatic_padded_offset += ContendedPaddingWidth;
4230       }
4231     }
4232 
4233     // handle static fields
4234   }
4235 
4236   // Entire class is contended, pad in the back.
4237   // This helps to alleviate memory contention effects for subclass fields
4238   // and/or adjacent object.
4239   if (is_contended_class) {
4240     next_nonstatic_padded_offset += ContendedPaddingWidth;
4241   }
4242 
4243   int notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;
4244 
4245   int nonstatic_fields_end      = align_up(notaligned_nonstatic_fields_end, heapOopSize);
4246   int instance_end              = align_up(notaligned_nonstatic_fields_end, wordSize);
4247   int static_fields_end         = align_up(next_static_byte_offset, wordSize);
4248 
4249   int static_field_size         = (static_fields_end -
4250                                    InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
4251   nonstatic_field_size          = nonstatic_field_size +
4252                                   (nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
4253 
4254   int instance_size             = align_object_size(instance_end / wordSize);
4255 
4256   assert(instance_size == align_object_size(align_up(
4257          (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize),
4258           wordSize) / wordSize), "consistent layout helper value");
4259 
4260   // Invariant: nonstatic_field end/start should only change if there are
4261   // nonstatic fields in the class, or if the class is contended. We compare
4262   // against the non-aligned value, so that end alignment will not fail the
4263   // assert without actually having the fields.
4264   assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
4265          is_contended_class ||
4266          (nonstatic_fields_count > 0), "double-check nonstatic start/end");
4267 
4268   // Number of non-static oop map blocks allocated at end of klass.
4269   const unsigned int total_oop_map_count =
4270     compute_oop_map_count(_super_klass, nonstatic_oop_map_count,
4271                           first_nonstatic_oop_offset);
4272 
4273 #ifndef PRODUCT
4274   if (PrintFieldLayout) {
4275     print_field_layout(_class_name,
4276           _fields,
4277           cp,
4278           instance_size,
4279           nonstatic_fields_start,
4280           nonstatic_fields_end,
4281           static_fields_end);
4282   }
4283 
4284 #endif
4285   // Pass back information needed for InstanceKlass creation
4286   info->nonstatic_oop_offsets = nonstatic_oop_offsets;
4287   info->nonstatic_oop_counts = nonstatic_oop_counts;
4288   info->nonstatic_oop_map_count = nonstatic_oop_map_count;
4289   info->total_oop_map_count = total_oop_map_count;
4290   info->instance_size = instance_size;
4291   info->static_field_size = static_field_size;
4292   info->nonstatic_field_size = nonstatic_field_size;
4293   info->has_nonstatic_fields = has_nonstatic_fields;
4294 }
4295 
4296 static void fill_oop_maps(const InstanceKlass* k,
4297                           unsigned int nonstatic_oop_map_count,
4298                           const int* nonstatic_oop_offsets,
4299                           const unsigned int* nonstatic_oop_counts) {
4300 
4301   assert(k != NULL, "invariant");
4302 
4303   OopMapBlock* this_oop_map = k->start_of_nonstatic_oop_maps();
4304   const InstanceKlass* const super = k->superklass();
4305   const unsigned int super_count = super ? super->nonstatic_oop_map_count() : 0;
4306   if (super_count > 0) {
4307     // Copy maps from superklass
4308     OopMapBlock* super_oop_map = super->start_of_nonstatic_oop_maps();
4309     for (unsigned int i = 0; i < super_count; ++i) {
4310       *this_oop_map++ = *super_oop_map++;
4311     }
4312   }
4313 
4314   if (nonstatic_oop_map_count > 0) {
4315     if (super_count + nonstatic_oop_map_count > k->nonstatic_oop_map_count()) {
4316       // The counts differ because there is no gap between superklass's last oop
4317       // field and the first local oop field.  Extend the last oop map copied
4318       // from the superklass instead of creating new one.
4319       nonstatic_oop_map_count--;
4320       nonstatic_oop_offsets++;
4321       this_oop_map--;
4322       this_oop_map->set_count(this_oop_map->count() + *nonstatic_oop_counts++);
4323       this_oop_map++;
4324     }
4325 
4326     // Add new map blocks, fill them
4327     while (nonstatic_oop_map_count-- > 0) {
4328       this_oop_map->set_offset(*nonstatic_oop_offsets++);
4329       this_oop_map->set_count(*nonstatic_oop_counts++);
4330       this_oop_map++;
4331     }
4332     assert(k->start_of_nonstatic_oop_maps() + k->nonstatic_oop_map_count() ==
4333            this_oop_map, "sanity");
4334   }
4335 }
4336 
4337 
4338 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4339   assert(ik != NULL, "invariant");
4340 
4341   const Klass* const super = ik->super();
4342 
4343   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4344   // in which case we don't have to register objects as finalizable
4345   if (!_has_empty_finalizer) {
4346     if (_has_finalizer ||
4347         (super != NULL && super->has_finalizer())) {
4348       ik->set_has_finalizer();
4349     }
4350   }
4351 
4352 #ifdef ASSERT
4353   bool f = false;
4354   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4355                                            vmSymbols::void_method_signature());
4356   if (m != NULL && !m->is_empty_method()) {
4357       f = true;
4358   }
4359 
4360   // Spec doesn't prevent agent from redefinition of empty finalizer.
4361   // Despite the fact that it's generally bad idea and redefined finalizer
4362   // will not work as expected we shouldn't abort vm in this case
4363   if (!ik->has_redefined_this_or_super()) {
4364     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4365   }
4366 #endif
4367 
4368   // Check if this klass supports the java.lang.Cloneable interface
4369   if (SystemDictionary::Cloneable_klass_loaded()) {
4370     if (ik->is_subtype_of(SystemDictionary::Cloneable_klass())) {
4371       ik->set_is_cloneable();
4372     }
4373   }
4374 
4375   // Check if this klass has a vanilla default constructor
4376   if (super == NULL) {
4377     // java.lang.Object has empty default constructor
4378     ik->set_has_vanilla_constructor();
4379   } else {
4380     if (super->has_vanilla_constructor() &&
4381         _has_vanilla_constructor) {
4382       ik->set_has_vanilla_constructor();
4383     }
4384 #ifdef ASSERT
4385     bool v = false;
4386     if (super->has_vanilla_constructor()) {
4387       const Method* const constructor =
4388         ik->find_method(vmSymbols::object_initializer_name(),
4389                        vmSymbols::void_method_signature());
4390       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4391         v = true;
4392       }
4393     }
4394     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4395 #endif
4396   }
4397 
4398   // If it cannot be fast-path allocated, set a bit in the layout helper.
4399   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4400   assert(ik->size_helper() > 0, "layout_helper is initialized");
4401   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4402       || ik->is_abstract() || ik->is_interface()
4403       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4404       || ik->size_helper() >= FastAllocateSizeLimit) {
4405     // Forbid fast-path allocation.
4406     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4407     ik->set_layout_helper(lh);
4408   }
4409 }
4410 
4411 // Attach super classes and interface classes to class loader data
4412 static void record_defined_class_dependencies(const InstanceKlass* defined_klass,
4413                                               TRAPS) {
4414   assert(defined_klass != NULL, "invariant");
4415 
4416   ClassLoaderData* const defining_loader_data = defined_klass->class_loader_data();
4417   if (defining_loader_data->is_the_null_class_loader_data()) {
4418       // Dependencies to null class loader data are implicit.
4419       return;
4420   } else {
4421     // add super class dependency
4422     Klass* const super = defined_klass->super();
4423     if (super != NULL) {
4424       defining_loader_data->record_dependency(super, CHECK);
4425     }
4426 
4427     // add super interface dependencies
4428     const Array<Klass*>* const local_interfaces = defined_klass->local_interfaces();
4429     if (local_interfaces != NULL) {
4430       const int length = local_interfaces->length();
4431       for (int i = 0; i < length; i++) {
4432         defining_loader_data->record_dependency(local_interfaces->at(i), CHECK);
4433       }
4434     }
4435   }
4436 }
4437 
4438 // utility methods for appending an array with check for duplicates
4439 
4440 static void append_interfaces(GrowableArray<Klass*>* result,
4441                               const Array<Klass*>* const ifs) {
4442   // iterate over new interfaces
4443   for (int i = 0; i < ifs->length(); i++) {
4444     Klass* const e = ifs->at(i);
4445     assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");
4446     // add new interface
4447     result->append_if_missing(e);
4448   }
4449 }
4450 
4451 static Array<Klass*>* compute_transitive_interfaces(const InstanceKlass* super,
4452                                                     Array<Klass*>* local_ifs,
4453                                                     ClassLoaderData* loader_data,
4454                                                     TRAPS) {
4455   assert(local_ifs != NULL, "invariant");
4456   assert(loader_data != NULL, "invariant");
4457 
4458   // Compute maximum size for transitive interfaces
4459   int max_transitive_size = 0;
4460   int super_size = 0;
4461   // Add superclass transitive interfaces size
4462   if (super != NULL) {
4463     super_size = super->transitive_interfaces()->length();
4464     max_transitive_size += super_size;
4465   }
4466   // Add local interfaces' super interfaces
4467   const int local_size = local_ifs->length();
4468   for (int i = 0; i < local_size; i++) {
4469     Klass* const l = local_ifs->at(i);
4470     max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();
4471   }
4472   // Finally add local interfaces
4473   max_transitive_size += local_size;
4474   // Construct array
4475   if (max_transitive_size == 0) {
4476     // no interfaces, use canonicalized array
4477     return Universe::the_empty_klass_array();
4478   } else if (max_transitive_size == super_size) {
4479     // no new local interfaces added, share superklass' transitive interface array
4480     return super->transitive_interfaces();
4481   } else if (max_transitive_size == local_size) {
4482     // only local interfaces added, share local interface array
4483     return local_ifs;
4484   } else {
4485     ResourceMark rm;
4486     GrowableArray<Klass*>* const result = new GrowableArray<Klass*>(max_transitive_size);
4487 
4488     // Copy down from superclass
4489     if (super != NULL) {
4490       append_interfaces(result, super->transitive_interfaces());
4491     }
4492 
4493     // Copy down from local interfaces' superinterfaces
4494     for (int i = 0; i < local_size; i++) {
4495       Klass* const l = local_ifs->at(i);
4496       append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());
4497     }
4498     // Finally add local interfaces
4499     append_interfaces(result, local_ifs);
4500 
4501     // length will be less than the max_transitive_size if duplicates were removed
4502     const int length = result->length();
4503     assert(length <= max_transitive_size, "just checking");
4504     Array<Klass*>* const new_result =
4505       MetadataFactory::new_array<Klass*>(loader_data, length, CHECK_NULL);
4506     for (int i = 0; i < length; i++) {
4507       Klass* const e = result->at(i);
4508       assert(e != NULL, "just checking");
4509       new_result->at_put(i, e);
4510     }
4511     return new_result;
4512   }
4513 }
4514 
4515 static void check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4516   assert(this_klass != NULL, "invariant");
4517   const Klass* const super = this_klass->super();
4518   if (super != NULL) {
4519 
4520     // If the loader is not the boot loader then throw an exception if its
4521     // superclass is in package jdk.internal.reflect and its loader is not a
4522     // special reflection class loader
4523     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4524       assert(super->is_instance_klass(), "super is not instance klass");
4525       PackageEntry* super_package = super->package();
4526       if (super_package != NULL &&
4527           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4528           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4529         ResourceMark rm(THREAD);
4530         Exceptions::fthrow(
4531           THREAD_AND_LOCATION,
4532           vmSymbols::java_lang_IllegalAccessError(),
4533           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4534           this_klass->external_name(),
4535           this_klass->class_loader_data()->loader_name(),
4536           super->external_name());
4537         return;
4538       }
4539     }
4540 
4541     Reflection::VerifyClassAccessResults vca_result =
4542       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4543     if (vca_result != Reflection::ACCESS_OK) {
4544       ResourceMark rm(THREAD);
4545       char* msg = Reflection::verify_class_access_msg(this_klass,
4546                                                       InstanceKlass::cast(super),
4547                                                       vca_result);
4548       if (msg == NULL) {
4549         Exceptions::fthrow(
4550           THREAD_AND_LOCATION,
4551           vmSymbols::java_lang_IllegalAccessError(),
4552           "class %s cannot access its superclass %s",
4553           this_klass->external_name(),
4554           super->external_name());
4555       } else {
4556         // Add additional message content.
4557         Exceptions::fthrow(
4558           THREAD_AND_LOCATION,
4559           vmSymbols::java_lang_IllegalAccessError(),
4560           "superclass access check failed: %s",
4561           msg);
4562       }
4563     }
4564   }
4565 }
4566 
4567 
4568 static void check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4569   assert(this_klass != NULL, "invariant");
4570   const Array<Klass*>* const local_interfaces = this_klass->local_interfaces();
4571   const int lng = local_interfaces->length();
4572   for (int i = lng - 1; i >= 0; i--) {
4573     Klass* const k = local_interfaces->at(i);
4574     assert (k != NULL && k->is_interface(), "invalid interface");
4575     Reflection::VerifyClassAccessResults vca_result =
4576       Reflection::verify_class_access(this_klass, InstanceKlass::cast(k), false);
4577     if (vca_result != Reflection::ACCESS_OK) {
4578       ResourceMark rm(THREAD);
4579       char* msg = Reflection::verify_class_access_msg(this_klass,
4580                                                       InstanceKlass::cast(k),
4581                                                       vca_result);
4582       if (msg == NULL) {
4583         Exceptions::fthrow(
4584           THREAD_AND_LOCATION,
4585           vmSymbols::java_lang_IllegalAccessError(),
4586           "class %s cannot access its superinterface %s",
4587           this_klass->external_name(),
4588           k->external_name());
4589       } else {
4590         // Add additional message content.
4591         Exceptions::fthrow(
4592           THREAD_AND_LOCATION,
4593           vmSymbols::java_lang_IllegalAccessError(),
4594           "superinterface check failed: %s",
4595           msg);
4596       }
4597     }
4598   }
4599 }
4600 
4601 
4602 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4603   assert(this_klass != NULL, "invariant");
4604   const Array<Method*>* const methods = this_klass->methods();
4605   const int num_methods = methods->length();
4606 
4607   // go thru each method and check if it overrides a final method
4608   for (int index = 0; index < num_methods; index++) {
4609     const Method* const m = methods->at(index);
4610 
4611     // skip private, static, and <init> methods
4612     if ((!m->is_private() && !m->is_static()) &&
4613         (m->name() != vmSymbols::object_initializer_name())) {
4614 
4615       const Symbol* const name = m->name();
4616       const Symbol* const signature = m->signature();
4617       const Klass* k = this_klass->super();
4618       const Method* super_m = NULL;
4619       while (k != NULL) {
4620         // skip supers that don't have final methods.
4621         if (k->has_final_method()) {
4622           // lookup a matching method in the super class hierarchy
4623           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4624           if (super_m == NULL) {
4625             break; // didn't find any match; get out
4626           }
4627 
4628           if (super_m->is_final() && !super_m->is_static() &&
4629               !super_m->access_flags().is_private() &&
4630               // matching method in super is final, and not static or private
4631               (Reflection::verify_field_access(this_klass,
4632                                                super_m->method_holder(),
4633                                                super_m->method_holder(),
4634                                                super_m->access_flags(), false))
4635             // this class can access super final method and therefore override
4636             ) {
4637             ResourceMark rm(THREAD);
4638             Exceptions::fthrow(
4639               THREAD_AND_LOCATION,
4640               vmSymbols::java_lang_VerifyError(),
4641               "class %s overrides final method %s.%s%s",
4642               this_klass->external_name(),
4643               super_m->method_holder()->external_name(),
4644               name->as_C_string(),
4645               signature->as_C_string()
4646             );
4647             return;
4648           }
4649 
4650           // continue to look from super_m's holder's super.
4651           k = super_m->method_holder()->super();
4652           continue;
4653         }
4654 
4655         k = k->super();
4656       }
4657     }
4658   }
4659 }
4660 
4661 
4662 // assumes that this_klass is an interface
4663 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4664   assert(this_klass != NULL, "invariant");
4665   assert(this_klass->is_interface(), "not an interface");
4666   const Array<Method*>* methods = this_klass->methods();
4667   const int num_methods = methods->length();
4668 
4669   for (int index = 0; index < num_methods; index++) {
4670     const Method* const m = methods->at(index);
4671     // if m is static and not the init method, throw a verify error
4672     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4673       ResourceMark rm(THREAD);
4674       Exceptions::fthrow(
4675         THREAD_AND_LOCATION,
4676         vmSymbols::java_lang_VerifyError(),
4677         "Illegal static method %s in interface %s",
4678         m->name()->as_C_string(),
4679         this_klass->external_name()
4680       );
4681       return;
4682     }
4683   }
4684 }
4685 
4686 // utility methods for format checking
4687 
4688 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4689   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4690   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4691   if (is_module) {
4692     ResourceMark rm(THREAD);
4693     Exceptions::fthrow(
4694       THREAD_AND_LOCATION,
4695       vmSymbols::java_lang_NoClassDefFoundError(),
4696       "%s is not a class because access_flag ACC_MODULE is set",
4697       _class_name->as_C_string());
4698     return;
4699   }
4700 
4701   if (!_need_verify) { return; }
4702 
4703   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4704   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4705   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4706   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4707   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4708   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4709   const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;
4710 
4711   if ((is_abstract && is_final) ||
4712       (is_interface && !is_abstract) ||
4713       (is_interface && major_gte_15 && (is_super || is_enum)) ||
4714       (!is_interface && major_gte_15 && is_annotation)) {
4715     ResourceMark rm(THREAD);
4716     Exceptions::fthrow(
4717       THREAD_AND_LOCATION,
4718       vmSymbols::java_lang_ClassFormatError(),
4719       "Illegal class modifiers in class %s: 0x%X",
4720       _class_name->as_C_string(), flags
4721     );
4722     return;
4723   }
4724 }
4725 
4726 static bool has_illegal_visibility(jint flags) {
4727   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4728   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4729   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4730 
4731   return ((is_public && is_protected) ||
4732           (is_public && is_private) ||
4733           (is_protected && is_private));
4734 }
4735 
4736 static bool is_supported_version(u2 major, u2 minor){
4737   const u2 max_version = JAVA_MAX_SUPPORTED_VERSION;
4738   return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
4739          (major <= max_version) &&
4740          ((major != max_version) ||
4741           (minor <= JAVA_MAX_SUPPORTED_MINOR_VERSION));
4742 }
4743 
4744 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4745                                                    bool is_interface,
4746                                                    TRAPS) const {
4747   if (!_need_verify) { return; }
4748 
4749   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4750   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4751   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4752   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4753   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4754   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4755   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4756   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4757   const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
4758 
4759   bool is_illegal = false;
4760 
4761   if (is_interface) {
4762     if (!is_public || !is_static || !is_final || is_private ||
4763         is_protected || is_volatile || is_transient ||
4764         (major_gte_15 && is_enum)) {
4765       is_illegal = true;
4766     }
4767   } else { // not interface
4768     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4769       is_illegal = true;
4770     }
4771   }
4772 
4773   if (is_illegal) {
4774     ResourceMark rm(THREAD);
4775     Exceptions::fthrow(
4776       THREAD_AND_LOCATION,
4777       vmSymbols::java_lang_ClassFormatError(),
4778       "Illegal field modifiers in class %s: 0x%X",
4779       _class_name->as_C_string(), flags);
4780     return;
4781   }
4782 }
4783 
4784 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4785                                                     bool is_interface,
4786                                                     const Symbol* name,
4787                                                     TRAPS) const {
4788   if (!_need_verify) { return; }
4789 
4790   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4791   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4792   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4793   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4794   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4795   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4796   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4797   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4798   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4799   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4800   const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
4801   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4802   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4803 
4804   bool is_illegal = false;
4805 
4806   if (is_interface) {
4807     if (major_gte_8) {
4808       // Class file version is JAVA_8_VERSION or later Methods of
4809       // interfaces may set any of the flags except ACC_PROTECTED,
4810       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4811       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4812       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4813           (is_native || is_protected || is_final || is_synchronized) ||
4814           // If a specific method of a class or interface has its
4815           // ACC_ABSTRACT flag set, it must not have any of its
4816           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4817           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4818           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4819           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4820           (is_abstract && (is_private || is_static || is_strict))) {
4821         is_illegal = true;
4822       }
4823     } else if (major_gte_15) {
4824       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4825       if (!is_public || is_private || is_protected || is_static || is_final ||
4826           is_synchronized || is_native || !is_abstract || is_strict) {
4827         is_illegal = true;
4828       }
4829     } else {
4830       // Class file version is pre-JAVA_1_5_VERSION
4831       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4832         is_illegal = true;
4833       }
4834     }
4835   } else { // not interface
4836     if (has_illegal_visibility(flags)) {
4837       is_illegal = true;
4838     } else {
4839       if (is_initializer) {
4840         if (is_static || is_final || is_synchronized || is_native ||
4841             is_abstract || (major_gte_15 && is_bridge)) {
4842           is_illegal = true;
4843         }
4844       } else { // not initializer
4845         if (is_abstract) {
4846           if ((is_final || is_native || is_private || is_static ||
4847               (major_gte_15 && (is_synchronized || is_strict)))) {
4848             is_illegal = true;
4849           }
4850         }
4851       }
4852     }
4853   }
4854 
4855   if (is_illegal) {
4856     ResourceMark rm(THREAD);
4857     Exceptions::fthrow(
4858       THREAD_AND_LOCATION,
4859       vmSymbols::java_lang_ClassFormatError(),
4860       "Method %s in class %s has illegal modifiers: 0x%X",
4861       name->as_C_string(), _class_name->as_C_string(), flags);
4862     return;
4863   }
4864 }
4865 
4866 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4867                                         int length,
4868                                         TRAPS) const {
4869   assert(_need_verify, "only called when _need_verify is true");
4870   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4871     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
4872   }
4873 }
4874 
4875 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4876 // In class names, '/' separates unqualified names.  This is verified in this function also.
4877 // Method names also may not contain the characters '<' or '>', unless <init>
4878 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4879 // method.  Because these names have been checked as special cases before
4880 // calling this method in verify_legal_method_name.
4881 //
4882 // This method is also called from the modular system APIs in modules.cpp
4883 // to verify the validity of module and package names.
4884 bool ClassFileParser::verify_unqualified_name(const char* name,
4885                                               unsigned int length,
4886                                               int type) {
4887   for (const char* p = name; p != name + length;) {
4888     jchar ch = *p;
4889     if (ch < 128) {
4890       if (ch == '.' || ch == ';' || ch == '[' ) {
4891         return false;   // do not permit '.', ';', or '['
4892       }
4893       if (ch == '/') {
4894         // check for '//' or leading or trailing '/' which are not legal
4895         // unqualified name must not be empty
4896         if (type == ClassFileParser::LegalClass) {
4897           if (p == name || p+1 >= name+length || *(p+1) == '/') {
4898            return false;
4899           }
4900         } else {
4901           return false;   // do not permit '/' unless it's class name
4902         }
4903       }
4904       if (type == ClassFileParser::LegalMethod && (ch == '<' || ch == '>')) {
4905         return false;   // do not permit '<' or '>' in method names
4906       }
4907       p++;
4908     } else {
4909       char* tmp_p = UTF8::next(p, &ch);
4910       p = tmp_p;
4911     }
4912   }
4913   return true;
4914 }
4915 
4916 // Take pointer to a string. Skip over the longest part of the string that could
4917 // be taken as a fieldname. Allow '/' if slash_ok is true.
4918 // Return a pointer to just past the fieldname.
4919 // Return NULL if no fieldname at all was found, or in the case of slash_ok
4920 // being true, we saw consecutive slashes (meaning we were looking for a
4921 // qualified path but found something that was badly-formed).
4922 static const char* skip_over_field_name(const char* name,
4923                                         bool slash_ok,
4924                                         unsigned int length) {
4925   const char* p;
4926   jboolean last_is_slash = false;
4927   jboolean not_first_ch = false;
4928 
4929   for (p = name; p != name + length; not_first_ch = true) {
4930     const char* old_p = p;
4931     jchar ch = *p;
4932     if (ch < 128) {
4933       p++;
4934       // quick check for ascii
4935       if ((ch >= 'a' && ch <= 'z') ||
4936         (ch >= 'A' && ch <= 'Z') ||
4937         (ch == '_' || ch == '$') ||
4938         (not_first_ch && ch >= '0' && ch <= '9')) {
4939         last_is_slash = false;
4940         continue;
4941       }
4942       if (slash_ok && ch == '/') {
4943         if (last_is_slash) {
4944           return NULL;  // Don't permit consecutive slashes
4945         }
4946         last_is_slash = true;
4947         continue;
4948       }
4949     }
4950     else {
4951       jint unicode_ch;
4952       char* tmp_p = UTF8::next_character(p, &unicode_ch);
4953       p = tmp_p;
4954       last_is_slash = false;
4955       // Check if ch is Java identifier start or is Java identifier part
4956       // 4672820: call java.lang.Character methods directly without generating separate tables.
4957       EXCEPTION_MARK;
4958 
4959       // return value
4960       JavaValue result(T_BOOLEAN);
4961       // Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart
4962       JavaCallArguments args;
4963       args.push_int(unicode_ch);
4964 
4965       // public static boolean isJavaIdentifierStart(char ch);
4966       JavaCalls::call_static(&result,
4967         SystemDictionary::Character_klass(),
4968         vmSymbols::isJavaIdentifierStart_name(),
4969         vmSymbols::int_bool_signature(),
4970         &args,
4971         THREAD);
4972 
4973       if (HAS_PENDING_EXCEPTION) {
4974         CLEAR_PENDING_EXCEPTION;
4975         return 0;
4976       }
4977       if (result.get_jboolean()) {
4978         continue;
4979       }
4980 
4981       if (not_first_ch) {
4982         // public static boolean isJavaIdentifierPart(char ch);
4983         JavaCalls::call_static(&result,
4984           SystemDictionary::Character_klass(),
4985           vmSymbols::isJavaIdentifierPart_name(),
4986           vmSymbols::int_bool_signature(),
4987           &args,
4988           THREAD);
4989 
4990         if (HAS_PENDING_EXCEPTION) {
4991           CLEAR_PENDING_EXCEPTION;
4992           return 0;
4993         }
4994 
4995         if (result.get_jboolean()) {
4996           continue;
4997         }
4998       }
4999     }
5000     return (not_first_ch) ? old_p : NULL;
5001   }
5002   return (not_first_ch) ? p : NULL;
5003 }
5004 
5005 // Take pointer to a string. Skip over the longest part of the string that could
5006 // be taken as a field signature. Allow "void" if void_ok.
5007 // Return a pointer to just past the signature.
5008 // Return NULL if no legal signature is found.
5009 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5010                                                        bool void_ok,
5011                                                        unsigned int length,
5012                                                        TRAPS) const {
5013   unsigned int array_dim = 0;
5014   while (length > 0) {
5015     switch (signature[0]) {
5016     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
5017     case JVM_SIGNATURE_BOOLEAN:
5018     case JVM_SIGNATURE_BYTE:
5019     case JVM_SIGNATURE_CHAR:
5020     case JVM_SIGNATURE_SHORT:
5021     case JVM_SIGNATURE_INT:
5022     case JVM_SIGNATURE_FLOAT:
5023     case JVM_SIGNATURE_LONG:
5024     case JVM_SIGNATURE_DOUBLE:
5025       return signature + 1;
5026     case JVM_SIGNATURE_CLASS: {
5027       if (_major_version < JAVA_1_5_VERSION) {
5028         // Skip over the class name if one is there
5029         const char* const p = skip_over_field_name(signature + 1, true, --length);
5030 
5031         // The next character better be a semicolon
5032         if (p && (p - signature) > 1 && p[0] == ';') {
5033           return p + 1;
5034         }
5035       }
5036       else {
5037         // Skip leading 'L' and ignore first appearance of ';'
5038         length--;
5039         signature++;
5040         char* c = strchr((char*) signature, ';');
5041         // Format check signature
5042         if (c != NULL) {
5043           ResourceMark rm(THREAD);
5044           int newlen = c - (char*) signature;
5045           char* sig = NEW_RESOURCE_ARRAY(char, newlen + 1);
5046           strncpy(sig, signature, newlen);
5047           sig[newlen] = '\0';
5048 
5049           bool legal = verify_unqualified_name(sig, newlen, LegalClass);
5050           if (!legal) {
5051             classfile_parse_error("Class name contains illegal character "
5052                                   "in descriptor in class file %s",
5053                                   CHECK_0);
5054             return NULL;
5055           }
5056           return signature + newlen + 1;
5057         }
5058       }
5059       return NULL;
5060     }
5061     case JVM_SIGNATURE_ARRAY:
5062       array_dim++;
5063       if (array_dim > 255) {
5064         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
5065         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
5066       }
5067       // The rest of what's there better be a legal signature
5068       signature++;
5069       length--;
5070       void_ok = false;
5071       break;
5072     default:
5073       return NULL;
5074     }
5075   }
5076   return NULL;
5077 }
5078 
5079 // Checks if name is a legal class name.
5080 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5081   if (!_need_verify || _relax_verify) { return; }
5082 
5083   char buf[fixed_buffer_size];
5084   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5085   unsigned int length = name->utf8_length();
5086   bool legal = false;
5087 
5088   if (length > 0) {
5089     const char* p;
5090     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5091       p = skip_over_field_signature(bytes, false, length, CHECK);
5092       legal = (p != NULL) && ((p - bytes) == (int)length);
5093     } else if (_major_version < JAVA_1_5_VERSION) {
5094       if (bytes[0] != '<') {
5095         p = skip_over_field_name(bytes, true, length);
5096         legal = (p != NULL) && ((p - bytes) == (int)length);
5097       }
5098     } else {
5099       // 4900761: relax the constraints based on JSR202 spec
5100       // Class names may be drawn from the entire Unicode character set.
5101       // Identifiers between '/' must be unqualified names.
5102       // The utf8 string has been verified when parsing cpool entries.
5103       legal = verify_unqualified_name(bytes, length, LegalClass);
5104     }
5105   }
5106   if (!legal) {
5107     ResourceMark rm(THREAD);
5108     assert(_class_name != NULL, "invariant");
5109     Exceptions::fthrow(
5110       THREAD_AND_LOCATION,
5111       vmSymbols::java_lang_ClassFormatError(),
5112       "Illegal class name \"%s\" in class file %s", bytes,
5113       _class_name->as_C_string()
5114     );
5115     return;
5116   }
5117 }
5118 
5119 // Checks if name is a legal field name.
5120 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5121   if (!_need_verify || _relax_verify) { return; }
5122 
5123   char buf[fixed_buffer_size];
5124   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5125   unsigned int length = name->utf8_length();
5126   bool legal = false;
5127 
5128   if (length > 0) {
5129     if (_major_version < JAVA_1_5_VERSION) {
5130       if (bytes[0] != '<') {
5131         const char* p = skip_over_field_name(bytes, false, length);
5132         legal = (p != NULL) && ((p - bytes) == (int)length);
5133       }
5134     } else {
5135       // 4881221: relax the constraints based on JSR202 spec
5136       legal = verify_unqualified_name(bytes, length, LegalField);
5137     }
5138   }
5139 
5140   if (!legal) {
5141     ResourceMark rm(THREAD);
5142     assert(_class_name != NULL, "invariant");
5143     Exceptions::fthrow(
5144       THREAD_AND_LOCATION,
5145       vmSymbols::java_lang_ClassFormatError(),
5146       "Illegal field name \"%s\" in class %s", bytes,
5147       _class_name->as_C_string()
5148     );
5149     return;
5150   }
5151 }
5152 
5153 // Checks if name is a legal method name.
5154 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5155   if (!_need_verify || _relax_verify) { return; }
5156 
5157   assert(name != NULL, "method name is null");
5158   char buf[fixed_buffer_size];
5159   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5160   unsigned int length = name->utf8_length();
5161   bool legal = false;
5162 
5163   if (length > 0) {
5164     if (bytes[0] == '<') {
5165       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5166         legal = true;
5167       }
5168     } else if (_major_version < JAVA_1_5_VERSION) {
5169       const char* p;
5170       p = skip_over_field_name(bytes, false, length);
5171       legal = (p != NULL) && ((p - bytes) == (int)length);
5172     } else {
5173       // 4881221: relax the constraints based on JSR202 spec
5174       legal = verify_unqualified_name(bytes, length, LegalMethod);
5175     }
5176   }
5177 
5178   if (!legal) {
5179     ResourceMark rm(THREAD);
5180     assert(_class_name != NULL, "invariant");
5181     Exceptions::fthrow(
5182       THREAD_AND_LOCATION,
5183       vmSymbols::java_lang_ClassFormatError(),
5184       "Illegal method name \"%s\" in class %s", bytes,
5185       _class_name->as_C_string()
5186     );
5187     return;
5188   }
5189 }
5190 
5191 
5192 // Checks if signature is a legal field signature.
5193 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5194                                                    const Symbol* signature,
5195                                                    TRAPS) const {
5196   if (!_need_verify) { return; }
5197 
5198   char buf[fixed_buffer_size];
5199   const char* const bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5200   const unsigned int length = signature->utf8_length();
5201   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5202 
5203   if (p == NULL || (p - bytes) != (int)length) {
5204     throwIllegalSignature("Field", name, signature, CHECK);
5205   }
5206 }
5207 
5208 // Checks if signature is a legal method signature.
5209 // Returns number of parameters
5210 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5211                                                    const Symbol* signature,
5212                                                    TRAPS) const {
5213   if (!_need_verify) {
5214     // make sure caller's args_size will be less than 0 even for non-static
5215     // method so it will be recomputed in compute_size_of_parameters().
5216     return -2;
5217   }
5218 
5219   // Class initializers cannot have args for class format version >= 51.
5220   if (name == vmSymbols::class_initializer_name() &&
5221       signature != vmSymbols::void_method_signature() &&
5222       _major_version >= JAVA_7_VERSION) {
5223     throwIllegalSignature("Method", name, signature, CHECK_0);
5224     return 0;
5225   }
5226 
5227   unsigned int args_size = 0;
5228   char buf[fixed_buffer_size];
5229   const char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5230   unsigned int length = signature->utf8_length();
5231   const char* nextp;
5232 
5233   // The first character must be a '('
5234   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5235     length--;
5236     // Skip over legal field signatures
5237     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5238     while ((length > 0) && (nextp != NULL)) {
5239       args_size++;
5240       if (p[0] == 'J' || p[0] == 'D') {
5241         args_size++;
5242       }
5243       length -= nextp - p;
5244       p = nextp;
5245       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5246     }
5247     // The first non-signature thing better be a ')'
5248     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5249       length--;
5250       if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
5251         // All internal methods must return void
5252         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
5253           return args_size;
5254         }
5255       } else {
5256         // Now we better just have a return value
5257         nextp = skip_over_field_signature(p, true, length, CHECK_0);
5258         if (nextp && ((int)length == (nextp - p))) {
5259           return args_size;
5260         }
5261       }
5262     }
5263   }
5264   // Report error
5265   throwIllegalSignature("Method", name, signature, CHECK_0);
5266   return 0;
5267 }
5268 
5269 int ClassFileParser::static_field_size() const {
5270   assert(_field_info != NULL, "invariant");
5271   return _field_info->static_field_size;
5272 }
5273 
5274 int ClassFileParser::total_oop_map_count() const {
5275   assert(_field_info != NULL, "invariant");
5276   return _field_info->total_oop_map_count;
5277 }
5278 
5279 jint ClassFileParser::layout_size() const {
5280   assert(_field_info != NULL, "invariant");
5281   return _field_info->instance_size;
5282 }
5283 
5284 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5285                                          const Array<Method*>* methods) {
5286   assert(ik != NULL, "invariant");
5287   assert(methods != NULL, "invariant");
5288 
5289   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5290   // (We used to do this lazily, but now we query it in Rewriter,
5291   // which is eagerly done for every method, so we might as well do it now,
5292   // when everything is fresh in memory.)
5293   const vmSymbols::SID klass_id = Method::klass_id_for_intrinsics(ik);
5294 
5295   if (klass_id != vmSymbols::NO_SID) {
5296     for (int j = 0; j < methods->length(); ++j) {
5297       Method* method = methods->at(j);
5298       method->init_intrinsic_id();
5299 
5300       if (CheckIntrinsics) {
5301         // Check if an intrinsic is defined for method 'method',
5302         // but the method is not annotated with @HotSpotIntrinsicCandidate.
5303         if (method->intrinsic_id() != vmIntrinsics::_none &&
5304             !method->intrinsic_candidate()) {
5305               tty->print("Compiler intrinsic is defined for method [%s], "
5306               "but the method is not annotated with @HotSpotIntrinsicCandidate.%s",
5307               method->name_and_sig_as_C_string(),
5308               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5309             );
5310           tty->cr();
5311           DEBUG_ONLY(vm_exit(1));
5312         }
5313         // Check is the method 'method' is annotated with @HotSpotIntrinsicCandidate,
5314         // but there is no intrinsic available for it.
5315         if (method->intrinsic_candidate() &&
5316           method->intrinsic_id() == vmIntrinsics::_none) {
5317             tty->print("Method [%s] is annotated with @HotSpotIntrinsicCandidate, "
5318               "but no compiler intrinsic is defined for the method.%s",
5319               method->name_and_sig_as_C_string(),
5320               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5321             );
5322           tty->cr();
5323           DEBUG_ONLY(vm_exit(1));
5324         }
5325       }
5326     } // end for
5327 
5328 #ifdef ASSERT
5329     if (CheckIntrinsics) {
5330       // Check for orphan methods in the current class. A method m
5331       // of a class C is orphan if an intrinsic is defined for method m,
5332       // but class C does not declare m.
5333       // The check is potentially expensive, therefore it is available
5334       // only in debug builds.
5335 
5336       for (int id = vmIntrinsics::FIRST_ID; id < (int)vmIntrinsics::ID_LIMIT; ++id) {
5337         if (vmIntrinsics::_compiledLambdaForm == id) {
5338           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5339           // generated for the JVM from a LambdaForm and therefore no method
5340           // is defined for it.
5341           continue;
5342         }
5343 
5344         if (vmIntrinsics::class_for(vmIntrinsics::ID_from(id)) == klass_id) {
5345           // Check if the current class contains a method with the same
5346           // name, flags, signature.
5347           bool match = false;
5348           for (int j = 0; j < methods->length(); ++j) {
5349             const Method* method = methods->at(j);
5350             if (method->intrinsic_id() == id) {
5351               match = true;
5352               break;
5353             }
5354           }
5355 
5356           if (!match) {
5357             char buf[1000];
5358             tty->print("Compiler intrinsic is defined for method [%s], "
5359                        "but the method is not available in class [%s].%s",
5360                         vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID_from(id),
5361                                                              buf, sizeof(buf)),
5362                         ik->name()->as_C_string(),
5363                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5364             );
5365             tty->cr();
5366             DEBUG_ONLY(vm_exit(1));
5367           }
5368         }
5369       } // end for
5370     } // CheckIntrinsics
5371 #endif // ASSERT
5372   }
5373 }
5374 
5375 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook, TRAPS) {
5376   if (_klass != NULL) {
5377     return _klass;
5378   }
5379 
5380   InstanceKlass* const ik =
5381     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5382 
5383   fill_instance_klass(ik, changed_by_loadhook, CHECK_NULL);
5384 
5385   assert(_klass == ik, "invariant");
5386 
5387   ik->set_has_passed_fingerprint_check(false);
5388   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
5389     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
5390     if (aot_fp != 0 && aot_fp == _stream->compute_fingerprint()) {
5391       // This class matches with a class saved in an AOT library
5392       ik->set_has_passed_fingerprint_check(true);
5393     } else {
5394       ResourceMark rm;
5395       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT,
5396                                  ik->external_name(), aot_fp, _stream->compute_fingerprint());
5397     }
5398   }
5399 
5400   return ik;
5401 }
5402 
5403 void ClassFileParser::fill_instance_klass(InstanceKlass* ik, bool changed_by_loadhook, TRAPS) {
5404   assert(ik != NULL, "invariant");
5405 
5406   set_klass_to_deallocate(ik);
5407 
5408   assert(_field_info != NULL, "invariant");
5409   assert(ik->static_field_size() == _field_info->static_field_size, "sanity");
5410   assert(ik->nonstatic_oop_map_count() == _field_info->total_oop_map_count,
5411     "sanity");
5412 
5413   assert(ik->is_instance_klass(), "sanity");
5414   assert(ik->size_helper() == _field_info->instance_size, "sanity");
5415 
5416   // Fill in information already parsed
5417   ik->set_should_verify_class(_need_verify);
5418 
5419   // Not yet: supers are done below to support the new subtype-checking fields
5420   ik->set_class_loader_data(_loader_data);
5421   ik->set_nonstatic_field_size(_field_info->nonstatic_field_size);
5422   ik->set_has_nonstatic_fields(_field_info->has_nonstatic_fields);
5423   assert(_fac != NULL, "invariant");
5424   ik->set_static_oop_field_count(_fac->count[STATIC_OOP]);
5425 
5426   // this transfers ownership of a lot of arrays from
5427   // the parser onto the InstanceKlass*
5428   apply_parsed_class_metadata(ik, _java_fields_count, CHECK);
5429 
5430   // note that is not safe to use the fields in the parser from this point on
5431   assert(NULL == _cp, "invariant");
5432   assert(NULL == _fields, "invariant");
5433   assert(NULL == _methods, "invariant");
5434   assert(NULL == _inner_classes, "invariant");
5435   assert(NULL == _nest_members, "invariant");
5436   assert(NULL == _local_interfaces, "invariant");
5437   assert(NULL == _transitive_interfaces, "invariant");
5438   assert(NULL == _combined_annotations, "invariant");
5439 
5440   if (_has_final_method) {
5441     ik->set_has_final_method();
5442   }
5443 
5444   ik->copy_method_ordering(_method_ordering, CHECK);
5445   // The InstanceKlass::_methods_jmethod_ids cache
5446   // is managed on the assumption that the initial cache
5447   // size is equal to the number of methods in the class. If
5448   // that changes, then InstanceKlass::idnum_can_increment()
5449   // has to be changed accordingly.
5450   ik->set_initial_method_idnum(ik->methods()->length());
5451 
5452   ik->set_name(_class_name);
5453 
5454   if (is_anonymous()) {
5455     // _this_class_index is a CONSTANT_Class entry that refers to this
5456     // anonymous class itself. If this class needs to refer to its own methods or
5457     // fields, it would use a CONSTANT_MethodRef, etc, which would reference
5458     // _this_class_index. However, because this class is anonymous (it's
5459     // not stored in SystemDictionary), _this_class_index cannot be resolved
5460     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5461     // Therefore, we must eagerly resolve _this_class_index now.
5462     ik->constants()->klass_at_put(_this_class_index, ik);
5463   }
5464 
5465   ik->set_minor_version(_minor_version);
5466   ik->set_major_version(_major_version);
5467   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5468   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5469 
5470   if (_host_klass != NULL) {
5471     assert (ik->is_anonymous(), "should be the same");
5472     ik->set_host_klass(_host_klass);
5473   }
5474 
5475   // Set PackageEntry for this_klass
5476   oop cl = ik->class_loader();
5477   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5478   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5479   ik->set_package(cld, CHECK);
5480 
5481   const Array<Method*>* const methods = ik->methods();
5482   assert(methods != NULL, "invariant");
5483   const int methods_len = methods->length();
5484 
5485   check_methods_for_intrinsics(ik, methods);
5486 
5487   // Fill in field values obtained by parse_classfile_attributes
5488   if (_parsed_annotations->has_any_annotations()) {
5489     _parsed_annotations->apply_to(ik);
5490   }
5491 
5492   apply_parsed_class_attributes(ik);
5493 
5494   // Miranda methods
5495   if ((_num_miranda_methods > 0) ||
5496       // if this class introduced new miranda methods or
5497       (_super_klass != NULL && _super_klass->has_miranda_methods())
5498         // super class exists and this class inherited miranda methods
5499      ) {
5500        ik->set_has_miranda_methods(); // then set a flag
5501   }
5502 
5503   // Fill in information needed to compute superclasses.
5504   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), CHECK);
5505 
5506   // Initialize itable offset tables
5507   klassItable::setup_itable_offset_table(ik);
5508 
5509   // Compute transitive closure of interfaces this class implements
5510   // Do final class setup
5511   fill_oop_maps(ik,
5512                 _field_info->nonstatic_oop_map_count,
5513                 _field_info->nonstatic_oop_offsets,
5514                 _field_info->nonstatic_oop_counts);
5515 
5516   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5517   set_precomputed_flags(ik);
5518 
5519   // check if this class can access its super class
5520   check_super_class_access(ik, CHECK);
5521 
5522   // check if this class can access its superinterfaces
5523   check_super_interface_access(ik, CHECK);
5524 
5525   // check if this class overrides any final method
5526   check_final_method_override(ik, CHECK);
5527 
5528   // reject static interface methods prior to Java 8
5529   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5530     check_illegal_static_method(ik, CHECK);
5531   }
5532 
5533   // Obtain this_klass' module entry
5534   ModuleEntry* module_entry = ik->module();
5535   assert(module_entry != NULL, "module_entry should always be set");
5536 
5537   // Obtain java.lang.Module
5538   Handle module_handle(THREAD, module_entry->module());
5539 
5540   // Allocate mirror and initialize static fields
5541   // The create_mirror() call will also call compute_modifiers()
5542   java_lang_Class::create_mirror(ik,
5543                                  Handle(THREAD, _loader_data->class_loader()),
5544                                  module_handle,
5545                                  _protection_domain,
5546                                  CHECK);
5547 
5548   assert(_all_mirandas != NULL, "invariant");
5549 
5550   // Generate any default methods - default methods are public interface methods
5551   // that have a default implementation.  This is new with Java 8.
5552   if (_has_nonstatic_concrete_methods) {
5553     DefaultMethods::generate_default_methods(ik,
5554                                              _all_mirandas,
5555                                              CHECK);
5556   }
5557 
5558   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5559   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5560       !module_entry->has_default_read_edges()) {
5561     if (!module_entry->set_has_default_read_edges()) {
5562       // We won a potential race
5563       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5564     }
5565   }
5566 
5567   // Update the loader_data graph.
5568   record_defined_class_dependencies(ik, CHECK);
5569 
5570   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5571 
5572   if (!is_internal()) {
5573     if (log_is_enabled(Info, class, load)) {
5574       ResourceMark rm;
5575       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
5576       ik->print_class_load_logging(_loader_data, module_name, _stream);
5577     }
5578 
5579     if (log_is_enabled(Debug, class, resolve))  {
5580       ResourceMark rm;
5581       // print out the superclass.
5582       const char * from = ik->external_name();
5583       if (ik->java_super() != NULL) {
5584         log_debug(class, resolve)("%s %s (super)",
5585                    from,
5586                    ik->java_super()->external_name());
5587       }
5588       // print out each of the interface classes referred to by this class.
5589       const Array<Klass*>* const local_interfaces = ik->local_interfaces();
5590       if (local_interfaces != NULL) {
5591         const int length = local_interfaces->length();
5592         for (int i = 0; i < length; i++) {
5593           const Klass* const k = local_interfaces->at(i);
5594           const char * to = k->external_name();
5595           log_debug(class, resolve)("%s %s (interface)", from, to);
5596         }
5597       }
5598     }
5599   }
5600 
5601   TRACE_INIT_ID(ik);
5602 
5603   // If we reach here, all is well.
5604   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5605   // in order for it to not be destroyed in the ClassFileParser destructor.
5606   set_klass_to_deallocate(NULL);
5607 
5608   // it's official
5609   set_klass(ik);
5610 
5611   debug_only(ik->verify();)
5612 }
5613 
5614 // For an anonymous class that is in the unnamed package, move it to its host class's
5615 // package by prepending its host class's package name to its class name and setting
5616 // its _class_name field.
5617 void ClassFileParser::prepend_host_package_name(const InstanceKlass* host_klass, TRAPS) {
5618   ResourceMark rm(THREAD);
5619   assert(strrchr(_class_name->as_C_string(), '/') == NULL,
5620          "Anonymous class should not be in a package");
5621   const char* host_pkg_name =
5622     ClassLoader::package_from_name(host_klass->name()->as_C_string(), NULL);
5623 
5624   if (host_pkg_name != NULL) {
5625     size_t host_pkg_len = strlen(host_pkg_name);
5626     int class_name_len = _class_name->utf8_length();
5627     char* new_anon_name =
5628       NEW_RESOURCE_ARRAY(char, host_pkg_len + 1 + class_name_len);
5629     // Copy host package name and trailing /.
5630     strncpy(new_anon_name, host_pkg_name, host_pkg_len);
5631     new_anon_name[host_pkg_len] = '/';
5632     // Append anonymous class name. The anonymous class name can contain odd
5633     // characters.  So, do a strncpy instead of using sprintf("%s...").
5634     strncpy(new_anon_name + host_pkg_len + 1, (char *)_class_name->base(), class_name_len);
5635 
5636     // Create a symbol and update the anonymous class name.
5637     _class_name = SymbolTable::new_symbol(new_anon_name,
5638                                           (int)host_pkg_len + 1 + class_name_len,
5639                                           CHECK);
5640   }
5641 }
5642 
5643 // If the host class and the anonymous class are in the same package then do
5644 // nothing.  If the anonymous class is in the unnamed package then move it to its
5645 // host's package.  If the classes are in different packages then throw an IAE
5646 // exception.
5647 void ClassFileParser::fix_anonymous_class_name(TRAPS) {
5648   assert(_host_klass != NULL, "Expected an anonymous class");
5649 
5650   const jbyte* anon_last_slash = UTF8::strrchr(_class_name->base(),
5651                                                _class_name->utf8_length(), '/');
5652   if (anon_last_slash == NULL) {  // Unnamed package
5653     prepend_host_package_name(_host_klass, CHECK);
5654   } else {
5655     if (!_host_klass->is_same_class_package(_host_klass->class_loader(), _class_name)) {
5656       ResourceMark rm(THREAD);
5657       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
5658         err_msg("Host class %s and anonymous class %s are in different packages",
5659         _host_klass->name()->as_C_string(), _class_name->as_C_string()));
5660     }
5661   }
5662 }
5663 
5664 static bool relax_format_check_for(ClassLoaderData* loader_data) {
5665   bool trusted = (loader_data->is_the_null_class_loader_data() ||
5666                   SystemDictionary::is_platform_class_loader(loader_data->class_loader()));
5667   bool need_verify =
5668     // verifyAll
5669     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
5670     // verifyRemote
5671     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
5672   return !need_verify;
5673 }
5674 
5675 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5676                                  Symbol* name,
5677                                  ClassLoaderData* loader_data,
5678                                  Handle protection_domain,
5679                                  const InstanceKlass* host_klass,
5680                                  GrowableArray<Handle>* cp_patches,
5681                                  Publicity pub_level,
5682                                  TRAPS) :
5683   _stream(stream),
5684   _requested_name(name),
5685   _loader_data(loader_data),
5686   _host_klass(host_klass),
5687   _cp_patches(cp_patches),
5688   _num_patched_klasses(0),
5689   _max_num_patched_klasses(0),
5690   _orig_cp_size(0),
5691   _first_patched_klass_resolved_index(0),
5692   _super_klass(),
5693   _cp(NULL),
5694   _fields(NULL),
5695   _methods(NULL),
5696   _inner_classes(NULL),
5697   _nest_members(NULL),
5698   _nest_top(0),
5699   _local_interfaces(NULL),
5700   _transitive_interfaces(NULL),
5701   _combined_annotations(NULL),
5702   _annotations(NULL),
5703   _type_annotations(NULL),
5704   _fields_annotations(NULL),
5705   _fields_type_annotations(NULL),
5706   _klass(NULL),
5707   _klass_to_deallocate(NULL),
5708   _parsed_annotations(NULL),
5709   _fac(NULL),
5710   _field_info(NULL),
5711   _method_ordering(NULL),
5712   _all_mirandas(NULL),
5713   _vtable_size(0),
5714   _itable_size(0),
5715   _num_miranda_methods(0),
5716   _rt(REF_NONE),
5717   _protection_domain(protection_domain),
5718   _access_flags(),
5719   _pub_level(pub_level),
5720   _bad_constant_seen(0),
5721   _synthetic_flag(false),
5722   _sde_length(false),
5723   _sde_buffer(NULL),
5724   _sourcefile_index(0),
5725   _generic_signature_index(0),
5726   _major_version(0),
5727   _minor_version(0),
5728   _this_class_index(0),
5729   _super_class_index(0),
5730   _itfs_len(0),
5731   _java_fields_count(0),
5732   _need_verify(false),
5733   _relax_verify(false),
5734   _has_nonstatic_concrete_methods(false),
5735   _declares_nonstatic_concrete_methods(false),
5736   _has_final_method(false),
5737   _has_finalizer(false),
5738   _has_empty_finalizer(false),
5739   _has_vanilla_constructor(false),
5740   _max_bootstrap_specifier_index(-1) {
5741 
5742   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5743 
5744   assert(THREAD->is_Java_thread(), "invariant");
5745   assert(_loader_data != NULL, "invariant");
5746   assert(stream != NULL, "invariant");
5747   assert(_stream != NULL, "invariant");
5748   assert(_stream->buffer() == _stream->current(), "invariant");
5749   assert(_class_name != NULL, "invariant");
5750   assert(0 == _access_flags.as_int(), "invariant");
5751 
5752   // Figure out whether we can skip format checking (matching classic VM behavior)
5753   if (DumpSharedSpaces) {
5754     // verify == true means it's a 'remote' class (i.e., non-boot class)
5755     // Verification decision is based on BytecodeVerificationRemote flag
5756     // for those classes.
5757     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
5758                                               BytecodeVerificationLocal;
5759   }
5760   else {
5761     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
5762                                                stream->need_verify());
5763   }
5764   if (_cp_patches != NULL) {
5765     int len = _cp_patches->length();
5766     for (int i=0; i<len; i++) {
5767       if (has_cp_patch_at(i)) {
5768         Handle patch = cp_patch_at(i);
5769         if (java_lang_String::is_instance(patch()) || java_lang_Class::is_instance(patch())) {
5770           // We need to append the names of the patched classes to the end of the constant pool,
5771           // because a patched class may have a Utf8 name that's not already included in the
5772           // original constant pool. These class names are used when patch_constant_pool()
5773           // calls patch_class().
5774           //
5775           // Note that a String in cp_patch_at(i) may be used to patch a Utf8, a String, or a Class.
5776           // At this point, we don't know the tag for index i yet, because we haven't parsed the
5777           // constant pool. So we can only assume the worst -- every String is used to patch a Class.
5778           _max_num_patched_klasses++;
5779         }
5780       }
5781     }
5782   }
5783 
5784   // synch back verification state to stream
5785   stream->set_verify(_need_verify);
5786 
5787   // Check if verification needs to be relaxed for this class file
5788   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5789   _relax_verify = relax_format_check_for(_loader_data);
5790 
5791   parse_stream(stream, CHECK);
5792 
5793   post_process_parsed_stream(stream, _cp, CHECK);
5794 }
5795 
5796 void ClassFileParser::clear_class_metadata() {
5797   // metadata created before the instance klass is created.  Must be
5798   // deallocated if classfile parsing returns an error.
5799   _cp = NULL;
5800   _fields = NULL;
5801   _methods = NULL;
5802   _inner_classes = NULL;
5803   _nest_members = NULL;
5804   _local_interfaces = NULL;
5805   _transitive_interfaces = NULL;
5806   _combined_annotations = NULL;
5807   _annotations = _type_annotations = NULL;
5808   _fields_annotations = _fields_type_annotations = NULL;
5809 }
5810 
5811 // Destructor to clean up
5812 ClassFileParser::~ClassFileParser() {
5813   if (_cp != NULL) {
5814     MetadataFactory::free_metadata(_loader_data, _cp);
5815   }
5816   if (_fields != NULL) {
5817     MetadataFactory::free_array<u2>(_loader_data, _fields);
5818   }
5819 
5820   if (_methods != NULL) {
5821     // Free methods
5822     InstanceKlass::deallocate_methods(_loader_data, _methods);
5823   }
5824 
5825   // beware of the Universe::empty_blah_array!!
5826   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
5827     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5828   }
5829 
5830   if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {
5831     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5832   }
5833 
5834   // Free interfaces
5835   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5836                                        _local_interfaces, _transitive_interfaces);
5837 
5838   if (_combined_annotations != NULL) {
5839     // After all annotations arrays have been created, they are installed into the
5840     // Annotations object that will be assigned to the InstanceKlass being created.
5841 
5842     // Deallocate the Annotations object and the installed annotations arrays.
5843     _combined_annotations->deallocate_contents(_loader_data);
5844 
5845     // If the _combined_annotations pointer is non-NULL,
5846     // then the other annotations fields should have been cleared.
5847     assert(_annotations             == NULL, "Should have been cleared");
5848     assert(_type_annotations        == NULL, "Should have been cleared");
5849     assert(_fields_annotations      == NULL, "Should have been cleared");
5850     assert(_fields_type_annotations == NULL, "Should have been cleared");
5851   } else {
5852     // If the annotations arrays were not installed into the Annotations object,
5853     // then they have to be deallocated explicitly.
5854     MetadataFactory::free_array<u1>(_loader_data, _annotations);
5855     MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
5856     Annotations::free_contents(_loader_data, _fields_annotations);
5857     Annotations::free_contents(_loader_data, _fields_type_annotations);
5858   }
5859 
5860   clear_class_metadata();
5861 
5862   // deallocate the klass if already created.  Don't directly deallocate, but add
5863   // to the deallocate list so that the klass is removed from the CLD::_klasses list
5864   // at a safepoint.
5865   if (_klass_to_deallocate != NULL) {
5866     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
5867   }
5868 }
5869 
5870 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
5871                                    TRAPS) {
5872 
5873   assert(stream != NULL, "invariant");
5874   assert(_class_name != NULL, "invariant");
5875 
5876   // BEGIN STREAM PARSING
5877   stream->guarantee_more(8, CHECK);  // magic, major, minor
5878   // Magic value
5879   const u4 magic = stream->get_u4_fast();
5880   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
5881                      "Incompatible magic value %u in class file %s",
5882                      magic, CHECK);
5883 
5884   // Version numbers
5885   _minor_version = stream->get_u2_fast();
5886   _major_version = stream->get_u2_fast();
5887 
5888   if (DumpSharedSpaces && _major_version < JAVA_1_5_VERSION) {
5889     ResourceMark rm;
5890     warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
5891             _major_version,  _minor_version, _class_name->as_C_string());
5892     Exceptions::fthrow(
5893       THREAD_AND_LOCATION,
5894       vmSymbols::java_lang_UnsupportedClassVersionError(),
5895       "Unsupported major.minor version for dump time %u.%u",
5896       _major_version,
5897       _minor_version);
5898   }
5899 
5900   // Check version numbers - we check this even with verifier off
5901   if (!is_supported_version(_major_version, _minor_version)) {
5902     ResourceMark rm(THREAD);
5903     Exceptions::fthrow(
5904       THREAD_AND_LOCATION,
5905       vmSymbols::java_lang_UnsupportedClassVersionError(),
5906       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
5907       "this version of the Java Runtime only recognizes class file versions up to %u.%u",
5908       _class_name->as_C_string(),
5909       _major_version,
5910       _minor_version,
5911       JAVA_MAX_SUPPORTED_VERSION,
5912       JAVA_MAX_SUPPORTED_MINOR_VERSION);
5913     return;
5914   }
5915 
5916   stream->guarantee_more(3, CHECK); // length, first cp tag
5917   u2 cp_size = stream->get_u2_fast();
5918 
5919   guarantee_property(
5920     cp_size >= 1, "Illegal constant pool size %u in class file %s",
5921     cp_size, CHECK);
5922 
5923   _orig_cp_size = cp_size;
5924   if (int(cp_size) + _max_num_patched_klasses > 0xffff) {
5925     THROW_MSG(vmSymbols::java_lang_InternalError(), "not enough space for patched classes");
5926   }
5927   cp_size += _max_num_patched_klasses;
5928 
5929   _cp = ConstantPool::allocate(_loader_data,
5930                                cp_size,
5931                                CHECK);
5932 
5933   ConstantPool* const cp = _cp;
5934 
5935   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5936 
5937   assert(cp_size == (const u2)cp->length(), "invariant");
5938 
5939   // ACCESS FLAGS
5940   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5941 
5942   // Access flags
5943   jint flags;
5944   // JVM_ACC_MODULE is defined in JDK-9 and later.
5945   if (_major_version >= JAVA_9_VERSION) {
5946     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5947   } else {
5948     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5949   }
5950 
5951   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5952     // Set abstract bit for old class files for backward compatibility
5953     flags |= JVM_ACC_ABSTRACT;
5954   }
5955 
5956   verify_legal_class_modifiers(flags, CHECK);
5957 
5958   short bad_constant = class_bad_constant_seen();
5959   if (bad_constant != 0) {
5960     // Do not throw CFE until after the access_flags are checked because if
5961     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5962     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, CHECK);
5963   }
5964 
5965   _access_flags.set_flags(flags);
5966 
5967   // This class and superclass
5968   _this_class_index = stream->get_u2_fast();
5969   check_property(
5970     valid_cp_range(_this_class_index, cp_size) &&
5971       cp->tag_at(_this_class_index).is_unresolved_klass(),
5972     "Invalid this class index %u in constant pool in class file %s",
5973     _this_class_index, CHECK);
5974 
5975   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5976   assert(class_name_in_cp != NULL, "class_name can't be null");
5977 
5978   // Update _class_name which could be null previously
5979   // to reflect the name in the constant pool
5980   _class_name = class_name_in_cp;
5981 
5982   // Don't need to check whether this class name is legal or not.
5983   // It has been checked when constant pool is parsed.
5984   // However, make sure it is not an array type.
5985   if (_need_verify) {
5986     guarantee_property(_class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
5987                        "Bad class name in class file %s",
5988                        CHECK);
5989   }
5990 
5991   // Checks if name in class file matches requested name
5992   if (_requested_name != NULL && _requested_name != _class_name) {
5993     ResourceMark rm(THREAD);
5994     Exceptions::fthrow(
5995       THREAD_AND_LOCATION,
5996       vmSymbols::java_lang_NoClassDefFoundError(),
5997       "%s (wrong name: %s)",
5998       _class_name->as_C_string(),
5999       _requested_name != NULL ? _requested_name->as_C_string() : "NoName"
6000     );
6001     return;
6002   }
6003 
6004   // if this is an anonymous class fix up its name if it's in the unnamed
6005   // package.  Otherwise, throw IAE if it is in a different package than
6006   // its host class.
6007   if (_host_klass != NULL) {
6008     fix_anonymous_class_name(CHECK);
6009   }
6010 
6011   // Verification prevents us from creating names with dots in them, this
6012   // asserts that that's the case.
6013   assert(is_internal_format(_class_name), "external class name format used internally");
6014 
6015   if (!is_internal()) {
6016     LogTarget(Debug, class, preorder) lt;
6017     if (lt.is_enabled()){
6018       ResourceMark rm(THREAD);
6019       LogStream ls(lt);
6020       ls.print("%s", _class_name->as_klass_external_name());
6021       if (stream->source() != NULL) {
6022         ls.print(" source: %s", stream->source());
6023       }
6024       ls.cr();
6025     }
6026 
6027 #if INCLUDE_CDS
6028     if (DumpLoadedClassList != NULL && stream->source() != NULL && classlist_file->is_open()) {
6029       // Only dump the classes that can be stored into CDS archive.
6030       // Anonymous classes such as generated LambdaForm classes are also not included.
6031       if (SystemDictionaryShared::is_sharing_possible(_loader_data) &&
6032           _host_klass == NULL) {
6033         oop class_loader = _loader_data->class_loader();
6034         ResourceMark rm(THREAD);
6035         // For the boot and platform class loaders, check if the class is not found in the
6036         // java runtime image. Additional check for the boot class loader is if the class
6037         // is not found in the boot loader's appended entries. This indicates that the class
6038         // is not useable during run time, such as the ones found in the --patch-module entries,
6039         // so it should not be included in the classlist file.
6040         if (((class_loader == NULL && !ClassLoader::contains_append_entry(stream->source())) ||
6041              SystemDictionary::is_platform_class_loader(class_loader)) &&
6042             !ClassLoader::is_jrt(stream->source())) {
6043           tty->print_cr("skip writing class %s from source %s to classlist file",
6044             _class_name->as_C_string(), stream->source());
6045         } else {
6046           classlist_file->print_cr("%s", _class_name->as_C_string());
6047           classlist_file->flush();
6048         }
6049       }
6050     }
6051 #endif
6052   }
6053 
6054   // SUPERKLASS
6055   _super_class_index = stream->get_u2_fast();
6056   _super_klass = parse_super_class(cp,
6057                                    _super_class_index,
6058                                    _need_verify,
6059                                    CHECK);
6060 
6061   // Interfaces
6062   _itfs_len = stream->get_u2_fast();
6063   parse_interfaces(stream,
6064                    _itfs_len,
6065                    cp,
6066                    &_has_nonstatic_concrete_methods,
6067                    CHECK);
6068 
6069   assert(_local_interfaces != NULL, "invariant");
6070 
6071   // Fields (offsets are filled in later)
6072   _fac = new FieldAllocationCount();
6073   parse_fields(stream,
6074                _access_flags.is_interface(),
6075                _fac,
6076                cp,
6077                cp_size,
6078                &_java_fields_count,
6079                CHECK);
6080 
6081   assert(_fields != NULL, "invariant");
6082 
6083   // Methods
6084   AccessFlags promoted_flags;
6085   parse_methods(stream,
6086                 _access_flags.is_interface(),
6087                 &promoted_flags,
6088                 &_has_final_method,
6089                 &_declares_nonstatic_concrete_methods,
6090                 CHECK);
6091 
6092   assert(_methods != NULL, "invariant");
6093 
6094   // promote flags from parse_methods() to the klass' flags
6095   _access_flags.add_promoted_flags(promoted_flags.as_int());
6096 
6097   if (_declares_nonstatic_concrete_methods) {
6098     _has_nonstatic_concrete_methods = true;
6099   }
6100 
6101   // Additional attributes/annotations
6102   _parsed_annotations = new ClassAnnotationCollector();
6103   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6104 
6105   assert(_inner_classes != NULL, "invariant");
6106 
6107   // Finalize the Annotations metadata object,
6108   // now that all annotation arrays have been created.
6109   create_combined_annotations(CHECK);
6110 
6111   // Make sure this is the end of class file stream
6112   guarantee_property(stream->at_eos(),
6113                      "Extra bytes at the end of class file %s",
6114                      CHECK);
6115 
6116   // all bytes in stream read and parsed
6117 }
6118 
6119 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6120                                                  ConstantPool* cp,
6121                                                  TRAPS) {
6122   assert(stream != NULL, "invariant");
6123   assert(stream->at_eos(), "invariant");
6124   assert(cp != NULL, "invariant");
6125   assert(_loader_data != NULL, "invariant");
6126 
6127   if (_class_name == vmSymbols::java_lang_Object()) {
6128     check_property(_local_interfaces == Universe::the_empty_klass_array(),
6129                    "java.lang.Object cannot implement an interface in class file %s",
6130                    CHECK);
6131   }
6132   // We check super class after class file is parsed and format is checked
6133   if (_super_class_index > 0 && NULL ==_super_klass) {
6134     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6135     if (_access_flags.is_interface()) {
6136       // Before attempting to resolve the superclass, check for class format
6137       // errors not checked yet.
6138       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6139         "Interfaces must have java.lang.Object as superclass in class file %s",
6140         CHECK);
6141     }
6142     Handle loader(THREAD, _loader_data->class_loader());
6143     _super_klass = (const InstanceKlass*)
6144                        SystemDictionary::resolve_super_or_fail(_class_name,
6145                                                                super_class_name,
6146                                                                loader,
6147                                                                _protection_domain,
6148                                                                true,
6149                                                                CHECK);
6150   }
6151 
6152   if (_super_klass != NULL) {
6153     if (_super_klass->has_nonstatic_concrete_methods()) {
6154       _has_nonstatic_concrete_methods = true;
6155     }
6156 
6157     if (_super_klass->is_interface()) {
6158       ResourceMark rm(THREAD);
6159       Exceptions::fthrow(
6160         THREAD_AND_LOCATION,
6161         vmSymbols::java_lang_IncompatibleClassChangeError(),
6162         "class %s has interface %s as super class",
6163         _class_name->as_klass_external_name(),
6164         _super_klass->external_name()
6165       );
6166       return;
6167     }
6168     // Make sure super class is not final
6169     if (_super_klass->is_final()) {
6170       THROW_MSG(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class");
6171     }
6172   }
6173 
6174   // Compute the transitive list of all unique interfaces implemented by this class
6175   _transitive_interfaces =
6176     compute_transitive_interfaces(_super_klass,
6177                                   _local_interfaces,
6178                                   _loader_data,
6179                                   CHECK);
6180 
6181   assert(_transitive_interfaces != NULL, "invariant");
6182 
6183   // sort methods
6184   _method_ordering = sort_methods(_methods);
6185 
6186   _all_mirandas = new GrowableArray<Method*>(20);
6187 
6188   Handle loader(THREAD, _loader_data->class_loader());
6189   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6190                                                     &_num_miranda_methods,
6191                                                     _all_mirandas,
6192                                                     _super_klass,
6193                                                     _methods,
6194                                                     _access_flags,
6195                                                     _major_version,
6196                                                     loader,
6197                                                     _class_name,
6198                                                     _local_interfaces,
6199                                                     CHECK);
6200 
6201   // Size of Java itable (in words)
6202   _itable_size = _access_flags.is_interface() ? 0 :
6203     klassItable::compute_itable_size(_transitive_interfaces);
6204 
6205   assert(_fac != NULL, "invariant");
6206   assert(_parsed_annotations != NULL, "invariant");
6207 
6208   _field_info = new FieldLayoutInfo();
6209   layout_fields(cp, _fac, _parsed_annotations, _field_info, CHECK);
6210 
6211   // Compute reference typ
6212   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();
6213 
6214 }
6215 
6216 void ClassFileParser::set_klass(InstanceKlass* klass) {
6217 
6218 #ifdef ASSERT
6219   if (klass != NULL) {
6220     assert(NULL == _klass, "leaking?");
6221   }
6222 #endif
6223 
6224   _klass = klass;
6225 }
6226 
6227 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6228 
6229 #ifdef ASSERT
6230   if (klass != NULL) {
6231     assert(NULL == _klass_to_deallocate, "leaking?");
6232   }
6233 #endif
6234 
6235   _klass_to_deallocate = klass;
6236 }
6237 
6238 // Caller responsible for ResourceMark
6239 // clone stream with rewound position
6240 const ClassFileStream* ClassFileParser::clone_stream() const {
6241   assert(_stream != NULL, "invariant");
6242 
6243   return _stream->clone();
6244 }
6245 // ----------------------------------------------------------------------------
6246 // debugging
6247 
6248 #ifdef ASSERT
6249 
6250 // return true if class_name contains no '.' (internal format is '/')
6251 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6252   if (class_name != NULL) {
6253     ResourceMark rm;
6254     char* name = class_name->as_C_string();
6255     return strchr(name, '.') == NULL;
6256   } else {
6257     return true;
6258   }
6259 }
6260 
6261 #endif