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