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