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