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