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