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