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