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