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