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