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