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