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