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