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 OopMapBlocksBuilder::OopMapBlocksBuilder(unsigned int max_blocks) {
4032   _max_nonstatic_oop_maps = max_blocks;
4033   _nonstatic_oop_map_count = 0;
4034   if (max_blocks == 0) {
4035     _nonstatic_oop_maps = NULL;
4036   } else {
4037     _nonstatic_oop_maps =
4038         NEW_RESOURCE_ARRAY(OopMapBlock, _max_nonstatic_oop_maps);
4039     memset(_nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
4040   }
4041 }
4042 
4043 OopMapBlock* OopMapBlocksBuilder::last_oop_map() const {
4044   assert(_nonstatic_oop_map_count > 0, "Has no oop maps");
4045   return _nonstatic_oop_maps + (_nonstatic_oop_map_count - 1);
4046 }
4047 
4048 // addition of super oop maps
4049 void OopMapBlocksBuilder::initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
4050   assert(nof_blocks && _nonstatic_oop_map_count == 0 &&
4051          nof_blocks <= _max_nonstatic_oop_maps, "invariant");
4052 
4053   memcpy(_nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
4054   _nonstatic_oop_map_count += nof_blocks;
4055 }
4056 
4057 // collection of oops
4058 void OopMapBlocksBuilder::add(int offset, int count) {
4059   if (_nonstatic_oop_map_count == 0) {
4060     _nonstatic_oop_map_count++;
4061   }
4062   OopMapBlock* nonstatic_oop_map = last_oop_map();
4063   if (nonstatic_oop_map->count() == 0) {  // Unused map, set it up
4064     nonstatic_oop_map->set_offset(offset);
4065     nonstatic_oop_map->set_count(count);
4066   } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
4067     nonstatic_oop_map->increment_count(count);
4068   } else { // Need a new one...
4069     _nonstatic_oop_map_count++;
4070     assert(_nonstatic_oop_map_count <= _max_nonstatic_oop_maps, "range check");
4071     nonstatic_oop_map = last_oop_map();
4072     nonstatic_oop_map->set_offset(offset);
4073     nonstatic_oop_map->set_count(count);
4074   }
4075 }
4076 
4077 // general purpose copy, e.g. into allocated instanceKlass
4078 void OopMapBlocksBuilder::copy(OopMapBlock* dst) {
4079   if (_nonstatic_oop_map_count != 0) {
4080     memcpy(dst, _nonstatic_oop_maps, sizeof(OopMapBlock) * _nonstatic_oop_map_count);
4081   }
4082 }
4083 
4084 // Sort and compact adjacent blocks
4085 void OopMapBlocksBuilder::compact() {
4086   if (_nonstatic_oop_map_count <= 1) {
4087     return;
4088   }
4089   /*
4090    * Since field layout sneeks in oops before values, we will be able to condense
4091    * blocks. There is potential to compact between super, own refs and values
4092    * containing refs.
4093    *
4094    * Currently compaction is slightly limited due to values being 8 byte aligned.
4095    * This may well change: FixMe if it doesn't, the code below is fairly general purpose
4096    * and maybe it doesn't need to be.
4097    */
4098   qsort(_nonstatic_oop_maps, _nonstatic_oop_map_count, sizeof(OopMapBlock),
4099         (_sort_Fn)OopMapBlock::compare_offset);
4100   if (_nonstatic_oop_map_count < 2) {
4101     return;
4102   }
4103 
4104   // Make a temp copy, and iterate through and copy back into the original
4105   ResourceMark rm;
4106   OopMapBlock* oop_maps_copy =
4107       NEW_RESOURCE_ARRAY(OopMapBlock, _nonstatic_oop_map_count);
4108   OopMapBlock* oop_maps_copy_end = oop_maps_copy + _nonstatic_oop_map_count;
4109   copy(oop_maps_copy);
4110   OopMapBlock* nonstatic_oop_map = _nonstatic_oop_maps;
4111   unsigned int new_count = 1;
4112   oop_maps_copy++;
4113   while(oop_maps_copy < oop_maps_copy_end) {
4114     assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
4115     if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
4116       nonstatic_oop_map->increment_count(oop_maps_copy->count());
4117     } else {
4118       nonstatic_oop_map++;
4119       new_count++;
4120       nonstatic_oop_map->set_offset(oop_maps_copy->offset());
4121       nonstatic_oop_map->set_count(oop_maps_copy->count());
4122     }
4123     oop_maps_copy++;
4124   }
4125   assert(new_count <= _nonstatic_oop_map_count, "end up with more maps after compact() ?");
4126   _nonstatic_oop_map_count = new_count;
4127 }
4128 
4129 void OopMapBlocksBuilder::print_on(outputStream* st) const {
4130   st->print_cr("  OopMapBlocks: %3d  /%3d", _nonstatic_oop_map_count, _max_nonstatic_oop_maps);
4131   if (_nonstatic_oop_map_count > 0) {
4132     OopMapBlock* map = _nonstatic_oop_maps;
4133     OopMapBlock* last_map = last_oop_map();
4134     assert(map <= last_map, "Last less than first");
4135     while (map <= last_map) {
4136       st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
4137                    map->offset() + map->offset_span() - heapOopSize, map->count());
4138       map++;
4139     }
4140   }
4141 }
4142 
4143 void OopMapBlocksBuilder::print_value_on(outputStream* st) const {
4144   print_on(st);
4145 }
4146 
4147 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4148   assert(ik != NULL, "invariant");
4149 
4150   const Klass* const super = ik->super();
4151 
4152   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4153   // in which case we don't have to register objects as finalizable
4154   if (!_has_empty_finalizer) {
4155     if (_has_finalizer ||
4156         (super != NULL && super->has_finalizer())) {
4157       ik->set_has_finalizer();
4158     }
4159   }
4160 
4161 #ifdef ASSERT
4162   bool f = false;
4163   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4164                                            vmSymbols::void_method_signature());
4165   if (m != NULL && !m->is_empty_method()) {
4166       f = true;
4167   }
4168 
4169   // Spec doesn't prevent agent from redefinition of empty finalizer.
4170   // Despite the fact that it's generally bad idea and redefined finalizer
4171   // will not work as expected we shouldn't abort vm in this case
4172   if (!ik->has_redefined_this_or_super()) {
4173     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4174   }
4175 #endif
4176 
4177   // Check if this klass supports the java.lang.Cloneable interface
4178   if (SystemDictionary::Cloneable_klass_loaded()) {
4179     if (ik->is_subtype_of(SystemDictionary::Cloneable_klass())) {
4180       ik->set_is_cloneable();
4181     }
4182   }
4183 
4184   // Check if this klass has a vanilla default constructor
4185   if (super == NULL) {
4186     // java.lang.Object has empty default constructor
4187     ik->set_has_vanilla_constructor();
4188   } else {
4189     if (super->has_vanilla_constructor() &&
4190         _has_vanilla_constructor) {
4191       ik->set_has_vanilla_constructor();
4192     }
4193 #ifdef ASSERT
4194     bool v = false;
4195     if (super->has_vanilla_constructor()) {
4196       const Method* const constructor =
4197         ik->find_method(vmSymbols::object_initializer_name(),
4198                        vmSymbols::void_method_signature());
4199       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4200         v = true;
4201       }
4202     }
4203     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4204 #endif
4205   }
4206 
4207   // If it cannot be fast-path allocated, set a bit in the layout helper.
4208   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4209   assert(ik->size_helper() > 0, "layout_helper is initialized");
4210   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4211       || ik->is_abstract() || ik->is_interface()
4212       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4213       || ik->size_helper() >= FastAllocateSizeLimit) {
4214     // Forbid fast-path allocation.
4215     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4216     ik->set_layout_helper(lh);
4217   }
4218 }
4219 
4220 // utility methods for appending an array with check for duplicates
4221 
4222 static void append_interfaces(GrowableArray<InstanceKlass*>* result,
4223                               const Array<InstanceKlass*>* const ifs) {
4224   // iterate over new interfaces
4225   for (int i = 0; i < ifs->length(); i++) {
4226     InstanceKlass* const e = ifs->at(i);
4227     assert(e->is_klass() && e->is_interface(), "just checking");
4228     // add new interface
4229     result->append_if_missing(e);
4230   }
4231 }
4232 
4233 static Array<InstanceKlass*>* compute_transitive_interfaces(const InstanceKlass* super,
4234                                                             Array<InstanceKlass*>* local_ifs,
4235                                                             ClassLoaderData* loader_data,
4236                                                             TRAPS) {
4237   assert(local_ifs != NULL, "invariant");
4238   assert(loader_data != NULL, "invariant");
4239 
4240   // Compute maximum size for transitive interfaces
4241   int max_transitive_size = 0;
4242   int super_size = 0;
4243   // Add superclass transitive interfaces size
4244   if (super != NULL) {
4245     super_size = super->transitive_interfaces()->length();
4246     max_transitive_size += super_size;
4247   }
4248   // Add local interfaces' super interfaces
4249   const int local_size = local_ifs->length();
4250   for (int i = 0; i < local_size; i++) {
4251     InstanceKlass* const l = local_ifs->at(i);
4252     max_transitive_size += l->transitive_interfaces()->length();
4253   }
4254   // Finally add local interfaces
4255   max_transitive_size += local_size;
4256   // Construct array
4257   if (max_transitive_size == 0) {
4258     // no interfaces, use canonicalized array
4259     return Universe::the_empty_instance_klass_array();
4260   } else if (max_transitive_size == super_size) {
4261     // no new local interfaces added, share superklass' transitive interface array
4262     return super->transitive_interfaces();
4263   } else if (max_transitive_size == local_size) {
4264     // only local interfaces added, share local interface array
4265     return local_ifs;
4266   } else {
4267     ResourceMark rm;
4268     GrowableArray<InstanceKlass*>* const result = new GrowableArray<InstanceKlass*>(max_transitive_size);
4269 
4270     // Copy down from superclass
4271     if (super != NULL) {
4272       append_interfaces(result, super->transitive_interfaces());
4273     }
4274 
4275     // Copy down from local interfaces' superinterfaces
4276     for (int i = 0; i < local_size; i++) {
4277       InstanceKlass* const l = local_ifs->at(i);
4278       append_interfaces(result, l->transitive_interfaces());
4279     }
4280     // Finally add local interfaces
4281     append_interfaces(result, local_ifs);
4282 
4283     // length will be less than the max_transitive_size if duplicates were removed
4284     const int length = result->length();
4285     assert(length <= max_transitive_size, "just checking");
4286     Array<InstanceKlass*>* const new_result =
4287       MetadataFactory::new_array<InstanceKlass*>(loader_data, length, CHECK_NULL);
4288     for (int i = 0; i < length; i++) {
4289       InstanceKlass* const e = result->at(i);
4290       assert(e != NULL, "just checking");
4291       new_result->at_put(i, e);
4292     }
4293     return new_result;
4294   }
4295 }
4296 
4297 static void check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4298   assert(this_klass != NULL, "invariant");
4299   const Klass* const super = this_klass->super();
4300 
4301   if (super != NULL) {
4302     const InstanceKlass* super_ik = InstanceKlass::cast(super);
4303 
4304     if (super->is_final()) {
4305       ResourceMark rm(THREAD);
4306       Exceptions::fthrow(
4307         THREAD_AND_LOCATION,
4308         vmSymbols::java_lang_VerifyError(),
4309         "class %s cannot inherit from final class %s",
4310         this_klass->external_name(),
4311         super_ik->external_name());
4312       return;
4313     }
4314 
4315     if (super_ik->is_sealed() && !super_ik->has_as_permitted_subclass(this_klass)) {
4316       ResourceMark rm(THREAD);
4317       Exceptions::fthrow(
4318         THREAD_AND_LOCATION,
4319         vmSymbols::java_lang_IncompatibleClassChangeError(),
4320         "class %s cannot inherit from sealed class %s",
4321         this_klass->external_name(),
4322         super_ik->external_name());
4323       return;
4324     }
4325 
4326     // If the loader is not the boot loader then throw an exception if its
4327     // superclass is in package jdk.internal.reflect and its loader is not a
4328     // special reflection class loader
4329     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4330       PackageEntry* super_package = super->package();
4331       if (super_package != NULL &&
4332           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4333           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4334         ResourceMark rm(THREAD);
4335         Exceptions::fthrow(
4336           THREAD_AND_LOCATION,
4337           vmSymbols::java_lang_IllegalAccessError(),
4338           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4339           this_klass->external_name(),
4340           this_klass->class_loader_data()->loader_name_and_id(),
4341           super->external_name());
4342         return;
4343       }
4344     }
4345 
4346     Reflection::VerifyClassAccessResults vca_result =
4347       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4348     if (vca_result != Reflection::ACCESS_OK) {
4349       ResourceMark rm(THREAD);
4350       char* msg = Reflection::verify_class_access_msg(this_klass,
4351                                                       InstanceKlass::cast(super),
4352                                                       vca_result);
4353       if (msg == NULL) {
4354         bool same_module = (this_klass->module() == super->module());
4355         Exceptions::fthrow(
4356           THREAD_AND_LOCATION,
4357           vmSymbols::java_lang_IllegalAccessError(),
4358           "class %s cannot access its %ssuperclass %s (%s%s%s)",
4359           this_klass->external_name(),
4360           super->is_abstract() ? "abstract " : "",
4361           super->external_name(),
4362           (same_module) ? this_klass->joint_in_module_of_loader(super) : this_klass->class_in_module_of_loader(),
4363           (same_module) ? "" : "; ",
4364           (same_module) ? "" : super->class_in_module_of_loader());
4365       } else {
4366         // Add additional message content.
4367         Exceptions::fthrow(
4368           THREAD_AND_LOCATION,
4369           vmSymbols::java_lang_IllegalAccessError(),
4370           "superclass access check failed: %s",
4371           msg);
4372       }
4373     }
4374   }
4375 }
4376 
4377 
4378 static void check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4379   assert(this_klass != NULL, "invariant");
4380   const Array<InstanceKlass*>* const local_interfaces = this_klass->local_interfaces();
4381   const int lng = local_interfaces->length();
4382   for (int i = lng - 1; i >= 0; i--) {
4383     InstanceKlass* const k = local_interfaces->at(i);
4384     assert (k != NULL && k->is_interface(), "invalid interface");
4385 
4386     if (k->is_sealed() && !k->has_as_permitted_subclass(this_klass)) {
4387       ResourceMark rm(THREAD);
4388       Exceptions::fthrow(
4389         THREAD_AND_LOCATION,
4390         vmSymbols::java_lang_IncompatibleClassChangeError(),
4391         "class %s cannot %s sealed interface %s",
4392         this_klass->external_name(),
4393         this_klass->is_interface() ? "extend" : "implement",
4394         k->external_name());
4395       return;
4396     }
4397 
4398     Reflection::VerifyClassAccessResults vca_result =
4399       Reflection::verify_class_access(this_klass, k, false);
4400     if (vca_result != Reflection::ACCESS_OK) {
4401       ResourceMark rm(THREAD);
4402       char* msg = Reflection::verify_class_access_msg(this_klass,
4403                                                       k,
4404                                                       vca_result);
4405       if (msg == NULL) {
4406         bool same_module = (this_klass->module() == k->module());
4407         Exceptions::fthrow(
4408           THREAD_AND_LOCATION,
4409           vmSymbols::java_lang_IllegalAccessError(),
4410           "class %s cannot access its superinterface %s (%s%s%s)",
4411           this_klass->external_name(),
4412           k->external_name(),
4413           (same_module) ? this_klass->joint_in_module_of_loader(k) : this_klass->class_in_module_of_loader(),
4414           (same_module) ? "" : "; ",
4415           (same_module) ? "" : k->class_in_module_of_loader());
4416       } else {
4417         // Add additional message content.
4418         Exceptions::fthrow(
4419           THREAD_AND_LOCATION,
4420           vmSymbols::java_lang_IllegalAccessError(),
4421           "superinterface check failed: %s",
4422           msg);
4423       }
4424     }
4425   }
4426 }
4427 
4428 
4429 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4430   assert(this_klass != NULL, "invariant");
4431   const Array<Method*>* const methods = this_klass->methods();
4432   const int num_methods = methods->length();
4433 
4434   // go thru each method and check if it overrides a final method
4435   for (int index = 0; index < num_methods; index++) {
4436     const Method* const m = methods->at(index);
4437 
4438     // skip private, static, and <init> methods
4439     if ((!m->is_private() && !m->is_static()) &&
4440         (m->name() != vmSymbols::object_initializer_name())) {
4441 
4442       const Symbol* const name = m->name();
4443       const Symbol* const signature = m->signature();
4444       const Klass* k = this_klass->super();
4445       const Method* super_m = NULL;
4446       while (k != NULL) {
4447         // skip supers that don't have final methods.
4448         if (k->has_final_method()) {
4449           // lookup a matching method in the super class hierarchy
4450           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4451           if (super_m == NULL) {
4452             break; // didn't find any match; get out
4453           }
4454 
4455           if (super_m->is_final() && !super_m->is_static() &&
4456               !super_m->access_flags().is_private()) {
4457             // matching method in super is final, and not static or private
4458             bool can_access = Reflection::verify_member_access(this_klass,
4459                                                                super_m->method_holder(),
4460                                                                super_m->method_holder(),
4461                                                                super_m->access_flags(),
4462                                                               false, false, CHECK);
4463             if (can_access) {
4464               // this class can access super final method and therefore override
4465               ResourceMark rm(THREAD);
4466               Exceptions::fthrow(THREAD_AND_LOCATION,
4467                                  vmSymbols::java_lang_VerifyError(),
4468                                  "class %s overrides final method %s.%s%s",
4469                                  this_klass->external_name(),
4470                                  super_m->method_holder()->external_name(),
4471                                  name->as_C_string(),
4472                                  signature->as_C_string()
4473                                  );
4474               return;
4475             }
4476           }
4477 
4478           // continue to look from super_m's holder's super.
4479           k = super_m->method_holder()->super();
4480           continue;
4481         }
4482 
4483         k = k->super();
4484       }
4485     }
4486   }
4487 }
4488 
4489 
4490 // assumes that this_klass is an interface
4491 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4492   assert(this_klass != NULL, "invariant");
4493   assert(this_klass->is_interface(), "not an interface");
4494   const Array<Method*>* methods = this_klass->methods();
4495   const int num_methods = methods->length();
4496 
4497   for (int index = 0; index < num_methods; index++) {
4498     const Method* const m = methods->at(index);
4499     // if m is static and not the init method, throw a verify error
4500     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4501       ResourceMark rm(THREAD);
4502       Exceptions::fthrow(
4503         THREAD_AND_LOCATION,
4504         vmSymbols::java_lang_VerifyError(),
4505         "Illegal static method %s in interface %s",
4506         m->name()->as_C_string(),
4507         this_klass->external_name()
4508       );
4509       return;
4510     }
4511   }
4512 }
4513 
4514 // utility methods for format checking
4515 
4516 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4517   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4518   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4519   if (is_module) {
4520     ResourceMark rm(THREAD);
4521     Exceptions::fthrow(
4522       THREAD_AND_LOCATION,
4523       vmSymbols::java_lang_NoClassDefFoundError(),
4524       "%s is not a class because access_flag ACC_MODULE is set",
4525       _class_name->as_C_string());
4526     return;
4527   }
4528 
4529   if (!_need_verify) { return; }
4530 
4531   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4532   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4533   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4534   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4535   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4536   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4537   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4538   const bool major_gte_14  = _major_version >= JAVA_14_VERSION;
4539 
4540   if ((is_abstract && is_final) ||
4541       (is_interface && !is_abstract) ||
4542       (is_interface && major_gte_1_5 && (is_super || is_enum)) ||
4543       (!is_interface && major_gte_1_5 && is_annotation)) {
4544     ResourceMark rm(THREAD);
4545     Exceptions::fthrow(
4546       THREAD_AND_LOCATION,
4547       vmSymbols::java_lang_ClassFormatError(),
4548       "Illegal class modifiers in class %s: 0x%X",
4549       _class_name->as_C_string(), flags
4550     );
4551     return;
4552   }
4553 }
4554 
4555 static bool has_illegal_visibility(jint flags) {
4556   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4557   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4558   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4559 
4560   return ((is_public && is_protected) ||
4561           (is_public && is_private) ||
4562           (is_protected && is_private));
4563 }
4564 
4565 // A legal major_version.minor_version must be one of the following:
4566 //
4567 //  Major_version >= 45 and major_version < 56, any minor_version.
4568 //  Major_version >= 56 and major_version <= JVM_CLASSFILE_MAJOR_VERSION and minor_version = 0.
4569 //  Major_version = JVM_CLASSFILE_MAJOR_VERSION and minor_version = 65535 and --enable-preview is present.
4570 //
4571 static void verify_class_version(u2 major, u2 minor, Symbol* class_name, TRAPS){
4572   ResourceMark rm(THREAD);
4573   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
4574   if (major < JAVA_MIN_SUPPORTED_VERSION) {
4575     Exceptions::fthrow(
4576       THREAD_AND_LOCATION,
4577       vmSymbols::java_lang_UnsupportedClassVersionError(),
4578       "%s (class file version %u.%u) was compiled with an invalid major version",
4579       class_name->as_C_string(), major, minor);
4580     return;
4581   }
4582 
4583   if (major > max_version) {
4584     Exceptions::fthrow(
4585       THREAD_AND_LOCATION,
4586       vmSymbols::java_lang_UnsupportedClassVersionError(),
4587       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
4588       "this version of the Java Runtime only recognizes class file versions up to %u.0",
4589       class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION);
4590     return;
4591   }
4592 
4593   if (major < JAVA_12_VERSION || minor == 0) {
4594     return;
4595   }
4596 
4597   if (minor == JAVA_PREVIEW_MINOR_VERSION) {
4598     if (major != max_version) {
4599       Exceptions::fthrow(
4600         THREAD_AND_LOCATION,
4601         vmSymbols::java_lang_UnsupportedClassVersionError(),
4602         "%s (class file version %u.%u) was compiled with preview features that are unsupported. "
4603         "This version of the Java Runtime only recognizes preview features for class file version %u.%u",
4604         class_name->as_C_string(), major, minor, JVM_CLASSFILE_MAJOR_VERSION, JAVA_PREVIEW_MINOR_VERSION);
4605       return;
4606     }
4607 
4608     if (!Arguments::enable_preview()) {
4609       Exceptions::fthrow(
4610         THREAD_AND_LOCATION,
4611         vmSymbols::java_lang_UnsupportedClassVersionError(),
4612         "Preview features are not enabled for %s (class file version %u.%u). Try running with '--enable-preview'",
4613         class_name->as_C_string(), major, minor);
4614       return;
4615     }
4616 
4617   } else { // minor != JAVA_PREVIEW_MINOR_VERSION
4618     Exceptions::fthrow(
4619         THREAD_AND_LOCATION,
4620         vmSymbols::java_lang_UnsupportedClassVersionError(),
4621         "%s (class file version %u.%u) was compiled with an invalid non-zero minor version",
4622         class_name->as_C_string(), major, minor);
4623   }
4624 }
4625 
4626 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4627                                                    bool is_interface,
4628                                                    TRAPS) const {
4629   if (!_need_verify) { return; }
4630 
4631   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4632   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4633   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4634   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4635   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4636   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4637   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4638   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4639   const bool major_gte_1_5 = _major_version >= JAVA_1_5_VERSION;
4640 
4641   bool is_illegal = false;
4642 
4643   if (is_interface) {
4644     if (!is_public || !is_static || !is_final || is_private ||
4645         is_protected || is_volatile || is_transient ||
4646         (major_gte_1_5 && is_enum)) {
4647       is_illegal = true;
4648     }
4649   } else { // not interface
4650     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4651       is_illegal = true;
4652     }
4653   }
4654 
4655   if (is_illegal) {
4656     ResourceMark rm(THREAD);
4657     Exceptions::fthrow(
4658       THREAD_AND_LOCATION,
4659       vmSymbols::java_lang_ClassFormatError(),
4660       "Illegal field modifiers in class %s: 0x%X",
4661       _class_name->as_C_string(), flags);
4662     return;
4663   }
4664 }
4665 
4666 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4667                                                     bool is_interface,
4668                                                     const Symbol* name,
4669                                                     TRAPS) const {
4670   if (!_need_verify) { return; }
4671 
4672   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4673   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4674   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4675   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4676   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4677   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4678   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4679   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4680   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4681   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4682   const bool major_gte_1_5   = _major_version >= JAVA_1_5_VERSION;
4683   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4684   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4685 
4686   bool is_illegal = false;
4687 
4688   if (is_interface) {
4689     if (major_gte_8) {
4690       // Class file version is JAVA_8_VERSION or later Methods of
4691       // interfaces may set any of the flags except ACC_PROTECTED,
4692       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4693       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4694       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4695           (is_native || is_protected || is_final || is_synchronized) ||
4696           // If a specific method of a class or interface has its
4697           // ACC_ABSTRACT flag set, it must not have any of its
4698           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4699           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4700           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4701           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4702           (is_abstract && (is_private || is_static || is_strict))) {
4703         is_illegal = true;
4704       }
4705     } else if (major_gte_1_5) {
4706       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4707       if (!is_public || is_private || is_protected || is_static || is_final ||
4708           is_synchronized || is_native || !is_abstract || is_strict) {
4709         is_illegal = true;
4710       }
4711     } else {
4712       // Class file version is pre-JAVA_1_5_VERSION
4713       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4714         is_illegal = true;
4715       }
4716     }
4717   } else { // not interface
4718     if (has_illegal_visibility(flags)) {
4719       is_illegal = true;
4720     } else {
4721       if (is_initializer) {
4722         if (is_static || is_final || is_synchronized || is_native ||
4723             is_abstract || (major_gte_1_5 && is_bridge)) {
4724           is_illegal = true;
4725         }
4726       } else { // not initializer
4727         if (is_abstract) {
4728           if ((is_final || is_native || is_private || is_static ||
4729               (major_gte_1_5 && (is_synchronized || is_strict)))) {
4730             is_illegal = true;
4731           }
4732         }
4733       }
4734     }
4735   }
4736 
4737   if (is_illegal) {
4738     ResourceMark rm(THREAD);
4739     Exceptions::fthrow(
4740       THREAD_AND_LOCATION,
4741       vmSymbols::java_lang_ClassFormatError(),
4742       "Method %s in class %s has illegal modifiers: 0x%X",
4743       name->as_C_string(), _class_name->as_C_string(), flags);
4744     return;
4745   }
4746 }
4747 
4748 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4749                                         int length,
4750                                         TRAPS) const {
4751   assert(_need_verify, "only called when _need_verify is true");
4752   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4753     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
4754   }
4755 }
4756 
4757 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4758 // In class names, '/' separates unqualified names.  This is verified in this function also.
4759 // Method names also may not contain the characters '<' or '>', unless <init>
4760 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4761 // method.  Because these names have been checked as special cases before
4762 // calling this method in verify_legal_method_name.
4763 //
4764 // This method is also called from the modular system APIs in modules.cpp
4765 // to verify the validity of module and package names.
4766 bool ClassFileParser::verify_unqualified_name(const char* name,
4767                                               unsigned int length,
4768                                               int type) {
4769   if (length == 0) return false;  // Must have at least one char.
4770   for (const char* p = name; p != name + length; p++) {
4771     switch(*p) {
4772       case JVM_SIGNATURE_DOT:
4773       case JVM_SIGNATURE_ENDCLASS:
4774       case JVM_SIGNATURE_ARRAY:
4775         // do not permit '.', ';', or '['
4776         return false;
4777       case JVM_SIGNATURE_SLASH:
4778         // check for '//' or leading or trailing '/' which are not legal
4779         // unqualified name must not be empty
4780         if (type == ClassFileParser::LegalClass) {
4781           if (p == name || p+1 >= name+length ||
4782               *(p+1) == JVM_SIGNATURE_SLASH) {
4783             return false;
4784           }
4785         } else {
4786           return false;   // do not permit '/' unless it's class name
4787         }
4788         break;
4789       case JVM_SIGNATURE_SPECIAL:
4790       case JVM_SIGNATURE_ENDSPECIAL:
4791         // do not permit '<' or '>' in method names
4792         if (type == ClassFileParser::LegalMethod) {
4793           return false;
4794         }
4795     }
4796   }
4797   return true;
4798 }
4799 
4800 // Take pointer to a UTF8 byte string (not NUL-terminated).
4801 // Skip over the longest part of the string that could
4802 // be taken as a fieldname. Allow '/' if slash_ok is true.
4803 // Return a pointer to just past the fieldname.
4804 // Return NULL if no fieldname at all was found, or in the case of slash_ok
4805 // being true, we saw consecutive slashes (meaning we were looking for a
4806 // qualified path but found something that was badly-formed).
4807 static const char* skip_over_field_name(const char* const name,
4808                                         bool slash_ok,
4809                                         unsigned int length) {
4810   const char* p;
4811   jboolean last_is_slash = false;
4812   jboolean not_first_ch = false;
4813 
4814   for (p = name; p != name + length; not_first_ch = true) {
4815     const char* old_p = p;
4816     jchar ch = *p;
4817     if (ch < 128) {
4818       p++;
4819       // quick check for ascii
4820       if ((ch >= 'a' && ch <= 'z') ||
4821         (ch >= 'A' && ch <= 'Z') ||
4822         (ch == '_' || ch == '$') ||
4823         (not_first_ch && ch >= '0' && ch <= '9')) {
4824         last_is_slash = false;
4825         continue;
4826       }
4827       if (slash_ok && ch == JVM_SIGNATURE_SLASH) {
4828         if (last_is_slash) {
4829           return NULL;  // Don't permit consecutive slashes
4830         }
4831         last_is_slash = true;
4832         continue;
4833       }
4834     }
4835     else {
4836       jint unicode_ch;
4837       char* tmp_p = UTF8::next_character(p, &unicode_ch);
4838       p = tmp_p;
4839       last_is_slash = false;
4840       // Check if ch is Java identifier start or is Java identifier part
4841       // 4672820: call java.lang.Character methods directly without generating separate tables.
4842       EXCEPTION_MARK;
4843       // return value
4844       JavaValue result(T_BOOLEAN);
4845       // Set up the arguments to isJavaIdentifierStart or isJavaIdentifierPart
4846       JavaCallArguments args;
4847       args.push_int(unicode_ch);
4848 
4849       if (not_first_ch) {
4850         // public static boolean isJavaIdentifierPart(char ch);
4851         JavaCalls::call_static(&result,
4852           SystemDictionary::Character_klass(),
4853           vmSymbols::isJavaIdentifierPart_name(),
4854           vmSymbols::int_bool_signature(),
4855           &args,
4856           THREAD);
4857       } else {
4858         // public static boolean isJavaIdentifierStart(char ch);
4859         JavaCalls::call_static(&result,
4860           SystemDictionary::Character_klass(),
4861           vmSymbols::isJavaIdentifierStart_name(),
4862           vmSymbols::int_bool_signature(),
4863           &args,
4864           THREAD);
4865       }
4866       if (HAS_PENDING_EXCEPTION) {
4867         CLEAR_PENDING_EXCEPTION;
4868         return NULL;
4869       }
4870       if(result.get_jboolean()) {
4871         continue;
4872       }
4873     }
4874     return (not_first_ch) ? old_p : NULL;
4875   }
4876   return (not_first_ch) ? p : NULL;
4877 }
4878 
4879 // Take pointer to a UTF8 byte string (not NUL-terminated).
4880 // Skip over the longest part of the string that could
4881 // be taken as a field signature. Allow "void" if void_ok.
4882 // Return a pointer to just past the signature.
4883 // Return NULL if no legal signature is found.
4884 const char* ClassFileParser::skip_over_field_signature(const char* signature,
4885                                                        bool void_ok,
4886                                                        unsigned int length,
4887                                                        TRAPS) const {
4888   unsigned int array_dim = 0;
4889   while (length > 0) {
4890     switch (signature[0]) {
4891     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
4892     case JVM_SIGNATURE_BOOLEAN:
4893     case JVM_SIGNATURE_BYTE:
4894     case JVM_SIGNATURE_CHAR:
4895     case JVM_SIGNATURE_SHORT:
4896     case JVM_SIGNATURE_INT:
4897     case JVM_SIGNATURE_FLOAT:
4898     case JVM_SIGNATURE_LONG:
4899     case JVM_SIGNATURE_DOUBLE:
4900       return signature + 1;
4901     case JVM_SIGNATURE_CLASS: {
4902       if (_major_version < JAVA_1_5_VERSION) {
4903         // Skip over the class name if one is there
4904         const char* const p = skip_over_field_name(signature + 1, true, --length);
4905 
4906         // The next character better be a semicolon
4907         if (p && (p - signature) > 1 && p[0] == JVM_SIGNATURE_ENDCLASS) {
4908           return p + 1;
4909         }
4910       }
4911       else {
4912         // Skip leading 'L' and ignore first appearance of ';'
4913         signature++;
4914         const char* c = (const char*) memchr(signature, JVM_SIGNATURE_ENDCLASS, length - 1);
4915         // Format check signature
4916         if (c != NULL) {
4917           int newlen = c - (char*) signature;
4918           bool legal = verify_unqualified_name(signature, newlen, LegalClass);
4919           if (!legal) {
4920             classfile_parse_error("Class name is empty or contains illegal character "
4921                                   "in descriptor in class file %s",
4922                                   CHECK_NULL);
4923             return NULL;
4924           }
4925           return signature + newlen + 1;
4926         }
4927       }
4928       return NULL;
4929     }
4930     case JVM_SIGNATURE_ARRAY:
4931       array_dim++;
4932       if (array_dim > 255) {
4933         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
4934         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_NULL);
4935       }
4936       // The rest of what's there better be a legal signature
4937       signature++;
4938       length--;
4939       void_ok = false;
4940       break;
4941     default:
4942       return NULL;
4943     }
4944   }
4945   return NULL;
4946 }
4947 
4948 // Checks if name is a legal class name.
4949 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
4950   if (!_need_verify || _relax_verify) { return; }
4951 
4952   assert(name->refcount() > 0, "symbol must be kept alive");
4953   char* bytes = (char*)name->bytes();
4954   unsigned int length = name->utf8_length();
4955   bool legal = false;
4956 
4957   if (length > 0) {
4958     const char* p;
4959     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4960       p = skip_over_field_signature(bytes, false, length, CHECK);
4961       legal = (p != NULL) && ((p - bytes) == (int)length);
4962     } else if (_major_version < JAVA_1_5_VERSION) {
4963       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4964         p = skip_over_field_name(bytes, true, length);
4965         legal = (p != NULL) && ((p - bytes) == (int)length);
4966       }
4967     } else {
4968       // 4900761: relax the constraints based on JSR202 spec
4969       // Class names may be drawn from the entire Unicode character set.
4970       // Identifiers between '/' must be unqualified names.
4971       // The utf8 string has been verified when parsing cpool entries.
4972       legal = verify_unqualified_name(bytes, length, LegalClass);
4973     }
4974   }
4975   if (!legal) {
4976     ResourceMark rm(THREAD);
4977     assert(_class_name != NULL, "invariant");
4978     Exceptions::fthrow(
4979       THREAD_AND_LOCATION,
4980       vmSymbols::java_lang_ClassFormatError(),
4981       "Illegal class name \"%.*s\" in class file %s", length, bytes,
4982       _class_name->as_C_string()
4983     );
4984     return;
4985   }
4986 }
4987 
4988 // Checks if name is a legal field name.
4989 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
4990   if (!_need_verify || _relax_verify) { return; }
4991 
4992   char* bytes = (char*)name->bytes();
4993   unsigned int length = name->utf8_length();
4994   bool legal = false;
4995 
4996   if (length > 0) {
4997     if (_major_version < JAVA_1_5_VERSION) {
4998       if (bytes[0] != JVM_SIGNATURE_SPECIAL) {
4999         const char* p = skip_over_field_name(bytes, false, length);
5000         legal = (p != NULL) && ((p - bytes) == (int)length);
5001       }
5002     } else {
5003       // 4881221: relax the constraints based on JSR202 spec
5004       legal = verify_unqualified_name(bytes, length, LegalField);
5005     }
5006   }
5007 
5008   if (!legal) {
5009     ResourceMark rm(THREAD);
5010     assert(_class_name != NULL, "invariant");
5011     Exceptions::fthrow(
5012       THREAD_AND_LOCATION,
5013       vmSymbols::java_lang_ClassFormatError(),
5014       "Illegal field name \"%.*s\" in class %s", length, bytes,
5015       _class_name->as_C_string()
5016     );
5017     return;
5018   }
5019 }
5020 
5021 // Checks if name is a legal method name.
5022 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5023   if (!_need_verify || _relax_verify) { return; }
5024 
5025   assert(name != NULL, "method name is null");
5026   char* bytes = (char*)name->bytes();
5027   unsigned int length = name->utf8_length();
5028   bool legal = false;
5029 
5030   if (length > 0) {
5031     if (bytes[0] == JVM_SIGNATURE_SPECIAL) {
5032       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5033         legal = true;
5034       }
5035     } else if (_major_version < JAVA_1_5_VERSION) {
5036       const char* p;
5037       p = skip_over_field_name(bytes, false, length);
5038       legal = (p != NULL) && ((p - bytes) == (int)length);
5039     } else {
5040       // 4881221: relax the constraints based on JSR202 spec
5041       legal = verify_unqualified_name(bytes, length, LegalMethod);
5042     }
5043   }
5044 
5045   if (!legal) {
5046     ResourceMark rm(THREAD);
5047     assert(_class_name != NULL, "invariant");
5048     Exceptions::fthrow(
5049       THREAD_AND_LOCATION,
5050       vmSymbols::java_lang_ClassFormatError(),
5051       "Illegal method name \"%.*s\" in class %s", length, bytes,
5052       _class_name->as_C_string()
5053     );
5054     return;
5055   }
5056 }
5057 
5058 
5059 // Checks if signature is a legal field signature.
5060 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5061                                                    const Symbol* signature,
5062                                                    TRAPS) const {
5063   if (!_need_verify) { return; }
5064 
5065   const char* const bytes = (const char* const)signature->bytes();
5066   const unsigned int length = signature->utf8_length();
5067   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5068 
5069   if (p == NULL || (p - bytes) != (int)length) {
5070     throwIllegalSignature("Field", name, signature, CHECK);
5071   }
5072 }
5073 
5074 // Checks if signature is a legal method signature.
5075 // Returns number of parameters
5076 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5077                                                    const Symbol* signature,
5078                                                    TRAPS) const {
5079   if (!_need_verify) {
5080     // make sure caller's args_size will be less than 0 even for non-static
5081     // method so it will be recomputed in compute_size_of_parameters().
5082     return -2;
5083   }
5084 
5085   // Class initializers cannot have args for class format version >= 51.
5086   if (name == vmSymbols::class_initializer_name() &&
5087       signature != vmSymbols::void_method_signature() &&
5088       _major_version >= JAVA_7_VERSION) {
5089     throwIllegalSignature("Method", name, signature, CHECK_0);
5090     return 0;
5091   }
5092 
5093   unsigned int args_size = 0;
5094   const char* p = (const char*)signature->bytes();
5095   unsigned int length = signature->utf8_length();
5096   const char* nextp;
5097 
5098   // The first character must be a '('
5099   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5100     length--;
5101     // Skip over legal field signatures
5102     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5103     while ((length > 0) && (nextp != NULL)) {
5104       args_size++;
5105       if (p[0] == 'J' || p[0] == 'D') {
5106         args_size++;
5107       }
5108       length -= nextp - p;
5109       p = nextp;
5110       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5111     }
5112     // The first non-signature thing better be a ')'
5113     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5114       length--;
5115       if (name->utf8_length() > 0 && name->char_at(0) == JVM_SIGNATURE_SPECIAL) {
5116         // All internal methods must return void
5117         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
5118           return args_size;
5119         }
5120       } else {
5121         // Now we better just have a return value
5122         nextp = skip_over_field_signature(p, true, length, CHECK_0);
5123         if (nextp && ((int)length == (nextp - p))) {
5124           return args_size;
5125         }
5126       }
5127     }
5128   }
5129   // Report error
5130   throwIllegalSignature("Method", name, signature, CHECK_0);
5131   return 0;
5132 }
5133 
5134 int ClassFileParser::static_field_size() const {
5135   assert(_field_info != NULL, "invariant");
5136   return _field_info->_static_field_size;
5137 }
5138 
5139 int ClassFileParser::total_oop_map_count() const {
5140   assert(_field_info != NULL, "invariant");
5141   return _field_info->oop_map_blocks->_nonstatic_oop_map_count;
5142 }
5143 
5144 jint ClassFileParser::layout_size() const {
5145   assert(_field_info != NULL, "invariant");
5146   return _field_info->_instance_size;
5147 }
5148 
5149 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5150                                          const Array<Method*>* methods) {
5151   assert(ik != NULL, "invariant");
5152   assert(methods != NULL, "invariant");
5153 
5154   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5155   // (We used to do this lazily, but now we query it in Rewriter,
5156   // which is eagerly done for every method, so we might as well do it now,
5157   // when everything is fresh in memory.)
5158   const vmSymbols::SID klass_id = Method::klass_id_for_intrinsics(ik);
5159 
5160   if (klass_id != vmSymbols::NO_SID) {
5161     for (int j = 0; j < methods->length(); ++j) {
5162       Method* method = methods->at(j);
5163       method->init_intrinsic_id();
5164 
5165       if (CheckIntrinsics) {
5166         // Check if an intrinsic is defined for method 'method',
5167         // but the method is not annotated with @HotSpotIntrinsicCandidate.
5168         if (method->intrinsic_id() != vmIntrinsics::_none &&
5169             !method->intrinsic_candidate()) {
5170               tty->print("Compiler intrinsic is defined for method [%s], "
5171               "but the method is not annotated with @HotSpotIntrinsicCandidate.%s",
5172               method->name_and_sig_as_C_string(),
5173               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5174             );
5175           tty->cr();
5176           DEBUG_ONLY(vm_exit(1));
5177         }
5178         // Check is the method 'method' is annotated with @HotSpotIntrinsicCandidate,
5179         // but there is no intrinsic available for it.
5180         if (method->intrinsic_candidate() &&
5181           method->intrinsic_id() == vmIntrinsics::_none) {
5182             tty->print("Method [%s] is annotated with @HotSpotIntrinsicCandidate, "
5183               "but no compiler intrinsic is defined for the method.%s",
5184               method->name_and_sig_as_C_string(),
5185               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5186             );
5187           tty->cr();
5188           DEBUG_ONLY(vm_exit(1));
5189         }
5190       }
5191     } // end for
5192 
5193 #ifdef ASSERT
5194     if (CheckIntrinsics) {
5195       // Check for orphan methods in the current class. A method m
5196       // of a class C is orphan if an intrinsic is defined for method m,
5197       // but class C does not declare m.
5198       // The check is potentially expensive, therefore it is available
5199       // only in debug builds.
5200 
5201       for (int id = vmIntrinsics::FIRST_ID; id < (int)vmIntrinsics::ID_LIMIT; ++id) {
5202         if (vmIntrinsics::_compiledLambdaForm == id) {
5203           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5204           // generated for the JVM from a LambdaForm and therefore no method
5205           // is defined for it.
5206           continue;
5207         }
5208 
5209         if (vmIntrinsics::class_for(vmIntrinsics::ID_from(id)) == klass_id) {
5210           // Check if the current class contains a method with the same
5211           // name, flags, signature.
5212           bool match = false;
5213           for (int j = 0; j < methods->length(); ++j) {
5214             const Method* method = methods->at(j);
5215             if (method->intrinsic_id() == id) {
5216               match = true;
5217               break;
5218             }
5219           }
5220 
5221           if (!match) {
5222             char buf[1000];
5223             tty->print("Compiler intrinsic is defined for method [%s], "
5224                        "but the method is not available in class [%s].%s",
5225                         vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID_from(id),
5226                                                              buf, sizeof(buf)),
5227                         ik->name()->as_C_string(),
5228                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5229             );
5230             tty->cr();
5231             DEBUG_ONLY(vm_exit(1));
5232           }
5233         }
5234       } // end for
5235     } // CheckIntrinsics
5236 #endif // ASSERT
5237   }
5238 }
5239 
5240 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook,
5241                                                       const ClassInstanceInfo& cl_inst_info,
5242                                                       TRAPS) {
5243   if (_klass != NULL) {
5244     return _klass;
5245   }
5246 
5247   InstanceKlass* const ik =
5248     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5249 
5250   if (is_hidden()) {
5251     mangle_hidden_class_name(ik);
5252   }
5253 
5254   fill_instance_klass(ik, changed_by_loadhook, cl_inst_info, CHECK_NULL);
5255 
5256   assert(_klass == ik, "invariant");
5257 
5258 
5259   if (ik->should_store_fingerprint()) {
5260     ik->store_fingerprint(_stream->compute_fingerprint());
5261   }
5262 
5263   ik->set_has_passed_fingerprint_check(false);
5264   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
5265     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
5266     uint64_t fp = ik->has_stored_fingerprint() ? ik->get_stored_fingerprint() : _stream->compute_fingerprint();
5267     if (aot_fp != 0 && aot_fp == fp) {
5268       // This class matches with a class saved in an AOT library
5269       ik->set_has_passed_fingerprint_check(true);
5270     } else {
5271       ResourceMark rm;
5272       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT,
5273                                  ik->external_name(), aot_fp, _stream->compute_fingerprint());
5274     }
5275   }
5276 
5277   return ik;
5278 }
5279 
5280 void ClassFileParser::fill_instance_klass(InstanceKlass* ik,
5281                                           bool changed_by_loadhook,
5282                                           const ClassInstanceInfo& cl_inst_info,
5283                                           TRAPS) {
5284   assert(ik != NULL, "invariant");
5285 
5286   // Set name and CLD before adding to CLD
5287   ik->set_class_loader_data(_loader_data);
5288   ik->set_name(_class_name);
5289 
5290   // Add all classes to our internal class loader list here,
5291   // including classes in the bootstrap (NULL) class loader.
5292   const bool publicize = !is_internal();
5293 
5294   _loader_data->add_class(ik, publicize);
5295 
5296   set_klass_to_deallocate(ik);
5297 
5298   assert(_field_info != NULL, "invariant");
5299   assert(ik->static_field_size() == _field_info->_static_field_size, "sanity");
5300   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->_nonstatic_oop_map_count,
5301          "sanity");
5302 
5303   assert(ik->is_instance_klass(), "sanity");
5304   assert(ik->size_helper() == _field_info->_instance_size, "sanity");
5305 
5306   // Fill in information already parsed
5307   ik->set_should_verify_class(_need_verify);
5308 
5309   // Not yet: supers are done below to support the new subtype-checking fields
5310   ik->set_nonstatic_field_size(_field_info->_nonstatic_field_size);
5311   ik->set_has_nonstatic_fields(_field_info->_has_nonstatic_fields);
5312   assert(_fac != NULL, "invariant");
5313   ik->set_static_oop_field_count(_fac->count[STATIC_OOP]);
5314 
5315   // this transfers ownership of a lot of arrays from
5316   // the parser onto the InstanceKlass*
5317   apply_parsed_class_metadata(ik, _java_fields_count, CHECK);
5318 
5319   // can only set dynamic nest-host after static nest information is set
5320   if (cl_inst_info.dynamic_nest_host() != NULL) {
5321     ik->set_nest_host(cl_inst_info.dynamic_nest_host(), THREAD);
5322   }
5323 
5324   // note that is not safe to use the fields in the parser from this point on
5325   assert(NULL == _cp, "invariant");
5326   assert(NULL == _fields, "invariant");
5327   assert(NULL == _methods, "invariant");
5328   assert(NULL == _inner_classes, "invariant");
5329   assert(NULL == _nest_members, "invariant");
5330   assert(NULL == _combined_annotations, "invariant");
5331   assert(NULL == _record_components, "invariant");
5332   assert(NULL == _permitted_subclasses, "invariant");
5333 
5334   if (_has_final_method) {
5335     ik->set_has_final_method();
5336   }
5337 
5338   ik->copy_method_ordering(_method_ordering, CHECK);
5339   // The InstanceKlass::_methods_jmethod_ids cache
5340   // is managed on the assumption that the initial cache
5341   // size is equal to the number of methods in the class. If
5342   // that changes, then InstanceKlass::idnum_can_increment()
5343   // has to be changed accordingly.
5344   ik->set_initial_method_idnum(ik->methods()->length());
5345 
5346   ik->set_this_class_index(_this_class_index);
5347 
5348   if (_is_hidden || is_unsafe_anonymous()) {
5349     // _this_class_index is a CONSTANT_Class entry that refers to this
5350     // hidden or anonymous class itself. If this class needs to refer to its own
5351     // methods or fields, it would use a CONSTANT_MethodRef, etc, which would reference
5352     // _this_class_index. However, because this class is hidden or anonymous (it's
5353     // not stored in SystemDictionary), _this_class_index cannot be resolved
5354     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5355     // Therefore, we must eagerly resolve _this_class_index now.
5356     ik->constants()->klass_at_put(_this_class_index, ik);
5357   }
5358 
5359   ik->set_minor_version(_minor_version);
5360   ik->set_major_version(_major_version);
5361   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5362   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5363 
5364   if (_unsafe_anonymous_host != NULL) {
5365     assert (ik->is_unsafe_anonymous(), "should be the same");
5366     ik->set_unsafe_anonymous_host(_unsafe_anonymous_host);
5367   }
5368   if (_is_hidden) {
5369     ik->set_is_hidden();
5370   }
5371 
5372   // Set PackageEntry for this_klass
5373   oop cl = ik->class_loader();
5374   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5375   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5376   ik->set_package(cld, NULL, CHECK);
5377 
5378   const Array<Method*>* const methods = ik->methods();
5379   assert(methods != NULL, "invariant");
5380   const int methods_len = methods->length();
5381 
5382   check_methods_for_intrinsics(ik, methods);
5383 
5384   // Fill in field values obtained by parse_classfile_attributes
5385   if (_parsed_annotations->has_any_annotations()) {
5386     _parsed_annotations->apply_to(ik);
5387   }
5388 
5389   apply_parsed_class_attributes(ik);
5390 
5391   // Miranda methods
5392   if ((_num_miranda_methods > 0) ||
5393       // if this class introduced new miranda methods or
5394       (_super_klass != NULL && _super_klass->has_miranda_methods())
5395         // super class exists and this class inherited miranda methods
5396      ) {
5397        ik->set_has_miranda_methods(); // then set a flag
5398   }
5399 
5400   // Fill in information needed to compute superclasses.
5401   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), _transitive_interfaces, CHECK);
5402   ik->set_transitive_interfaces(_transitive_interfaces);
5403   ik->set_local_interfaces(_local_interfaces);
5404   _transitive_interfaces = NULL;
5405   _local_interfaces = NULL;
5406 
5407   // Initialize itable offset tables
5408   klassItable::setup_itable_offset_table(ik);
5409 
5410   // Compute transitive closure of interfaces this class implements
5411   // Do final class setup
5412   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5413   if (oop_map_blocks->_nonstatic_oop_map_count > 0) {
5414     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5415   }
5416 
5417   if (_has_contended_fields || _parsed_annotations->is_contended() ||
5418       ( _super_klass != NULL && _super_klass->has_contended_annotations())) {
5419     ik->set_has_contended_annotations(true);
5420   }
5421 
5422   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5423   set_precomputed_flags(ik);
5424 
5425   // check if this class can access its super class
5426   check_super_class_access(ik, CHECK);
5427 
5428   // check if this class can access its superinterfaces
5429   check_super_interface_access(ik, CHECK);
5430 
5431   // check if this class overrides any final method
5432   check_final_method_override(ik, CHECK);
5433 
5434   // reject static interface methods prior to Java 8
5435   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5436     check_illegal_static_method(ik, CHECK);
5437   }
5438 
5439   // Obtain this_klass' module entry
5440   ModuleEntry* module_entry = ik->module();
5441   assert(module_entry != NULL, "module_entry should always be set");
5442 
5443   // Obtain java.lang.Module
5444   Handle module_handle(THREAD, module_entry->module());
5445 
5446   // Allocate mirror and initialize static fields
5447   // The create_mirror() call will also call compute_modifiers()
5448   java_lang_Class::create_mirror(ik,
5449                                  Handle(THREAD, _loader_data->class_loader()),
5450                                  module_handle,
5451                                  _protection_domain,
5452                                  cl_inst_info.class_data(),
5453                                  CHECK);
5454 
5455   assert(_all_mirandas != NULL, "invariant");
5456 
5457   // Generate any default methods - default methods are public interface methods
5458   // that have a default implementation.  This is new with Java 8.
5459   if (_has_nonstatic_concrete_methods) {
5460     DefaultMethods::generate_default_methods(ik,
5461                                              _all_mirandas,
5462                                              CHECK);
5463   }
5464 
5465   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5466   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5467       !module_entry->has_default_read_edges()) {
5468     if (!module_entry->set_has_default_read_edges()) {
5469       // We won a potential race
5470       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5471     }
5472   }
5473 
5474   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5475 
5476   if (!is_internal()) {
5477     if (log_is_enabled(Info, class, load)) {
5478       ResourceMark rm;
5479       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
5480       ik->print_class_load_logging(_loader_data, module_name, _stream);
5481     }
5482 
5483     if (ik->minor_version() == JAVA_PREVIEW_MINOR_VERSION &&
5484         ik->major_version() == JVM_CLASSFILE_MAJOR_VERSION &&
5485         log_is_enabled(Info, class, preview)) {
5486       ResourceMark rm;
5487       log_info(class, preview)("Loading class %s that depends on preview features (class file version %d.65535)",
5488                                ik->external_name(), JVM_CLASSFILE_MAJOR_VERSION);
5489     }
5490 
5491     if (log_is_enabled(Debug, class, resolve))  {
5492       ResourceMark rm;
5493       // print out the superclass.
5494       const char * from = ik->external_name();
5495       if (ik->java_super() != NULL) {
5496         log_debug(class, resolve)("%s %s (super)",
5497                    from,
5498                    ik->java_super()->external_name());
5499       }
5500       // print out each of the interface classes referred to by this class.
5501       const Array<InstanceKlass*>* const local_interfaces = ik->local_interfaces();
5502       if (local_interfaces != NULL) {
5503         const int length = local_interfaces->length();
5504         for (int i = 0; i < length; i++) {
5505           const InstanceKlass* const k = local_interfaces->at(i);
5506           const char * to = k->external_name();
5507           log_debug(class, resolve)("%s %s (interface)", from, to);
5508         }
5509       }
5510     }
5511   }
5512 
5513   JFR_ONLY(INIT_ID(ik);)
5514 
5515   // If we reach here, all is well.
5516   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5517   // in order for it to not be destroyed in the ClassFileParser destructor.
5518   set_klass_to_deallocate(NULL);
5519 
5520   // it's official
5521   set_klass(ik);
5522 
5523   debug_only(ik->verify();)
5524 }
5525 
5526 void ClassFileParser::update_class_name(Symbol* new_class_name) {
5527   // Decrement the refcount in the old name, since we're clobbering it.
5528   _class_name->decrement_refcount();
5529 
5530   _class_name = new_class_name;
5531   // Increment the refcount of the new name.
5532   // Now the ClassFileParser owns this name and will decrement in
5533   // the destructor.
5534   _class_name->increment_refcount();
5535 }
5536 
5537 // For an unsafe anonymous class that is in the unnamed package, move it to its host class's
5538 // package by prepending its host class's package name to its class name and setting
5539 // its _class_name field.
5540 void ClassFileParser::prepend_host_package_name(const InstanceKlass* unsafe_anonymous_host, TRAPS) {
5541   ResourceMark rm(THREAD);
5542   assert(strrchr(_class_name->as_C_string(), JVM_SIGNATURE_SLASH) == NULL,
5543          "Unsafe anonymous class should not be in a package");
5544   TempNewSymbol host_pkg_name =
5545     ClassLoader::package_from_class_name(unsafe_anonymous_host->name());
5546 
5547   if (host_pkg_name != NULL) {
5548     int host_pkg_len = host_pkg_name->utf8_length();
5549     int class_name_len = _class_name->utf8_length();
5550     int symbol_len = host_pkg_len + 1 + class_name_len;
5551     char* new_anon_name = NEW_RESOURCE_ARRAY(char, symbol_len + 1);
5552     int n = os::snprintf(new_anon_name, symbol_len + 1, "%.*s/%.*s",
5553                          host_pkg_len, host_pkg_name->base(), class_name_len, _class_name->base());
5554     assert(n == symbol_len, "Unexpected number of characters in string");
5555 
5556     // Decrement old _class_name to avoid leaking.
5557     _class_name->decrement_refcount();
5558 
5559     // Create a symbol and update the anonymous class name.
5560     // The new class name is created with a refcount of one. When installed into the InstanceKlass,
5561     // it'll be two and when the ClassFileParser destructor runs, it'll go back to one and get deleted
5562     // when the class is unloaded.
5563     _class_name = SymbolTable::new_symbol(new_anon_name, symbol_len);
5564   }
5565 }
5566 
5567 // If the host class and the anonymous class are in the same package then do
5568 // nothing.  If the anonymous class is in the unnamed package then move it to its
5569 // host's package.  If the classes are in different packages then throw an IAE
5570 // exception.
5571 void ClassFileParser::fix_unsafe_anonymous_class_name(TRAPS) {
5572   assert(_unsafe_anonymous_host != NULL, "Expected an unsafe anonymous class");
5573 
5574   const jbyte* anon_last_slash = UTF8::strrchr((const jbyte*)_class_name->base(),
5575                                                _class_name->utf8_length(), JVM_SIGNATURE_SLASH);
5576   if (anon_last_slash == NULL) {  // Unnamed package
5577     prepend_host_package_name(_unsafe_anonymous_host, CHECK);
5578   } else {
5579     if (!_unsafe_anonymous_host->is_same_class_package(_unsafe_anonymous_host->class_loader(), _class_name)) {
5580       ResourceMark rm(THREAD);
5581       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
5582         err_msg("Host class %s and anonymous class %s are in different packages",
5583         _unsafe_anonymous_host->name()->as_C_string(), _class_name->as_C_string()));
5584     }
5585   }
5586 }
5587 
5588 static bool relax_format_check_for(ClassLoaderData* loader_data) {
5589   bool trusted = loader_data->is_boot_class_loader_data() ||
5590                  loader_data->is_platform_class_loader_data();
5591   bool need_verify =
5592     // verifyAll
5593     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
5594     // verifyRemote
5595     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
5596   return !need_verify;
5597 }
5598 
5599 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5600                                  Symbol* name,
5601                                  ClassLoaderData* loader_data,
5602                                  const ClassLoadInfo* cl_info,
5603                                  Publicity pub_level,
5604                                  TRAPS) :
5605   _stream(stream),
5606   _class_name(NULL),
5607   _loader_data(loader_data),
5608   _unsafe_anonymous_host(cl_info->unsafe_anonymous_host()),
5609   _cp_patches(cl_info->cp_patches()),
5610   _is_hidden(cl_info->is_hidden()),
5611   _can_access_vm_annotations(cl_info->can_access_vm_annotations()),
5612   _num_patched_klasses(0),
5613   _max_num_patched_klasses(0),
5614   _orig_cp_size(0),
5615   _first_patched_klass_resolved_index(0),
5616   _super_klass(),
5617   _cp(NULL),
5618   _fields(NULL),
5619   _methods(NULL),
5620   _inner_classes(NULL),
5621   _nest_members(NULL),
5622   _nest_host(0),
5623   _permitted_subclasses(NULL),
5624   _record_components(NULL),
5625   _local_interfaces(NULL),
5626   _transitive_interfaces(NULL),
5627   _combined_annotations(NULL),
5628   _class_annotations(NULL),
5629   _class_type_annotations(NULL),
5630   _fields_annotations(NULL),
5631   _fields_type_annotations(NULL),
5632   _klass(NULL),
5633   _klass_to_deallocate(NULL),
5634   _parsed_annotations(NULL),
5635   _fac(NULL),
5636   _field_info(NULL),
5637   _method_ordering(NULL),
5638   _all_mirandas(NULL),
5639   _vtable_size(0),
5640   _itable_size(0),
5641   _num_miranda_methods(0),
5642   _rt(REF_NONE),
5643   _protection_domain(cl_info->protection_domain()),
5644   _access_flags(),
5645   _pub_level(pub_level),
5646   _bad_constant_seen(0),
5647   _synthetic_flag(false),
5648   _sde_length(false),
5649   _sde_buffer(NULL),
5650   _sourcefile_index(0),
5651   _generic_signature_index(0),
5652   _major_version(0),
5653   _minor_version(0),
5654   _this_class_index(0),
5655   _super_class_index(0),
5656   _itfs_len(0),
5657   _java_fields_count(0),
5658   _need_verify(false),
5659   _relax_verify(false),
5660   _has_nonstatic_concrete_methods(false),
5661   _declares_nonstatic_concrete_methods(false),
5662   _has_final_method(false),
5663   _has_contended_fields(false),
5664   _has_finalizer(false),
5665   _has_empty_finalizer(false),
5666   _has_vanilla_constructor(false),
5667   _max_bootstrap_specifier_index(-1) {
5668 
5669   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5670   _class_name->increment_refcount();
5671 
5672   assert(THREAD->is_Java_thread(), "invariant");
5673   assert(_loader_data != NULL, "invariant");
5674   assert(stream != NULL, "invariant");
5675   assert(_stream != NULL, "invariant");
5676   assert(_stream->buffer() == _stream->current(), "invariant");
5677   assert(_class_name != NULL, "invariant");
5678   assert(0 == _access_flags.as_int(), "invariant");
5679 
5680   // Figure out whether we can skip format checking (matching classic VM behavior)
5681   if (DumpSharedSpaces) {
5682     // verify == true means it's a 'remote' class (i.e., non-boot class)
5683     // Verification decision is based on BytecodeVerificationRemote flag
5684     // for those classes.
5685     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
5686                                               BytecodeVerificationLocal;
5687   }
5688   else {
5689     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
5690                                                stream->need_verify());
5691   }
5692   if (_cp_patches != NULL) {
5693     int len = _cp_patches->length();
5694     for (int i=0; i<len; i++) {
5695       if (has_cp_patch_at(i)) {
5696         Handle patch = cp_patch_at(i);
5697         if (java_lang_String::is_instance(patch()) || java_lang_Class::is_instance(patch())) {
5698           // We need to append the names of the patched classes to the end of the constant pool,
5699           // because a patched class may have a Utf8 name that's not already included in the
5700           // original constant pool. These class names are used when patch_constant_pool()
5701           // calls patch_class().
5702           //
5703           // Note that a String in cp_patch_at(i) may be used to patch a Utf8, a String, or a Class.
5704           // At this point, we don't know the tag for index i yet, because we haven't parsed the
5705           // constant pool. So we can only assume the worst -- every String is used to patch a Class.
5706           _max_num_patched_klasses++;
5707         }
5708       }
5709     }
5710   }
5711 
5712   // synch back verification state to stream
5713   stream->set_verify(_need_verify);
5714 
5715   // Check if verification needs to be relaxed for this class file
5716   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5717   _relax_verify = relax_format_check_for(_loader_data);
5718 
5719   parse_stream(stream, CHECK);
5720 
5721   post_process_parsed_stream(stream, _cp, CHECK);
5722 }
5723 
5724 void ClassFileParser::clear_class_metadata() {
5725   // metadata created before the instance klass is created.  Must be
5726   // deallocated if classfile parsing returns an error.
5727   _cp = NULL;
5728   _fields = NULL;
5729   _methods = NULL;
5730   _inner_classes = NULL;
5731   _nest_members = NULL;
5732   _permitted_subclasses = NULL;
5733   _combined_annotations = NULL;
5734   _class_annotations = _class_type_annotations = NULL;
5735   _fields_annotations = _fields_type_annotations = NULL;
5736   _record_components = NULL;
5737 }
5738 
5739 // Destructor to clean up
5740 ClassFileParser::~ClassFileParser() {
5741   _class_name->decrement_refcount();
5742 
5743   if (_cp != NULL) {
5744     MetadataFactory::free_metadata(_loader_data, _cp);
5745   }
5746   if (_fields != NULL) {
5747     MetadataFactory::free_array<u2>(_loader_data, _fields);
5748   }
5749 
5750   if (_methods != NULL) {
5751     // Free methods
5752     InstanceKlass::deallocate_methods(_loader_data, _methods);
5753   }
5754 
5755   // beware of the Universe::empty_blah_array!!
5756   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
5757     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5758   }
5759 
5760   if (_nest_members != NULL && _nest_members != Universe::the_empty_short_array()) {
5761     MetadataFactory::free_array<u2>(_loader_data, _nest_members);
5762   }
5763 
5764   if (_record_components != NULL) {
5765     InstanceKlass::deallocate_record_components(_loader_data, _record_components);
5766   }
5767 
5768   if (_permitted_subclasses != NULL && _permitted_subclasses != Universe::the_empty_short_array()) {
5769     MetadataFactory::free_array<u2>(_loader_data, _permitted_subclasses);
5770   }
5771 
5772   // Free interfaces
5773   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5774                                        _local_interfaces, _transitive_interfaces);
5775 
5776   if (_combined_annotations != NULL) {
5777     // After all annotations arrays have been created, they are installed into the
5778     // Annotations object that will be assigned to the InstanceKlass being created.
5779 
5780     // Deallocate the Annotations object and the installed annotations arrays.
5781     _combined_annotations->deallocate_contents(_loader_data);
5782 
5783     // If the _combined_annotations pointer is non-NULL,
5784     // then the other annotations fields should have been cleared.
5785     assert(_class_annotations       == NULL, "Should have been cleared");
5786     assert(_class_type_annotations  == NULL, "Should have been cleared");
5787     assert(_fields_annotations      == NULL, "Should have been cleared");
5788     assert(_fields_type_annotations == NULL, "Should have been cleared");
5789   } else {
5790     // If the annotations arrays were not installed into the Annotations object,
5791     // then they have to be deallocated explicitly.
5792     MetadataFactory::free_array<u1>(_loader_data, _class_annotations);
5793     MetadataFactory::free_array<u1>(_loader_data, _class_type_annotations);
5794     Annotations::free_contents(_loader_data, _fields_annotations);
5795     Annotations::free_contents(_loader_data, _fields_type_annotations);
5796   }
5797 
5798   clear_class_metadata();
5799   _transitive_interfaces = NULL;
5800   _local_interfaces = NULL;
5801 
5802   // deallocate the klass if already created.  Don't directly deallocate, but add
5803   // to the deallocate list so that the klass is removed from the CLD::_klasses list
5804   // at a safepoint.
5805   if (_klass_to_deallocate != NULL) {
5806     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
5807   }
5808 }
5809 
5810 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
5811                                    TRAPS) {
5812 
5813   assert(stream != NULL, "invariant");
5814   assert(_class_name != NULL, "invariant");
5815 
5816   // BEGIN STREAM PARSING
5817   stream->guarantee_more(8, CHECK);  // magic, major, minor
5818   // Magic value
5819   const u4 magic = stream->get_u4_fast();
5820   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
5821                      "Incompatible magic value %u in class file %s",
5822                      magic, CHECK);
5823 
5824   // Version numbers
5825   _minor_version = stream->get_u2_fast();
5826   _major_version = stream->get_u2_fast();
5827 
5828   if (DumpSharedSpaces && _major_version < JAVA_6_VERSION) {
5829     ResourceMark rm;
5830     warning("Pre JDK 6 class not supported by CDS: %u.%u %s",
5831             _major_version,  _minor_version, _class_name->as_C_string());
5832     Exceptions::fthrow(
5833       THREAD_AND_LOCATION,
5834       vmSymbols::java_lang_UnsupportedClassVersionError(),
5835       "Unsupported major.minor version for dump time %u.%u",
5836       _major_version,
5837       _minor_version);
5838   }
5839 
5840   // Check version numbers - we check this even with verifier off
5841   verify_class_version(_major_version, _minor_version, _class_name, CHECK);
5842 
5843   stream->guarantee_more(3, CHECK); // length, first cp tag
5844   u2 cp_size = stream->get_u2_fast();
5845 
5846   guarantee_property(
5847     cp_size >= 1, "Illegal constant pool size %u in class file %s",
5848     cp_size, CHECK);
5849 
5850   _orig_cp_size = cp_size;
5851   if (is_hidden()) { // Add a slot for hidden class name.
5852     assert(_max_num_patched_klasses == 0, "Sanity check");
5853     cp_size++;
5854   } else {
5855     if (int(cp_size) + _max_num_patched_klasses > 0xffff) {
5856       THROW_MSG(vmSymbols::java_lang_InternalError(), "not enough space for patched classes");
5857     }
5858     cp_size += _max_num_patched_klasses;
5859   }
5860 
5861   _cp = ConstantPool::allocate(_loader_data,
5862                                cp_size,
5863                                CHECK);
5864 
5865   ConstantPool* const cp = _cp;
5866 
5867   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
5868 
5869   assert(cp_size == (const u2)cp->length(), "invariant");
5870 
5871   // ACCESS FLAGS
5872   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
5873 
5874   // Access flags
5875   jint flags;
5876   // JVM_ACC_MODULE is defined in JDK-9 and later.
5877   if (_major_version >= JAVA_9_VERSION) {
5878     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
5879   } else {
5880     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
5881   }
5882 
5883   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
5884     // Set abstract bit for old class files for backward compatibility
5885     flags |= JVM_ACC_ABSTRACT;
5886   }
5887 
5888   verify_legal_class_modifiers(flags, CHECK);
5889 
5890   short bad_constant = class_bad_constant_seen();
5891   if (bad_constant != 0) {
5892     // Do not throw CFE until after the access_flags are checked because if
5893     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
5894     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, CHECK);
5895   }
5896 
5897   _access_flags.set_flags(flags);
5898 
5899   // This class and superclass
5900   _this_class_index = stream->get_u2_fast();
5901   check_property(
5902     valid_cp_range(_this_class_index, cp_size) &&
5903       cp->tag_at(_this_class_index).is_unresolved_klass(),
5904     "Invalid this class index %u in constant pool in class file %s",
5905     _this_class_index, CHECK);
5906 
5907   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
5908   assert(class_name_in_cp != NULL, "class_name can't be null");
5909 
5910   // Don't need to check whether this class name is legal or not.
5911   // It has been checked when constant pool is parsed.
5912   // However, make sure it is not an array type.
5913   if (_need_verify) {
5914     guarantee_property(class_name_in_cp->char_at(0) != JVM_SIGNATURE_ARRAY,
5915                        "Bad class name in class file %s",
5916                        CHECK);
5917   }
5918 
5919 #ifdef ASSERT
5920   // Basic sanity checks
5921   assert(!(_is_hidden && (_unsafe_anonymous_host != NULL)), "mutually exclusive variants");
5922 
5923   if (_unsafe_anonymous_host != NULL) {
5924     assert(_class_name == vmSymbols::unknown_class_name(), "A named anonymous class???");
5925   }
5926   if (_is_hidden) {
5927     assert(_class_name != vmSymbols::unknown_class_name(), "hidden classes should have a special name");
5928   }
5929 #endif
5930 
5931   // Update the _class_name as needed depending on whether this is a named,
5932   // un-named, hidden or unsafe-anonymous class.
5933 
5934   if (_is_hidden) {
5935     assert(_class_name != NULL, "Unexpected null _class_name");
5936 #ifdef ASSERT
5937     if (_need_verify) {
5938       verify_legal_class_name(_class_name, CHECK);
5939     }
5940 #endif
5941 
5942   // NOTE: !_is_hidden does not imply "findable" as it could be an old-style
5943   //       "hidden" unsafe-anonymous class
5944 
5945   // If this is an anonymous class fix up its name if it is in the unnamed
5946   // package.  Otherwise, throw IAE if it is in a different package than
5947   // its host class.
5948   } else if (_unsafe_anonymous_host != NULL) {
5949     update_class_name(class_name_in_cp);
5950     fix_unsafe_anonymous_class_name(CHECK);
5951 
5952   } else {
5953     // Check if name in class file matches given name
5954     if (_class_name != class_name_in_cp) {
5955       if (_class_name != vmSymbols::unknown_class_name()) {
5956         ResourceMark rm(THREAD);
5957         Exceptions::fthrow(THREAD_AND_LOCATION,
5958                            vmSymbols::java_lang_NoClassDefFoundError(),
5959                            "%s (wrong name: %s)",
5960                            class_name_in_cp->as_C_string(),
5961                            _class_name->as_C_string()
5962                            );
5963         return;
5964       } else {
5965         // The class name was not known by the caller so we set it from
5966         // the value in the CP.
5967         update_class_name(class_name_in_cp);
5968       }
5969       // else nothing to do: the expected class name matches what is in the CP
5970     }
5971   }
5972 
5973   // Verification prevents us from creating names with dots in them, this
5974   // asserts that that's the case.
5975   assert(is_internal_format(_class_name), "external class name format used internally");
5976 
5977   if (!is_internal()) {
5978     LogTarget(Debug, class, preorder) lt;
5979     if (lt.is_enabled()){
5980       ResourceMark rm(THREAD);
5981       LogStream ls(lt);
5982       ls.print("%s", _class_name->as_klass_external_name());
5983       if (stream->source() != NULL) {
5984         ls.print(" source: %s", stream->source());
5985       }
5986       ls.cr();
5987     }
5988 
5989 #if INCLUDE_CDS
5990     if (DumpLoadedClassList != NULL && stream->source() != NULL && classlist_file->is_open()) {
5991       if (!ClassLoader::has_jrt_entry()) {
5992         warning("DumpLoadedClassList and CDS are not supported in exploded build");
5993         DumpLoadedClassList = NULL;
5994       } else if (SystemDictionaryShared::is_sharing_possible(_loader_data) &&
5995                  !_is_hidden &&
5996                  _unsafe_anonymous_host == NULL) {
5997         // Only dump the classes that can be stored into CDS archive.
5998         // Hidden and unsafe anonymous classes such as generated LambdaForm classes are also not included.
5999         oop class_loader = _loader_data->class_loader();
6000         ResourceMark rm(THREAD);
6001         bool skip = false;
6002         if (class_loader == NULL || SystemDictionary::is_platform_class_loader(class_loader)) {
6003           // For the boot and platform class loaders, skip classes that are not found in the
6004           // java runtime image, such as those found in the --patch-module entries.
6005           // These classes can't be loaded from the archive during runtime.
6006           if (!stream->from_boot_loader_modules_image() && strncmp(stream->source(), "jrt:", 4) != 0) {
6007             skip = true;
6008           }
6009 
6010           if (class_loader == NULL && ClassLoader::contains_append_entry(stream->source())) {
6011             // .. but don't skip the boot classes that are loaded from -Xbootclasspath/a
6012             // as they can be loaded from the archive during runtime.
6013             skip = false;
6014           }
6015         }
6016         if (skip) {
6017           tty->print_cr("skip writing class %s from source %s to classlist file",
6018             _class_name->as_C_string(), stream->source());
6019         } else {
6020           classlist_file->print_cr("%s", _class_name->as_C_string());
6021           classlist_file->flush();
6022         }
6023       }
6024     }
6025 #endif
6026   }
6027 
6028   // SUPERKLASS
6029   _super_class_index = stream->get_u2_fast();
6030   _super_klass = parse_super_class(cp,
6031                                    _super_class_index,
6032                                    _need_verify,
6033                                    CHECK);
6034 
6035   // Interfaces
6036   _itfs_len = stream->get_u2_fast();
6037   parse_interfaces(stream,
6038                    _itfs_len,
6039                    cp,
6040                    &_has_nonstatic_concrete_methods,
6041                    CHECK);
6042 
6043   assert(_local_interfaces != NULL, "invariant");
6044 
6045   // Fields (offsets are filled in later)
6046   _fac = new FieldAllocationCount();
6047   parse_fields(stream,
6048                _access_flags.is_interface(),
6049                _fac,
6050                cp,
6051                cp_size,
6052                &_java_fields_count,
6053                CHECK);
6054 
6055   assert(_fields != NULL, "invariant");
6056 
6057   // Methods
6058   AccessFlags promoted_flags;
6059   parse_methods(stream,
6060                 _access_flags.is_interface(),
6061                 &promoted_flags,
6062                 &_has_final_method,
6063                 &_declares_nonstatic_concrete_methods,
6064                 CHECK);
6065 
6066   assert(_methods != NULL, "invariant");
6067 
6068   // promote flags from parse_methods() to the klass' flags
6069   _access_flags.add_promoted_flags(promoted_flags.as_int());
6070 
6071   if (_declares_nonstatic_concrete_methods) {
6072     _has_nonstatic_concrete_methods = true;
6073   }
6074 
6075   // Additional attributes/annotations
6076   _parsed_annotations = new ClassAnnotationCollector();
6077   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6078 
6079   assert(_inner_classes != NULL, "invariant");
6080 
6081   // Finalize the Annotations metadata object,
6082   // now that all annotation arrays have been created.
6083   create_combined_annotations(CHECK);
6084 
6085   // Make sure this is the end of class file stream
6086   guarantee_property(stream->at_eos(),
6087                      "Extra bytes at the end of class file %s",
6088                      CHECK);
6089 
6090   // all bytes in stream read and parsed
6091 }
6092 
6093 void ClassFileParser::mangle_hidden_class_name(InstanceKlass* const ik) {
6094   ResourceMark rm;
6095   // Construct hidden name from _class_name, "+", and &ik. Note that we can't
6096   // use a '/' because that confuses finding the class's package.  Also, can't
6097   // use an illegal char such as ';' because that causes serialization issues
6098   // and issues with hidden classes that create their own hidden classes.
6099   char addr_buf[20];
6100   jio_snprintf(addr_buf, 20, INTPTR_FORMAT, p2i(ik));
6101   size_t new_name_len = _class_name->utf8_length() + 2 + strlen(addr_buf);
6102   char* new_name = NEW_RESOURCE_ARRAY(char, new_name_len);
6103   jio_snprintf(new_name, new_name_len, "%s+%s",
6104                _class_name->as_C_string(), addr_buf);
6105   update_class_name(SymbolTable::new_symbol(new_name));
6106 
6107   // Add a Utf8 entry containing the hidden name.
6108   assert(_class_name != NULL, "Unexpected null _class_name");
6109   int hidden_index = _orig_cp_size; // this is an extra slot we added
6110   _cp->symbol_at_put(hidden_index, _class_name);
6111 
6112   // Update this_class_index's slot in the constant pool with the new Utf8 entry.
6113   // We have to update the resolved_klass_index and the name_index together
6114   // so extract the existing resolved_klass_index first.
6115   CPKlassSlot cp_klass_slot = _cp->klass_slot_at(_this_class_index);
6116   int resolved_klass_index = cp_klass_slot.resolved_klass_index();
6117   _cp->unresolved_klass_at_put(_this_class_index, hidden_index, resolved_klass_index);
6118   assert(_cp->klass_slot_at(_this_class_index).name_index() == _orig_cp_size,
6119          "Bad name_index");
6120 }
6121 
6122 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6123                                                  ConstantPool* cp,
6124                                                  TRAPS) {
6125   assert(stream != NULL, "invariant");
6126   assert(stream->at_eos(), "invariant");
6127   assert(cp != NULL, "invariant");
6128   assert(_loader_data != NULL, "invariant");
6129 
6130   if (_class_name == vmSymbols::java_lang_Object()) {
6131     check_property(_local_interfaces == Universe::the_empty_instance_klass_array(),
6132                    "java.lang.Object cannot implement an interface in class file %s",
6133                    CHECK);
6134   }
6135   // We check super class after class file is parsed and format is checked
6136   if (_super_class_index > 0 && NULL ==_super_klass) {
6137     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6138     if (_access_flags.is_interface()) {
6139       // Before attempting to resolve the superclass, check for class format
6140       // errors not checked yet.
6141       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6142         "Interfaces must have java.lang.Object as superclass in class file %s",
6143         CHECK);
6144     }
6145     Handle loader(THREAD, _loader_data->class_loader());
6146     _super_klass = (const InstanceKlass*)
6147                        SystemDictionary::resolve_super_or_fail(_class_name,
6148                                                                super_class_name,
6149                                                                loader,
6150                                                                _protection_domain,
6151                                                                true,
6152                                                                CHECK);
6153   }
6154 
6155   if (_super_klass != NULL) {
6156     if (_super_klass->has_nonstatic_concrete_methods()) {
6157       _has_nonstatic_concrete_methods = true;
6158     }
6159 
6160     if (_super_klass->is_interface()) {
6161       ResourceMark rm(THREAD);
6162       Exceptions::fthrow(
6163         THREAD_AND_LOCATION,
6164         vmSymbols::java_lang_IncompatibleClassChangeError(),
6165         "class %s has interface %s as super class",
6166         _class_name->as_klass_external_name(),
6167         _super_klass->external_name()
6168       );
6169       return;
6170     }
6171   }
6172 
6173   // Compute the transitive list of all unique interfaces implemented by this class
6174   _transitive_interfaces =
6175     compute_transitive_interfaces(_super_klass,
6176                                   _local_interfaces,
6177                                   _loader_data,
6178                                   CHECK);
6179 
6180   assert(_transitive_interfaces != NULL, "invariant");
6181 
6182   // sort methods
6183   _method_ordering = sort_methods(_methods);
6184 
6185   _all_mirandas = new GrowableArray<Method*>(20);
6186 
6187   Handle loader(THREAD, _loader_data->class_loader());
6188   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6189                                                     &_num_miranda_methods,
6190                                                     _all_mirandas,
6191                                                     _super_klass,
6192                                                     _methods,
6193                                                     _access_flags,
6194                                                     _major_version,
6195                                                     loader,
6196                                                     _class_name,
6197                                                     _local_interfaces,
6198                                                     CHECK);
6199 
6200   // Size of Java itable (in words)
6201   _itable_size = _access_flags.is_interface() ? 0 :
6202     klassItable::compute_itable_size(_transitive_interfaces);
6203 
6204   assert(_fac != NULL, "invariant");
6205   assert(_parsed_annotations != NULL, "invariant");
6206 
6207   _field_info = new FieldLayoutInfo();
6208   FieldLayoutBuilder lb(class_name(), super_klass(), _cp, _fields,
6209                         _parsed_annotations->is_contended(), _field_info);
6210   lb.build_layout();
6211 
6212   // Compute reference typ
6213   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();
6214 
6215 }
6216 
6217 void ClassFileParser::set_klass(InstanceKlass* klass) {
6218 
6219 #ifdef ASSERT
6220   if (klass != NULL) {
6221     assert(NULL == _klass, "leaking?");
6222   }
6223 #endif
6224 
6225   _klass = klass;
6226 }
6227 
6228 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6229 
6230 #ifdef ASSERT
6231   if (klass != NULL) {
6232     assert(NULL == _klass_to_deallocate, "leaking?");
6233   }
6234 #endif
6235 
6236   _klass_to_deallocate = klass;
6237 }
6238 
6239 // Caller responsible for ResourceMark
6240 // clone stream with rewound position
6241 const ClassFileStream* ClassFileParser::clone_stream() const {
6242   assert(_stream != NULL, "invariant");
6243 
6244   return _stream->clone();
6245 }
6246 // ----------------------------------------------------------------------------
6247 // debugging
6248 
6249 #ifdef ASSERT
6250 
6251 // return true if class_name contains no '.' (internal format is '/')
6252 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6253   if (class_name != NULL) {
6254     ResourceMark rm;
6255     char* name = class_name->as_C_string();
6256     return strchr(name, JVM_SIGNATURE_DOT) == NULL;
6257   } else {
6258     return true;
6259   }
6260 }
6261 
6262 #endif