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