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