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