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   // Attempt to redistribute NONSTATIC_VALUETYPE alloc type
1474   FieldAllocationType redistribute_value(bool oops, int value_size) {
1475     FieldAllocationType atype = NONSTATIC_VALUETYPE;
1476     switch (value_size) {
1477     case 1:
1478       atype = NONSTATIC_BYTE;
1479       break;
1480     case 2:
1481       atype = NONSTATIC_SHORT;
1482       break;
1483     case 4:
1484       atype = (oops) ? NONSTATIC_OOP : NONSTATIC_WORD;
1485       break;
1486     default:
1487       assert(is_size_aligned(value_size, BytesPerLong), "Unaligned value %d", value_size);
1488       return atype;
1489     }
1490     count[atype]++;
1491     count[NONSTATIC_VALUETYPE]--; // Leave only large variable sized behind
1492     return atype;
1493   }
1494 };
1495 
1496 // Side-effects: populates the _fields, _fields_annotations,
1497 // _fields_type_annotations fields
1498 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1499                                    bool is_interface,
1500                                    FieldAllocationCount* const fac,
1501                                    ConstantPool* cp,
1502                                    const int cp_size,
1503                                    u2* const java_fields_count_ptr,
1504                                    TRAPS) {
1505 
1506   assert(cfs != NULL, "invariant");
1507   assert(fac != NULL, "invariant");
1508   assert(cp != NULL, "invariant");
1509   assert(java_fields_count_ptr != NULL, "invariant");
1510 
1511   assert(NULL == _fields, "invariant");
1512   assert(NULL == _fields_annotations, "invariant");
1513   assert(NULL == _fields_type_annotations, "invariant");
1514 
1515   cfs->guarantee_more(2, CHECK);  // length
1516   const u2 length = cfs->get_u2_fast();
1517   *java_fields_count_ptr = length;
1518 
1519   int num_injected = 0;
1520   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1521                                                                   &num_injected);
1522   const int total_fields = length + num_injected;
1523 
1524   // The field array starts with tuples of shorts
1525   // [access, name index, sig index, initial value index, byte offset].
1526   // A generic signature slot only exists for field with generic
1527   // signature attribute. And the access flag is set with
1528   // JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE for that field. The generic
1529   // signature slots are at the end of the field array and after all
1530   // other fields data.
1531   //
1532   //   f1: [access, name index, sig index, initial value index, low_offset, high_offset]
1533   //   f2: [access, name index, sig index, initial value index, low_offset, high_offset]
1534   //       ...
1535   //   fn: [access, name index, sig index, initial value index, low_offset, high_offset]
1536   //       [generic signature index]
1537   //       [generic signature index]
1538   //       ...
1539   //
1540   // Allocate a temporary resource array for field data. For each field,
1541   // a slot is reserved in the temporary array for the generic signature
1542   // index. After parsing all fields, the data are copied to a permanent
1543   // array and any unused slots will be discarded.
1544   ResourceMark rm(THREAD);
1545   u2* const fa = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
1546                                               u2,
1547                                               total_fields * (FieldInfo::field_slots + 1));
1548 
1549   // The generic signature slots start after all other fields' data.
1550   int generic_signature_slot = total_fields * FieldInfo::field_slots;
1551   int num_generic_signature = 0;
1552   for (int n = 0; n < length; n++) {
1553     // access_flags, name_index, descriptor_index, attributes_count
1554     cfs->guarantee_more(8, CHECK);
1555 
1556     AccessFlags access_flags;
1557     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1558     verify_legal_field_modifiers(flags, is_interface, CHECK);
1559     access_flags.set_flags(flags);
1560 
1561     const u2 name_index = cfs->get_u2_fast();
1562     check_property(valid_symbol_at(name_index),
1563       "Invalid constant pool index %u for field name in class file %s",
1564       name_index, CHECK);
1565     const Symbol* const name = cp->symbol_at(name_index);
1566     verify_legal_field_name(name, CHECK);
1567 
1568     const u2 signature_index = cfs->get_u2_fast();
1569     check_property(valid_symbol_at(signature_index),
1570       "Invalid constant pool index %u for field signature in class file %s",
1571       signature_index, CHECK);
1572     const Symbol* const sig = cp->symbol_at(signature_index);
1573     verify_legal_field_signature(name, sig, CHECK);
1574     if (sig->starts_with("Q")) {
1575       _has_value_fields = true;
1576     }
1577 
1578     u2 constantvalue_index = 0;
1579     bool is_synthetic = false;
1580     u2 generic_signature_index = 0;
1581     const bool is_static = access_flags.is_static();
1582     FieldAnnotationCollector parsed_annotations(_loader_data);
1583 
1584     const u2 attributes_count = cfs->get_u2_fast();
1585     if (attributes_count > 0) {
1586       parse_field_attributes(cfs,
1587                              attributes_count,
1588                              is_static,
1589                              signature_index,
1590                              &constantvalue_index,
1591                              &is_synthetic,
1592                              &generic_signature_index,
1593                              &parsed_annotations,
1594                              CHECK);
1595 
1596       if (parsed_annotations.field_annotations() != NULL) {
1597         if (_fields_annotations == NULL) {
1598           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1599                                              _loader_data, length, NULL,
1600                                              CHECK);
1601         }
1602         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1603         parsed_annotations.set_field_annotations(NULL);
1604       }
1605       if (parsed_annotations.field_type_annotations() != NULL) {
1606         if (_fields_type_annotations == NULL) {
1607           _fields_type_annotations =
1608             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1609                                                          length,
1610                                                          NULL,
1611                                                          CHECK);
1612         }
1613         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1614         parsed_annotations.set_field_type_annotations(NULL);
1615       }
1616 
1617       if (is_synthetic) {
1618         access_flags.set_is_synthetic();
1619       }
1620       if (generic_signature_index != 0) {
1621         access_flags.set_field_has_generic_signature();
1622         fa[generic_signature_slot] = generic_signature_index;
1623         generic_signature_slot ++;
1624         num_generic_signature ++;
1625       }
1626     }
1627 
1628     FieldInfo* const field = FieldInfo::from_field_array(fa, n);
1629     field->initialize(access_flags.as_short(),
1630                       name_index,
1631                       signature_index,
1632                       constantvalue_index);
1633     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1634 
1635     // Remember how many oops we encountered and compute allocation type
1636     const FieldAllocationType atype = fac->update(is_static, type);
1637     field->set_allocation_type(atype);
1638 
1639     // After field is initialized with type, we can augment it with aux info
1640     if (parsed_annotations.has_any_annotations())
1641       parsed_annotations.apply_to(field);
1642   }
1643 
1644   int index = length;
1645   if (num_injected != 0) {
1646     for (int n = 0; n < num_injected; n++) {
1647       // Check for duplicates
1648       if (injected[n].may_be_java) {
1649         const Symbol* const name      = injected[n].name();
1650         const Symbol* const signature = injected[n].signature();
1651         bool duplicate = false;
1652         for (int i = 0; i < length; i++) {
1653           const FieldInfo* const f = FieldInfo::from_field_array(fa, i);
1654           if (name      == cp->symbol_at(f->name_index()) &&
1655               signature == cp->symbol_at(f->signature_index())) {
1656             // Symbol is desclared in Java so skip this one
1657             duplicate = true;
1658             break;
1659           }
1660         }
1661         if (duplicate) {
1662           // These will be removed from the field array at the end
1663           continue;
1664         }
1665       }
1666 
1667       // Injected field
1668       FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1669       field->initialize(JVM_ACC_FIELD_INTERNAL,
1670                         injected[n].name_index,
1671                         injected[n].signature_index,
1672                         0);
1673 
1674       const BasicType type = FieldType::basic_type(injected[n].signature());
1675 
1676       // Remember how many oops we encountered and compute allocation type
1677       const FieldAllocationType atype = fac->update(false, type);
1678       field->set_allocation_type(atype);
1679       index++;
1680     }
1681   }
1682 
1683   assert(NULL == _fields, "invariant");
1684 
1685   _fields =
1686     MetadataFactory::new_array<u2>(_loader_data,
1687                                    index * FieldInfo::field_slots + num_generic_signature,
1688                                    CHECK);
1689   // Sometimes injected fields already exist in the Java source so
1690   // the fields array could be too long.  In that case the
1691   // fields array is trimed. Also unused slots that were reserved
1692   // for generic signature indexes are discarded.
1693   {
1694     int i = 0;
1695     for (; i < index * FieldInfo::field_slots; i++) {
1696       _fields->at_put(i, fa[i]);
1697     }
1698     for (int j = total_fields * FieldInfo::field_slots;
1699          j < generic_signature_slot; j++) {
1700       _fields->at_put(i++, fa[j]);
1701     }
1702     assert(_fields->length() == i, "");
1703   }
1704 
1705   if (_need_verify && length > 1) {
1706     // Check duplicated fields
1707     ResourceMark rm(THREAD);
1708     NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
1709       THREAD, NameSigHash*, HASH_ROW_SIZE);
1710     initialize_hashtable(names_and_sigs);
1711     bool dup = false;
1712     const Symbol* name = NULL;
1713     const Symbol* sig = NULL;
1714     {
1715       debug_only(NoSafepointVerifier nsv;)
1716       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
1717         name = fs.name();
1718         sig = fs.signature();
1719         // If no duplicates, add name/signature in hashtable names_and_sigs.
1720         if (!put_after_lookup(name, sig, names_and_sigs)) {
1721           dup = true;
1722           break;
1723         }
1724       }
1725     }
1726     if (dup) {
1727       classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1728                              name->as_C_string(), sig->as_klass_external_name(), CHECK);
1729     }
1730   }
1731 }
1732 
1733 
1734 static void copy_u2_with_conversion(u2* dest, const u2* src, int length) {
1735   while (length-- > 0) {
1736     *dest++ = Bytes::get_Java_u2((u1*) (src++));
1737   }
1738 }
1739 
1740 const u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs,
1741                                                  u4 code_length,
1742                                                  u4 exception_table_length,
1743                                                  TRAPS) {
1744   assert(cfs != NULL, "invariant");
1745 
1746   const u2* const exception_table_start = cfs->get_u2_buffer();
1747   assert(exception_table_start != NULL, "null exception table");
1748 
1749   cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc,
1750                                                                // end_pc,
1751                                                                // handler_pc,
1752                                                                // catch_type_index
1753 
1754   // Will check legal target after parsing code array in verifier.
1755   if (_need_verify) {
1756     for (unsigned int i = 0; i < exception_table_length; i++) {
1757       const u2 start_pc = cfs->get_u2_fast();
1758       const u2 end_pc = cfs->get_u2_fast();
1759       const u2 handler_pc = cfs->get_u2_fast();
1760       const u2 catch_type_index = cfs->get_u2_fast();
1761       guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1762                          "Illegal exception table range in class file %s",
1763                          CHECK_NULL);
1764       guarantee_property(handler_pc < code_length,
1765                          "Illegal exception table handler in class file %s",
1766                          CHECK_NULL);
1767       if (catch_type_index != 0) {
1768         guarantee_property(valid_klass_reference_at(catch_type_index),
1769                            "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
1770       }
1771     }
1772   } else {
1773     cfs->skip_u2_fast(exception_table_length * 4);
1774   }
1775   return exception_table_start;
1776 }
1777 
1778 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length,
1779                                              u4 code_length,
1780                                              CompressedLineNumberWriteStream**const write_stream,
1781                                              TRAPS) {
1782 
1783   const ClassFileStream* const cfs = _stream;
1784   unsigned int num_entries = cfs->get_u2(CHECK);
1785 
1786   // Each entry is a u2 start_pc, and a u2 line_number
1787   const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2);
1788 
1789   // Verify line number attribute and table length
1790   check_property(
1791     code_attribute_length == sizeof(u2) + length_in_bytes,
1792     "LineNumberTable attribute has wrong length in class file %s", CHECK);
1793 
1794   cfs->guarantee_more(length_in_bytes, CHECK);
1795 
1796   if ((*write_stream) == NULL) {
1797     if (length_in_bytes > fixed_buffer_size) {
1798       (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1799     } else {
1800       (*write_stream) = new CompressedLineNumberWriteStream(
1801         _linenumbertable_buffer, fixed_buffer_size);
1802     }
1803   }
1804 
1805   while (num_entries-- > 0) {
1806     const u2 bci  = cfs->get_u2_fast(); // start_pc
1807     const u2 line = cfs->get_u2_fast(); // line_number
1808     guarantee_property(bci < code_length,
1809         "Invalid pc in LineNumberTable in class file %s", CHECK);
1810     (*write_stream)->write_pair(bci, line);
1811   }
1812 }
1813 
1814 
1815 class LVT_Hash : public AllStatic {
1816  public:
1817 
1818   static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) {
1819   /*
1820    * 3-tuple start_bci/length/slot has to be unique key,
1821    * so the following comparison seems to be redundant:
1822    *       && elem->name_cp_index == entry->_elem->name_cp_index
1823    */
1824     return (e0.start_bci     == e1.start_bci &&
1825             e0.length        == e1.length &&
1826             e0.name_cp_index == e1.name_cp_index &&
1827             e0.slot          == e1.slot);
1828   }
1829 
1830   static unsigned int hash(LocalVariableTableElement const& e0) {
1831     unsigned int raw_hash = e0.start_bci;
1832 
1833     raw_hash = e0.length        + raw_hash * 37;
1834     raw_hash = e0.name_cp_index + raw_hash * 37;
1835     raw_hash = e0.slot          + raw_hash * 37;
1836 
1837     return raw_hash;
1838   }
1839 };
1840 
1841 
1842 // Class file LocalVariableTable elements.
1843 class Classfile_LVT_Element VALUE_OBJ_CLASS_SPEC {
1844  public:
1845   u2 start_bci;
1846   u2 length;
1847   u2 name_cp_index;
1848   u2 descriptor_cp_index;
1849   u2 slot;
1850 };
1851 
1852 static void copy_lvt_element(const Classfile_LVT_Element* const src,
1853                              LocalVariableTableElement* const lvt) {
1854   lvt->start_bci           = Bytes::get_Java_u2((u1*) &src->start_bci);
1855   lvt->length              = Bytes::get_Java_u2((u1*) &src->length);
1856   lvt->name_cp_index       = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1857   lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1858   lvt->signature_cp_index  = 0;
1859   lvt->slot                = Bytes::get_Java_u2((u1*) &src->slot);
1860 }
1861 
1862 // Function is used to parse both attributes:
1863 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1864 const u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs,
1865                                                      u4 code_length,
1866                                                      u2 max_locals,
1867                                                      u4 code_attribute_length,
1868                                                      u2* const localvariable_table_length,
1869                                                      bool isLVTT,
1870                                                      TRAPS) {
1871   const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1872   *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1873   const unsigned int size =
1874     (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);
1875 
1876   const ConstantPool* const cp = _cp;
1877 
1878   // Verify local variable table attribute has right length
1879   if (_need_verify) {
1880     guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1881                        "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1882   }
1883 
1884   const u2* const localvariable_table_start = cfs->get_u2_buffer();
1885   assert(localvariable_table_start != NULL, "null local variable table");
1886   if (!_need_verify) {
1887     cfs->skip_u2_fast(size);
1888   } else {
1889     cfs->guarantee_more(size * 2, CHECK_NULL);
1890     for(int i = 0; i < (*localvariable_table_length); i++) {
1891       const u2 start_pc = cfs->get_u2_fast();
1892       const u2 length = cfs->get_u2_fast();
1893       const u2 name_index = cfs->get_u2_fast();
1894       const u2 descriptor_index = cfs->get_u2_fast();
1895       const u2 index = cfs->get_u2_fast();
1896       // Assign to a u4 to avoid overflow
1897       const u4 end_pc = (u4)start_pc + (u4)length;
1898 
1899       if (start_pc >= code_length) {
1900         classfile_parse_error(
1901           "Invalid start_pc %u in %s in class file %s",
1902           start_pc, tbl_name, CHECK_NULL);
1903       }
1904       if (end_pc > code_length) {
1905         classfile_parse_error(
1906           "Invalid length %u in %s in class file %s",
1907           length, tbl_name, CHECK_NULL);
1908       }
1909       const int cp_size = cp->length();
1910       guarantee_property(valid_symbol_at(name_index),
1911         "Name index %u in %s has bad constant type in class file %s",
1912         name_index, tbl_name, CHECK_NULL);
1913       guarantee_property(valid_symbol_at(descriptor_index),
1914         "Signature index %u in %s has bad constant type in class file %s",
1915         descriptor_index, tbl_name, CHECK_NULL);
1916 
1917       const Symbol* const name = cp->symbol_at(name_index);
1918       const Symbol* const sig = cp->symbol_at(descriptor_index);
1919       verify_legal_field_name(name, CHECK_NULL);
1920       u2 extra_slot = 0;
1921       if (!isLVTT) {
1922         verify_legal_field_signature(name, sig, CHECK_NULL);
1923 
1924         // 4894874: check special cases for double and long local variables
1925         if (sig == vmSymbols::type_signature(T_DOUBLE) ||
1926             sig == vmSymbols::type_signature(T_LONG)) {
1927           extra_slot = 1;
1928         }
1929       }
1930       guarantee_property((index + extra_slot) < max_locals,
1931                           "Invalid index %u in %s in class file %s",
1932                           index, tbl_name, CHECK_NULL);
1933     }
1934   }
1935   return localvariable_table_start;
1936 }
1937 
1938 
1939 void ClassFileParser::parse_type_array(u2 array_length,
1940                                        u4 code_length,
1941                                        u4* const u1_index,
1942                                        u4* const u2_index,
1943                                        u1* const u1_array,
1944                                        u2* const u2_array,
1945                                        TRAPS) {
1946   const ClassFileStream* const cfs = _stream;
1947   u2 index = 0; // index in the array with long/double occupying two slots
1948   u4 i1 = *u1_index;
1949   u4 i2 = *u2_index + 1;
1950   for(int i = 0; i < array_length; i++) {
1951     const u1 tag = u1_array[i1++] = cfs->get_u1(CHECK);
1952     index++;
1953     if (tag == ITEM_Long || tag == ITEM_Double) {
1954       index++;
1955     } else if (tag == ITEM_Object) {
1956       const u2 class_index = u2_array[i2++] = cfs->get_u2(CHECK);
1957       guarantee_property(valid_klass_reference_at(class_index),
1958                          "Bad class index %u in StackMap in class file %s",
1959                          class_index, CHECK);
1960     } else if (tag == ITEM_Uninitialized) {
1961       const u2 offset = u2_array[i2++] = cfs->get_u2(CHECK);
1962       guarantee_property(
1963         offset < code_length,
1964         "Bad uninitialized type offset %u in StackMap in class file %s",
1965         offset, CHECK);
1966     } else {
1967       guarantee_property(
1968         tag <= (u1)ITEM_Uninitialized,
1969         "Unknown variable type %u in StackMap in class file %s",
1970         tag, CHECK);
1971     }
1972   }
1973   u2_array[*u2_index] = index;
1974   *u1_index = i1;
1975   *u2_index = i2;
1976 }
1977 
1978 static const u1* parse_stackmap_table(const ClassFileStream* const cfs,
1979                                       u4 code_attribute_length,
1980                                       bool need_verify,
1981                                       TRAPS) {
1982   assert(cfs != NULL, "invariant");
1983 
1984   if (0 == code_attribute_length) {
1985     return NULL;
1986   }
1987 
1988   const u1* const stackmap_table_start = cfs->get_u1_buffer();
1989   assert(stackmap_table_start != NULL, "null stackmap table");
1990 
1991   // check code_attribute_length first
1992   cfs->skip_u1(code_attribute_length, CHECK_NULL);
1993 
1994   if (!need_verify && !DumpSharedSpaces) {
1995     return NULL;
1996   }
1997   return stackmap_table_start;
1998 }
1999 
2000 const u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs,
2001                                                     u2* const checked_exceptions_length,
2002                                                     u4 method_attribute_length,
2003                                                     TRAPS) {
2004   assert(cfs != NULL, "invariant");
2005   assert(checked_exceptions_length != NULL, "invariant");
2006 
2007   cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
2008   *checked_exceptions_length = cfs->get_u2_fast();
2009   const unsigned int size =
2010     (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
2011   const u2* const checked_exceptions_start = cfs->get_u2_buffer();
2012   assert(checked_exceptions_start != NULL, "null checked exceptions");
2013   if (!_need_verify) {
2014     cfs->skip_u2_fast(size);
2015   } else {
2016     // Verify each value in the checked exception table
2017     u2 checked_exception;
2018     const u2 len = *checked_exceptions_length;
2019     cfs->guarantee_more(2 * len, CHECK_NULL);
2020     for (int i = 0; i < len; i++) {
2021       checked_exception = cfs->get_u2_fast();
2022       check_property(
2023         valid_klass_reference_at(checked_exception),
2024         "Exception name has bad type at constant pool %u in class file %s",
2025         checked_exception, CHECK_NULL);
2026     }
2027   }
2028   // check exceptions attribute length
2029   if (_need_verify) {
2030     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
2031                                                    sizeof(u2) * size),
2032                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
2033   }
2034   return checked_exceptions_start;
2035 }
2036 
2037 void ClassFileParser::throwIllegalSignature(const char* type,
2038                                             const Symbol* name,
2039                                             const Symbol* sig,
2040                                             TRAPS) const {
2041   assert(name != NULL, "invariant");
2042   assert(sig != NULL, "invariant");
2043 
2044   ResourceMark rm(THREAD);
2045   Exceptions::fthrow(THREAD_AND_LOCATION,
2046       vmSymbols::java_lang_ClassFormatError(),
2047       "%s \"%s\" in class %s has illegal signature \"%s\"", type,
2048       name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
2049 }
2050 
2051 AnnotationCollector::ID
2052 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
2053                                       const Symbol* name) {
2054   const vmSymbols::SID sid = vmSymbols::find_sid(name);
2055   // Privileged code can use all annotations.  Other code silently drops some.
2056   const bool privileged = loader_data->is_the_null_class_loader_data() ||
2057                           loader_data->is_platform_class_loader_data() ||
2058                           loader_data->is_anonymous();
2059   switch (sid) {
2060     case vmSymbols::VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
2061       if (_location != _in_method)  break;  // only allow for methods
2062       if (!privileged)              break;  // only allow in privileged code
2063       return _method_CallerSensitive;
2064     }
2065     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
2066       if (_location != _in_method)  break;  // only allow for methods
2067       if (!privileged)              break;  // only allow in privileged code
2068       return _method_ForceInline;
2069     }
2070     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): {
2071       if (_location != _in_method)  break;  // only allow for methods
2072       if (!privileged)              break;  // only allow in privileged code
2073       return _method_DontInline;
2074     }
2075     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): {
2076       if (_location != _in_method)  break;  // only allow for methods
2077       if (!privileged)              break;  // only allow in privileged code
2078       return _method_InjectedProfile;
2079     }
2080     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): {
2081       if (_location != _in_method)  break;  // only allow for methods
2082       if (!privileged)              break;  // only allow in privileged code
2083       return _method_LambdaForm_Compiled;
2084     }
2085     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Hidden_signature): {
2086       if (_location != _in_method)  break;  // only allow for methods
2087       if (!privileged)              break;  // only allow in privileged code
2088       return _method_LambdaForm_Hidden;
2089     }
2090     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_HotSpotIntrinsicCandidate_signature): {
2091       if (_location != _in_method)  break;  // only allow for methods
2092       if (!privileged)              break;  // only allow in privileged code
2093       return _method_HotSpotIntrinsicCandidate;
2094     }
2095     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): {
2096       if (_location != _in_field)   break;  // only allow for fields
2097       if (!privileged)              break;  // only allow in privileged code
2098       return _field_Stable;
2099     }
2100     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
2101       if (_location != _in_field && _location != _in_class) {
2102         break;  // only allow for fields and classes
2103       }
2104       if (!EnableContended || (RestrictContended && !privileged)) {
2105         break;  // honor privileges
2106       }
2107       return _jdk_internal_vm_annotation_Contended;
2108     }
2109     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
2110       if (_location != _in_method)  break;  // only allow for methods
2111       if (RestrictReservedStack && !privileged) break; // honor privileges
2112       return _jdk_internal_vm_annotation_ReservedStackAccess;
2113     }
2114     case vmSymbols::VM_SYMBOL_ENUM_NAME(jvm_internal_value_DeriveValueType_signature) : {
2115       if (_location != _in_class) {
2116         break;
2117       }
2118       return _jvm_internal_value_DeriveValueType;
2119     }
2120     default: {
2121       break;
2122     }
2123   }
2124   return AnnotationCollector::_unknown;
2125 }
2126 
2127 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2128   if (is_contended())
2129     f->set_contended_group(contended_group());
2130   if (is_stable())
2131     f->set_stable(true);
2132 }
2133 
2134 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2135   // If there's an error deallocate metadata for field annotations
2136   MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
2137   MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
2138 }
2139 
2140 void MethodAnnotationCollector::apply_to(methodHandle m) {
2141   if (has_annotation(_method_CallerSensitive))
2142     m->set_caller_sensitive(true);
2143   if (has_annotation(_method_ForceInline))
2144     m->set_force_inline(true);
2145   if (has_annotation(_method_DontInline))
2146     m->set_dont_inline(true);
2147   if (has_annotation(_method_InjectedProfile))
2148     m->set_has_injected_profile(true);
2149   if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
2150     m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
2151   if (has_annotation(_method_LambdaForm_Hidden))
2152     m->set_hidden(true);
2153   if (has_annotation(_method_HotSpotIntrinsicCandidate) && !m->is_synthetic())
2154     m->set_intrinsic_candidate(true);
2155   if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess))
2156     m->set_has_reserved_stack_access(true);
2157 }
2158 
2159 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) {
2160   assert(ik != NULL, "invariant");
2161   ik->set_is_contended(is_contended());
2162 }
2163 
2164 #define MAX_ARGS_SIZE 255
2165 #define MAX_CODE_SIZE 65535
2166 #define INITIAL_MAX_LVT_NUMBER 256
2167 
2168 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2169  *
2170  * Rules for LVT's and LVTT's are:
2171  *   - There can be any number of LVT's and LVTT's.
2172  *   - If there are n LVT's, it is the same as if there was just
2173  *     one LVT containing all the entries from the n LVT's.
2174  *   - There may be no more than one LVT entry per local variable.
2175  *     Two LVT entries are 'equal' if these fields are the same:
2176  *        start_pc, length, name, slot
2177  *   - There may be no more than one LVTT entry per each LVT entry.
2178  *     Each LVTT entry has to match some LVT entry.
2179  *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
2180  */
2181 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm,
2182                                                int lvt_cnt,
2183                                                u2* const localvariable_table_length,
2184                                                const u2**const localvariable_table_start,
2185                                                int lvtt_cnt,
2186                                                u2* const localvariable_type_table_length,
2187                                                const u2**const localvariable_type_table_start,
2188                                                TRAPS) {
2189 
2190   ResourceMark rm(THREAD);
2191 
2192   typedef ResourceHashtable<LocalVariableTableElement, LocalVariableTableElement*,
2193                             &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable;
2194 
2195   LVT_HashTable* const table = new LVT_HashTable();
2196 
2197   // To fill LocalVariableTable in
2198   const Classfile_LVT_Element* cf_lvt;
2199   LocalVariableTableElement* lvt = cm->localvariable_table_start();
2200 
2201   for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
2202     cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
2203     for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
2204       copy_lvt_element(&cf_lvt[idx], lvt);
2205       // If no duplicates, add LVT elem in hashtable.
2206       if (table->put(*lvt, lvt) == false
2207           && _need_verify
2208           && _major_version >= JAVA_1_5_VERSION) {
2209         classfile_parse_error("Duplicated LocalVariableTable attribute "
2210                               "entry for '%s' in class file %s",
2211                                _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
2212                                CHECK);
2213       }
2214     }
2215   }
2216 
2217   // To merge LocalVariableTable and LocalVariableTypeTable
2218   const Classfile_LVT_Element* cf_lvtt;
2219   LocalVariableTableElement lvtt_elem;
2220 
2221   for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2222     cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2223     for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2224       copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2225       LocalVariableTableElement** entry = table->get(lvtt_elem);
2226       if (entry == NULL) {
2227         if (_need_verify) {
2228           classfile_parse_error("LVTT entry for '%s' in class file %s "
2229                                 "does not match any LVT entry",
2230                                  _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2231                                  CHECK);
2232         }
2233       } else if ((*entry)->signature_cp_index != 0 && _need_verify) {
2234         classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2235                               "entry for '%s' in class file %s",
2236                                _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2237                                CHECK);
2238       } else {
2239         // to add generic signatures into LocalVariableTable
2240         (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index;
2241       }
2242     }
2243   }
2244 }
2245 
2246 
2247 void ClassFileParser::copy_method_annotations(ConstMethod* cm,
2248                                        const u1* runtime_visible_annotations,
2249                                        int runtime_visible_annotations_length,
2250                                        const u1* runtime_invisible_annotations,
2251                                        int runtime_invisible_annotations_length,
2252                                        const u1* runtime_visible_parameter_annotations,
2253                                        int runtime_visible_parameter_annotations_length,
2254                                        const u1* runtime_invisible_parameter_annotations,
2255                                        int runtime_invisible_parameter_annotations_length,
2256                                        const u1* runtime_visible_type_annotations,
2257                                        int runtime_visible_type_annotations_length,
2258                                        const u1* runtime_invisible_type_annotations,
2259                                        int runtime_invisible_type_annotations_length,
2260                                        const u1* annotation_default,
2261                                        int annotation_default_length,
2262                                        TRAPS) {
2263 
2264   AnnotationArray* a;
2265 
2266   if (runtime_visible_annotations_length +
2267       runtime_invisible_annotations_length > 0) {
2268      a = assemble_annotations(runtime_visible_annotations,
2269                               runtime_visible_annotations_length,
2270                               runtime_invisible_annotations,
2271                               runtime_invisible_annotations_length,
2272                               CHECK);
2273      cm->set_method_annotations(a);
2274   }
2275 
2276   if (runtime_visible_parameter_annotations_length +
2277       runtime_invisible_parameter_annotations_length > 0) {
2278     a = assemble_annotations(runtime_visible_parameter_annotations,
2279                              runtime_visible_parameter_annotations_length,
2280                              runtime_invisible_parameter_annotations,
2281                              runtime_invisible_parameter_annotations_length,
2282                              CHECK);
2283     cm->set_parameter_annotations(a);
2284   }
2285 
2286   if (annotation_default_length > 0) {
2287     a = assemble_annotations(annotation_default,
2288                              annotation_default_length,
2289                              NULL,
2290                              0,
2291                              CHECK);
2292     cm->set_default_annotations(a);
2293   }
2294 
2295   if (runtime_visible_type_annotations_length +
2296       runtime_invisible_type_annotations_length > 0) {
2297     a = assemble_annotations(runtime_visible_type_annotations,
2298                              runtime_visible_type_annotations_length,
2299                              runtime_invisible_type_annotations,
2300                              runtime_invisible_type_annotations_length,
2301                              CHECK);
2302     cm->set_type_annotations(a);
2303   }
2304 }
2305 
2306 
2307 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2308 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2309 // Method* to save footprint, so we only know the size of the resulting Method* when the
2310 // entire method attribute is parsed.
2311 //
2312 // The promoted_flags parameter is used to pass relevant access_flags
2313 // from the method back up to the containing klass. These flag values
2314 // are added to klass's access_flags.
2315 
2316 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2317                                       bool is_interface,
2318                                       const ConstantPool* cp,
2319                                       AccessFlags* const promoted_flags,
2320                                       TRAPS) {
2321   assert(cfs != NULL, "invariant");
2322   assert(cp != NULL, "invariant");
2323   assert(promoted_flags != NULL, "invariant");
2324 
2325   ResourceMark rm(THREAD);
2326   // Parse fixed parts:
2327   // access_flags, name_index, descriptor_index, attributes_count
2328   cfs->guarantee_more(8, CHECK_NULL);
2329 
2330   int flags = cfs->get_u2_fast();
2331   const u2 name_index = cfs->get_u2_fast();
2332   const int cp_size = cp->length();
2333   check_property(
2334     valid_symbol_at(name_index),
2335     "Illegal constant pool index %u for method name in class file %s",
2336     name_index, CHECK_NULL);
2337   const Symbol* const name = cp->symbol_at(name_index);
2338   verify_legal_method_name(name, CHECK_NULL);
2339 
2340   const u2 signature_index = cfs->get_u2_fast();
2341   guarantee_property(
2342     valid_symbol_at(signature_index),
2343     "Illegal constant pool index %u for method signature in class file %s",
2344     signature_index, CHECK_NULL);
2345   const Symbol* const signature = cp->symbol_at(signature_index);
2346 
2347   if (name == vmSymbols::class_initializer_name()) {
2348     // We ignore the other access flags for a valid class initializer.
2349     // (JVM Spec 2nd ed., chapter 4.6)
2350     if (_major_version < 51) { // backward compatibility
2351       flags = JVM_ACC_STATIC;
2352     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2353       flags &= JVM_ACC_STATIC | JVM_ACC_STRICT;
2354     } else {
2355       classfile_parse_error("Method <clinit> is not static in class file %s", CHECK_NULL);
2356     }
2357   } else {
2358     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2359   }
2360 
2361   if (name == vmSymbols::object_initializer_name() && is_interface) {
2362     classfile_parse_error("Interface cannot have a method named <init>, class file %s", CHECK_NULL);
2363   }
2364 
2365   int args_size = -1;  // only used when _need_verify is true
2366   if (_need_verify) {
2367     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2368                  verify_legal_method_signature(name, signature, CHECK_NULL);
2369     if (args_size > MAX_ARGS_SIZE) {
2370       classfile_parse_error("Too many arguments in method signature in class file %s", CHECK_NULL);
2371     }
2372   }
2373 
2374   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2375 
2376   // Default values for code and exceptions attribute elements
2377   u2 max_stack = 0;
2378   u2 max_locals = 0;
2379   u4 code_length = 0;
2380   const u1* code_start = 0;
2381   u2 exception_table_length = 0;
2382   const u2* exception_table_start = NULL;
2383   Array<int>* exception_handlers = Universe::the_empty_int_array();
2384   u2 checked_exceptions_length = 0;
2385   const u2* checked_exceptions_start = NULL;
2386   CompressedLineNumberWriteStream* linenumber_table = NULL;
2387   int linenumber_table_length = 0;
2388   int total_lvt_length = 0;
2389   u2 lvt_cnt = 0;
2390   u2 lvtt_cnt = 0;
2391   bool lvt_allocated = false;
2392   u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
2393   u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
2394   u2* localvariable_table_length = NULL;
2395   const u2** localvariable_table_start = NULL;
2396   u2* localvariable_type_table_length = NULL;
2397   const u2** localvariable_type_table_start = NULL;
2398   int method_parameters_length = -1;
2399   const u1* method_parameters_data = NULL;
2400   bool method_parameters_seen = false;
2401   bool parsed_code_attribute = false;
2402   bool parsed_checked_exceptions_attribute = false;
2403   bool parsed_stackmap_attribute = false;
2404   // stackmap attribute - JDK1.5
2405   const u1* stackmap_data = NULL;
2406   int stackmap_data_length = 0;
2407   u2 generic_signature_index = 0;
2408   MethodAnnotationCollector parsed_annotations;
2409   const u1* runtime_visible_annotations = NULL;
2410   int runtime_visible_annotations_length = 0;
2411   const u1* runtime_invisible_annotations = NULL;
2412   int runtime_invisible_annotations_length = 0;
2413   const u1* runtime_visible_parameter_annotations = NULL;
2414   int runtime_visible_parameter_annotations_length = 0;
2415   const u1* runtime_invisible_parameter_annotations = NULL;
2416   int runtime_invisible_parameter_annotations_length = 0;
2417   const u1* runtime_visible_type_annotations = NULL;
2418   int runtime_visible_type_annotations_length = 0;
2419   const u1* runtime_invisible_type_annotations = NULL;
2420   int runtime_invisible_type_annotations_length = 0;
2421   bool runtime_invisible_annotations_exists = false;
2422   bool runtime_invisible_type_annotations_exists = false;
2423   bool runtime_invisible_parameter_annotations_exists = false;
2424   const u1* annotation_default = NULL;
2425   int annotation_default_length = 0;
2426 
2427   // Parse code and exceptions attribute
2428   u2 method_attributes_count = cfs->get_u2_fast();
2429   while (method_attributes_count--) {
2430     cfs->guarantee_more(6, CHECK_NULL);  // method_attribute_name_index, method_attribute_length
2431     const u2 method_attribute_name_index = cfs->get_u2_fast();
2432     const u4 method_attribute_length = cfs->get_u4_fast();
2433     check_property(
2434       valid_symbol_at(method_attribute_name_index),
2435       "Invalid method attribute name index %u in class file %s",
2436       method_attribute_name_index, CHECK_NULL);
2437 
2438     const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index);
2439     if (method_attribute_name == vmSymbols::tag_code()) {
2440       // Parse Code attribute
2441       if (_need_verify) {
2442         guarantee_property(
2443             !access_flags.is_native() && !access_flags.is_abstract(),
2444                         "Code attribute in native or abstract methods in class file %s",
2445                          CHECK_NULL);
2446       }
2447       if (parsed_code_attribute) {
2448         classfile_parse_error("Multiple Code attributes in class file %s",
2449                               CHECK_NULL);
2450       }
2451       parsed_code_attribute = true;
2452 
2453       // Stack size, locals size, and code size
2454       if (_major_version == 45 && _minor_version <= 2) {
2455         cfs->guarantee_more(4, CHECK_NULL);
2456         max_stack = cfs->get_u1_fast();
2457         max_locals = cfs->get_u1_fast();
2458         code_length = cfs->get_u2_fast();
2459       } else {
2460         cfs->guarantee_more(8, CHECK_NULL);
2461         max_stack = cfs->get_u2_fast();
2462         max_locals = cfs->get_u2_fast();
2463         code_length = cfs->get_u4_fast();
2464       }
2465       if (_need_verify) {
2466         guarantee_property(args_size <= max_locals,
2467                            "Arguments can't fit into locals in class file %s",
2468                            CHECK_NULL);
2469         guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
2470                            "Invalid method Code length %u in class file %s",
2471                            code_length, CHECK_NULL);
2472       }
2473       // Code pointer
2474       code_start = cfs->get_u1_buffer();
2475       assert(code_start != NULL, "null code start");
2476       cfs->guarantee_more(code_length, CHECK_NULL);
2477       cfs->skip_u1_fast(code_length);
2478 
2479       // Exception handler table
2480       cfs->guarantee_more(2, CHECK_NULL);  // exception_table_length
2481       exception_table_length = cfs->get_u2_fast();
2482       if (exception_table_length > 0) {
2483         exception_table_start = parse_exception_table(cfs,
2484                                                       code_length,
2485                                                       exception_table_length,
2486                                                       CHECK_NULL);
2487       }
2488 
2489       // Parse additional attributes in code attribute
2490       cfs->guarantee_more(2, CHECK_NULL);  // code_attributes_count
2491       u2 code_attributes_count = cfs->get_u2_fast();
2492 
2493       unsigned int calculated_attribute_length = 0;
2494 
2495       if (_major_version > 45 || (_major_version == 45 && _minor_version > 2)) {
2496         calculated_attribute_length =
2497             sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
2498       } else {
2499         // max_stack, locals and length are smaller in pre-version 45.2 classes
2500         calculated_attribute_length = sizeof(u1) + sizeof(u1) + sizeof(u2);
2501       }
2502       calculated_attribute_length +=
2503         code_length +
2504         sizeof(exception_table_length) +
2505         sizeof(code_attributes_count) +
2506         exception_table_length *
2507             ( sizeof(u2) +   // start_pc
2508               sizeof(u2) +   // end_pc
2509               sizeof(u2) +   // handler_pc
2510               sizeof(u2) );  // catch_type_index
2511 
2512       while (code_attributes_count--) {
2513         cfs->guarantee_more(6, CHECK_NULL);  // code_attribute_name_index, code_attribute_length
2514         const u2 code_attribute_name_index = cfs->get_u2_fast();
2515         const u4 code_attribute_length = cfs->get_u4_fast();
2516         calculated_attribute_length += code_attribute_length +
2517                                        sizeof(code_attribute_name_index) +
2518                                        sizeof(code_attribute_length);
2519         check_property(valid_symbol_at(code_attribute_name_index),
2520                        "Invalid code attribute name index %u in class file %s",
2521                        code_attribute_name_index,
2522                        CHECK_NULL);
2523         if (LoadLineNumberTables &&
2524             cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
2525           // Parse and compress line number table
2526           parse_linenumber_table(code_attribute_length,
2527                                  code_length,
2528                                  &linenumber_table,
2529                                  CHECK_NULL);
2530 
2531         } else if (LoadLocalVariableTables &&
2532                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
2533           // Parse local variable table
2534           if (!lvt_allocated) {
2535             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2536               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2537             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2538               THREAD, const u2*, INITIAL_MAX_LVT_NUMBER);
2539             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2540               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2541             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2542               THREAD, const u2*, INITIAL_MAX_LVT_NUMBER);
2543             lvt_allocated = true;
2544           }
2545           if (lvt_cnt == max_lvt_cnt) {
2546             max_lvt_cnt <<= 1;
2547             localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
2548             localvariable_table_start  = REALLOC_RESOURCE_ARRAY(const u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
2549           }
2550           localvariable_table_start[lvt_cnt] =
2551             parse_localvariable_table(cfs,
2552                                       code_length,
2553                                       max_locals,
2554                                       code_attribute_length,
2555                                       &localvariable_table_length[lvt_cnt],
2556                                       false,    // is not LVTT
2557                                       CHECK_NULL);
2558           total_lvt_length += localvariable_table_length[lvt_cnt];
2559           lvt_cnt++;
2560         } else if (LoadLocalVariableTypeTables &&
2561                    _major_version >= JAVA_1_5_VERSION &&
2562                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
2563           if (!lvt_allocated) {
2564             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2565               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2566             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2567               THREAD, const u2*, INITIAL_MAX_LVT_NUMBER);
2568             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2569               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2570             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2571               THREAD, const u2*, INITIAL_MAX_LVT_NUMBER);
2572             lvt_allocated = true;
2573           }
2574           // Parse local variable type table
2575           if (lvtt_cnt == max_lvtt_cnt) {
2576             max_lvtt_cnt <<= 1;
2577             localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
2578             localvariable_type_table_start  = REALLOC_RESOURCE_ARRAY(const u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
2579           }
2580           localvariable_type_table_start[lvtt_cnt] =
2581             parse_localvariable_table(cfs,
2582                                       code_length,
2583                                       max_locals,
2584                                       code_attribute_length,
2585                                       &localvariable_type_table_length[lvtt_cnt],
2586                                       true,     // is LVTT
2587                                       CHECK_NULL);
2588           lvtt_cnt++;
2589         } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2590                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
2591           // Stack map is only needed by the new verifier in JDK1.5.
2592           if (parsed_stackmap_attribute) {
2593             classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_NULL);
2594           }
2595           stackmap_data = parse_stackmap_table(cfs, code_attribute_length, _need_verify, CHECK_NULL);
2596           stackmap_data_length = code_attribute_length;
2597           parsed_stackmap_attribute = true;
2598         } else {
2599           // Skip unknown attributes
2600           cfs->skip_u1(code_attribute_length, CHECK_NULL);
2601         }
2602       }
2603       // check method attribute length
2604       if (_need_verify) {
2605         guarantee_property(method_attribute_length == calculated_attribute_length,
2606                            "Code segment has wrong length in class file %s",
2607                            CHECK_NULL);
2608       }
2609     } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
2610       // Parse Exceptions attribute
2611       if (parsed_checked_exceptions_attribute) {
2612         classfile_parse_error("Multiple Exceptions attributes in class file %s",
2613                               CHECK_NULL);
2614       }
2615       parsed_checked_exceptions_attribute = true;
2616       checked_exceptions_start =
2617             parse_checked_exceptions(cfs,
2618                                      &checked_exceptions_length,
2619                                      method_attribute_length,
2620                                      CHECK_NULL);
2621     } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2622       // reject multiple method parameters
2623       if (method_parameters_seen) {
2624         classfile_parse_error("Multiple MethodParameters attributes in class file %s",
2625                               CHECK_NULL);
2626       }
2627       method_parameters_seen = true;
2628       method_parameters_length = cfs->get_u1_fast();
2629       const u2 real_length = (method_parameters_length * 4u) + 1u;
2630       if (method_attribute_length != real_length) {
2631         classfile_parse_error(
2632           "Invalid MethodParameters method attribute length %u in class file",
2633           method_attribute_length, CHECK_NULL);
2634       }
2635       method_parameters_data = cfs->get_u1_buffer();
2636       cfs->skip_u2_fast(method_parameters_length);
2637       cfs->skip_u2_fast(method_parameters_length);
2638       // ignore this attribute if it cannot be reflected
2639       if (!SystemDictionary::Parameter_klass_loaded())
2640         method_parameters_length = -1;
2641     } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
2642       if (method_attribute_length != 0) {
2643         classfile_parse_error(
2644           "Invalid Synthetic method attribute length %u in class file %s",
2645           method_attribute_length, CHECK_NULL);
2646       }
2647       // Should we check that there hasn't already been a synthetic attribute?
2648       access_flags.set_is_synthetic();
2649     } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
2650       if (method_attribute_length != 0) {
2651         classfile_parse_error(
2652           "Invalid Deprecated method attribute length %u in class file %s",
2653           method_attribute_length, CHECK_NULL);
2654       }
2655     } else if (_major_version >= JAVA_1_5_VERSION) {
2656       if (method_attribute_name == vmSymbols::tag_signature()) {
2657         if (generic_signature_index != 0) {
2658           classfile_parse_error(
2659             "Multiple Signature attributes for method in class file %s",
2660             CHECK_NULL);
2661         }
2662         if (method_attribute_length != 2) {
2663           classfile_parse_error(
2664             "Invalid Signature attribute length %u in class file %s",
2665             method_attribute_length, CHECK_NULL);
2666         }
2667         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL);
2668       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
2669         if (runtime_visible_annotations != NULL) {
2670           classfile_parse_error(
2671             "Multiple RuntimeVisibleAnnotations attributes for method in class file %s",
2672             CHECK_NULL);
2673         }
2674         runtime_visible_annotations_length = method_attribute_length;
2675         runtime_visible_annotations = cfs->get_u1_buffer();
2676         assert(runtime_visible_annotations != NULL, "null visible annotations");
2677         cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL);
2678         parse_annotations(cp,
2679                           runtime_visible_annotations,
2680                           runtime_visible_annotations_length,
2681                           &parsed_annotations,
2682                           _loader_data,
2683                           CHECK_NULL);
2684         cfs->skip_u1_fast(runtime_visible_annotations_length);
2685       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
2686         if (runtime_invisible_annotations_exists) {
2687           classfile_parse_error(
2688             "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s",
2689             CHECK_NULL);
2690         }
2691         runtime_invisible_annotations_exists = true;
2692         if (PreserveAllAnnotations) {
2693           runtime_invisible_annotations_length = method_attribute_length;
2694           runtime_invisible_annotations = cfs->get_u1_buffer();
2695           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
2696         }
2697         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2698       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
2699         if (runtime_visible_parameter_annotations != NULL) {
2700           classfile_parse_error(
2701             "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s",
2702             CHECK_NULL);
2703         }
2704         runtime_visible_parameter_annotations_length = method_attribute_length;
2705         runtime_visible_parameter_annotations = cfs->get_u1_buffer();
2706         assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");
2707         cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL);
2708       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
2709         if (runtime_invisible_parameter_annotations_exists) {
2710           classfile_parse_error(
2711             "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s",
2712             CHECK_NULL);
2713         }
2714         runtime_invisible_parameter_annotations_exists = true;
2715         if (PreserveAllAnnotations) {
2716           runtime_invisible_parameter_annotations_length = method_attribute_length;
2717           runtime_invisible_parameter_annotations = cfs->get_u1_buffer();
2718           assert(runtime_invisible_parameter_annotations != NULL,
2719             "null invisible parameter annotations");
2720         }
2721         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2722       } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
2723         if (annotation_default != NULL) {
2724           classfile_parse_error(
2725             "Multiple AnnotationDefault attributes for method in class file %s",
2726             CHECK_NULL);
2727         }
2728         annotation_default_length = method_attribute_length;
2729         annotation_default = cfs->get_u1_buffer();
2730         assert(annotation_default != NULL, "null annotation default");
2731         cfs->skip_u1(annotation_default_length, CHECK_NULL);
2732       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2733         if (runtime_visible_type_annotations != NULL) {
2734           classfile_parse_error(
2735             "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
2736             CHECK_NULL);
2737         }
2738         runtime_visible_type_annotations_length = method_attribute_length;
2739         runtime_visible_type_annotations = cfs->get_u1_buffer();
2740         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
2741         // No need for the VM to parse Type annotations
2742         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL);
2743       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
2744         if (runtime_invisible_type_annotations_exists) {
2745           classfile_parse_error(
2746             "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
2747             CHECK_NULL);
2748         } else {
2749           runtime_invisible_type_annotations_exists = true;
2750         }
2751         if (PreserveAllAnnotations) {
2752           runtime_invisible_type_annotations_length = method_attribute_length;
2753           runtime_invisible_type_annotations = cfs->get_u1_buffer();
2754           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
2755         }
2756         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2757       } else {
2758         // Skip unknown attributes
2759         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2760       }
2761     } else {
2762       // Skip unknown attributes
2763       cfs->skip_u1(method_attribute_length, CHECK_NULL);
2764     }
2765   }
2766 
2767   if (linenumber_table != NULL) {
2768     linenumber_table->write_terminator();
2769     linenumber_table_length = linenumber_table->position();
2770   }
2771 
2772   // Make sure there's at least one Code attribute in non-native/non-abstract method
2773   if (_need_verify) {
2774     guarantee_property(access_flags.is_native() ||
2775                        access_flags.is_abstract() ||
2776                        parsed_code_attribute,
2777                        "Absent Code attribute in method that is not native or abstract in class file %s",
2778                        CHECK_NULL);
2779   }
2780 
2781   // All sizing information for a Method* is finally available, now create it
2782   InlineTableSizes sizes(
2783       total_lvt_length,
2784       linenumber_table_length,
2785       exception_table_length,
2786       checked_exceptions_length,
2787       method_parameters_length,
2788       generic_signature_index,
2789       runtime_visible_annotations_length +
2790            runtime_invisible_annotations_length,
2791       runtime_visible_parameter_annotations_length +
2792            runtime_invisible_parameter_annotations_length,
2793       runtime_visible_type_annotations_length +
2794            runtime_invisible_type_annotations_length,
2795       annotation_default_length,
2796       0);
2797 
2798   Method* const m = Method::allocate(_loader_data,
2799                                      code_length,
2800                                      access_flags,
2801                                      &sizes,
2802                                      ConstMethod::NORMAL,
2803                                      CHECK_NULL);
2804 
2805   ClassLoadingService::add_class_method_size(m->size()*wordSize);
2806 
2807   // Fill in information from fixed part (access_flags already set)
2808   m->set_constants(_cp);
2809   m->set_name_index(name_index);
2810   m->set_signature_index(signature_index);
2811 
2812   ResultTypeFinder rtf(cp->symbol_at(signature_index));
2813   m->constMethod()->set_result_type(rtf.type());
2814 
2815   if (args_size >= 0) {
2816     m->set_size_of_parameters(args_size);
2817   } else {
2818     m->compute_size_of_parameters(THREAD);
2819   }
2820 #ifdef ASSERT
2821   if (args_size >= 0) {
2822     m->compute_size_of_parameters(THREAD);
2823     assert(args_size == m->size_of_parameters(), "");
2824   }
2825 #endif
2826 
2827   // Fill in code attribute information
2828   m->set_max_stack(max_stack);
2829   m->set_max_locals(max_locals);
2830   if (stackmap_data != NULL) {
2831     m->constMethod()->copy_stackmap_data(_loader_data,
2832                                          (u1*)stackmap_data,
2833                                          stackmap_data_length,
2834                                          CHECK_NULL);
2835   }
2836 
2837   // Copy byte codes
2838   m->set_code((u1*)code_start);
2839 
2840   // Copy line number table
2841   if (linenumber_table != NULL) {
2842     memcpy(m->compressed_linenumber_table(),
2843            linenumber_table->buffer(),
2844            linenumber_table_length);
2845   }
2846 
2847   // Copy exception table
2848   if (exception_table_length > 0) {
2849     int size =
2850       exception_table_length * sizeof(ExceptionTableElement) / sizeof(u2);
2851     copy_u2_with_conversion((u2*) m->exception_table_start(),
2852                             exception_table_start, size);
2853   }
2854 
2855   // Copy method parameters
2856   if (method_parameters_length > 0) {
2857     MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2858     for (int i = 0; i < method_parameters_length; i++) {
2859       elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data);
2860       method_parameters_data += 2;
2861       elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data);
2862       method_parameters_data += 2;
2863     }
2864   }
2865 
2866   // Copy checked exceptions
2867   if (checked_exceptions_length > 0) {
2868     const int size =
2869       checked_exceptions_length * sizeof(CheckedExceptionElement) / sizeof(u2);
2870     copy_u2_with_conversion((u2*) m->checked_exceptions_start(),
2871                             checked_exceptions_start,
2872                             size);
2873   }
2874 
2875   // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2876   if (total_lvt_length > 0) {
2877     promoted_flags->set_has_localvariable_table();
2878     copy_localvariable_table(m->constMethod(),
2879                              lvt_cnt,
2880                              localvariable_table_length,
2881                              localvariable_table_start,
2882                              lvtt_cnt,
2883                              localvariable_type_table_length,
2884                              localvariable_type_table_start,
2885                              CHECK_NULL);
2886   }
2887 
2888   if (parsed_annotations.has_any_annotations())
2889     parsed_annotations.apply_to(m);
2890 
2891   // Copy annotations
2892   copy_method_annotations(m->constMethod(),
2893                           runtime_visible_annotations,
2894                           runtime_visible_annotations_length,
2895                           runtime_invisible_annotations,
2896                           runtime_invisible_annotations_length,
2897                           runtime_visible_parameter_annotations,
2898                           runtime_visible_parameter_annotations_length,
2899                           runtime_invisible_parameter_annotations,
2900                           runtime_invisible_parameter_annotations_length,
2901                           runtime_visible_type_annotations,
2902                           runtime_visible_type_annotations_length,
2903                           runtime_invisible_type_annotations,
2904                           runtime_invisible_type_annotations_length,
2905                           annotation_default,
2906                           annotation_default_length,
2907                           CHECK_NULL);
2908 
2909   if (name == vmSymbols::finalize_method_name() &&
2910       signature == vmSymbols::void_method_signature()) {
2911     if (m->is_empty_method()) {
2912       _has_empty_finalizer = true;
2913     } else {
2914       _has_finalizer = true;
2915     }
2916   }
2917   if (name == vmSymbols::object_initializer_name() &&
2918       signature == vmSymbols::void_method_signature() &&
2919       m->is_vanilla_constructor()) {
2920     _has_vanilla_constructor = true;
2921   }
2922 
2923   NOT_PRODUCT(m->verify());
2924   return m;
2925 }
2926 
2927 
2928 // The promoted_flags parameter is used to pass relevant access_flags
2929 // from the methods back up to the containing klass. These flag values
2930 // are added to klass's access_flags.
2931 // Side-effects: populates the _methods field in the parser
2932 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2933                                     bool is_interface,
2934                                     AccessFlags* promoted_flags,
2935                                     bool* has_final_method,
2936                                     bool* declares_nonstatic_concrete_methods,
2937                                     TRAPS) {
2938   assert(cfs != NULL, "invariant");
2939   assert(promoted_flags != NULL, "invariant");
2940   assert(has_final_method != NULL, "invariant");
2941   assert(declares_nonstatic_concrete_methods != NULL, "invariant");
2942 
2943   assert(NULL == _methods, "invariant");
2944 
2945   cfs->guarantee_more(2, CHECK);  // length
2946   const u2 length = cfs->get_u2_fast();
2947   if (length == 0) {
2948     _methods = Universe::the_empty_method_array();
2949   } else {
2950     _methods = MetadataFactory::new_array<Method*>(_loader_data,
2951                                                    length,
2952                                                    NULL,
2953                                                    CHECK);
2954 
2955     for (int index = 0; index < length; index++) {
2956       Method* method = parse_method(cfs,
2957                                     is_interface,
2958                                     _cp,
2959                                     promoted_flags,
2960                                     CHECK);
2961 
2962       if (method->is_final()) {
2963         *has_final_method = true;
2964       }
2965       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
2966       // used for interface initialization, and default method inheritance analysis
2967       if (is_interface && !(*declares_nonstatic_concrete_methods)
2968         && !method->is_abstract() && !method->is_static()) {
2969         *declares_nonstatic_concrete_methods = true;
2970       }
2971       _methods->at_put(index, method);
2972     }
2973 
2974     if (_need_verify && length > 1) {
2975       // Check duplicated methods
2976       ResourceMark rm(THREAD);
2977       NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
2978         THREAD, NameSigHash*, HASH_ROW_SIZE);
2979       initialize_hashtable(names_and_sigs);
2980       bool dup = false;
2981       const Symbol* name = NULL;
2982       const Symbol* sig = NULL;
2983       {
2984         debug_only(NoSafepointVerifier nsv;)
2985         for (int i = 0; i < length; i++) {
2986           const Method* const m = _methods->at(i);
2987           name = m->name();
2988           sig = m->signature();
2989           // If no duplicates, add name/signature in hashtable names_and_sigs.
2990           if (!put_after_lookup(name, sig, names_and_sigs)) {
2991             dup = true;
2992             break;
2993           }
2994         }
2995       }
2996       if (dup) {
2997         classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
2998                                name->as_C_string(), sig->as_klass_external_name(), CHECK);
2999       }
3000     }
3001   }
3002 }
3003 
3004 static const intArray* sort_methods(Array<Method*>* methods) {
3005   const int length = methods->length();
3006   // If JVMTI original method ordering or sharing is enabled we have to
3007   // remember the original class file ordering.
3008   // We temporarily use the vtable_index field in the Method* to store the
3009   // class file index, so we can read in after calling qsort.
3010   // Put the method ordering in the shared archive.
3011   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
3012     for (int index = 0; index < length; index++) {
3013       Method* const m = methods->at(index);
3014       assert(!m->valid_vtable_index(), "vtable index should not be set");
3015       m->set_vtable_index(index);
3016     }
3017   }
3018   // Sort method array by ascending method name (for faster lookups & vtable construction)
3019   // Note that the ordering is not alphabetical, see Symbol::fast_compare
3020   Method::sort_methods(methods);
3021 
3022   intArray* method_ordering = NULL;
3023   // If JVMTI original method ordering or sharing is enabled construct int
3024   // array remembering the original ordering
3025   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
3026     method_ordering = new intArray(length, length, -1);
3027     for (int index = 0; index < length; index++) {
3028       Method* const m = methods->at(index);
3029       const int old_index = m->vtable_index();
3030       assert(old_index >= 0 && old_index < length, "invalid method index");
3031       method_ordering->at_put(index, old_index);
3032       m->set_vtable_index(Method::invalid_vtable_index);
3033     }
3034   }
3035   return method_ordering;
3036 }
3037 
3038 // Parse generic_signature attribute for methods and fields
3039 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs,
3040                                                       TRAPS) {
3041   assert(cfs != NULL, "invariant");
3042 
3043   cfs->guarantee_more(2, CHECK_0);  // generic_signature_index
3044   const u2 generic_signature_index = cfs->get_u2_fast();
3045   check_property(
3046     valid_symbol_at(generic_signature_index),
3047     "Invalid Signature attribute at constant pool index %u in class file %s",
3048     generic_signature_index, CHECK_0);
3049   return generic_signature_index;
3050 }
3051 
3052 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs,
3053                                                            TRAPS) {
3054 
3055   assert(cfs != NULL, "invariant");
3056 
3057   cfs->guarantee_more(2, CHECK);  // sourcefile_index
3058   const u2 sourcefile_index = cfs->get_u2_fast();
3059   check_property(
3060     valid_symbol_at(sourcefile_index),
3061     "Invalid SourceFile attribute at constant pool index %u in class file %s",
3062     sourcefile_index, CHECK);
3063   set_class_sourcefile_index(sourcefile_index);
3064 }
3065 
3066 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
3067                                                                        int length,
3068                                                                        TRAPS) {
3069   assert(cfs != NULL, "invariant");
3070 
3071   const u1* const sde_buffer = cfs->get_u1_buffer();
3072   assert(sde_buffer != NULL, "null sde buffer");
3073 
3074   // Don't bother storing it if there is no way to retrieve it
3075   if (JvmtiExport::can_get_source_debug_extension()) {
3076     assert((length+1) > length, "Overflow checking");
3077     u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
3078     for (int i = 0; i < length; i++) {
3079       sde[i] = sde_buffer[i];
3080     }
3081     sde[length] = '\0';
3082     set_class_sde_buffer((const char*)sde, length);
3083   }
3084   // Got utf8 string, set stream position forward
3085   cfs->skip_u1(length, CHECK);
3086 }
3087 
3088 
3089 // Inner classes can be static, private or protected (classic VM does this)
3090 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \
3091                                            JVM_ACC_PRIVATE |                \
3092                                            JVM_ACC_PROTECTED |              \
3093                                            JVM_ACC_STATIC                   \
3094                                          )
3095 
3096 // Return number of classes in the inner classes attribute table
3097 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
3098                                                             const u1* const inner_classes_attribute_start,
3099                                                             bool parsed_enclosingmethod_attribute,
3100                                                             u2 enclosing_method_class_index,
3101                                                             u2 enclosing_method_method_index,
3102                                                             TRAPS) {
3103   const u1* const current_mark = cfs->current();
3104   u2 length = 0;
3105   if (inner_classes_attribute_start != NULL) {
3106     cfs->set_current(inner_classes_attribute_start);
3107     cfs->guarantee_more(2, CHECK_0);  // length
3108     length = cfs->get_u2_fast();
3109   }
3110 
3111   // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
3112   // method data:
3113   //   [inner_class_info_index,
3114   //    outer_class_info_index,
3115   //    inner_name_index,
3116   //    inner_class_access_flags,
3117   //    ...
3118   //    enclosing_method_class_index,
3119   //    enclosing_method_method_index]
3120   const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
3121   Array<u2>* const inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3122   _inner_classes = inner_classes;
3123 
3124   int index = 0;
3125   const int cp_size = _cp->length();
3126   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
3127   for (int n = 0; n < length; n++) {
3128     // Inner class index
3129     const u2 inner_class_info_index = cfs->get_u2_fast();
3130     check_property(
3131       valid_klass_reference_at(inner_class_info_index),
3132       "inner_class_info_index %u has bad constant type in class file %s",
3133       inner_class_info_index, CHECK_0);
3134     // Outer class index
3135     const u2 outer_class_info_index = cfs->get_u2_fast();
3136     check_property(
3137       outer_class_info_index == 0 ||
3138         valid_klass_reference_at(outer_class_info_index),
3139       "outer_class_info_index %u has bad constant type in class file %s",
3140       outer_class_info_index, CHECK_0);
3141     // Inner class name
3142     const u2 inner_name_index = cfs->get_u2_fast();
3143     check_property(
3144       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3145       "inner_name_index %u has bad constant type in class file %s",
3146       inner_name_index, CHECK_0);
3147     if (_need_verify) {
3148       guarantee_property(inner_class_info_index != outer_class_info_index,
3149                          "Class is both outer and inner class in class file %s", CHECK_0);
3150     }
3151     // Access flags
3152     jint flags;
3153     // JVM_ACC_MODULE is defined in JDK-9 and later.
3154     if (_major_version >= JAVA_9_VERSION) {
3155       flags = cfs->get_u2_fast() & (RECOGNIZED_INNER_CLASS_MODIFIERS | JVM_ACC_MODULE);
3156     } else {
3157       flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
3158     }
3159     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3160       // Set abstract bit for old class files for backward compatibility
3161       flags |= JVM_ACC_ABSTRACT;
3162     }
3163     verify_legal_class_modifiers(flags, CHECK_0);
3164     AccessFlags inner_access_flags(flags);
3165 
3166     inner_classes->at_put(index++, inner_class_info_index);
3167     inner_classes->at_put(index++, outer_class_info_index);
3168     inner_classes->at_put(index++, inner_name_index);
3169     inner_classes->at_put(index++, inner_access_flags.as_short());
3170   }
3171 
3172   // 4347400: make sure there's no duplicate entry in the classes array
3173   if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
3174     for(int i = 0; i < length * 4; i += 4) {
3175       for(int j = i + 4; j < length * 4; j += 4) {
3176         guarantee_property((inner_classes->at(i)   != inner_classes->at(j) ||
3177                             inner_classes->at(i+1) != inner_classes->at(j+1) ||
3178                             inner_classes->at(i+2) != inner_classes->at(j+2) ||
3179                             inner_classes->at(i+3) != inner_classes->at(j+3)),
3180                             "Duplicate entry in InnerClasses in class file %s",
3181                             CHECK_0);
3182       }
3183     }
3184   }
3185 
3186   // Set EnclosingMethod class and method indexes.
3187   if (parsed_enclosingmethod_attribute) {
3188     inner_classes->at_put(index++, enclosing_method_class_index);
3189     inner_classes->at_put(index++, enclosing_method_method_index);
3190   }
3191   assert(index == size, "wrong size");
3192 
3193   // Restore buffer's current position.
3194   cfs->set_current(current_mark);
3195 
3196   return length;
3197 }
3198 
3199 void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
3200   set_class_synthetic_flag(true);
3201 }
3202 
3203 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3204   assert(cfs != NULL, "invariant");
3205 
3206   const u2 signature_index = cfs->get_u2(CHECK);
3207   check_property(
3208     valid_symbol_at(signature_index),
3209     "Invalid constant pool index %u in Signature attribute in class file %s",
3210     signature_index, CHECK);
3211   set_class_generic_signature_index(signature_index);
3212 }
3213 
3214 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3215                                                                   ConstantPool* cp,
3216                                                                   u4 attribute_byte_length,
3217                                                                   TRAPS) {
3218   assert(cfs != NULL, "invariant");
3219   assert(cp != NULL, "invariant");
3220 
3221   const u1* const current_start = cfs->current();
3222 
3223   guarantee_property(attribute_byte_length >= sizeof(u2),
3224                      "Invalid BootstrapMethods attribute length %u in class file %s",
3225                      attribute_byte_length,
3226                      CHECK);
3227 
3228   cfs->guarantee_more(attribute_byte_length, CHECK);
3229 
3230   const int attribute_array_length = cfs->get_u2_fast();
3231 
3232   guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
3233                      "Short length on BootstrapMethods in class file %s",
3234                      CHECK);
3235 
3236 
3237   // The attribute contains a counted array of counted tuples of shorts,
3238   // represending bootstrap specifiers:
3239   //    length*{bootstrap_method_index, argument_count*{argument_index}}
3240   const int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3241   // operand_count = number of shorts in attr, except for leading length
3242 
3243   // The attribute is copied into a short[] array.
3244   // The array begins with a series of short[2] pairs, one for each tuple.
3245   const int index_size = (attribute_array_length * 2);
3246 
3247   Array<u2>* const operands =
3248     MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
3249 
3250   // Eagerly assign operands so they will be deallocated with the constant
3251   // pool if there is an error.
3252   cp->set_operands(operands);
3253 
3254   int operand_fill_index = index_size;
3255   const int cp_size = cp->length();
3256 
3257   for (int n = 0; n < attribute_array_length; n++) {
3258     // Store a 32-bit offset into the header of the operand array.
3259     ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
3260 
3261     // Read a bootstrap specifier.
3262     cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
3263     const u2 bootstrap_method_index = cfs->get_u2_fast();
3264     const u2 argument_count = cfs->get_u2_fast();
3265     check_property(
3266       valid_cp_range(bootstrap_method_index, cp_size) &&
3267       cp->tag_at(bootstrap_method_index).is_method_handle(),
3268       "bootstrap_method_index %u has bad constant type in class file %s",
3269       bootstrap_method_index,
3270       CHECK);
3271 
3272     guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
3273       "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
3274       CHECK);
3275 
3276     operands->at_put(operand_fill_index++, bootstrap_method_index);
3277     operands->at_put(operand_fill_index++, argument_count);
3278 
3279     cfs->guarantee_more(sizeof(u2) * argument_count, CHECK);  // argv[argc]
3280     for (int j = 0; j < argument_count; j++) {
3281       const u2 argument_index = cfs->get_u2_fast();
3282       check_property(
3283         valid_cp_range(argument_index, cp_size) &&
3284         cp->tag_at(argument_index).is_loadable_constant(),
3285         "argument_index %u has bad constant type in class file %s",
3286         argument_index,
3287         CHECK);
3288       operands->at_put(operand_fill_index++, argument_index);
3289     }
3290   }
3291   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3292                      "Bad length on BootstrapMethods in class file %s",
3293                      CHECK);
3294 }
3295 
3296 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3297                                                  ConstantPool* cp,
3298                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3299                                                  TRAPS) {
3300   assert(cfs != NULL, "invariant");
3301   assert(cp != NULL, "invariant");
3302   assert(parsed_annotations != NULL, "invariant");
3303 
3304   // Set inner classes attribute to default sentinel
3305   _inner_classes = Universe::the_empty_short_array();
3306   cfs->guarantee_more(2, CHECK);  // attributes_count
3307   u2 attributes_count = cfs->get_u2_fast();
3308   bool parsed_sourcefile_attribute = false;
3309   bool parsed_innerclasses_attribute = false;
3310   bool parsed_enclosingmethod_attribute = false;
3311   bool parsed_bootstrap_methods_attribute = false;
3312   const u1* runtime_visible_annotations = NULL;
3313   int runtime_visible_annotations_length = 0;
3314   const u1* runtime_invisible_annotations = NULL;
3315   int runtime_invisible_annotations_length = 0;
3316   const u1* runtime_visible_type_annotations = NULL;
3317   int runtime_visible_type_annotations_length = 0;
3318   const u1* runtime_invisible_type_annotations = NULL;
3319   int runtime_invisible_type_annotations_length = 0;
3320   bool runtime_invisible_type_annotations_exists = false;
3321   bool runtime_invisible_annotations_exists = false;
3322   bool parsed_source_debug_ext_annotations_exist = false;
3323   const u1* inner_classes_attribute_start = NULL;
3324   u4  inner_classes_attribute_length = 0;
3325   u2  enclosing_method_class_index = 0;
3326   u2  enclosing_method_method_index = 0;
3327   // Iterate over attributes
3328   while (attributes_count--) {
3329     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3330     const u2 attribute_name_index = cfs->get_u2_fast();
3331     const u4 attribute_length = cfs->get_u4_fast();
3332     check_property(
3333       valid_symbol_at(attribute_name_index),
3334       "Attribute name has bad constant pool index %u in class file %s",
3335       attribute_name_index, CHECK);
3336     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3337     if (tag == vmSymbols::tag_source_file()) {
3338       // Check for SourceFile tag
3339       if (_need_verify) {
3340         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3341       }
3342       if (parsed_sourcefile_attribute) {
3343         classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
3344       } else {
3345         parsed_sourcefile_attribute = true;
3346       }
3347       parse_classfile_sourcefile_attribute(cfs, CHECK);
3348     } else if (tag == vmSymbols::tag_source_debug_extension()) {
3349       // Check for SourceDebugExtension tag
3350       if (parsed_source_debug_ext_annotations_exist) {
3351           classfile_parse_error(
3352             "Multiple SourceDebugExtension attributes in class file %s", CHECK);
3353       }
3354       parsed_source_debug_ext_annotations_exist = true;
3355       parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3356     } else if (tag == vmSymbols::tag_inner_classes()) {
3357       // Check for InnerClasses tag
3358       if (parsed_innerclasses_attribute) {
3359         classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
3360       } else {
3361         parsed_innerclasses_attribute = true;
3362       }
3363       inner_classes_attribute_start = cfs->get_u1_buffer();
3364       inner_classes_attribute_length = attribute_length;
3365       cfs->skip_u1(inner_classes_attribute_length, CHECK);
3366     } else if (tag == vmSymbols::tag_synthetic()) {
3367       // Check for Synthetic tag
3368       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3369       if (attribute_length != 0) {
3370         classfile_parse_error(
3371           "Invalid Synthetic classfile attribute length %u in class file %s",
3372           attribute_length, CHECK);
3373       }
3374       parse_classfile_synthetic_attribute(CHECK);
3375     } else if (tag == vmSymbols::tag_deprecated()) {
3376       // Check for Deprecatd tag - 4276120
3377       if (attribute_length != 0) {
3378         classfile_parse_error(
3379           "Invalid Deprecated classfile attribute length %u in class file %s",
3380           attribute_length, CHECK);
3381       }
3382     } else if (_major_version >= JAVA_1_5_VERSION) {
3383       if (tag == vmSymbols::tag_signature()) {
3384         if (_generic_signature_index != 0) {
3385           classfile_parse_error(
3386             "Multiple Signature attributes in class file %s", CHECK);
3387         }
3388         if (attribute_length != 2) {
3389           classfile_parse_error(
3390             "Wrong Signature attribute length %u in class file %s",
3391             attribute_length, CHECK);
3392         }
3393         parse_classfile_signature_attribute(cfs, CHECK);
3394       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3395         if (runtime_visible_annotations != NULL) {
3396           classfile_parse_error(
3397             "Multiple RuntimeVisibleAnnotations attributes in class file %s", CHECK);
3398         }
3399         runtime_visible_annotations_length = attribute_length;
3400         runtime_visible_annotations = cfs->get_u1_buffer();
3401         assert(runtime_visible_annotations != NULL, "null visible annotations");
3402         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3403         parse_annotations(cp,
3404                           runtime_visible_annotations,
3405                           runtime_visible_annotations_length,
3406                           parsed_annotations,
3407                           _loader_data,
3408                           CHECK);
3409         cfs->skip_u1_fast(runtime_visible_annotations_length);
3410       } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3411         if (runtime_invisible_annotations_exists) {
3412           classfile_parse_error(
3413             "Multiple RuntimeInvisibleAnnotations attributes in class file %s", CHECK);
3414         }
3415         runtime_invisible_annotations_exists = true;
3416         if (PreserveAllAnnotations) {
3417           runtime_invisible_annotations_length = attribute_length;
3418           runtime_invisible_annotations = cfs->get_u1_buffer();
3419           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
3420         }
3421         cfs->skip_u1(attribute_length, CHECK);
3422       } else if (tag == vmSymbols::tag_enclosing_method()) {
3423         if (parsed_enclosingmethod_attribute) {
3424           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
3425         } else {
3426           parsed_enclosingmethod_attribute = true;
3427         }
3428         guarantee_property(attribute_length == 4,
3429           "Wrong EnclosingMethod attribute length %u in class file %s",
3430           attribute_length, CHECK);
3431         cfs->guarantee_more(4, CHECK);  // class_index, method_index
3432         enclosing_method_class_index  = cfs->get_u2_fast();
3433         enclosing_method_method_index = cfs->get_u2_fast();
3434         if (enclosing_method_class_index == 0) {
3435           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
3436         }
3437         // Validate the constant pool indices and types
3438         check_property(valid_klass_reference_at(enclosing_method_class_index),
3439           "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3440         if (enclosing_method_method_index != 0 &&
3441             (!cp->is_within_bounds(enclosing_method_method_index) ||
3442              !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3443           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
3444         }
3445       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3446                  _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3447         if (parsed_bootstrap_methods_attribute) {
3448           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
3449         }
3450         parsed_bootstrap_methods_attribute = true;
3451         parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3452       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3453         if (runtime_visible_type_annotations != NULL) {
3454           classfile_parse_error(
3455             "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);
3456         }
3457         runtime_visible_type_annotations_length = attribute_length;
3458         runtime_visible_type_annotations = cfs->get_u1_buffer();
3459         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
3460         // No need for the VM to parse Type annotations
3461         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3462       } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3463         if (runtime_invisible_type_annotations_exists) {
3464           classfile_parse_error(
3465             "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);
3466         } else {
3467           runtime_invisible_type_annotations_exists = true;
3468         }
3469         if (PreserveAllAnnotations) {
3470           runtime_invisible_type_annotations_length = attribute_length;
3471           runtime_invisible_type_annotations = cfs->get_u1_buffer();
3472           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
3473         }
3474         cfs->skip_u1(attribute_length, CHECK);
3475       } else {
3476         // Unknown attribute
3477         cfs->skip_u1(attribute_length, CHECK);
3478       }
3479     } else {
3480       // Unknown attribute
3481       cfs->skip_u1(attribute_length, CHECK);
3482     }
3483   }
3484   _annotations = assemble_annotations(runtime_visible_annotations,
3485                                       runtime_visible_annotations_length,
3486                                       runtime_invisible_annotations,
3487                                       runtime_invisible_annotations_length,
3488                                       CHECK);
3489   _type_annotations = assemble_annotations(runtime_visible_type_annotations,
3490                                            runtime_visible_type_annotations_length,
3491                                            runtime_invisible_type_annotations,
3492                                            runtime_invisible_type_annotations_length,
3493                                            CHECK);
3494 
3495   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3496     const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3497                             cfs,
3498                             inner_classes_attribute_start,
3499                             parsed_innerclasses_attribute,
3500                             enclosing_method_class_index,
3501                             enclosing_method_method_index,
3502                             CHECK);
3503     if (parsed_innerclasses_attribute &&_need_verify && _major_version >= JAVA_1_5_VERSION) {
3504       guarantee_property(
3505         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3506         "Wrong InnerClasses attribute length in class file %s", CHECK);
3507     }
3508   }
3509 
3510   if (_max_bootstrap_specifier_index >= 0) {
3511     guarantee_property(parsed_bootstrap_methods_attribute,
3512                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3513   }
3514 }
3515 
3516 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3517   assert(k != NULL, "invariant");
3518 
3519   if (_synthetic_flag)
3520     k->set_is_synthetic();
3521   if (_sourcefile_index != 0) {
3522     k->set_source_file_name_index(_sourcefile_index);
3523   }
3524   if (_generic_signature_index != 0) {
3525     k->set_generic_signature_index(_generic_signature_index);
3526   }
3527   if (_sde_buffer != NULL) {
3528     k->set_source_debug_extension(_sde_buffer, _sde_length);
3529   }
3530 }
3531 
3532 // Create the Annotations object that will
3533 // hold the annotations array for the Klass.
3534 void ClassFileParser::create_combined_annotations(TRAPS) {
3535     if (_annotations == NULL &&
3536         _type_annotations == NULL &&
3537         _fields_annotations == NULL &&
3538         _fields_type_annotations == NULL) {
3539       // Don't create the Annotations object unnecessarily.
3540       return;
3541     }
3542 
3543     Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3544     annotations->set_class_annotations(_annotations);
3545     annotations->set_class_type_annotations(_type_annotations);
3546     annotations->set_fields_annotations(_fields_annotations);
3547     annotations->set_fields_type_annotations(_fields_type_annotations);
3548 
3549     // This is the Annotations object that will be
3550     // assigned to InstanceKlass being constructed.
3551     _combined_annotations = annotations;
3552 
3553     // The annotations arrays below has been transfered the
3554     // _combined_annotations so these fields can now be cleared.
3555     _annotations             = NULL;
3556     _type_annotations        = NULL;
3557     _fields_annotations      = NULL;
3558     _fields_type_annotations = NULL;
3559 }
3560 
3561 // Transfer ownership of metadata allocated to the InstanceKlass.
3562 void ClassFileParser::apply_parsed_class_metadata(
3563                                             InstanceKlass* this_klass,
3564                                             int java_fields_count, TRAPS) {
3565   assert(this_klass != NULL, "invariant");
3566 
3567   _cp->set_pool_holder(this_klass);
3568   this_klass->set_constants(_cp);
3569   this_klass->set_fields(_fields, java_fields_count);
3570   this_klass->set_methods(_methods);
3571   this_klass->set_inner_classes(_inner_classes);
3572   this_klass->set_local_interfaces(_local_interfaces);
3573   this_klass->set_transitive_interfaces(_transitive_interfaces);
3574   this_klass->set_annotations(_combined_annotations);
3575 
3576   // Clear out these fields so they don't get deallocated by the destructor
3577   clear_class_metadata();
3578 }
3579 
3580 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3581                                                        int runtime_visible_annotations_length,
3582                                                        const u1* const runtime_invisible_annotations,
3583                                                        int runtime_invisible_annotations_length,
3584                                                        TRAPS) {
3585   AnnotationArray* annotations = NULL;
3586   if (runtime_visible_annotations != NULL ||
3587       runtime_invisible_annotations != NULL) {
3588     annotations = MetadataFactory::new_array<u1>(_loader_data,
3589                                           runtime_visible_annotations_length +
3590                                           runtime_invisible_annotations_length,
3591                                           CHECK_(annotations));
3592     if (runtime_visible_annotations != NULL) {
3593       for (int i = 0; i < runtime_visible_annotations_length; i++) {
3594         annotations->at_put(i, runtime_visible_annotations[i]);
3595       }
3596     }
3597     if (runtime_invisible_annotations != NULL) {
3598       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3599         int append = runtime_visible_annotations_length+i;
3600         annotations->at_put(append, runtime_invisible_annotations[i]);
3601       }
3602     }
3603   }
3604   return annotations;
3605 }
3606 
3607 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3608                                                         const int super_class_index,
3609                                                         const bool need_verify,
3610                                                         TRAPS) {
3611   assert(cp != NULL, "invariant");
3612   const InstanceKlass* super_klass = NULL;
3613 
3614   if (super_class_index == 0) {
3615     check_property(_class_name == vmSymbols::java_lang_Object()
3616                    || (_access_flags.get_flags() & JVM_ACC_VALUE),
3617                    "Invalid superclass index %u in class file %s",
3618                    super_class_index,
3619                    CHECK_NULL);
3620   } else {
3621     check_property(valid_klass_reference_at(super_class_index),
3622                    "Invalid superclass index %u in class file %s",
3623                    super_class_index,
3624                    CHECK_NULL);
3625     // The class name should be legal because it is checked when parsing constant pool.
3626     // However, make sure it is not an array type.
3627     bool is_array = false;
3628     if (cp->tag_at(super_class_index).is_klass()) {
3629       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3630       if (need_verify)
3631         is_array = super_klass->is_array_klass();
3632     } else if (need_verify) {
3633       is_array = (cp->klass_name_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
3634     }
3635     if (need_verify) {
3636       guarantee_property(!is_array,
3637                         "Bad superclass name in class file %s", CHECK_NULL);
3638     }
3639   }
3640   return super_klass;
3641 }
3642 
3643 #ifndef PRODUCT
3644 static void print_field_layout(const Symbol* name,
3645                                Array<u2>* fields,
3646                                constantPoolHandle cp,
3647                                int instance_size,
3648                                int instance_fields_start,
3649                                int instance_fields_end,
3650                                int static_fields_end) {
3651 
3652   assert(name != NULL, "invariant");
3653 
3654   tty->print("%s: field layout\n", name->as_klass_external_name());
3655   tty->print("  @%3d %s\n", instance_fields_start, "--- instance fields start ---");
3656   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3657     if (!fs.access_flags().is_static()) {
3658       tty->print("  @%3d \"%s\" %s\n",
3659         fs.offset(),
3660         fs.name()->as_klass_external_name(),
3661         fs.signature()->as_klass_external_name());
3662     }
3663   }
3664   tty->print("  @%3d %s\n", instance_fields_end, "--- instance fields end ---");
3665   tty->print("  @%3d %s\n", instance_size * wordSize, "--- instance ends ---");
3666   tty->print("  @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");
3667   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3668     if (fs.access_flags().is_static()) {
3669       tty->print("  @%3d \"%s\" %s\n",
3670         fs.offset(),
3671         fs.name()->as_klass_external_name(),
3672         fs.signature()->as_klass_external_name());
3673     }
3674   }
3675   tty->print("  @%3d %s\n", static_fields_end, "--- static fields end ---");
3676   tty->print("\n");
3677 }
3678 #endif
3679 
3680 // Values needed for oopmap and InstanceKlass creation
3681 class ClassFileParser::FieldLayoutInfo : public ResourceObj {
3682  public:
3683   OopMapBlocksBuilder* oop_map_blocks;
3684   int           instance_size;
3685   int           nonstatic_field_size;
3686   int           static_field_size;
3687   bool          has_nonstatic_fields;
3688 };
3689 
3690 // Utility to collect and compact oop maps during layout
3691 class ClassFileParser::OopMapBlocksBuilder : public ResourceObj {
3692  public:
3693   OopMapBlock*  nonstatic_oop_maps;
3694   unsigned int  nonstatic_oop_map_count;
3695   unsigned int  max_nonstatic_oop_maps;
3696 
3697  public:
3698   OopMapBlocksBuilder(unsigned int  max_blocks, TRAPS) {
3699     max_nonstatic_oop_maps = max_blocks;
3700     nonstatic_oop_map_count = 0;
3701     if (max_blocks == 0) {
3702       nonstatic_oop_maps = NULL;
3703     } else {
3704       nonstatic_oop_maps = NEW_RESOURCE_ARRAY_IN_THREAD(
3705         THREAD, OopMapBlock, max_nonstatic_oop_maps);
3706       memset(nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3707     }
3708   }
3709 
3710   OopMapBlock* last_oop_map() const {
3711     assert(nonstatic_oop_map_count > 0, "Has no oop maps");
3712     return nonstatic_oop_maps + (nonstatic_oop_map_count - 1);
3713   }
3714 
3715   // addition of super oop maps
3716   void initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
3717     assert(nof_blocks && nonstatic_oop_map_count == 0 &&
3718         nof_blocks <= max_nonstatic_oop_maps, "invariant");
3719 
3720     memcpy(nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
3721     nonstatic_oop_map_count += nof_blocks;
3722   }
3723 
3724   // collection of oops
3725   void add(int offset, int count) {
3726     if (nonstatic_oop_map_count == 0) {
3727       nonstatic_oop_map_count++;
3728     }
3729     OopMapBlock*  nonstatic_oop_map = last_oop_map();
3730     if (nonstatic_oop_map->count() == 0) {  // Unused map, set it up
3731       nonstatic_oop_map->set_offset(offset);
3732       nonstatic_oop_map->set_count(count);
3733     } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
3734       nonstatic_oop_map->increment_count(count);
3735     } else { // Need a new one...
3736       nonstatic_oop_map_count++;
3737       assert(nonstatic_oop_map_count <= max_nonstatic_oop_maps, "range check");
3738       nonstatic_oop_map = last_oop_map();
3739       nonstatic_oop_map->set_offset(offset);
3740       nonstatic_oop_map->set_count(count);
3741     }
3742   }
3743 
3744   // general purpose copy, e.g. into allocated instanceKlass
3745   void copy(OopMapBlock* dst) {
3746     if (nonstatic_oop_map_count != 0) {
3747       memcpy(dst, nonstatic_oop_maps, sizeof(OopMapBlock) * nonstatic_oop_map_count);
3748     }
3749   }
3750 
3751   // Sort and compact adjacent blocks
3752   void compact(TRAPS) {
3753     if (nonstatic_oop_map_count <= 1) {
3754       return;
3755     }
3756     /*
3757      * Since field layout sneeks in oops before values, we will be able to condense
3758      * blocks. There is potential to compact between super, own refs and values
3759      * containing refs.
3760      *
3761      * Currently compaction is slightly limited due to values being 8 byte aligned.
3762      * This may well change: FixMe if doesn't, the code below is fairly general purpose
3763      * and maybe it doesn't need to be.
3764      */
3765     qsort(nonstatic_oop_maps, nonstatic_oop_map_count, sizeof(OopMapBlock),
3766         (_sort_Fn)OopMapBlock::compare_offset);
3767     if (nonstatic_oop_map_count < 2) {
3768       return;
3769     }
3770 
3771      //Make a temp copy, and iterate through and copy back into the orig
3772     ResourceMark rm(THREAD);
3773     OopMapBlock* oop_maps_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, OopMapBlock,
3774         nonstatic_oop_map_count);
3775     OopMapBlock* oop_maps_copy_end = oop_maps_copy + nonstatic_oop_map_count;
3776     copy(oop_maps_copy);
3777     OopMapBlock*  nonstatic_oop_map = nonstatic_oop_maps;
3778     unsigned int new_count = 1;
3779     oop_maps_copy++;
3780     while(oop_maps_copy < oop_maps_copy_end) {
3781       assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
3782       if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
3783         nonstatic_oop_map->increment_count(oop_maps_copy->count());
3784       } else {
3785         nonstatic_oop_map++;
3786         new_count++;
3787         nonstatic_oop_map->set_offset(oop_maps_copy->offset());
3788         nonstatic_oop_map->set_count(oop_maps_copy->count());
3789       }
3790       oop_maps_copy++;
3791     }
3792     assert(new_count <= nonstatic_oop_map_count, "end up with more maps after compact() ?");
3793     nonstatic_oop_map_count = new_count;
3794   }
3795 
3796   void print_on(outputStream* st) const {
3797     st->print_cr("  OopMapBlocks: %3d  /%3d", nonstatic_oop_map_count, max_nonstatic_oop_maps);
3798     if (nonstatic_oop_map_count > 0) {
3799       OopMapBlock* map = nonstatic_oop_maps;
3800       OopMapBlock* last_map = last_oop_map();
3801       assert(map <= last_map, "Last less than first");
3802       while (map <= last_map) {
3803         st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
3804             map->offset() + map->offset_span() - heapOopSize, map->count());
3805         map++;
3806       }
3807     }
3808   }
3809 
3810   void print_value_on(outputStream* st) const {
3811     print_on(st);
3812   }
3813 
3814 };
3815 
3816 void ClassFileParser::throwValueTypeLimitation(THREAD_AND_LOCATION_DECL,
3817                                                const char* msg,
3818                                                const Symbol* name,
3819                                                const Symbol* sig) const {
3820 
3821   ResourceMark rm(THREAD);
3822   if (name == NULL || sig == NULL) {
3823     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
3824         vmSymbols::java_lang_ClassFormatError(),
3825         "class: %s - %s", _class_name->as_C_string(), msg);
3826   }
3827   else {
3828     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
3829         vmSymbols::java_lang_ClassFormatError(),
3830         "\"%s\" sig: \"%s\" class: %s - %s", name->as_C_string(), sig->as_C_string(),
3831         _class_name->as_C_string(), msg);
3832   }
3833 }
3834 
3835 // Layout fields and fill in FieldLayoutInfo.  Could use more refactoring!
3836 void ClassFileParser::layout_fields(ConstantPool* cp,
3837                                     FieldAllocationCount* fac,
3838                                     const ClassAnnotationCollector* parsed_annotations,
3839                                     FieldLayoutInfo* info,
3840                                     TRAPS) {
3841 
3842   assert(cp != NULL, "invariant");
3843 
3844   // Field size and offset computation
3845   int nonstatic_field_size = _super_klass == NULL ? 0 :
3846                                _super_klass->nonstatic_field_size();
3847   int next_nonstatic_valuetype_offset = 0;
3848   int first_nonstatic_valuetype_offset = 0;
3849 
3850   // Fields that are value types are handled differently depending if they are static or not:
3851   // - static fields are oops
3852   // - non-static fields are embedded
3853 
3854   // Count the contended fields by type.
3855   //
3856   // We ignore static fields, because @Contended is not supported for them.
3857   // The layout code below will also ignore the static fields.
3858   int nonstatic_contended_count = 0;
3859   FieldAllocationCount fac_contended;
3860 
3861   // Redistribute value types if possible, gather their klasses, oopmap count...
3862   unsigned int value_type_oop_map_count = 0;
3863   int large_value_count = 0;
3864   ValueKlass** nonstatic_value_type_klasses =
3865       NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, ValueKlass*, fac->count[NONSTATIC_VALUETYPE]);
3866 
3867   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
3868     FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
3869     if (fs.is_contended()) {
3870       fac_contended.count[atype]++;
3871       if (!fs.access_flags().is_static()) {
3872         nonstatic_contended_count++;
3873       }
3874     }
3875     else if (atype == NONSTATIC_VALUETYPE) {
3876       Symbol* signature = fs.signature();
3877       Klass* klass = SystemDictionary::resolve_or_fail(signature,
3878                                                        Handle(THREAD, _loader_data->class_loader()),
3879                                                        _protection_domain, true, CHECK);
3880       assert(klass != NULL && klass->access_flags().is_value_type(), "Sanity check");
3881       ValueKlass* vklass = ValueKlass::cast(klass);
3882       if (vklass->contains_oops()) {
3883         value_type_oop_map_count += vklass->nonstatic_oop_map_count();
3884       }
3885       int raw_value_size = vklass->raw_value_byte_size();
3886       FieldAllocationType atype = fac->redistribute_value(vklass->contains_oops(), raw_value_size);
3887       if (atype == NONSTATIC_VALUETYPE) {
3888         // Failed to slot in with the others, allocate large values last jlong align for safe copy
3889         nonstatic_value_type_klasses[large_value_count++] = vklass;
3890       } else {
3891         fs.coerce_allocation_type(NONSTATIC_VALUETYPE, (int) atype);
3892       }
3893     }
3894   }
3895 
3896 
3897   // Calculate the starting byte offsets
3898   int next_static_oop_offset    = InstanceMirrorKlass::offset_of_static_fields();
3899   // Value types in static fields are nor embedded, they are handled with oops
3900   int next_static_double_offset = next_static_oop_offset +
3901                                   ((fac->count[STATIC_OOP] + fac->count[STATIC_VALUETYPE]) * heapOopSize);
3902   if ( fac->count[STATIC_DOUBLE] &&
3903        (Universe::field_type_should_be_aligned(T_DOUBLE) ||
3904         Universe::field_type_should_be_aligned(T_LONG)) ) {
3905     next_static_double_offset = align_size_up(next_static_double_offset, BytesPerLong);
3906   }
3907 
3908   int next_static_word_offset   = next_static_double_offset +
3909                                     ((fac->count[STATIC_DOUBLE]) * BytesPerLong);
3910   int next_static_short_offset  = next_static_word_offset +
3911                                     ((fac->count[STATIC_WORD]) * BytesPerInt);
3912   int next_static_byte_offset   = next_static_short_offset +
3913                                   ((fac->count[STATIC_SHORT]) * BytesPerShort);
3914 
3915   int nonstatic_fields_start  = instanceOopDesc::base_offset_in_bytes() +
3916                                 nonstatic_field_size * heapOopSize;
3917 
3918   // First field of value types is aligned on a long boundary in order to ease
3919   // in-lining of value types (with header removal) in packed arrays and
3920   // flatten value types
3921   int initial_value_type_padding = 0;
3922   if (is_value_type() || is_derive_value_type()) {
3923     int old = nonstatic_fields_start;
3924     nonstatic_fields_start = align_size_up(nonstatic_fields_start, BytesPerLong);
3925     initial_value_type_padding = nonstatic_fields_start - old;
3926   }
3927 
3928   int next_nonstatic_field_offset = nonstatic_fields_start;
3929 
3930   const bool is_contended_class     = parsed_annotations->is_contended();
3931 
3932   // Class is contended, pad before all the fields
3933   if (is_contended_class) {
3934     next_nonstatic_field_offset += ContendedPaddingWidth;
3935   }
3936 
3937   // Temporary value types restrictions
3938   if (is_value_type() || is_derive_value_type()) {
3939     if (is_contended_class) {
3940       throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support @Contended annotation yet");
3941       return;
3942     }
3943   }
3944 
3945   // Compute the non-contended fields count.
3946   // The packing code below relies on these counts to determine if some field
3947   // can be squeezed into the alignment gap. Contended fields are obviously
3948   // exempt from that.
3949   unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
3950   unsigned int nonstatic_word_count   = fac->count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
3951   unsigned int nonstatic_short_count  = fac->count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
3952   unsigned int nonstatic_byte_count   = fac->count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
3953   unsigned int nonstatic_oop_count    = fac->count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];
3954   unsigned int nonstatic_value_type_count = fac->count[NONSTATIC_VALUETYPE];
3955 
3956   // Total non-static fields count, including every contended field
3957   unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +
3958                                         fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +
3959                                         fac->count[NONSTATIC_OOP] + fac->count[NONSTATIC_VALUETYPE];
3960 
3961   const bool super_has_nonstatic_fields =
3962           (_super_klass != NULL && _super_klass->has_nonstatic_fields());
3963   const bool has_nonstatic_fields =
3964     super_has_nonstatic_fields || (nonstatic_fields_count != 0);
3965   const bool has_nonstatic_value_fields = nonstatic_value_type_count > 0;
3966 
3967   // Prepare list of oops for oop map generation.
3968   //
3969   // "offset" and "count" lists are describing the set of contiguous oop
3970   // regions. offset[i] is the start of the i-th region, which then has
3971   // count[i] oops following. Before we know how many regions are required,
3972   // we pessimistically allocate the maps to fit all the oops into the
3973   // distinct regions.
3974   //
3975   int super_oop_map_count = (_super_klass == NULL) ? 0 :_super_klass->nonstatic_oop_map_count();
3976   int max_oop_map_count =
3977       super_oop_map_count +
3978       fac->count[NONSTATIC_OOP] +
3979       value_type_oop_map_count;
3980 
3981   OopMapBlocksBuilder* nonstatic_oop_maps = new OopMapBlocksBuilder(max_oop_map_count, THREAD);
3982   if (super_oop_map_count > 0) {
3983     nonstatic_oop_maps->initialize_inherited_blocks(_super_klass->start_of_nonstatic_oop_maps(),
3984                                                     _super_klass->nonstatic_oop_map_count());
3985   }
3986 
3987   int first_nonstatic_oop_offset = 0; // will be set for first oop field
3988 
3989   bool compact_fields   = CompactFields;
3990   int allocation_style = FieldsAllocationStyle;
3991   if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
3992     assert(false, "0 <= FieldsAllocationStyle <= 2");
3993     allocation_style = 1; // Optimistic
3994   }
3995 
3996   // The next classes have predefined hard-coded fields offsets
3997   // (see in JavaClasses::compute_hard_coded_offsets()).
3998   // Use default fields allocation order for them.
3999   if( (allocation_style != 0 || compact_fields ) && _loader_data->class_loader() == NULL &&
4000       (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
4001        _class_name == vmSymbols::java_lang_Class() ||
4002        _class_name == vmSymbols::java_lang_ClassLoader() ||
4003        _class_name == vmSymbols::java_lang_ref_Reference() ||
4004        _class_name == vmSymbols::java_lang_ref_SoftReference() ||
4005        _class_name == vmSymbols::java_lang_StackTraceElement() ||
4006        _class_name == vmSymbols::java_lang_String() ||
4007        _class_name == vmSymbols::java_lang_Throwable() ||
4008        _class_name == vmSymbols::java_lang_Boolean() ||
4009        _class_name == vmSymbols::java_lang_Character() ||
4010        _class_name == vmSymbols::java_lang_Float() ||
4011        _class_name == vmSymbols::java_lang_Double() ||
4012        _class_name == vmSymbols::java_lang_Byte() ||
4013        _class_name == vmSymbols::java_lang_Short() ||
4014        _class_name == vmSymbols::java_lang_Integer() ||
4015        _class_name == vmSymbols::java_lang_Long())) {
4016     allocation_style = 0;     // Allocate oops first
4017     compact_fields   = false; // Don't compact fields
4018   }
4019 
4020   int next_nonstatic_oop_offset = 0;
4021   int next_nonstatic_double_offset = 0;
4022 
4023   // Rearrange fields for a given allocation style
4024   if( allocation_style == 0 ) {
4025     // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
4026     next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4027     next_nonstatic_double_offset = next_nonstatic_oop_offset +
4028                                     (nonstatic_oop_count * heapOopSize);
4029   } else if( allocation_style == 1 ) {
4030     // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
4031     next_nonstatic_double_offset = next_nonstatic_field_offset;
4032   } else if( allocation_style == 2 ) {
4033     // Fields allocation: oops fields in super and sub classes are together.
4034     if( nonstatic_field_size > 0 && super_oop_map_count > 0 ) {
4035       if (next_nonstatic_field_offset == nonstatic_oop_maps->last_oop_map()->end_offset()) {
4036         allocation_style = 0;   // allocate oops first
4037         next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4038         next_nonstatic_double_offset = next_nonstatic_oop_offset +
4039                                        (nonstatic_oop_count * heapOopSize);
4040       }
4041     }
4042     if( allocation_style == 2 ) {
4043       allocation_style = 1;     // allocate oops last
4044       next_nonstatic_double_offset = next_nonstatic_field_offset;
4045     }
4046   } else {
4047     ShouldNotReachHere();
4048   }
4049 
4050   int nonstatic_oop_space_count   = 0;
4051   int nonstatic_word_space_count  = 0;
4052   int nonstatic_short_space_count = 0;
4053   int nonstatic_byte_space_count  = 0;
4054   int nonstatic_oop_space_offset = 0;
4055   int nonstatic_word_space_offset = 0;
4056   int nonstatic_short_space_offset = 0;
4057   int nonstatic_byte_space_offset = 0;
4058 
4059   // Try to squeeze some of the fields into the gaps due to
4060   // long/double alignment.
4061   if (nonstatic_double_count > 0) {
4062     int offset = next_nonstatic_double_offset;
4063     next_nonstatic_double_offset = align_size_up(offset, BytesPerLong);
4064     if (compact_fields && offset != next_nonstatic_double_offset) {
4065       // Allocate available fields into the gap before double field.
4066       int length = next_nonstatic_double_offset - offset;
4067       assert(length == BytesPerInt, "");
4068       nonstatic_word_space_offset = offset;
4069       if (nonstatic_word_count > 0) {
4070         nonstatic_word_count      -= 1;
4071         nonstatic_word_space_count = 1; // Only one will fit
4072         length -= BytesPerInt;
4073         offset += BytesPerInt;
4074       }
4075       nonstatic_short_space_offset = offset;
4076       while (length >= BytesPerShort && nonstatic_short_count > 0) {
4077         nonstatic_short_count       -= 1;
4078         nonstatic_short_space_count += 1;
4079         length -= BytesPerShort;
4080         offset += BytesPerShort;
4081       }
4082       nonstatic_byte_space_offset = offset;
4083       while (length > 0 && nonstatic_byte_count > 0) {
4084         nonstatic_byte_count       -= 1;
4085         nonstatic_byte_space_count += 1;
4086         length -= 1;
4087       }
4088       // Allocate oop field in the gap if there are no other fields for that.
4089       nonstatic_oop_space_offset = offset;
4090       if (length >= heapOopSize && nonstatic_oop_count > 0 &&
4091           allocation_style != 0) { // when oop fields not first
4092         nonstatic_oop_count      -= 1;
4093         nonstatic_oop_space_count = 1; // Only one will fit
4094         length -= heapOopSize;
4095         offset += heapOopSize;
4096       }
4097     }
4098   }
4099 
4100   int next_nonstatic_word_offset = next_nonstatic_double_offset +
4101                                      (nonstatic_double_count * BytesPerLong);
4102   int next_nonstatic_short_offset = next_nonstatic_word_offset +
4103                                       (nonstatic_word_count * BytesPerInt);
4104   int next_nonstatic_byte_offset = next_nonstatic_short_offset +
4105                                      (nonstatic_short_count * BytesPerShort);
4106   int next_nonstatic_padded_offset = next_nonstatic_byte_offset +
4107                                        nonstatic_byte_count;
4108 
4109   // let oops jump before padding with this allocation style
4110   if( allocation_style == 1 ) {
4111     next_nonstatic_oop_offset = next_nonstatic_padded_offset;
4112     if( nonstatic_oop_count > 0 ) {
4113       next_nonstatic_oop_offset = align_size_up(next_nonstatic_oop_offset, heapOopSize);
4114     }
4115     next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
4116   }
4117 
4118   // Aligning embedded value types
4119   // bug below, the current algorithm to layout embedded value types always put them at the
4120   // end of the layout, which doesn't match the different allocation policies the VM is
4121   // supposed to provide => FixMe
4122   // Note also that the current alignment policy is to make each value type starting on a
4123   // 64 bits boundary. This could be optimized later. For instance, it could be nice to
4124   // align value types according to their most constrained internal type.
4125   next_nonstatic_valuetype_offset = align_size_up(next_nonstatic_padded_offset, BytesPerLong);
4126   int next_value_type_index = 0;
4127 
4128   // Iterate over fields again and compute correct offsets.
4129   // The field allocation type was temporarily stored in the offset slot.
4130   // oop fields are located before non-oop fields (static and non-static).
4131   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4132 
4133     // skip already laid out fields
4134     if (fs.is_offset_set()) continue;
4135 
4136     // contended instance fields are handled below
4137     if (fs.is_contended() && !fs.access_flags().is_static()) continue;
4138 
4139     int real_offset = 0;
4140     const FieldAllocationType atype = (const FieldAllocationType) fs.allocation_type();
4141 
4142     // pack the rest of the fields
4143     switch (atype) {
4144       // Value types in static fields are handled with oops
4145       case STATIC_VALUETYPE:   // Fallthrough
4146       case STATIC_OOP:
4147         real_offset = next_static_oop_offset;
4148         next_static_oop_offset += heapOopSize;
4149         break;
4150       case STATIC_BYTE:
4151         real_offset = next_static_byte_offset;
4152         next_static_byte_offset += 1;
4153         break;
4154       case STATIC_SHORT:
4155         real_offset = next_static_short_offset;
4156         next_static_short_offset += BytesPerShort;
4157         break;
4158       case STATIC_WORD:
4159         real_offset = next_static_word_offset;
4160         next_static_word_offset += BytesPerInt;
4161         break;
4162       case STATIC_DOUBLE:
4163         real_offset = next_static_double_offset;
4164         next_static_double_offset += BytesPerLong;
4165         break;
4166       case NONSTATIC_VALUETYPE:
4167       {
4168         real_offset = next_nonstatic_valuetype_offset;
4169 
4170         assert(next_value_type_index < large_value_count, "Incorrect number of value alloc types");
4171         ValueKlass* vklass = nonstatic_value_type_klasses[next_value_type_index++];
4172         if (vklass->contains_oops()) { // add flatten oop maps
4173           int diff = real_offset - vklass->first_field_offset();
4174           const OopMapBlock* map = vklass->start_of_nonstatic_oop_maps();
4175           const OopMapBlock* const last_map = map + vklass->nonstatic_oop_map_count();
4176           while (map < last_map) {
4177             nonstatic_oop_maps->add(map->offset() + diff, map->count());
4178             map++;
4179           }
4180         }
4181         next_nonstatic_valuetype_offset += vklass->raw_value_byte_size();
4182       }
4183       break;
4184       case NONSTATIC_OOP:
4185         if( nonstatic_oop_space_count > 0 ) {
4186           real_offset = nonstatic_oop_space_offset;
4187           nonstatic_oop_space_offset += heapOopSize;
4188           nonstatic_oop_space_count  -= 1;
4189         } else {
4190           real_offset = next_nonstatic_oop_offset;
4191           next_nonstatic_oop_offset += heapOopSize;
4192         }
4193         nonstatic_oop_maps->add(real_offset, 1);
4194         break;
4195       case NONSTATIC_BYTE:
4196         if( nonstatic_byte_space_count > 0 ) {
4197           real_offset = nonstatic_byte_space_offset;
4198           nonstatic_byte_space_offset += 1;
4199           nonstatic_byte_space_count  -= 1;
4200         } else {
4201           real_offset = next_nonstatic_byte_offset;
4202           next_nonstatic_byte_offset += 1;
4203         }
4204         break;
4205       case NONSTATIC_SHORT:
4206         if( nonstatic_short_space_count > 0 ) {
4207           real_offset = nonstatic_short_space_offset;
4208           nonstatic_short_space_offset += BytesPerShort;
4209           nonstatic_short_space_count  -= 1;
4210         } else {
4211           real_offset = next_nonstatic_short_offset;
4212           next_nonstatic_short_offset += BytesPerShort;
4213         }
4214         break;
4215       case NONSTATIC_WORD:
4216         if( nonstatic_word_space_count > 0 ) {
4217           real_offset = nonstatic_word_space_offset;
4218           nonstatic_word_space_offset += BytesPerInt;
4219           nonstatic_word_space_count  -= 1;
4220         } else {
4221           real_offset = next_nonstatic_word_offset;
4222           next_nonstatic_word_offset += BytesPerInt;
4223         }
4224         break;
4225       case NONSTATIC_DOUBLE:
4226         real_offset = next_nonstatic_double_offset;
4227         next_nonstatic_double_offset += BytesPerLong;
4228         break;
4229       default:
4230         ShouldNotReachHere();
4231     }
4232     fs.set_offset(real_offset);
4233   }
4234 
4235 
4236   // Handle the contended cases.
4237   //
4238   // Each contended field should not intersect the cache line with another contended field.
4239   // In the absence of alignment information, we end up with pessimistically separating
4240   // the fields with full-width padding.
4241   //
4242   // Additionally, this should not break alignment for the fields, so we round the alignment up
4243   // for each field.
4244   if (nonstatic_contended_count > 0) {
4245 
4246     // if there is at least one contended field, we need to have pre-padding for them
4247     next_nonstatic_padded_offset += ContendedPaddingWidth;
4248 
4249     // collect all contended groups
4250     ResourceBitMap bm(cp->size());
4251     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4252       // skip already laid out fields
4253       if (fs.is_offset_set()) continue;
4254 
4255       if (fs.is_contended()) {
4256         bm.set_bit(fs.contended_group());
4257       }
4258     }
4259 
4260     int current_group = -1;
4261     while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
4262 
4263       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4264 
4265         // skip already laid out fields
4266         if (fs.is_offset_set()) continue;
4267 
4268         // skip non-contended fields and fields from different group
4269         if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
4270 
4271         // handle statics below
4272         if (fs.access_flags().is_static()) continue;
4273 
4274         int real_offset = 0;
4275         FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
4276 
4277         switch (atype) {
4278           case NONSTATIC_BYTE:
4279             next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, 1);
4280             real_offset = next_nonstatic_padded_offset;
4281             next_nonstatic_padded_offset += 1;
4282             break;
4283 
4284           case NONSTATIC_SHORT:
4285             next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerShort);
4286             real_offset = next_nonstatic_padded_offset;
4287             next_nonstatic_padded_offset += BytesPerShort;
4288             break;
4289 
4290           case NONSTATIC_WORD:
4291             next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerInt);
4292             real_offset = next_nonstatic_padded_offset;
4293             next_nonstatic_padded_offset += BytesPerInt;
4294             break;
4295 
4296           case NONSTATIC_DOUBLE:
4297             next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerLong);
4298             real_offset = next_nonstatic_padded_offset;
4299             next_nonstatic_padded_offset += BytesPerLong;
4300             break;
4301 
4302             // Value types in static fields are handled with oops
4303           case NONSTATIC_VALUETYPE:
4304             throwValueTypeLimitation(THREAD_AND_LOCATION,
4305                                      "@Contended annotation not supported for value types yet", fs.name(), fs.signature());
4306             return;
4307 
4308           case NONSTATIC_OOP:
4309             next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, heapOopSize);
4310             real_offset = next_nonstatic_padded_offset;
4311             next_nonstatic_padded_offset += heapOopSize;
4312             nonstatic_oop_maps->add(real_offset, 1);
4313             break;
4314 
4315           default:
4316             ShouldNotReachHere();
4317         }
4318 
4319         if (fs.contended_group() == 0) {
4320           // Contended group defines the equivalence class over the fields:
4321           // the fields within the same contended group are not inter-padded.
4322           // The only exception is default group, which does not incur the
4323           // equivalence, and so requires intra-padding.
4324           next_nonstatic_padded_offset += ContendedPaddingWidth;
4325         }
4326 
4327         fs.set_offset(real_offset);
4328       } // for
4329 
4330       // Start laying out the next group.
4331       // Note that this will effectively pad the last group in the back;
4332       // this is expected to alleviate memory contention effects for
4333       // subclass fields and/or adjacent object.
4334       // If this was the default group, the padding is already in place.
4335       if (current_group != 0) {
4336         next_nonstatic_padded_offset += ContendedPaddingWidth;
4337       }
4338     }
4339 
4340     // handle static fields
4341   }
4342 
4343   // Entire class is contended, pad in the back.
4344   // This helps to alleviate memory contention effects for subclass fields
4345   // and/or adjacent object.
4346   if (is_contended_class) {
4347     assert(!is_value_type() && !is_derive_value_type(), "@Contended not supported for value types yet");
4348     next_nonstatic_padded_offset += ContendedPaddingWidth;
4349   }
4350 
4351   int notaligned_nonstatic_fields_end;
4352   if (has_nonstatic_value_fields) {
4353     notaligned_nonstatic_fields_end = next_nonstatic_valuetype_offset;
4354   } else {
4355     notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;
4356   }
4357 
4358   int nonstatic_field_sz_align = heapOopSize;
4359   if (is_value_type() || is_derive_value_type()) {
4360     if ((notaligned_nonstatic_fields_end - nonstatic_fields_start) > heapOopSize) {
4361       nonstatic_field_sz_align = BytesPerLong; // value copy of fields only uses jlong copy
4362     }
4363   }
4364   int nonstatic_fields_end      = align_size_up(notaligned_nonstatic_fields_end, nonstatic_field_sz_align);
4365   int instance_end              = align_size_up(notaligned_nonstatic_fields_end, wordSize);
4366   int static_fields_end         = align_size_up(next_static_byte_offset, wordSize);
4367 
4368   int static_field_size         = (static_fields_end -
4369                                    InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
4370   nonstatic_field_size          = nonstatic_field_size +
4371                                   (nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
4372 
4373   int instance_size             = align_object_size(instance_end / wordSize);
4374 
4375   assert(instance_size == align_object_size(align_size_up(
4376          (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize)
4377          + initial_value_type_padding, wordSize) / wordSize), "consistent layout helper value");
4378 
4379 
4380   // Invariant: nonstatic_field end/start should only change if there are
4381   // nonstatic fields in the class, or if the class is contended. We compare
4382   // against the non-aligned value, so that end alignment will not fail the
4383   // assert without actually having the fields.
4384   assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
4385          is_contended_class ||
4386          (nonstatic_fields_count > 0), "double-check nonstatic start/end");
4387 
4388   // Number of non-static oop map blocks allocated at end of klass.
4389   nonstatic_oop_maps->compact(THREAD);
4390 
4391 #ifndef PRODUCT
4392   if ((PrintFieldLayout && !is_value_type()) ||
4393       (PrintValueLayout && (is_value_type() || has_nonstatic_value_fields))) {
4394     print_field_layout(_class_name,
4395           _fields,
4396           cp,
4397           instance_size,
4398           nonstatic_fields_start,
4399           nonstatic_fields_end,
4400           static_fields_end);
4401     nonstatic_oop_maps->print_on(tty);
4402     tty->print("\n");
4403   }
4404 
4405 #endif
4406   // Pass back information needed for InstanceKlass creation
4407   info->oop_map_blocks = nonstatic_oop_maps;
4408   info->instance_size = instance_size;
4409   info->static_field_size = static_field_size;
4410   info->nonstatic_field_size = nonstatic_field_size;
4411   info->has_nonstatic_fields = has_nonstatic_fields;
4412 }
4413 
4414 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4415   assert(ik != NULL, "invariant");
4416 
4417   const Klass* const super = ik->super();
4418 
4419   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4420   // in which case we don't have to register objects as finalizable
4421   if (!_has_empty_finalizer) {
4422     if (_has_finalizer ||
4423         (super != NULL && super->has_finalizer())) {
4424       ik->set_has_finalizer();
4425     }
4426   }
4427 
4428 #ifdef ASSERT
4429   bool f = false;
4430   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4431                                            vmSymbols::void_method_signature());
4432   if (m != NULL && !m->is_empty_method()) {
4433       f = true;
4434   }
4435 
4436   // Spec doesn't prevent agent from redefinition of empty finalizer.
4437   // Despite the fact that it's generally bad idea and redefined finalizer
4438   // will not work as expected we shouldn't abort vm in this case
4439   if (!ik->has_redefined_this_or_super()) {
4440     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4441   }
4442 #endif
4443 
4444   // Check if this klass supports the java.lang.Cloneable interface
4445   if (SystemDictionary::Cloneable_klass_loaded()) {
4446     if (ik->is_subtype_of(SystemDictionary::Cloneable_klass())) {
4447       ik->set_is_cloneable();
4448     }
4449   }
4450 
4451   // Check if this klass has a vanilla default constructor
4452   if (super == NULL) {
4453     // java.lang.Object has empty default constructor
4454     ik->set_has_vanilla_constructor();
4455   } else {
4456     if (super->has_vanilla_constructor() &&
4457         _has_vanilla_constructor) {
4458       ik->set_has_vanilla_constructor();
4459     }
4460 #ifdef ASSERT
4461     bool v = false;
4462     if (super->has_vanilla_constructor()) {
4463       const Method* const constructor =
4464         ik->find_method(vmSymbols::object_initializer_name(),
4465                        vmSymbols::void_method_signature());
4466       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4467         v = true;
4468       }
4469     }
4470     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4471 #endif
4472   }
4473 
4474   // If it cannot be fast-path allocated, set a bit in the layout helper.
4475   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4476   assert(ik->size_helper() > 0, "layout_helper is initialized");
4477   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4478       || ik->is_abstract() || ik->is_interface()
4479       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4480       || ik->size_helper() >= FastAllocateSizeLimit) {
4481     // Forbid fast-path allocation.
4482     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4483     ik->set_layout_helper(lh);
4484   }
4485 }
4486 
4487 // Attach super classes and interface classes to class loader data
4488 static void record_defined_class_dependencies(const InstanceKlass* defined_klass,
4489                                               TRAPS) {
4490   assert(defined_klass != NULL, "invariant");
4491 
4492   ClassLoaderData* const defining_loader_data = defined_klass->class_loader_data();
4493   if (defining_loader_data->is_the_null_class_loader_data()) {
4494       // Dependencies to null class loader data are implicit.
4495       return;
4496   } else {
4497     // add super class dependency
4498     Klass* const super = defined_klass->super();
4499     if (super != NULL) {
4500       defining_loader_data->record_dependency(super, CHECK);
4501     }
4502 
4503     // add super interface dependencies
4504     const Array<Klass*>* const local_interfaces = defined_klass->local_interfaces();
4505     if (local_interfaces != NULL) {
4506       const int length = local_interfaces->length();
4507       for (int i = 0; i < length; i++) {
4508         defining_loader_data->record_dependency(local_interfaces->at(i), CHECK);
4509       }
4510     }
4511 
4512     for (FieldStream st((InstanceKlass*)defined_klass, false, false); !st.eos(); st.next()) {
4513       Symbol* signature = st.signature();
4514       if (signature->starts_with("Q")) {
4515         Klass* klass = SystemDictionary::resolve_or_fail(signature,
4516                                                          Handle(THREAD, defined_klass->class_loader()),
4517                                                          Handle(THREAD, defined_klass->protection_domain()), true, CHECK);
4518         assert(klass != NULL, "Sanity check");
4519         assert(klass->access_flags().is_value_type(), "Value type expected");
4520         defining_loader_data->record_dependency(klass, CHECK);
4521       }
4522     }
4523   }
4524 }
4525 
4526 // utility methods for appending an array with check for duplicates
4527 
4528 static void append_interfaces(GrowableArray<Klass*>* result,
4529                               const Array<Klass*>* const ifs) {
4530   // iterate over new interfaces
4531   for (int i = 0; i < ifs->length(); i++) {
4532     Klass* const e = ifs->at(i);
4533     assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");
4534     // add new interface
4535     result->append_if_missing(e);
4536   }
4537 }
4538 
4539 static Array<Klass*>* compute_transitive_interfaces(const InstanceKlass* super,
4540                                                     Array<Klass*>* local_ifs,
4541                                                     ClassLoaderData* loader_data,
4542                                                     TRAPS) {
4543   assert(local_ifs != NULL, "invariant");
4544   assert(loader_data != NULL, "invariant");
4545 
4546   // Compute maximum size for transitive interfaces
4547   int max_transitive_size = 0;
4548   int super_size = 0;
4549   // Add superclass transitive interfaces size
4550   if (super != NULL) {
4551     super_size = super->transitive_interfaces()->length();
4552     max_transitive_size += super_size;
4553   }
4554   // Add local interfaces' super interfaces
4555   const int local_size = local_ifs->length();
4556   for (int i = 0; i < local_size; i++) {
4557     Klass* const l = local_ifs->at(i);
4558     max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();
4559   }
4560   // Finally add local interfaces
4561   max_transitive_size += local_size;
4562   // Construct array
4563   if (max_transitive_size == 0) {
4564     // no interfaces, use canonicalized array
4565     return Universe::the_empty_klass_array();
4566   } else if (max_transitive_size == super_size) {
4567     // no new local interfaces added, share superklass' transitive interface array
4568     return super->transitive_interfaces();
4569   } else if (max_transitive_size == local_size) {
4570     // only local interfaces added, share local interface array
4571     return local_ifs;
4572   } else {
4573     ResourceMark rm;
4574     GrowableArray<Klass*>* const result = new GrowableArray<Klass*>(max_transitive_size);
4575 
4576     // Copy down from superclass
4577     if (super != NULL) {
4578       append_interfaces(result, super->transitive_interfaces());
4579     }
4580 
4581     // Copy down from local interfaces' superinterfaces
4582     for (int i = 0; i < local_size; i++) {
4583       Klass* const l = local_ifs->at(i);
4584       append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());
4585     }
4586     // Finally add local interfaces
4587     append_interfaces(result, local_ifs);
4588 
4589     // length will be less than the max_transitive_size if duplicates were removed
4590     const int length = result->length();
4591     assert(length <= max_transitive_size, "just checking");
4592     Array<Klass*>* const new_result =
4593       MetadataFactory::new_array<Klass*>(loader_data, length, CHECK_NULL);
4594     for (int i = 0; i < length; i++) {
4595       Klass* const e = result->at(i);
4596       assert(e != NULL, "just checking");
4597       new_result->at_put(i, e);
4598     }
4599     return new_result;
4600   }
4601 }
4602 
4603 static void check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4604   assert(this_klass != NULL, "invariant");
4605   const Klass* const super = this_klass->super();
4606   if (super != NULL) {
4607 
4608     // If the loader is not the boot loader then throw an exception if its
4609     // superclass is in package jdk.internal.reflect and its loader is not a
4610     // special reflection class loader
4611     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4612       assert(super->is_instance_klass(), "super is not instance klass");
4613       PackageEntry* super_package = super->package();
4614       if (super_package != NULL &&
4615           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4616           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4617         ResourceMark rm(THREAD);
4618         Exceptions::fthrow(
4619           THREAD_AND_LOCATION,
4620           vmSymbols::java_lang_IllegalAccessError(),
4621           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4622           this_klass->external_name(),
4623           this_klass->class_loader_data()->loader_name(),
4624           super->external_name());
4625         return;
4626       }
4627     }
4628 
4629     Reflection::VerifyClassAccessResults vca_result =
4630       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4631     if (vca_result != Reflection::ACCESS_OK) {
4632       ResourceMark rm(THREAD);
4633       char* msg = Reflection::verify_class_access_msg(this_klass,
4634                                                       InstanceKlass::cast(super),
4635                                                       vca_result);
4636       if (msg == NULL) {
4637         Exceptions::fthrow(
4638           THREAD_AND_LOCATION,
4639           vmSymbols::java_lang_IllegalAccessError(),
4640           "class %s cannot access its superclass %s",
4641           this_klass->external_name(),
4642           super->external_name());
4643       } else {
4644         // Add additional message content.
4645         Exceptions::fthrow(
4646           THREAD_AND_LOCATION,
4647           vmSymbols::java_lang_IllegalAccessError(),
4648           "superclass access check failed: %s",
4649           msg);
4650       }
4651     }
4652   }
4653 }
4654 
4655 
4656 static void check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4657   assert(this_klass != NULL, "invariant");
4658   const Array<Klass*>* const local_interfaces = this_klass->local_interfaces();
4659   const int lng = local_interfaces->length();
4660   for (int i = lng - 1; i >= 0; i--) {
4661     Klass* const k = local_interfaces->at(i);
4662     assert (k != NULL && k->is_interface(), "invalid interface");
4663     Reflection::VerifyClassAccessResults vca_result =
4664       Reflection::verify_class_access(this_klass, InstanceKlass::cast(k), false);
4665     if (vca_result != Reflection::ACCESS_OK) {
4666       ResourceMark rm(THREAD);
4667       char* msg = Reflection::verify_class_access_msg(this_klass,
4668                                                       InstanceKlass::cast(k),
4669                                                       vca_result);
4670       if (msg == NULL) {
4671         Exceptions::fthrow(
4672           THREAD_AND_LOCATION,
4673           vmSymbols::java_lang_IllegalAccessError(),
4674           "class %s cannot access its superinterface %s",
4675           this_klass->external_name(),
4676           k->external_name());
4677       } else {
4678         // Add additional message content.
4679         Exceptions::fthrow(
4680           THREAD_AND_LOCATION,
4681           vmSymbols::java_lang_IllegalAccessError(),
4682           "superinterface check failed: %s",
4683           msg);
4684       }
4685     }
4686   }
4687 }
4688 
4689 
4690 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4691   assert(this_klass != NULL, "invariant");
4692   const Array<Method*>* const methods = this_klass->methods();
4693   const int num_methods = methods->length();
4694 
4695   // go thru each method and check if it overrides a final method
4696   for (int index = 0; index < num_methods; index++) {
4697     const Method* const m = methods->at(index);
4698 
4699     // skip private, static, and <init> methods
4700     if ((!m->is_private() && !m->is_static()) &&
4701         (m->name() != vmSymbols::object_initializer_name())) {
4702 
4703       const Symbol* const name = m->name();
4704       const Symbol* const signature = m->signature();
4705       const Klass* k = this_klass->super();
4706       const Method* super_m = NULL;
4707       while (k != NULL) {
4708         // skip supers that don't have final methods.
4709         if (k->has_final_method()) {
4710           // lookup a matching method in the super class hierarchy
4711           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4712           if (super_m == NULL) {
4713             break; // didn't find any match; get out
4714           }
4715 
4716           if (super_m->is_final() && !super_m->is_static() &&
4717               // matching method in super is final, and not static
4718               (Reflection::verify_field_access(this_klass,
4719                                                super_m->method_holder(),
4720                                                super_m->method_holder(),
4721                                                super_m->access_flags(), false))
4722             // this class can access super final method and therefore override
4723             ) {
4724             ResourceMark rm(THREAD);
4725             Exceptions::fthrow(
4726               THREAD_AND_LOCATION,
4727               vmSymbols::java_lang_VerifyError(),
4728               "class %s overrides final method %s.%s%s",
4729               this_klass->external_name(),
4730               super_m->method_holder()->external_name(),
4731               name->as_C_string(),
4732               signature->as_C_string()
4733             );
4734             return;
4735           }
4736 
4737           // continue to look from super_m's holder's super.
4738           k = super_m->method_holder()->super();
4739           continue;
4740         }
4741 
4742         k = k->super();
4743       }
4744     }
4745   }
4746 }
4747 
4748 
4749 // assumes that this_klass is an interface
4750 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4751   assert(this_klass != NULL, "invariant");
4752   assert(this_klass->is_interface(), "not an interface");
4753   const Array<Method*>* methods = this_klass->methods();
4754   const int num_methods = methods->length();
4755 
4756   for (int index = 0; index < num_methods; index++) {
4757     const Method* const m = methods->at(index);
4758     // if m is static and not the init method, throw a verify error
4759     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4760       ResourceMark rm(THREAD);
4761       Exceptions::fthrow(
4762         THREAD_AND_LOCATION,
4763         vmSymbols::java_lang_VerifyError(),
4764         "Illegal static method %s in interface %s",
4765         m->name()->as_C_string(),
4766         this_klass->external_name()
4767       );
4768       return;
4769     }
4770   }
4771 }
4772 
4773 // utility methods for format checking
4774 
4775 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4776   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4777   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4778   if (is_module) {
4779     ResourceMark rm(THREAD);
4780     Exceptions::fthrow(
4781       THREAD_AND_LOCATION,
4782       vmSymbols::java_lang_NoClassDefFoundError(),
4783       "%s is not a class because access_flag ACC_MODULE is set",
4784       _class_name->as_C_string());
4785     return;
4786   }
4787 
4788   if (!_need_verify) { return; }
4789 
4790   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4791   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4792   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4793   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4794   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4795   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4796   const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;
4797 
4798   if ((is_abstract && is_final) ||
4799       (is_interface && !is_abstract) ||
4800       (is_interface && major_gte_15 && (is_super || is_enum)) ||
4801       (!is_interface && major_gte_15 && is_annotation)) {
4802     ResourceMark rm(THREAD);
4803     Exceptions::fthrow(
4804       THREAD_AND_LOCATION,
4805       vmSymbols::java_lang_ClassFormatError(),
4806       "Illegal class modifiers in class %s: 0x%X",
4807       _class_name->as_C_string(), flags
4808     );
4809     return;
4810   }
4811 }
4812 
4813 static bool has_illegal_visibility(jint flags) {
4814   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4815   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4816   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4817 
4818   return ((is_public && is_protected) ||
4819           (is_public && is_private) ||
4820           (is_protected && is_private));
4821 }
4822 
4823 static bool is_supported_version(u2 major, u2 minor){
4824   const u2 max_version = JAVA_MAX_SUPPORTED_VERSION;
4825   return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
4826          (major <= max_version) &&
4827          ((major != max_version) ||
4828           (minor <= JAVA_MAX_SUPPORTED_MINOR_VERSION));
4829 }
4830 
4831 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4832                                                    bool is_interface,
4833                                                    TRAPS) const {
4834   if (!_need_verify) { return; }
4835 
4836   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4837   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4838   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4839   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4840   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4841   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4842   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4843   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4844   const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
4845 
4846   bool is_illegal = false;
4847 
4848   if (is_interface) {
4849     if (!is_public || !is_static || !is_final || is_private ||
4850         is_protected || is_volatile || is_transient ||
4851         (major_gte_15 && is_enum)) {
4852       is_illegal = true;
4853     }
4854   } else { // not interface
4855     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4856       is_illegal = true;
4857     }
4858   }
4859 
4860   if (is_illegal) {
4861     ResourceMark rm(THREAD);
4862     Exceptions::fthrow(
4863       THREAD_AND_LOCATION,
4864       vmSymbols::java_lang_ClassFormatError(),
4865       "Illegal field modifiers in class %s: 0x%X",
4866       _class_name->as_C_string(), flags);
4867     return;
4868   }
4869 }
4870 
4871 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4872                                                     bool is_interface,
4873                                                     const Symbol* name,
4874                                                     TRAPS) const {
4875   if (!_need_verify) { return; }
4876 
4877   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4878   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4879   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4880   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4881   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4882   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4883   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4884   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4885   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4886   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4887   const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
4888   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4889   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4890 
4891   bool is_illegal = false;
4892 
4893   if (is_interface) {
4894     if (major_gte_8) {
4895       // Class file version is JAVA_8_VERSION or later Methods of
4896       // interfaces may set any of the flags except ACC_PROTECTED,
4897       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
4898       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
4899       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
4900           (is_native || is_protected || is_final || is_synchronized) ||
4901           // If a specific method of a class or interface has its
4902           // ACC_ABSTRACT flag set, it must not have any of its
4903           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
4904           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
4905           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
4906           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
4907           (is_abstract && (is_private || is_static || is_strict))) {
4908         is_illegal = true;
4909       }
4910     } else if (major_gte_15) {
4911       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
4912       if (!is_public || is_private || is_protected || is_static || is_final ||
4913           is_synchronized || is_native || !is_abstract || is_strict) {
4914         is_illegal = true;
4915       }
4916     } else {
4917       // Class file version is pre-JAVA_1_5_VERSION
4918       if (!is_public || is_static || is_final || is_native || !is_abstract) {
4919         is_illegal = true;
4920       }
4921     }
4922   } else { // not interface
4923     if (has_illegal_visibility(flags)) {
4924       is_illegal = true;
4925     } else {
4926       if (is_initializer) {
4927         if (is_static || is_final || is_synchronized || is_native ||
4928             is_abstract || (major_gte_15 && is_bridge)) {
4929           is_illegal = true;
4930         }
4931       } else { // not initializer
4932         if (is_abstract) {
4933           if ((is_final || is_native || is_private || is_static ||
4934               (major_gte_15 && (is_synchronized || is_strict)))) {
4935             is_illegal = true;
4936           }
4937         }
4938       }
4939     }
4940   }
4941 
4942   if (is_illegal) {
4943     ResourceMark rm(THREAD);
4944     Exceptions::fthrow(
4945       THREAD_AND_LOCATION,
4946       vmSymbols::java_lang_ClassFormatError(),
4947       "Method %s in class %s has illegal modifiers: 0x%X",
4948       name->as_C_string(), _class_name->as_C_string(), flags);
4949     return;
4950   }
4951 }
4952 
4953 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
4954                                         int length,
4955                                         TRAPS) const {
4956   assert(_need_verify, "only called when _need_verify is true");
4957   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
4958     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
4959   }
4960 }
4961 
4962 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4963 // In class names, '/' separates unqualified names.  This is verified in this function also.
4964 // Method names also may not contain the characters '<' or '>', unless <init>
4965 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4966 // method.  Because these names have been checked as special cases before
4967 // calling this method in verify_legal_method_name.
4968 //
4969 // This method is also called from the modular system APIs in modules.cpp
4970 // to verify the validity of module and package names.
4971 bool ClassFileParser::verify_unqualified_name(const char* name,
4972                                               unsigned int length,
4973                                               int type) {
4974   for (const char* p = name; p != name + length;) {
4975     jchar ch = *p;
4976     if (ch < 128) {
4977       if (ch == '.' || ch == ';' || ch == '[' ) {
4978         return false;   // do not permit '.', ';', or '['
4979       }
4980       if (ch == '/') {
4981         // check for '//' or leading or trailing '/' which are not legal
4982         // unqualified name must not be empty
4983         if (type == ClassFileParser::LegalClass) {
4984           if (p == name || p+1 >= name+length || *(p+1) == '/') {
4985            return false;
4986           }
4987         } else {
4988           return false;   // do not permit '/' unless it's class name
4989         }
4990       }
4991       if (type == ClassFileParser::LegalMethod && (ch == '<' || ch == '>')) {
4992         return false;   // do not permit '<' or '>' in method names
4993       }
4994       p++;
4995     } else {
4996       char* tmp_p = UTF8::next(p, &ch);
4997       p = tmp_p;
4998     }
4999   }
5000   return true;
5001 }
5002 
5003 // Take pointer to a string. Skip over the longest part of the string that could
5004 // be taken as a fieldname. Allow '/' if slash_ok is true.
5005 // Return a pointer to just past the fieldname.
5006 // Return NULL if no fieldname at all was found, or in the case of slash_ok
5007 // being true, we saw consecutive slashes (meaning we were looking for a
5008 // qualified path but found something that was badly-formed).
5009 static const char* skip_over_field_name(const char* name,
5010                                         bool slash_ok,
5011                                         unsigned int length) {
5012   const char* p;
5013   jboolean last_is_slash = false;
5014   jboolean not_first_ch = false;
5015 
5016   for (p = name; p != name + length; not_first_ch = true) {
5017     const char* old_p = p;
5018     jchar ch = *p;
5019     if (ch < 128) {
5020       p++;
5021       // quick check for ascii
5022       if ((ch >= 'a' && ch <= 'z') ||
5023         (ch >= 'A' && ch <= 'Z') ||
5024         (ch == '_' || ch == '$') ||
5025         (not_first_ch && ch >= '0' && ch <= '9')) {
5026         last_is_slash = false;
5027         continue;
5028       }
5029       if (slash_ok && ch == '/') {
5030         if (last_is_slash) {
5031           return NULL;  // Don't permit consecutive slashes
5032         }
5033         last_is_slash = true;
5034         continue;
5035       }
5036     }
5037     else {
5038       jint unicode_ch;
5039       char* tmp_p = UTF8::next_character(p, &unicode_ch);
5040       p = tmp_p;
5041       last_is_slash = false;
5042       // Check if ch is Java identifier start or is Java identifier part
5043       // 4672820: call java.lang.Character methods directly without generating separate tables.
5044       EXCEPTION_MARK;
5045 
5046       // return value
5047       JavaValue result(T_BOOLEAN);
5048       // Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart
5049       JavaCallArguments args;
5050       args.push_int(unicode_ch);
5051 
5052       // public static boolean isJavaIdentifierStart(char ch);
5053       JavaCalls::call_static(&result,
5054         SystemDictionary::Character_klass(),
5055         vmSymbols::isJavaIdentifierStart_name(),
5056         vmSymbols::int_bool_signature(),
5057         &args,
5058         THREAD);
5059 
5060       if (HAS_PENDING_EXCEPTION) {
5061         CLEAR_PENDING_EXCEPTION;
5062         return 0;
5063       }
5064       if (result.get_jboolean()) {
5065         continue;
5066       }
5067 
5068       if (not_first_ch) {
5069         // public static boolean isJavaIdentifierPart(char ch);
5070         JavaCalls::call_static(&result,
5071           SystemDictionary::Character_klass(),
5072           vmSymbols::isJavaIdentifierPart_name(),
5073           vmSymbols::int_bool_signature(),
5074           &args,
5075           THREAD);
5076 
5077         if (HAS_PENDING_EXCEPTION) {
5078           CLEAR_PENDING_EXCEPTION;
5079           return 0;
5080         }
5081 
5082         if (result.get_jboolean()) {
5083           continue;
5084         }
5085       }
5086     }
5087     return (not_first_ch) ? old_p : NULL;
5088   }
5089   return (not_first_ch) ? p : NULL;
5090 }
5091 
5092 // Take pointer to a string. Skip over the longest part of the string that could
5093 // be taken as a field signature. Allow "void" if void_ok.
5094 // Return a pointer to just past the signature.
5095 // Return NULL if no legal signature is found.
5096 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5097                                                        bool void_ok,
5098                                                        unsigned int length,
5099                                                        TRAPS) const {
5100   unsigned int array_dim = 0;
5101   while (length > 0) {
5102     switch (signature[0]) {
5103     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
5104     case JVM_SIGNATURE_BOOLEAN:
5105     case JVM_SIGNATURE_BYTE:
5106     case JVM_SIGNATURE_CHAR:
5107     case JVM_SIGNATURE_SHORT:
5108     case JVM_SIGNATURE_INT:
5109     case JVM_SIGNATURE_FLOAT:
5110     case JVM_SIGNATURE_LONG:
5111     case JVM_SIGNATURE_DOUBLE:
5112       return signature + 1;
5113     case JVM_SIGNATURE_CLASS:
5114     case JVM_SIGNATURE_VALUE_CLASS: {
5115       if (_major_version < JAVA_1_5_VERSION) {
5116         // Skip over the class name if one is there
5117         const char* const p = skip_over_field_name(signature + 1, true, --length);
5118 
5119         // The next character better be a semicolon
5120         if (p && (p - signature) > 1 && p[0] == ';') {
5121           return p + 1;
5122         }
5123       }
5124       else {
5125         // Skip leading 'L' and ignore first appearance of ';'
5126         length--;
5127         signature++;
5128         char* c = strchr((char*) signature, ';');
5129         // Format check signature
5130         if (c != NULL) {
5131           ResourceMark rm(THREAD);
5132           int newlen = c - (char*) signature;
5133           char* sig = NEW_RESOURCE_ARRAY(char, newlen + 1);
5134           strncpy(sig, signature, newlen);
5135           sig[newlen] = '\0';
5136 
5137           bool legal = verify_unqualified_name(sig, newlen, LegalClass);
5138           if (!legal) {
5139             classfile_parse_error("Class name contains illegal character "
5140                                   "in descriptor in class file %s",
5141                                   CHECK_0);
5142             return NULL;
5143           }
5144           return signature + newlen + 1;
5145         }
5146       }
5147       return NULL;
5148     }
5149     case JVM_SIGNATURE_ARRAY:
5150       array_dim++;
5151       if (array_dim > 255) {
5152         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
5153         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
5154       }
5155       // The rest of what's there better be a legal signature
5156       signature++;
5157       length--;
5158       void_ok = false;
5159       break;
5160     default:
5161       return NULL;
5162     }
5163   }
5164   return NULL;
5165 }
5166 
5167 // Checks if name is a legal class name.
5168 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5169   if (!_need_verify || _relax_verify) { return; }
5170 
5171   char buf[fixed_buffer_size];
5172   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5173   unsigned int length = name->utf8_length();
5174   bool legal = false;
5175 
5176   if (length > 0) {
5177     const char* p;
5178     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5179       p = skip_over_field_signature(bytes, false, length, CHECK);
5180       legal = (p != NULL) && ((p - bytes) == (int)length);
5181     } else if (_major_version < JAVA_1_5_VERSION) {
5182       if (bytes[0] != '<') {
5183         p = skip_over_field_name(bytes, true, length);
5184         legal = (p != NULL) && ((p - bytes) == (int)length);
5185       }
5186     } else {
5187       // 4900761: relax the constraints based on JSR202 spec
5188       // Class names may be drawn from the entire Unicode character set.
5189       // Identifiers between '/' must be unqualified names.
5190       // The utf8 string has been verified when parsing cpool entries.
5191       legal = verify_unqualified_name(bytes, length, LegalClass);
5192     }
5193   }
5194   if (!legal) {
5195     ResourceMark rm(THREAD);
5196     assert(_class_name != NULL, "invariant");
5197     Exceptions::fthrow(
5198       THREAD_AND_LOCATION,
5199       vmSymbols::java_lang_ClassFormatError(),
5200       "Illegal class name \"%s\" in class file %s", bytes,
5201       _class_name->as_C_string()
5202     );
5203     return;
5204   }
5205 }
5206 
5207 // Checks if name is a legal field name.
5208 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5209   if (!_need_verify || _relax_verify) { return; }
5210 
5211   char buf[fixed_buffer_size];
5212   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5213   unsigned int length = name->utf8_length();
5214   bool legal = false;
5215 
5216   if (length > 0) {
5217     if (_major_version < JAVA_1_5_VERSION) {
5218       if (bytes[0] != '<') {
5219         const char* p = skip_over_field_name(bytes, false, length);
5220         legal = (p != NULL) && ((p - bytes) == (int)length);
5221       }
5222     } else {
5223       // 4881221: relax the constraints based on JSR202 spec
5224       legal = verify_unqualified_name(bytes, length, LegalField);
5225     }
5226   }
5227 
5228   if (!legal) {
5229     ResourceMark rm(THREAD);
5230     assert(_class_name != NULL, "invariant");
5231     Exceptions::fthrow(
5232       THREAD_AND_LOCATION,
5233       vmSymbols::java_lang_ClassFormatError(),
5234       "Illegal field name \"%s\" in class %s", bytes,
5235       _class_name->as_C_string()
5236     );
5237     return;
5238   }
5239 }
5240 
5241 // Checks if name is a legal method name.
5242 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5243   if (!_need_verify || _relax_verify) { return; }
5244 
5245   assert(name != NULL, "method name is null");
5246   char buf[fixed_buffer_size];
5247   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5248   unsigned int length = name->utf8_length();
5249   bool legal = false;
5250 
5251   if (length > 0) {
5252     if (bytes[0] == '<') {
5253       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5254         legal = true;
5255       }
5256     } else if (_major_version < JAVA_1_5_VERSION) {
5257       const char* p;
5258       p = skip_over_field_name(bytes, false, length);
5259       legal = (p != NULL) && ((p - bytes) == (int)length);
5260     } else {
5261       // 4881221: relax the constraints based on JSR202 spec
5262       legal = verify_unqualified_name(bytes, length, LegalMethod);
5263     }
5264   }
5265 
5266   if (!legal) {
5267     ResourceMark rm(THREAD);
5268     assert(_class_name != NULL, "invariant");
5269     Exceptions::fthrow(
5270       THREAD_AND_LOCATION,
5271       vmSymbols::java_lang_ClassFormatError(),
5272       "Illegal method name \"%s\" in class %s", bytes,
5273       _class_name->as_C_string()
5274     );
5275     return;
5276   }
5277 }
5278 
5279 
5280 // Checks if signature is a legal field signature.
5281 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5282                                                    const Symbol* signature,
5283                                                    TRAPS) const {
5284   if (!_need_verify) { return; }
5285 
5286   char buf[fixed_buffer_size];
5287   const char* const bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5288   const unsigned int length = signature->utf8_length();
5289   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5290 
5291   if (p == NULL || (p - bytes) != (int)length) {
5292     throwIllegalSignature("Field", name, signature, CHECK);
5293   }
5294 }
5295 
5296 // Checks if signature is a legal method signature.
5297 // Returns number of parameters
5298 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5299                                                    const Symbol* signature,
5300                                                    TRAPS) const {
5301   if (!_need_verify) {
5302     // make sure caller's args_size will be less than 0 even for non-static
5303     // method so it will be recomputed in compute_size_of_parameters().
5304     return -2;
5305   }
5306 
5307   // Class initializers cannot have args for class format version >= 51.
5308   if (name == vmSymbols::class_initializer_name() &&
5309       signature != vmSymbols::void_method_signature() &&
5310       _major_version >= JAVA_7_VERSION) {
5311     throwIllegalSignature("Method", name, signature, CHECK_0);
5312     return 0;
5313   }
5314 
5315   unsigned int args_size = 0;
5316   char buf[fixed_buffer_size];
5317   const char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5318   unsigned int length = signature->utf8_length();
5319   const char* nextp;
5320 
5321   // The first character must be a '('
5322   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5323     length--;
5324     // Skip over legal field signatures
5325     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5326     while ((length > 0) && (nextp != NULL)) {
5327       args_size++;
5328       if (p[0] == 'J' || p[0] == 'D') {
5329         args_size++;
5330       }
5331       length -= nextp - p;
5332       p = nextp;
5333       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5334     }
5335     // The first non-signature thing better be a ')'
5336     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5337       length--;
5338       if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
5339         // All internal methods must return void
5340         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
5341           return args_size;
5342         }
5343       } else {
5344         // Now we better just have a return value
5345         nextp = skip_over_field_signature(p, true, length, CHECK_0);
5346         if (nextp && ((int)length == (nextp - p))) {
5347           return args_size;
5348         }
5349       }
5350     }
5351   }
5352   // Report error
5353   throwIllegalSignature("Method", name, signature, CHECK_0);
5354   return 0;
5355 }
5356 
5357 int ClassFileParser::static_field_size() const {
5358   assert(_field_info != NULL, "invariant");
5359   return _field_info->static_field_size;
5360 }
5361 
5362 int ClassFileParser::total_oop_map_count() const {
5363   assert(_field_info != NULL, "invariant");
5364   return _field_info->oop_map_blocks->nonstatic_oop_map_count;
5365 }
5366 
5367 jint ClassFileParser::layout_size() const {
5368   assert(_field_info != NULL, "invariant");
5369   return _field_info->instance_size;
5370 }
5371 
5372 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5373                                          const Array<Method*>* methods) {
5374   assert(ik != NULL, "invariant");
5375   assert(methods != NULL, "invariant");
5376 
5377   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5378   // (We used to do this lazily, but now we query it in Rewriter,
5379   // which is eagerly done for every method, so we might as well do it now,
5380   // when everything is fresh in memory.)
5381   const vmSymbols::SID klass_id = Method::klass_id_for_intrinsics(ik);
5382 
5383   if (klass_id != vmSymbols::NO_SID) {
5384     for (int j = 0; j < methods->length(); ++j) {
5385       Method* method = methods->at(j);
5386       method->init_intrinsic_id();
5387 
5388       if (CheckIntrinsics) {
5389         // Check if an intrinsic is defined for method 'method',
5390         // but the method is not annotated with @HotSpotIntrinsicCandidate.
5391         if (method->intrinsic_id() != vmIntrinsics::_none &&
5392             !method->intrinsic_candidate()) {
5393               tty->print("Compiler intrinsic is defined for method [%s], "
5394               "but the method is not annotated with @HotSpotIntrinsicCandidate.%s",
5395               method->name_and_sig_as_C_string(),
5396               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5397             );
5398           tty->cr();
5399           DEBUG_ONLY(vm_exit(1));
5400         }
5401         // Check is the method 'method' is annotated with @HotSpotIntrinsicCandidate,
5402         // but there is no intrinsic available for it.
5403         if (method->intrinsic_candidate() &&
5404           method->intrinsic_id() == vmIntrinsics::_none) {
5405             tty->print("Method [%s] is annotated with @HotSpotIntrinsicCandidate, "
5406               "but no compiler intrinsic is defined for the method.%s",
5407               method->name_and_sig_as_C_string(),
5408               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5409             );
5410           tty->cr();
5411           DEBUG_ONLY(vm_exit(1));
5412         }
5413       }
5414     } // end for
5415 
5416 #ifdef ASSERT
5417     if (CheckIntrinsics) {
5418       // Check for orphan methods in the current class. A method m
5419       // of a class C is orphan if an intrinsic is defined for method m,
5420       // but class C does not declare m.
5421       // The check is potentially expensive, therefore it is available
5422       // only in debug builds.
5423 
5424       for (int id = vmIntrinsics::FIRST_ID; id < (int)vmIntrinsics::ID_LIMIT; ++id) {
5425         if (vmIntrinsics::_compiledLambdaForm == id) {
5426           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5427           // generated for the JVM from a LambdaForm and therefore no method
5428           // is defined for it.
5429           continue;
5430         }
5431 
5432         if (vmIntrinsics::class_for(vmIntrinsics::ID_from(id)) == klass_id) {
5433           // Check if the current class contains a method with the same
5434           // name, flags, signature.
5435           bool match = false;
5436           for (int j = 0; j < methods->length(); ++j) {
5437             const Method* method = methods->at(j);
5438             if (method->intrinsic_id() == id) {
5439               match = true;
5440               break;
5441             }
5442           }
5443 
5444           if (!match) {
5445             char buf[1000];
5446             tty->print("Compiler intrinsic is defined for method [%s], "
5447                        "but the method is not available in class [%s].%s",
5448                         vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID_from(id),
5449                                                              buf, sizeof(buf)),
5450                         ik->name()->as_C_string(),
5451                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5452             );
5453             tty->cr();
5454             DEBUG_ONLY(vm_exit(1));
5455           }
5456         }
5457       } // end for
5458     } // CheckIntrinsics
5459 #endif // ASSERT
5460   }
5461 }
5462 
5463 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook, TRAPS) {
5464   if (_klass != NULL) {
5465     return _klass;
5466   }
5467 
5468   InstanceKlass* const ik =
5469     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5470 
5471   fill_instance_klass(ik, changed_by_loadhook, CHECK_NULL);
5472 
5473   assert(_klass == ik, "invariant");
5474 
5475   ik->set_has_passed_fingerprint_check(false);
5476   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
5477     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
5478     if (aot_fp != 0 && aot_fp == _stream->compute_fingerprint()) {
5479       // This class matches with a class saved in an AOT library
5480       ik->set_has_passed_fingerprint_check(true);
5481     } else {
5482       ResourceMark rm;
5483       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT,
5484                                  ik->external_name(), aot_fp, _stream->compute_fingerprint());
5485     }
5486   }
5487 
5488   return ik;
5489 }
5490 
5491 void ClassFileParser::fill_instance_klass(InstanceKlass* ik, bool changed_by_loadhook, TRAPS) {
5492   assert(ik != NULL, "invariant");
5493 
5494   set_klass_to_deallocate(ik);
5495 
5496   assert(_field_info != NULL, "invariant");
5497   assert(ik->static_field_size() == _field_info->static_field_size, "sanity");
5498   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->nonstatic_oop_map_count,
5499     "sanity");
5500 
5501   assert(ik->is_instance_klass(), "sanity");
5502   assert(ik->size_helper() == _field_info->instance_size, "sanity");
5503 
5504   // Fill in information already parsed
5505   ik->set_should_verify_class(_need_verify);
5506 
5507   // Not yet: supers are done below to support the new subtype-checking fields
5508   ik->set_class_loader_data(_loader_data);
5509   ik->set_nonstatic_field_size(_field_info->nonstatic_field_size);
5510   ik->set_has_nonstatic_fields(_field_info->has_nonstatic_fields);
5511   assert(_fac != NULL, "invariant");
5512   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_VALUETYPE]);
5513 
5514   // this transfers ownership of a lot of arrays from
5515   // the parser onto the InstanceKlass*
5516   apply_parsed_class_metadata(ik, _java_fields_count, CHECK);
5517 
5518   // note that is not safe to use the fields in the parser from this point on
5519   assert(NULL == _cp, "invariant");
5520   assert(NULL == _fields, "invariant");
5521   assert(NULL == _methods, "invariant");
5522   assert(NULL == _inner_classes, "invariant");
5523   assert(NULL == _local_interfaces, "invariant");
5524   assert(NULL == _transitive_interfaces, "invariant");
5525   assert(NULL == _combined_annotations, "invariant");
5526 
5527   if (_has_final_method) {
5528     ik->set_has_final_method();
5529   }
5530 
5531   ik->copy_method_ordering(_method_ordering, CHECK);
5532   // The InstanceKlass::_methods_jmethod_ids cache
5533   // is managed on the assumption that the initial cache
5534   // size is equal to the number of methods in the class. If
5535   // that changes, then InstanceKlass::idnum_can_increment()
5536   // has to be changed accordingly.
5537   ik->set_initial_method_idnum(ik->methods()->length());
5538 
5539   ik->set_name(_class_name);
5540 
5541   if (is_anonymous()) {
5542     // _this_class_index is a CONSTANT_Class entry that refers to this
5543     // anonymous class itself. If this class needs to refer to its own methods or
5544     // fields, it would use a CONSTANT_MethodRef, etc, which would reference
5545     // _this_class_index. However, because this class is anonymous (it's
5546     // not stored in SystemDictionary), _this_class_index cannot be resolved
5547     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5548     // Therefore, we must eagerly resolve _this_class_index now.
5549     ik->constants()->klass_at_put(_this_class_index, ik);
5550   }
5551 
5552   ik->set_minor_version(_minor_version);
5553   ik->set_major_version(_major_version);
5554   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5555   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5556 
5557   if (_host_klass != NULL) {
5558     assert (ik->is_anonymous(), "should be the same");
5559     ik->set_host_klass(_host_klass);
5560   }
5561 
5562   // Set PackageEntry for this_klass
5563   oop cl = ik->class_loader();
5564   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5565   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5566   ik->set_package(cld, CHECK);
5567 
5568   const Array<Method*>* const methods = ik->methods();
5569   assert(methods != NULL, "invariant");
5570   const int methods_len = methods->length();
5571 
5572   check_methods_for_intrinsics(ik, methods);
5573 
5574   // Fill in field values obtained by parse_classfile_attributes
5575   if (_parsed_annotations->has_any_annotations()) {
5576     _parsed_annotations->apply_to(ik);
5577   }
5578 
5579   apply_parsed_class_attributes(ik);
5580 
5581   // Miranda methods
5582   if ((_num_miranda_methods > 0) ||
5583       // if this class introduced new miranda methods or
5584       (_super_klass != NULL && _super_klass->has_miranda_methods())
5585         // super class exists and this class inherited miranda methods
5586      ) {
5587        ik->set_has_miranda_methods(); // then set a flag
5588   }
5589 
5590   // Fill in information needed to compute superclasses.
5591   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), CHECK);
5592 
5593   // Initialize itable offset tables
5594   klassItable::setup_itable_offset_table(ik);
5595 
5596   // Compute transitive closure of interfaces this class implements
5597   // Do final class setup
5598   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5599   if (oop_map_blocks->nonstatic_oop_map_count > 0) {
5600     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5601   }
5602 
5603   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5604   set_precomputed_flags(ik);
5605 
5606   // check if this class can access its super class
5607   check_super_class_access(ik, CHECK);
5608 
5609   // check if this class can access its superinterfaces
5610   check_super_interface_access(ik, CHECK);
5611 
5612   // check if this class overrides any final method
5613   check_final_method_override(ik, CHECK);
5614 
5615   // reject static interface methods prior to Java 8
5616   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5617     check_illegal_static_method(ik, CHECK);
5618   }
5619 
5620   // Obtain this_klass' module entry
5621   ModuleEntry* module_entry = ik->module();
5622   assert(module_entry != NULL, "module_entry should always be set");
5623 
5624   // Obtain java.lang.Module
5625   Handle module_handle(THREAD, JNIHandles::resolve(module_entry->module()));
5626 
5627   // Allocate mirror and initialize static fields
5628   // The create_mirror() call will also call compute_modifiers()
5629   java_lang_Class::create_mirror(ik,
5630                                  Handle(THREAD, _loader_data->class_loader()),
5631                                  module_handle,
5632                                  _protection_domain,
5633                                  CHECK);
5634 
5635   assert(_all_mirandas != NULL, "invariant");
5636 
5637   // Generate any default methods - default methods are public interface methods
5638   // that have a default implementation.  This is new with Java 8.
5639   if (_has_nonstatic_concrete_methods) {
5640     DefaultMethods::generate_default_methods(ik,
5641                                              _all_mirandas,
5642                                              CHECK);
5643   }
5644 
5645   // Valhalla shady value type conversion
5646   if (_parsed_annotations->is_derive_value_type()) {
5647     ik->create_derive_value_type(Handle(THREAD, _loader_data->class_loader()),
5648                                  _protection_domain, CHECK);
5649   }
5650 
5651   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5652   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5653       !module_entry->has_default_read_edges()) {
5654     if (!module_entry->set_has_default_read_edges()) {
5655       // We won a potential race
5656       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5657     }
5658   }
5659 
5660   // Update the loader_data graph.
5661   record_defined_class_dependencies(ik, CHECK);
5662 
5663   for (FieldStream st((InstanceKlass*)ik, false, false); !st.eos(); st.next()) {
5664     Symbol* signature = st.signature();
5665     if (signature->starts_with("Q")) {
5666       Klass* klass = SystemDictionary::resolve_or_fail(signature,
5667                                                        Handle(THREAD, ik->class_loader()),
5668                                                        Handle(THREAD, ik->protection_domain()), true, CHECK);
5669       assert(klass != NULL, "Sanity check");
5670       assert(klass->access_flags().is_value_type(), "Value type expected");
5671       ik->set_value_field_klass(st.index(), klass);
5672     }
5673   }
5674 
5675   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5676 
5677   if (!is_internal()) {
5678     if (log_is_enabled(Info, class, load)) {
5679       ResourceMark rm;
5680       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
5681       ik->print_class_load_logging(_loader_data, module_name, _stream);
5682     }
5683 
5684     if (log_is_enabled(Debug, class, resolve))  {
5685       ResourceMark rm;
5686       // print out the superclass.
5687       const char * from = ik->external_name();
5688       if (ik->java_super() != NULL) {
5689         log_debug(class, resolve)("%s %s (super)",
5690                    from,
5691                    ik->java_super()->external_name());
5692       }
5693       // print out each of the interface classes referred to by this class.
5694       const Array<Klass*>* const local_interfaces = ik->local_interfaces();
5695       if (local_interfaces != NULL) {
5696         const int length = local_interfaces->length();
5697         for (int i = 0; i < length; i++) {
5698           const Klass* const k = local_interfaces->at(i);
5699           const char * to = k->external_name();
5700           log_debug(class, resolve)("%s %s (interface)", from, to);
5701         }
5702       }
5703     }
5704   }
5705 
5706   TRACE_INIT_ID(ik);
5707 
5708   // If we reach here, all is well.
5709   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5710   // in order for it to not be destroyed in the ClassFileParser destructor.
5711   set_klass_to_deallocate(NULL);
5712 
5713   // it's official
5714   set_klass(ik);
5715 
5716   debug_only(ik->verify();)
5717 }
5718 
5719 // For an anonymous class that is in the unnamed package, move it to its host class's
5720 // package by prepending its host class's package name to its class name and setting
5721 // its _class_name field.
5722 void ClassFileParser::prepend_host_package_name(const InstanceKlass* host_klass, TRAPS) {
5723   ResourceMark rm(THREAD);
5724   assert(strrchr(_class_name->as_C_string(), '/') == NULL,
5725          "Anonymous class should not be in a package");
5726   const char* host_pkg_name =
5727     ClassLoader::package_from_name(host_klass->name()->as_C_string(), NULL);
5728 
5729   if (host_pkg_name != NULL) {
5730     size_t host_pkg_len = strlen(host_pkg_name);
5731     int class_name_len = _class_name->utf8_length();
5732     char* new_anon_name =
5733       NEW_RESOURCE_ARRAY(char, host_pkg_len + 1 + class_name_len);
5734     // Copy host package name and trailing /.
5735     strncpy(new_anon_name, host_pkg_name, host_pkg_len);
5736     new_anon_name[host_pkg_len] = '/';
5737     // Append anonymous class name. The anonymous class name can contain odd
5738     // characters.  So, do a strncpy instead of using sprintf("%s...").
5739     strncpy(new_anon_name + host_pkg_len + 1, (char *)_class_name->base(), class_name_len);
5740 
5741     // Create a symbol and update the anonymous class name.
5742     _class_name = SymbolTable::new_symbol(new_anon_name,
5743                                           (int)host_pkg_len + 1 + class_name_len,
5744                                           CHECK);
5745   }
5746 }
5747 
5748 // If the host class and the anonymous class are in the same package then do
5749 // nothing.  If the anonymous class is in the unnamed package then move it to its
5750 // host's package.  If the classes are in different packages then throw an IAE
5751 // exception.
5752 void ClassFileParser::fix_anonymous_class_name(TRAPS) {
5753   assert(_host_klass != NULL, "Expected an anonymous class");
5754 
5755   const jbyte* anon_last_slash = UTF8::strrchr(_class_name->base(),
5756                                                _class_name->utf8_length(), '/');
5757   if (anon_last_slash == NULL) {  // Unnamed package
5758     prepend_host_package_name(_host_klass, CHECK);
5759   } else {
5760     if (!InstanceKlass::is_same_class_package(_host_klass->class_loader(),
5761                                               _host_klass->name(),
5762                                               _host_klass->class_loader(),
5763                                               _class_name)) {
5764       ResourceMark rm(THREAD);
5765       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
5766         err_msg("Host class %s and anonymous class %s are in different packages",
5767         _host_klass->name()->as_C_string(), _class_name->as_C_string()));
5768     }
5769   }
5770 }
5771 
5772 static bool relax_format_check_for(ClassLoaderData* loader_data) {
5773   bool trusted = (loader_data->is_the_null_class_loader_data() ||
5774                   SystemDictionary::is_platform_class_loader(loader_data->class_loader()));
5775   bool need_verify =
5776     // verifyAll
5777     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
5778     // verifyRemote
5779     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
5780   return !need_verify;
5781 }
5782 
5783 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5784                                  Symbol* name,
5785                                  ClassLoaderData* loader_data,
5786                                  Handle protection_domain,
5787                                  const InstanceKlass* host_klass,
5788                                  GrowableArray<Handle>* cp_patches,
5789                                  Publicity pub_level,
5790                                  TRAPS) :
5791   _stream(stream),
5792   _requested_name(name),
5793   _loader_data(loader_data),
5794   _host_klass(host_klass),
5795   _cp_patches(cp_patches),
5796   _num_patched_klasses(0),
5797   _max_num_patched_klasses(0),
5798   _orig_cp_size(0),
5799   _first_patched_klass_resolved_index(0),
5800   _super_klass(),
5801   _cp(NULL),
5802   _fields(NULL),
5803   _methods(NULL),
5804   _inner_classes(NULL),
5805   _local_interfaces(NULL),
5806   _transitive_interfaces(NULL),
5807   _combined_annotations(NULL),
5808   _annotations(NULL),
5809   _type_annotations(NULL),
5810   _fields_annotations(NULL),
5811   _fields_type_annotations(NULL),
5812   _klass(NULL),
5813   _klass_to_deallocate(NULL),
5814   _parsed_annotations(NULL),
5815   _fac(NULL),
5816   _field_info(NULL),
5817   _method_ordering(NULL),
5818   _all_mirandas(NULL),
5819   _vtable_size(0),
5820   _itable_size(0),
5821   _num_miranda_methods(0),
5822   _rt(REF_NONE),
5823   _protection_domain(protection_domain),
5824   _access_flags(),
5825   _pub_level(pub_level),
5826   _bad_constant_seen(0),
5827   _synthetic_flag(false),
5828   _sde_length(false),
5829   _sde_buffer(NULL),
5830   _sourcefile_index(0),
5831   _generic_signature_index(0),
5832   _major_version(0),
5833   _minor_version(0),
5834   _this_class_index(0),
5835   _super_class_index(0),
5836   _itfs_len(0),
5837   _java_fields_count(0),
5838   _need_verify(false),
5839   _relax_verify(false),
5840   _has_nonstatic_concrete_methods(false),
5841   _declares_nonstatic_concrete_methods(false),
5842   _has_final_method(false),
5843   _has_finalizer(false),
5844   _has_empty_finalizer(false),
5845   _has_vanilla_constructor(false),
5846   _max_bootstrap_specifier_index(-1),
5847   _has_value_fields(false) {
5848 
5849   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5850 
5851   assert(THREAD->is_Java_thread(), "invariant");
5852   assert(_loader_data != NULL, "invariant");
5853   assert(stream != NULL, "invariant");
5854   assert(_stream != NULL, "invariant");
5855   assert(_stream->buffer() == _stream->current(), "invariant");
5856   assert(_class_name != NULL, "invariant");
5857   assert(0 == _access_flags.as_int(), "invariant");
5858 
5859   // Figure out whether we can skip format checking (matching classic VM behavior)
5860   if (DumpSharedSpaces) {
5861     // verify == true means it's a 'remote' class (i.e., non-boot class)
5862     // Verification decision is based on BytecodeVerificationRemote flag
5863     // for those classes.
5864     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
5865                                               BytecodeVerificationLocal;
5866   }
5867   else {
5868     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
5869                                                stream->need_verify());
5870   }
5871   if (_cp_patches != NULL) {
5872     int len = _cp_patches->length();
5873     for (int i=0; i<len; i++) {
5874       if (has_cp_patch_at(i)) {
5875         Handle patch = cp_patch_at(i);
5876         if (java_lang_String::is_instance(patch()) || java_lang_Class::is_instance(patch())) {
5877           // We need to append the names of the patched classes to the end of the constant pool,
5878           // because a patched class may have a Utf8 name that's not already included in the
5879           // original constant pool. These class names are used when patch_constant_pool()
5880           // calls patch_class().
5881           //
5882           // Note that a String in cp_patch_at(i) may be used to patch a Utf8, a String, or a Class.
5883           // At this point, we don't know the tag for index i yet, because we haven't parsed the
5884           // constant pool. So we can only assume the worst -- every String is used to patch a Class.
5885           _max_num_patched_klasses++;
5886         }
5887       }
5888     }
5889   }
5890 
5891   // synch back verification state to stream
5892   stream->set_verify(_need_verify);
5893 
5894   // Check if verification needs to be relaxed for this class file
5895   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
5896   _relax_verify = relax_format_check_for(_loader_data);
5897 
5898   parse_stream(stream, CHECK);
5899 
5900   post_process_parsed_stream(stream, _cp, CHECK);
5901 }
5902 
5903 void ClassFileParser::clear_class_metadata() {
5904   // metadata created before the instance klass is created.  Must be
5905   // deallocated if classfile parsing returns an error.
5906   _cp = NULL;
5907   _fields = NULL;
5908   _methods = NULL;
5909   _inner_classes = NULL;
5910   _local_interfaces = NULL;
5911   _transitive_interfaces = NULL;
5912   _combined_annotations = NULL;
5913   _annotations = _type_annotations = NULL;
5914   _fields_annotations = _fields_type_annotations = NULL;
5915 }
5916 
5917 // Destructor to clean up
5918 ClassFileParser::~ClassFileParser() {
5919   if (_cp != NULL) {
5920     MetadataFactory::free_metadata(_loader_data, _cp);
5921   }
5922   if (_fields != NULL) {
5923     MetadataFactory::free_array<u2>(_loader_data, _fields);
5924   }
5925 
5926   if (_methods != NULL) {
5927     // Free methods
5928     InstanceKlass::deallocate_methods(_loader_data, _methods);
5929   }
5930 
5931   // beware of the Universe::empty_blah_array!!
5932   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
5933     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
5934   }
5935 
5936   // Free interfaces
5937   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
5938                                        _local_interfaces, _transitive_interfaces);
5939 
5940   if (_combined_annotations != NULL) {
5941     // After all annotations arrays have been created, they are installed into the
5942     // Annotations object that will be assigned to the InstanceKlass being created.
5943 
5944     // Deallocate the Annotations object and the installed annotations arrays.
5945     _combined_annotations->deallocate_contents(_loader_data);
5946 
5947     // If the _combined_annotations pointer is non-NULL,
5948     // then the other annotations fields should have been cleared.
5949     assert(_annotations             == NULL, "Should have been cleared");
5950     assert(_type_annotations        == NULL, "Should have been cleared");
5951     assert(_fields_annotations      == NULL, "Should have been cleared");
5952     assert(_fields_type_annotations == NULL, "Should have been cleared");
5953   } else {
5954     // If the annotations arrays were not installed into the Annotations object,
5955     // then they have to be deallocated explicitly.
5956     MetadataFactory::free_array<u1>(_loader_data, _annotations);
5957     MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
5958     Annotations::free_contents(_loader_data, _fields_annotations);
5959     Annotations::free_contents(_loader_data, _fields_type_annotations);
5960   }
5961 
5962   clear_class_metadata();
5963 
5964   // deallocate the klass if already created.  Don't directly deallocate, but add
5965   // to the deallocate list so that the klass is removed from the CLD::_klasses list
5966   // at a safepoint.
5967   if (_klass_to_deallocate != NULL) {
5968     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
5969   }
5970 }
5971 
5972 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
5973                                    TRAPS) {
5974 
5975   assert(stream != NULL, "invariant");
5976   assert(_class_name != NULL, "invariant");
5977 
5978   // BEGIN STREAM PARSING
5979   stream->guarantee_more(8, CHECK);  // magic, major, minor
5980   // Magic value
5981   const u4 magic = stream->get_u4_fast();
5982   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
5983                      "Incompatible magic value %u in class file %s",
5984                      magic, CHECK);
5985 
5986   // Version numbers
5987   _minor_version = stream->get_u2_fast();
5988   _major_version = stream->get_u2_fast();
5989 
5990   if (DumpSharedSpaces && _major_version < JAVA_1_5_VERSION) {
5991     ResourceMark rm;
5992     warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
5993             _major_version,  _minor_version, _class_name->as_C_string());
5994     Exceptions::fthrow(
5995       THREAD_AND_LOCATION,
5996       vmSymbols::java_lang_UnsupportedClassVersionError(),
5997       "Unsupported major.minor version for dump time %u.%u",
5998       _major_version,
5999       _minor_version);
6000   }
6001 
6002   // Check version numbers - we check this even with verifier off
6003   if (!is_supported_version(_major_version, _minor_version)) {
6004     ResourceMark rm(THREAD);
6005     Exceptions::fthrow(
6006       THREAD_AND_LOCATION,
6007       vmSymbols::java_lang_UnsupportedClassVersionError(),
6008       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
6009       "this version of the Java Runtime only recognizes class file versions up to %u.%u",
6010       _class_name->as_C_string(),
6011       _major_version,
6012       _minor_version,
6013       JAVA_MAX_SUPPORTED_VERSION,
6014       JAVA_MAX_SUPPORTED_MINOR_VERSION);
6015     return;
6016   }
6017 
6018   stream->guarantee_more(3, CHECK); // length, first cp tag
6019   u2 cp_size = stream->get_u2_fast();
6020 
6021   guarantee_property(
6022     cp_size >= 1, "Illegal constant pool size %u in class file %s",
6023     cp_size, CHECK);
6024 
6025   _orig_cp_size = cp_size;
6026   if (int(cp_size) + _max_num_patched_klasses > 0xffff) {
6027     THROW_MSG(vmSymbols::java_lang_InternalError(), "not enough space for patched classes");
6028   }
6029   cp_size += _max_num_patched_klasses;
6030 
6031   _cp = ConstantPool::allocate(_loader_data,
6032                                cp_size,
6033                                CHECK);
6034 
6035   ConstantPool* const cp = _cp;
6036 
6037   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6038 
6039   assert(cp_size == (const u2)cp->length(), "invariant");
6040 
6041   // ACCESS FLAGS
6042   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6043 
6044   // Access flags
6045   jint flags;
6046   // JVM_ACC_MODULE is defined in JDK-9 and later.
6047   if (_major_version >= JAVA_9_VERSION) {
6048     flags = stream->get_u2_fast() & (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_MODULE);
6049   } else {
6050     flags = stream->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
6051   }
6052 
6053   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6054     // Set abstract bit for old class files for backward compatibility
6055     flags |= JVM_ACC_ABSTRACT;
6056   }
6057 
6058   verify_legal_class_modifiers(flags, CHECK);
6059 
6060   short bad_constant = class_bad_constant_seen();
6061   if (bad_constant != 0) {
6062     // Do not throw CFE until after the access_flags are checked because if
6063     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6064     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, CHECK);
6065   }
6066 
6067   _access_flags.set_flags(flags);
6068 
6069   // This class and superclass
6070   _this_class_index = stream->get_u2_fast();
6071   check_property(
6072     valid_cp_range(_this_class_index, cp_size) &&
6073       cp->tag_at(_this_class_index).is_unresolved_klass(),
6074     "Invalid this class index %u in constant pool in class file %s",
6075     _this_class_index, CHECK);
6076 
6077   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6078   assert(class_name_in_cp != NULL, "class_name can't be null");
6079 
6080   // Update _class_name which could be null previously
6081   // to reflect the name in the constant pool
6082   _class_name = class_name_in_cp;
6083 
6084   // Don't need to check whether this class name is legal or not.
6085   // It has been checked when constant pool is parsed.
6086   // However, make sure it is not an array type.
6087   if (_need_verify) {
6088     guarantee_property(_class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
6089                        "Bad class name in class file %s",
6090                        CHECK);
6091   }
6092 
6093   // Checks if name in class file matches requested name
6094   if (_requested_name != NULL && _requested_name != _class_name) {
6095     ResourceMark rm(THREAD);
6096     Exceptions::fthrow(
6097       THREAD_AND_LOCATION,
6098       vmSymbols::java_lang_NoClassDefFoundError(),
6099       "%s (wrong name: %s)",
6100       _class_name->as_C_string(),
6101       _requested_name != NULL ? _requested_name->as_C_string() : "NoName"
6102     );
6103     return;
6104   }
6105 
6106   // if this is an anonymous class fix up its name if it's in the unnamed
6107   // package.  Otherwise, throw IAE if it is in a different package than
6108   // its host class.
6109   if (_host_klass != NULL) {
6110     fix_anonymous_class_name(CHECK);
6111   }
6112 
6113   // Verification prevents us from creating names with dots in them, this
6114   // asserts that that's the case.
6115   assert(is_internal_format(_class_name), "external class name format used internally");
6116 
6117   if (!is_internal()) {
6118     if (log_is_enabled(Debug, class, preorder)){
6119       ResourceMark rm(THREAD);
6120       outputStream* log = Log(class, preorder)::debug_stream();
6121       log->print("%s", _class_name->as_klass_external_name());
6122       if (stream->source() != NULL) {
6123         log->print(" source: %s", stream->source());
6124       }
6125       log->cr();
6126     }
6127 
6128 #if INCLUDE_CDS
6129     if (DumpLoadedClassList != NULL && stream->source() != NULL && classlist_file->is_open()) {
6130       // Only dump the classes that can be stored into CDS archive.
6131       // Anonymous classes such as generated LambdaForm classes are also not included.
6132       if (SystemDictionaryShared::is_sharing_possible(_loader_data) &&
6133           _host_klass == NULL) {
6134         oop class_loader = _loader_data->class_loader();
6135         ResourceMark rm(THREAD);
6136         // For the boot and platform class loaders, check if the class is not found in the
6137         // java runtime image. Additional check for the boot class loader is if the class
6138         // is not found in the boot loader's appended entries. This indicates that the class
6139         // is not useable during run time, such as the ones found in the --patch-module entries,
6140         // so it should not be included in the classlist file.
6141         if (((class_loader == NULL && !ClassLoader::contains_append_entry(stream->source())) ||
6142              SystemDictionary::is_platform_class_loader(class_loader)) &&
6143             !ClassLoader::is_jrt(stream->source())) {
6144           tty->print_cr("skip writing class %s from source %s to classlist file",
6145             _class_name->as_C_string(), stream->source());
6146         } else {
6147           classlist_file->print_cr("%s", _class_name->as_C_string());
6148           classlist_file->flush();
6149         }
6150       }
6151     }
6152 #endif
6153   }
6154 
6155   // SUPERKLASS
6156   _super_class_index = stream->get_u2_fast();
6157   _super_klass = parse_super_class(cp,
6158                                    _super_class_index,
6159                                    _need_verify,
6160                                    CHECK);
6161 
6162   // Interfaces
6163   _itfs_len = stream->get_u2_fast();
6164   parse_interfaces(stream,
6165                    _itfs_len,
6166                    cp,
6167                    &_has_nonstatic_concrete_methods,
6168                    CHECK);
6169 
6170   assert(_local_interfaces != NULL, "invariant");
6171 
6172   // Fields (offsets are filled in later)
6173   _fac = new FieldAllocationCount();
6174   parse_fields(stream,
6175                _access_flags.is_interface(),
6176                _fac,
6177                cp,
6178                cp_size,
6179                &_java_fields_count,
6180                CHECK);
6181 
6182   assert(_fields != NULL, "invariant");
6183 
6184   // Methods
6185   AccessFlags promoted_flags;
6186   parse_methods(stream,
6187                 _access_flags.is_interface(),
6188                 &promoted_flags,
6189                 &_has_final_method,
6190                 &_declares_nonstatic_concrete_methods,
6191                 CHECK);
6192 
6193   assert(_methods != NULL, "invariant");
6194 
6195   // promote flags from parse_methods() to the klass' flags
6196   _access_flags.add_promoted_flags(promoted_flags.as_int());
6197 
6198   if (_declares_nonstatic_concrete_methods) {
6199     _has_nonstatic_concrete_methods = true;
6200   }
6201 
6202   // Additional attributes/annotations
6203   _parsed_annotations = new ClassAnnotationCollector();
6204   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6205 
6206   assert(_inner_classes != NULL, "invariant");
6207 
6208   // Finalize the Annotations metadata object,
6209   // now that all annotation arrays have been created.
6210   create_combined_annotations(CHECK);
6211 
6212   // Make sure this is the end of class file stream
6213   guarantee_property(stream->at_eos(),
6214                      "Extra bytes at the end of class file %s",
6215                      CHECK);
6216 
6217   // all bytes in stream read and parsed
6218 }
6219 
6220 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6221                                                  ConstantPool* cp,
6222                                                  TRAPS) {
6223   assert(stream != NULL, "invariant");
6224   assert(stream->at_eos(), "invariant");
6225   assert(cp != NULL, "invariant");
6226   assert(_loader_data != NULL, "invariant");
6227 
6228   if (_class_name == vmSymbols::java_lang_Object()) {
6229     check_property(_local_interfaces == Universe::the_empty_klass_array(),
6230                    "java.lang.Object cannot implement an interface in class file %s",
6231                    CHECK);
6232   }
6233   // We check super class after class file is parsed and format is checked
6234   if (_super_class_index > 0 && NULL ==_super_klass) {
6235     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6236     if (_access_flags.is_interface()) {
6237       // Before attempting to resolve the superclass, check for class format
6238       // errors not checked yet.
6239       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6240         "Interfaces must have java.lang.Object as superclass in class file %s",
6241         CHECK);
6242     }
6243     Handle loader(THREAD, _loader_data->class_loader());
6244     _super_klass = (const InstanceKlass*)
6245                        SystemDictionary::resolve_super_or_fail(_class_name,
6246                                                                super_class_name,
6247                                                                loader,
6248                                                                _protection_domain,
6249                                                                true,
6250                                                                CHECK);
6251   }
6252 
6253   if (_super_klass != NULL) {
6254     if (_super_klass->has_nonstatic_concrete_methods()) {
6255       _has_nonstatic_concrete_methods = true;
6256     }
6257 
6258     if (_super_klass->is_interface()) {
6259       ResourceMark rm(THREAD);
6260       Exceptions::fthrow(
6261         THREAD_AND_LOCATION,
6262         vmSymbols::java_lang_IncompatibleClassChangeError(),
6263         "class %s has interface %s as super class",
6264         _class_name->as_klass_external_name(),
6265         _super_klass->external_name()
6266       );
6267       return;
6268     }
6269     // Make sure super class is not final
6270     if (_super_klass->is_final()
6271         && !(_super_klass->name() == vmSymbols::java_lang____Value()
6272         && (_access_flags.get_flags() & JVM_ACC_VALUE))) {
6273       THROW_MSG(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class");
6274     }
6275   }
6276 
6277   // Compute the transitive list of all unique interfaces implemented by this class
6278   _transitive_interfaces =
6279     compute_transitive_interfaces(_super_klass,
6280                                   _local_interfaces,
6281                                   _loader_data,
6282                                   CHECK);
6283 
6284   assert(_transitive_interfaces != NULL, "invariant");
6285 
6286   // sort methods
6287   _method_ordering = sort_methods(_methods);
6288 
6289   _all_mirandas = new GrowableArray<Method*>(20);
6290 
6291   Handle loader(THREAD, _loader_data->class_loader());
6292   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6293                                                     &_num_miranda_methods,
6294                                                     _all_mirandas,
6295                                                     _super_klass,
6296                                                     _methods,
6297                                                     _access_flags,
6298                                                     _major_version,
6299                                                     loader,
6300                                                     _class_name,
6301                                                     _local_interfaces,
6302                                                     CHECK);
6303 
6304   // Size of Java itable (in words)
6305   _itable_size = _access_flags.is_interface() ? 0 :
6306     klassItable::compute_itable_size(_transitive_interfaces);
6307 
6308   assert(_fac != NULL, "invariant");
6309   assert(_parsed_annotations != NULL, "invariant");
6310 
6311   _field_info = new FieldLayoutInfo();
6312   layout_fields(cp, _fac, _parsed_annotations, _field_info, CHECK);
6313 
6314   // Compute reference typ
6315   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();
6316 
6317 }
6318 
6319 void ClassFileParser::set_klass(InstanceKlass* klass) {
6320 
6321 #ifdef ASSERT
6322   if (klass != NULL) {
6323     assert(NULL == _klass, "leaking?");
6324   }
6325 #endif
6326 
6327   _klass = klass;
6328 }
6329 
6330 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6331 
6332 #ifdef ASSERT
6333   if (klass != NULL) {
6334     assert(NULL == _klass_to_deallocate, "leaking?");
6335   }
6336 #endif
6337 
6338   _klass_to_deallocate = klass;
6339 }
6340 
6341 // Caller responsible for ResourceMark
6342 // clone stream with rewound position
6343 const ClassFileStream* ClassFileParser::clone_stream() const {
6344   assert(_stream != NULL, "invariant");
6345 
6346   return _stream->clone();
6347 }
6348 
6349 bool ClassFileParser::is_derive_value_type() const {
6350   return _parsed_annotations->is_derive_value_type();
6351 }
6352 
6353 // ----------------------------------------------------------------------------
6354 // debugging
6355 
6356 #ifdef ASSERT
6357 
6358 // return true if class_name contains no '.' (internal format is '/')
6359 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6360   if (class_name != NULL) {
6361     ResourceMark rm;
6362     char* name = class_name->as_C_string();
6363     return strchr(name, '.') == NULL;
6364   } else {
6365     return true;
6366   }
6367 }
6368 
6369 #endif