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