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