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