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