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     return;
4078   }
4079 
4080   // Prepare list of oops for oop map generation.
4081   //
4082   // "offset" and "count" lists are describing the set of contiguous oop
4083   // regions. offset[i] is the start of the i-th region, which then has
4084   // count[i] oops following. Before we know how many regions are required,
4085   // we pessimistically allocate the maps to fit all the oops into the
4086   // distinct regions.
4087   //
4088   int super_oop_map_count = (_super_klass == NULL) ? 0 :_super_klass->nonstatic_oop_map_count();
4089   int max_oop_map_count =
4090       super_oop_map_count +
4091       fac->count[NONSTATIC_OOP] +
4092       value_type_oop_map_count +
4093       not_flattened_value_types;
4094 
4095   OopMapBlocksBuilder* nonstatic_oop_maps = new OopMapBlocksBuilder(max_oop_map_count, THREAD);
4096   if (super_oop_map_count > 0) {
4097     nonstatic_oop_maps->initialize_inherited_blocks(_super_klass->start_of_nonstatic_oop_maps(),
4098                                                     _super_klass->nonstatic_oop_map_count());
4099   }
4100 
4101   int first_nonstatic_oop_offset = 0; // will be set for first oop field
4102 
4103   bool compact_fields   = CompactFields;
4104   int allocation_style = FieldsAllocationStyle;
4105   if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
4106     assert(false, "0 <= FieldsAllocationStyle <= 2");
4107     allocation_style = 1; // Optimistic
4108   }
4109 
4110   // The next classes have predefined hard-coded fields offsets
4111   // (see in JavaClasses::compute_hard_coded_offsets()).
4112   // Use default fields allocation order for them.
4113   if( (allocation_style != 0 || compact_fields ) && _loader_data->class_loader() == NULL &&
4114       (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
4115        _class_name == vmSymbols::java_lang_Class() ||
4116        _class_name == vmSymbols::java_lang_ClassLoader() ||
4117        _class_name == vmSymbols::java_lang_ref_Reference() ||
4118        _class_name == vmSymbols::java_lang_ref_SoftReference() ||
4119        _class_name == vmSymbols::java_lang_StackTraceElement() ||
4120        _class_name == vmSymbols::java_lang_String() ||
4121        _class_name == vmSymbols::java_lang_Throwable() ||
4122        _class_name == vmSymbols::java_lang_Boolean() ||
4123        _class_name == vmSymbols::java_lang_Character() ||
4124        _class_name == vmSymbols::java_lang_Float() ||
4125        _class_name == vmSymbols::java_lang_Double() ||
4126        _class_name == vmSymbols::java_lang_Byte() ||
4127        _class_name == vmSymbols::java_lang_Short() ||
4128        _class_name == vmSymbols::java_lang_Integer() ||
4129        _class_name == vmSymbols::java_lang_Long())) {
4130     allocation_style = 0;     // Allocate oops first
4131     compact_fields   = false; // Don't compact fields
4132   }
4133 
4134   int next_nonstatic_oop_offset = 0;
4135   int next_nonstatic_double_offset = 0;
4136 
4137   // Rearrange fields for a given allocation style
4138   if( allocation_style == 0 ) {
4139     // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
4140     next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4141     next_nonstatic_double_offset = next_nonstatic_oop_offset +
4142                                     (nonstatic_oop_count * heapOopSize);
4143   } else if( allocation_style == 1 ) {
4144     // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
4145     next_nonstatic_double_offset = next_nonstatic_field_offset;
4146   } else if( allocation_style == 2 ) {
4147     // Fields allocation: oops fields in super and sub classes are together.
4148     if( nonstatic_field_size > 0 && super_oop_map_count > 0 ) {
4149       if (next_nonstatic_field_offset == nonstatic_oop_maps->last_oop_map()->end_offset()) {
4150         allocation_style = 0;   // allocate oops first
4151         next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4152         next_nonstatic_double_offset = next_nonstatic_oop_offset +
4153                                        (nonstatic_oop_count * heapOopSize);
4154       }
4155     }
4156     if( allocation_style == 2 ) {
4157       allocation_style = 1;     // allocate oops last
4158       next_nonstatic_double_offset = next_nonstatic_field_offset;
4159     }
4160   } else {
4161     ShouldNotReachHere();
4162   }
4163 
4164   int nonstatic_oop_space_count   = 0;
4165   int nonstatic_word_space_count  = 0;
4166   int nonstatic_short_space_count = 0;
4167   int nonstatic_byte_space_count  = 0;
4168   int nonstatic_oop_space_offset = 0;
4169   int nonstatic_word_space_offset = 0;
4170   int nonstatic_short_space_offset = 0;
4171   int nonstatic_byte_space_offset = 0;
4172 
4173   // Try to squeeze some of the fields into the gaps due to
4174   // long/double alignment.
4175   if (nonstatic_double_count > 0) {
4176     int offset = next_nonstatic_double_offset;
4177     next_nonstatic_double_offset = align_up(offset, BytesPerLong);
4178     if (compact_fields && offset != next_nonstatic_double_offset) {
4179       // Allocate available fields into the gap before double field.
4180       int length = next_nonstatic_double_offset - offset;
4181       assert(length == BytesPerInt, "");
4182       nonstatic_word_space_offset = offset;
4183       if (nonstatic_word_count > 0) {
4184         nonstatic_word_count      -= 1;
4185         nonstatic_word_space_count = 1; // Only one will fit
4186         length -= BytesPerInt;
4187         offset += BytesPerInt;
4188       }
4189       nonstatic_short_space_offset = offset;
4190       while (length >= BytesPerShort && nonstatic_short_count > 0) {
4191         nonstatic_short_count       -= 1;
4192         nonstatic_short_space_count += 1;
4193         length -= BytesPerShort;
4194         offset += BytesPerShort;
4195       }
4196       nonstatic_byte_space_offset = offset;
4197       while (length > 0 && nonstatic_byte_count > 0) {
4198         nonstatic_byte_count       -= 1;
4199         nonstatic_byte_space_count += 1;
4200         length -= 1;
4201       }
4202       // Allocate oop field in the gap if there are no other fields for that.
4203       nonstatic_oop_space_offset = offset;
4204       if (length >= heapOopSize && nonstatic_oop_count > 0 &&
4205           allocation_style != 0) { // when oop fields not first
4206         nonstatic_oop_count      -= 1;
4207         nonstatic_oop_space_count = 1; // Only one will fit
4208         length -= heapOopSize;
4209         offset += heapOopSize;
4210       }
4211     }
4212   }
4213 
4214   int next_nonstatic_word_offset = next_nonstatic_double_offset +
4215                                      (nonstatic_double_count * BytesPerLong);
4216   int next_nonstatic_short_offset = next_nonstatic_word_offset +
4217                                       (nonstatic_word_count * BytesPerInt);
4218   int next_nonstatic_byte_offset = next_nonstatic_short_offset +
4219                                      (nonstatic_short_count * BytesPerShort);
4220   int next_nonstatic_padded_offset = next_nonstatic_byte_offset +
4221                                        nonstatic_byte_count;
4222 
4223   // let oops jump before padding with this allocation style
4224   if( allocation_style == 1 ) {
4225     next_nonstatic_oop_offset = next_nonstatic_padded_offset;
4226     if( nonstatic_oop_count > 0 ) {
4227       next_nonstatic_oop_offset = align_up(next_nonstatic_oop_offset, heapOopSize);
4228     }
4229     next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
4230   }
4231 
4232   // Aligning embedded value types
4233   // bug below, the current algorithm to layout embedded value types always put them at the
4234   // end of the layout, which doesn't match the different allocation policies the VM is
4235   // supposed to provide => FixMe
4236   // Note also that the current alignment policy is to make each value type starting on a
4237   // 64 bits boundary. This could be optimized later. For instance, it could be nice to
4238   // align value types according to their most constrained internal type.
4239   next_nonstatic_valuetype_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4240   int next_value_type_index = 0;
4241 
4242   // Iterate over fields again and compute correct offsets.
4243   // The field allocation type was temporarily stored in the offset slot.
4244   // oop fields are located before non-oop fields (static and non-static).
4245   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4246 
4247     // skip already laid out fields
4248     if (fs.is_offset_set()) continue;
4249 
4250     // contended instance fields are handled below
4251     if (fs.is_contended() && !fs.access_flags().is_static()) continue;
4252 
4253     int real_offset = 0;
4254     const FieldAllocationType atype = (const FieldAllocationType) fs.allocation_type();
4255 
4256     // pack the rest of the fields
4257     switch (atype) {
4258       // Value types in static fields are handled with oops
4259       case STATIC_FLATTENABLE:   // Fallthrough
4260       case STATIC_OOP:
4261         real_offset = next_static_oop_offset;
4262         next_static_oop_offset += heapOopSize;
4263         break;
4264       case STATIC_BYTE:
4265         real_offset = next_static_byte_offset;
4266         next_static_byte_offset += 1;
4267         break;
4268       case STATIC_SHORT:
4269         real_offset = next_static_short_offset;
4270         next_static_short_offset += BytesPerShort;
4271         break;
4272       case STATIC_WORD:
4273         real_offset = next_static_word_offset;
4274         next_static_word_offset += BytesPerInt;
4275         break;
4276       case STATIC_DOUBLE:
4277         real_offset = next_static_double_offset;
4278         next_static_double_offset += BytesPerLong;
4279         break;
4280       case NONSTATIC_FLATTENABLE:
4281         if (fs.is_flattened()) {
4282           Klass* klass = nonstatic_value_type_klasses[next_value_type_index];
4283           assert(klass != NULL, "Klass should have been loaded and resolved earlier");
4284           assert(klass->access_flags().is_value_type(),"Must be a value type");
4285           ValueKlass* vklass = ValueKlass::cast(klass);
4286           real_offset = next_nonstatic_valuetype_offset;
4287           next_nonstatic_valuetype_offset += (vklass->size_helper()) * wordSize - vklass->first_field_offset();
4288           // aligning next value type on a 64 bits boundary
4289           next_nonstatic_valuetype_offset = align_up(next_nonstatic_valuetype_offset, BytesPerLong);
4290           next_value_type_index += 1;
4291 
4292           if (vklass->contains_oops()) { // add flatten oop maps
4293             int diff = real_offset - vklass->first_field_offset();
4294             const OopMapBlock* map = vklass->start_of_nonstatic_oop_maps();
4295             const OopMapBlock* const last_map = map + vklass->nonstatic_oop_map_count();
4296             while (map < last_map) {
4297               nonstatic_oop_maps->add(map->offset() + diff, map->count());
4298               map++;
4299             }
4300           }
4301           break;
4302         } else {
4303           // Fall through
4304         }
4305       case NONSTATIC_OOP:
4306         if( nonstatic_oop_space_count > 0 ) {
4307           real_offset = nonstatic_oop_space_offset;
4308           nonstatic_oop_space_offset += heapOopSize;
4309           nonstatic_oop_space_count  -= 1;
4310         } else {
4311           real_offset = next_nonstatic_oop_offset;
4312           next_nonstatic_oop_offset += heapOopSize;
4313         }
4314         nonstatic_oop_maps->add(real_offset, 1);
4315         break;
4316       case NONSTATIC_BYTE:
4317         if( nonstatic_byte_space_count > 0 ) {
4318           real_offset = nonstatic_byte_space_offset;
4319           nonstatic_byte_space_offset += 1;
4320           nonstatic_byte_space_count  -= 1;
4321         } else {
4322           real_offset = next_nonstatic_byte_offset;
4323           next_nonstatic_byte_offset += 1;
4324         }
4325         break;
4326       case NONSTATIC_SHORT:
4327         if( nonstatic_short_space_count > 0 ) {
4328           real_offset = nonstatic_short_space_offset;
4329           nonstatic_short_space_offset += BytesPerShort;
4330           nonstatic_short_space_count  -= 1;
4331         } else {
4332           real_offset = next_nonstatic_short_offset;
4333           next_nonstatic_short_offset += BytesPerShort;
4334         }
4335         break;
4336       case NONSTATIC_WORD:
4337         if( nonstatic_word_space_count > 0 ) {
4338           real_offset = nonstatic_word_space_offset;
4339           nonstatic_word_space_offset += BytesPerInt;
4340           nonstatic_word_space_count  -= 1;
4341         } else {
4342           real_offset = next_nonstatic_word_offset;
4343           next_nonstatic_word_offset += BytesPerInt;
4344         }
4345         break;
4346       case NONSTATIC_DOUBLE:
4347         real_offset = next_nonstatic_double_offset;
4348         next_nonstatic_double_offset += BytesPerLong;
4349         break;
4350       default:
4351         ShouldNotReachHere();
4352     }
4353     fs.set_offset(real_offset);
4354   }
4355 
4356 
4357   // Handle the contended cases.
4358   //
4359   // Each contended field should not intersect the cache line with another contended field.
4360   // In the absence of alignment information, we end up with pessimistically separating
4361   // the fields with full-width padding.
4362   //
4363   // Additionally, this should not break alignment for the fields, so we round the alignment up
4364   // for each field.
4365   if (nonstatic_contended_count > 0) {
4366 
4367     // if there is at least one contended field, we need to have pre-padding for them
4368     next_nonstatic_padded_offset += ContendedPaddingWidth;
4369 
4370     // collect all contended groups
4371     ResourceBitMap bm(cp->size());
4372     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4373       // skip already laid out fields
4374       if (fs.is_offset_set()) continue;
4375 
4376       if (fs.is_contended()) {
4377         bm.set_bit(fs.contended_group());
4378       }
4379     }
4380 
4381     int current_group = -1;
4382     while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
4383 
4384       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4385 
4386         // skip already laid out fields
4387         if (fs.is_offset_set()) continue;
4388 
4389         // skip non-contended fields and fields from different group
4390         if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
4391 
4392         // handle statics below
4393         if (fs.access_flags().is_static()) continue;
4394 
4395         int real_offset = 0;
4396         FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
4397 
4398         switch (atype) {
4399           case NONSTATIC_BYTE:
4400             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, 1);
4401             real_offset = next_nonstatic_padded_offset;
4402             next_nonstatic_padded_offset += 1;
4403             break;
4404 
4405           case NONSTATIC_SHORT:
4406             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerShort);
4407             real_offset = next_nonstatic_padded_offset;
4408             next_nonstatic_padded_offset += BytesPerShort;
4409             break;
4410 
4411           case NONSTATIC_WORD:
4412             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerInt);
4413             real_offset = next_nonstatic_padded_offset;
4414             next_nonstatic_padded_offset += BytesPerInt;
4415             break;
4416 
4417           case NONSTATIC_DOUBLE:
4418             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4419             real_offset = next_nonstatic_padded_offset;
4420             next_nonstatic_padded_offset += BytesPerLong;
4421             break;
4422 
4423             // Value types in static fields are handled with oops
4424           case NONSTATIC_FLATTENABLE:
4425             throwValueTypeLimitation(THREAD_AND_LOCATION,
4426                                      "@Contended annotation not supported for value types yet", fs.name(), fs.signature());
4427             return;
4428 
4429           case NONSTATIC_OOP:
4430             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, heapOopSize);
4431             real_offset = next_nonstatic_padded_offset;
4432             next_nonstatic_padded_offset += heapOopSize;
4433             nonstatic_oop_maps->add(real_offset, 1);
4434             break;
4435 
4436           default:
4437             ShouldNotReachHere();
4438         }
4439 
4440         if (fs.contended_group() == 0) {
4441           // Contended group defines the equivalence class over the fields:
4442           // the fields within the same contended group are not inter-padded.
4443           // The only exception is default group, which does not incur the
4444           // equivalence, and so requires intra-padding.
4445           next_nonstatic_padded_offset += ContendedPaddingWidth;
4446         }
4447 
4448         fs.set_offset(real_offset);
4449       } // for
4450 
4451       // Start laying out the next group.
4452       // Note that this will effectively pad the last group in the back;
4453       // this is expected to alleviate memory contention effects for
4454       // subclass fields and/or adjacent object.
4455       // If this was the default group, the padding is already in place.
4456       if (current_group != 0) {
4457         next_nonstatic_padded_offset += ContendedPaddingWidth;
4458       }
4459     }
4460 
4461     // handle static fields
4462   }
4463 
4464   // Entire class is contended, pad in the back.
4465   // This helps to alleviate memory contention effects for subclass fields
4466   // and/or adjacent object.
4467   if (is_contended_class) {
4468     assert(!is_value_type(), "@Contended not supported for value types yet");
4469     next_nonstatic_padded_offset += ContendedPaddingWidth;
4470   }
4471 
4472   int notaligned_nonstatic_fields_end;
4473   if (nonstatic_value_type_count != 0) {
4474     notaligned_nonstatic_fields_end = next_nonstatic_valuetype_offset;
4475   } else {
4476     notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;
4477   }
4478 
4479   int nonstatic_field_sz_align = heapOopSize;
4480   if (is_value_type()) {
4481     if ((notaligned_nonstatic_fields_end - nonstatic_fields_start) > heapOopSize) {
4482       nonstatic_field_sz_align = BytesPerLong; // value copy of fields only uses jlong copy
4483     }
4484   }
4485   int nonstatic_fields_end      = align_up(notaligned_nonstatic_fields_end, nonstatic_field_sz_align);
4486   int instance_end              = align_up(notaligned_nonstatic_fields_end, wordSize);
4487   int static_fields_end         = align_up(next_static_byte_offset, wordSize);
4488 
4489   int static_field_size         = (static_fields_end -
4490                                    InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
4491   nonstatic_field_size          = nonstatic_field_size +
4492                                   (nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
4493 
4494   int instance_size             = align_object_size(instance_end / wordSize);
4495 
4496   assert(instance_size == align_object_size(align_up(
4497          (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize)
4498          + initial_value_type_padding, wordSize) / wordSize), "consistent layout helper value");
4499 
4500 
4501   // Invariant: nonstatic_field end/start should only change if there are
4502   // nonstatic fields in the class, or if the class is contended. We compare
4503   // against the non-aligned value, so that end alignment will not fail the
4504   // assert without actually having the fields.
4505   assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
4506          is_contended_class ||
4507          (nonstatic_fields_count > 0), "double-check nonstatic start/end");
4508 
4509   // Number of non-static oop map blocks allocated at end of klass.
4510   nonstatic_oop_maps->compact(THREAD);
4511 
4512 #ifndef PRODUCT
4513   if ((PrintFieldLayout && !is_value_type()) ||
4514       (PrintValueLayout && (is_value_type() || has_nonstatic_value_fields))) {
4515     print_field_layout(_class_name,
4516           _fields,
4517           cp,
4518           instance_size,
4519           nonstatic_fields_start,
4520           nonstatic_fields_end,
4521           static_fields_end);
4522     nonstatic_oop_maps->print_on(tty);
4523     tty->print("\n");
4524   }
4525 
4526 #endif
4527   // Pass back information needed for InstanceKlass creation
4528   info->oop_map_blocks = nonstatic_oop_maps;
4529   info->instance_size = instance_size;
4530   info->static_field_size = static_field_size;
4531   info->nonstatic_field_size = nonstatic_field_size;
4532   info->has_nonstatic_fields = has_nonstatic_fields;
4533 }
4534 
4535 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik, TRAPS) {
4536   assert(ik != NULL, "invariant");
4537 
4538   const Klass* const super = ik->super();
4539 
4540   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4541   // in which case we don't have to register objects as finalizable
4542   if (!_has_empty_finalizer) {
4543     if (_has_finalizer ||
4544         (super != NULL && super->has_finalizer())) {
4545       ik->set_has_finalizer();
4546     }
4547   }
4548 
4549 #ifdef ASSERT
4550   bool f = false;
4551   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4552                                            vmSymbols::void_method_signature());
4553   if (m != NULL && !m->is_empty_method()) {
4554       f = true;
4555   }
4556 
4557   // Spec doesn't prevent agent from redefinition of empty finalizer.
4558   // Despite the fact that it's generally bad idea and redefined finalizer
4559   // will not work as expected we shouldn't abort vm in this case
4560   if (!ik->has_redefined_this_or_super()) {
4561     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4562   }
4563 #endif
4564 
4565   // Check if this klass supports the java.lang.Cloneable interface
4566   if (SystemDictionary::Cloneable_klass_loaded()) {
4567     if (ik->is_subtype_of(SystemDictionary::Cloneable_klass())) {
4568       if (ik->is_value()) {
4569         throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support Cloneable");
4570         return;
4571       }
4572       ik->set_is_cloneable();
4573     }
4574   }
4575 
4576   // Check if this klass has a vanilla default constructor
4577   if (super == NULL) {
4578     // java.lang.Object has empty default constructor
4579     ik->set_has_vanilla_constructor();
4580   } else {
4581     if (super->has_vanilla_constructor() &&
4582         _has_vanilla_constructor) {
4583       ik->set_has_vanilla_constructor();
4584     }
4585 #ifdef ASSERT
4586     bool v = false;
4587     if (super->has_vanilla_constructor()) {
4588       const Method* const constructor =
4589         ik->find_method(vmSymbols::object_initializer_name(),
4590                        vmSymbols::void_method_signature());
4591       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4592         v = true;
4593       }
4594     }
4595     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4596 #endif
4597   }
4598 
4599   // If it cannot be fast-path allocated, set a bit in the layout helper.
4600   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4601   assert(ik->size_helper() > 0, "layout_helper is initialized");
4602   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4603       || ik->is_abstract() || ik->is_interface()
4604       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4605       || ik->size_helper() >= FastAllocateSizeLimit) {
4606     // Forbid fast-path allocation.
4607     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4608     ik->set_layout_helper(lh);
4609   }
4610 }
4611 
4612 bool ClassFileParser::supports_value_types() const {
4613   // Value types are only supported by class file version 55 and later
4614   return _major_version >= JAVA_11_VERSION;
4615 }
4616 
4617 // Attach super classes and interface classes to class loader data
4618 static void record_defined_class_dependencies(const InstanceKlass* defined_klass,
4619                                               TRAPS) {
4620   assert(defined_klass != NULL, "invariant");
4621 
4622   ClassLoaderData* const defining_loader_data = defined_klass->class_loader_data();
4623   if (defining_loader_data->is_the_null_class_loader_data()) {
4624       // Dependencies to null class loader data are implicit.
4625       return;
4626   } else {
4627     // add super class dependency
4628     Klass* const super = defined_klass->super();
4629     if (super != NULL) {
4630       defining_loader_data->record_dependency(super, CHECK);
4631     }
4632 
4633     // add super interface dependencies
4634     const Array<Klass*>* const local_interfaces = defined_klass->local_interfaces();
4635     if (local_interfaces != NULL) {
4636       const int length = local_interfaces->length();
4637       for (int i = 0; i < length; i++) {
4638         defining_loader_data->record_dependency(local_interfaces->at(i), CHECK);
4639       }
4640     }
4641 
4642     for(int i = 0; i < defined_klass->java_fields_count(); i++) {
4643       if ((defined_klass->field_access_flags(i) & JVM_ACC_FLATTENABLE) != 0) {
4644         const Klass* klass = defined_klass->get_value_field_klass(i);
4645         defining_loader_data->record_dependency(klass, CHECK);
4646       }
4647     }
4648   }
4649 }
4650 
4651 // utility methods for appending an array with check for duplicates
4652 
4653 static void append_interfaces(GrowableArray<Klass*>* result,
4654                               const Array<Klass*>* const ifs) {
4655   // iterate over new interfaces
4656   for (int i = 0; i < ifs->length(); i++) {
4657     Klass* const e = ifs->at(i);
4658     assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");
4659     // add new interface
4660     result->append_if_missing(e);
4661   }
4662 }
4663 
4664 static Array<Klass*>* compute_transitive_interfaces(const InstanceKlass* super,
4665                                                     Array<Klass*>* local_ifs,
4666                                                     ClassLoaderData* loader_data,
4667                                                     TRAPS) {
4668   assert(local_ifs != NULL, "invariant");
4669   assert(loader_data != NULL, "invariant");
4670 
4671   // Compute maximum size for transitive interfaces
4672   int max_transitive_size = 0;
4673   int super_size = 0;
4674   // Add superclass transitive interfaces size
4675   if (super != NULL) {
4676     super_size = super->transitive_interfaces()->length();
4677     max_transitive_size += super_size;
4678   }
4679   // Add local interfaces' super interfaces
4680   const int local_size = local_ifs->length();
4681   for (int i = 0; i < local_size; i++) {
4682     Klass* const l = local_ifs->at(i);
4683     max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();
4684   }
4685   // Finally add local interfaces
4686   max_transitive_size += local_size;
4687   // Construct array
4688   if (max_transitive_size == 0) {
4689     // no interfaces, use canonicalized array
4690     return Universe::the_empty_klass_array();
4691   } else if (max_transitive_size == super_size) {
4692     // no new local interfaces added, share superklass' transitive interface array
4693     return super->transitive_interfaces();
4694   } else if (max_transitive_size == local_size) {
4695     // only local interfaces added, share local interface array
4696     return local_ifs;
4697   } else {
4698     ResourceMark rm;
4699     GrowableArray<Klass*>* const result = new GrowableArray<Klass*>(max_transitive_size);
4700 
4701     // Copy down from superclass
4702     if (super != NULL) {
4703       append_interfaces(result, super->transitive_interfaces());
4704     }
4705 
4706     // Copy down from local interfaces' superinterfaces
4707     for (int i = 0; i < local_size; i++) {
4708       Klass* const l = local_ifs->at(i);
4709       append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());
4710     }
4711     // Finally add local interfaces
4712     append_interfaces(result, local_ifs);
4713 
4714     // length will be less than the max_transitive_size if duplicates were removed
4715     const int length = result->length();
4716     assert(length <= max_transitive_size, "just checking");
4717     Array<Klass*>* const new_result =
4718       MetadataFactory::new_array<Klass*>(loader_data, length, CHECK_NULL);
4719     for (int i = 0; i < length; i++) {
4720       Klass* const e = result->at(i);
4721       assert(e != NULL, "just checking");
4722       new_result->at_put(i, e);
4723     }
4724     return new_result;
4725   }
4726 }
4727 
4728 static void check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4729   assert(this_klass != NULL, "invariant");
4730   const Klass* const super = this_klass->super();
4731   if (super != NULL) {
4732 
4733     // If the loader is not the boot loader then throw an exception if its
4734     // superclass is in package jdk.internal.reflect and its loader is not a
4735     // special reflection class loader
4736     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4737       assert(super->is_instance_klass(), "super is not instance klass");
4738       PackageEntry* super_package = super->package();
4739       if (super_package != NULL &&
4740           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4741           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4742         ResourceMark rm(THREAD);
4743         Exceptions::fthrow(
4744           THREAD_AND_LOCATION,
4745           vmSymbols::java_lang_IllegalAccessError(),
4746           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4747           this_klass->external_name(),
4748           this_klass->class_loader_data()->loader_name(),
4749           super->external_name());
4750         return;
4751       }
4752     }
4753 
4754     Reflection::VerifyClassAccessResults vca_result =
4755       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4756     if (vca_result != Reflection::ACCESS_OK) {
4757       ResourceMark rm(THREAD);
4758       char* msg = Reflection::verify_class_access_msg(this_klass,
4759                                                       InstanceKlass::cast(super),
4760                                                       vca_result);
4761       if (msg == NULL) {
4762         Exceptions::fthrow(
4763           THREAD_AND_LOCATION,
4764           vmSymbols::java_lang_IllegalAccessError(),
4765           "class %s cannot access its superclass %s",
4766           this_klass->external_name(),
4767           super->external_name());
4768       } else {
4769         // Add additional message content.
4770         Exceptions::fthrow(
4771           THREAD_AND_LOCATION,
4772           vmSymbols::java_lang_IllegalAccessError(),
4773           "superclass access check failed: %s",
4774           msg);
4775       }
4776     }
4777   }
4778 }
4779 
4780 
4781 static void check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4782   assert(this_klass != NULL, "invariant");
4783   const Array<Klass*>* const local_interfaces = this_klass->local_interfaces();
4784   const int lng = local_interfaces->length();
4785   for (int i = lng - 1; i >= 0; i--) {
4786     Klass* const k = local_interfaces->at(i);
4787     assert (k != NULL && k->is_interface(), "invalid interface");
4788     Reflection::VerifyClassAccessResults vca_result =
4789       Reflection::verify_class_access(this_klass, InstanceKlass::cast(k), false);
4790     if (vca_result != Reflection::ACCESS_OK) {
4791       ResourceMark rm(THREAD);
4792       char* msg = Reflection::verify_class_access_msg(this_klass,
4793                                                       InstanceKlass::cast(k),
4794                                                       vca_result);
4795       if (msg == NULL) {
4796         Exceptions::fthrow(
4797           THREAD_AND_LOCATION,
4798           vmSymbols::java_lang_IllegalAccessError(),
4799           "class %s cannot access its superinterface %s",
4800           this_klass->external_name(),
4801           k->external_name());
4802       } else {
4803         // Add additional message content.
4804         Exceptions::fthrow(
4805           THREAD_AND_LOCATION,
4806           vmSymbols::java_lang_IllegalAccessError(),
4807           "superinterface check failed: %s",
4808           msg);
4809       }
4810     }
4811   }
4812 }
4813 
4814 
4815 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4816   assert(this_klass != NULL, "invariant");
4817   const Array<Method*>* const methods = this_klass->methods();
4818   const int num_methods = methods->length();
4819 
4820   // go thru each method and check if it overrides a final method
4821   for (int index = 0; index < num_methods; index++) {
4822     const Method* const m = methods->at(index);
4823 
4824     // skip private, static, and <init> methods
4825     if ((!m->is_private() && !m->is_static()) &&
4826         (m->name() != vmSymbols::object_initializer_name())) {
4827 
4828       const Symbol* const name = m->name();
4829       const Symbol* const signature = m->signature();
4830       const Klass* k = this_klass->super();
4831       const Method* super_m = NULL;
4832       while (k != NULL) {
4833         // skip supers that don't have final methods.
4834         if (k->has_final_method()) {
4835           // lookup a matching method in the super class hierarchy
4836           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4837           if (super_m == NULL) {
4838             break; // didn't find any match; get out
4839           }
4840 
4841           if (super_m->is_final() && !super_m->is_static() &&
4842               // matching method in super is final, and not static
4843               (Reflection::verify_field_access(this_klass,
4844                                                super_m->method_holder(),
4845                                                super_m->method_holder(),
4846                                                super_m->access_flags(), false))
4847             // this class can access super final method and therefore override
4848             ) {
4849             ResourceMark rm(THREAD);
4850             Exceptions::fthrow(
4851               THREAD_AND_LOCATION,
4852               vmSymbols::java_lang_VerifyError(),
4853               "class %s overrides final method %s.%s%s",
4854               this_klass->external_name(),
4855               super_m->method_holder()->external_name(),
4856               name->as_C_string(),
4857               signature->as_C_string()
4858             );
4859             return;
4860           }
4861 
4862           // continue to look from super_m's holder's super.
4863           k = super_m->method_holder()->super();
4864           continue;
4865         }
4866 
4867         k = k->super();
4868       }
4869     }
4870   }
4871 }
4872 
4873 
4874 // assumes that this_klass is an interface
4875 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4876   assert(this_klass != NULL, "invariant");
4877   assert(this_klass->is_interface(), "not an interface");
4878   const Array<Method*>* methods = this_klass->methods();
4879   const int num_methods = methods->length();
4880 
4881   for (int index = 0; index < num_methods; index++) {
4882     const Method* const m = methods->at(index);
4883     // if m is static and not the init method, throw a verify error
4884     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4885       ResourceMark rm(THREAD);
4886       Exceptions::fthrow(
4887         THREAD_AND_LOCATION,
4888         vmSymbols::java_lang_VerifyError(),
4889         "Illegal static method %s in interface %s",
4890         m->name()->as_C_string(),
4891         this_klass->external_name()
4892       );
4893       return;
4894     }
4895   }
4896 }
4897 
4898 // utility methods for format checking
4899 
4900 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4901   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4902   const bool is_value_type = (flags & JVM_ACC_VALUE) != 0;
4903   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4904   assert(supports_value_types() || !is_value_type, "JVM_ACC_VALUE should not be set");
4905   if (is_module) {
4906     ResourceMark rm(THREAD);
4907     Exceptions::fthrow(
4908       THREAD_AND_LOCATION,
4909       vmSymbols::java_lang_NoClassDefFoundError(),
4910       "%s is not a class because access_flag ACC_MODULE is set",
4911       _class_name->as_C_string());
4912     return;
4913   }
4914 
4915   if (!_need_verify) { return; }
4916 
4917   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4918   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4919   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4920   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4921   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4922   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4923   const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;
4924 
4925   if ((is_abstract && is_final) ||
4926       (is_interface && !is_abstract) ||
4927       (is_interface && major_gte_15 && (is_super || is_enum)) ||
4928       (!is_interface && major_gte_15 && is_annotation) ||
4929       (is_value_type && (is_interface || is_abstract || is_enum || !is_final))) {
4930     ResourceMark rm(THREAD);
4931     Exceptions::fthrow(
4932       THREAD_AND_LOCATION,
4933       vmSymbols::java_lang_ClassFormatError(),
4934       "Illegal class modifiers in class %s: 0x%X",
4935       _class_name->as_C_string(), flags
4936     );
4937     return;
4938   }
4939 }
4940 
4941 static bool has_illegal_visibility(jint flags) {
4942   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4943   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4944   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4945 
4946   return ((is_public && is_protected) ||
4947           (is_public && is_private) ||
4948           (is_protected && is_private));
4949 }
4950 
4951 static bool is_supported_version(u2 major, u2 minor) {
4952   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
4953   return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
4954          (major <= max_version) &&
4955          ((major != max_version) ||
4956           (minor <= JVM_CLASSFILE_MINOR_VERSION));
4957 }
4958 
4959 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4960                                                    bool is_interface,
4961                                                    bool is_value_type,
4962                                                    TRAPS) const {
4963   if (!_need_verify) { return; }
4964 
4965   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4966   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4967   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4968   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4969   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4970   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4971   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4972   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4973   const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
4974 
4975   bool is_illegal = false;
4976 
4977   if (is_interface) {
4978     if (!is_public || !is_static || !is_final || is_private ||
4979         is_protected || is_volatile || is_transient ||
4980         (major_gte_15 && is_enum)) {
4981       is_illegal = true;
4982     }
4983   } else { // not interface
4984     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4985       is_illegal = true;
4986     } else {
4987       if (is_value_type && !is_static && !is_final) {
4988         is_illegal = true;
4989       }
4990     }
4991   }
4992 
4993   if (is_illegal) {
4994     ResourceMark rm(THREAD);
4995     Exceptions::fthrow(
4996       THREAD_AND_LOCATION,
4997       vmSymbols::java_lang_ClassFormatError(),
4998       "Illegal field modifiers in class %s: 0x%X",
4999       _class_name->as_C_string(), flags);
5000     return;
5001   }
5002 }
5003 
5004 void ClassFileParser::verify_legal_method_modifiers(jint flags,
5005                                                     bool is_interface,
5006                                                     bool is_value_type,
5007                                                     const Symbol* name,
5008                                                     TRAPS) const {
5009   if (!_need_verify) { return; }
5010 
5011   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
5012   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
5013   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
5014   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
5015   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
5016   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
5017   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
5018   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
5019   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
5020   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
5021   const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
5022   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
5023   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
5024 
5025   bool is_illegal = false;
5026 
5027   if (is_interface) {
5028     if (major_gte_8) {
5029       // Class file version is JAVA_8_VERSION or later Methods of
5030       // interfaces may set any of the flags except ACC_PROTECTED,
5031       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
5032       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
5033       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
5034           (is_native || is_protected || is_final || is_synchronized) ||
5035           // If a specific method of a class or interface has its
5036           // ACC_ABSTRACT flag set, it must not have any of its
5037           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
5038           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
5039           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
5040           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
5041           (is_abstract && (is_private || is_static || is_strict))) {
5042         is_illegal = true;
5043       }
5044     } else if (major_gte_15) {
5045       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
5046       if (!is_public || is_private || is_protected || is_static || is_final ||
5047           is_synchronized || is_native || !is_abstract || is_strict) {
5048         is_illegal = true;
5049       }
5050     } else {
5051       // Class file version is pre-JAVA_1_5_VERSION
5052       if (!is_public || is_static || is_final || is_native || !is_abstract) {
5053         is_illegal = true;
5054       }
5055     }
5056   } else { // not interface
5057     if (has_illegal_visibility(flags)) {
5058       is_illegal = true;
5059     } else {
5060       if (is_initializer) {
5061         if (is_static || is_final || is_synchronized || is_native ||
5062             is_abstract || (major_gte_15 && is_bridge)) {
5063           is_illegal = true;
5064         }
5065       } else { // not initializer
5066         if (is_value_type && is_synchronized && !is_static) {
5067           is_illegal = true;
5068         } else {
5069           if (is_abstract) {
5070             if ((is_final || is_native || is_private || is_static ||
5071                 (major_gte_15 && (is_synchronized || is_strict)))) {
5072               is_illegal = true;
5073             }
5074           }
5075         }
5076       }
5077     }
5078   }
5079 
5080   if (is_illegal) {
5081     ResourceMark rm(THREAD);
5082     Exceptions::fthrow(
5083       THREAD_AND_LOCATION,
5084       vmSymbols::java_lang_ClassFormatError(),
5085       "Method %s in class %s has illegal modifiers: 0x%X",
5086       name->as_C_string(), _class_name->as_C_string(), flags);
5087     return;
5088   }
5089 }
5090 
5091 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
5092                                         int length,
5093                                         TRAPS) const {
5094   assert(_need_verify, "only called when _need_verify is true");
5095   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
5096     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
5097   }
5098 }
5099 
5100 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
5101 // In class names, '/' separates unqualified names.  This is verified in this function also.
5102 // Method names also may not contain the characters '<' or '>', unless <init>
5103 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
5104 // method.  Because these names have been checked as special cases before
5105 // calling this method in verify_legal_method_name.
5106 //
5107 // This method is also called from the modular system APIs in modules.cpp
5108 // to verify the validity of module and package names.
5109 bool ClassFileParser::verify_unqualified_name(const char* name,
5110                                               unsigned int length,
5111                                               int type) {
5112   for (const char* p = name; p != name + length;) {
5113     jchar ch = *p;
5114     if (ch < 128) {
5115       if (ch == '.' || ch == ';' || ch == '[' ) {
5116         return false;   // do not permit '.', ';', or '['
5117       }
5118       if (ch == '/') {
5119         // check for '//' or leading or trailing '/' which are not legal
5120         // unqualified name must not be empty
5121         if (type == ClassFileParser::LegalClass) {
5122           if (p == name || p+1 >= name+length || *(p+1) == '/') {
5123            return false;
5124           }
5125         } else {
5126           return false;   // do not permit '/' unless it's class name
5127         }
5128       }
5129       if (type == ClassFileParser::LegalMethod && (ch == '<' || ch == '>')) {
5130         return false;   // do not permit '<' or '>' in method names
5131       }
5132       p++;
5133     } else {
5134       char* tmp_p = UTF8::next(p, &ch);
5135       p = tmp_p;
5136     }
5137   }
5138   return true;
5139 }
5140 
5141 // Take pointer to a string. Skip over the longest part of the string that could
5142 // be taken as a fieldname. Allow '/' if slash_ok is true.
5143 // Return a pointer to just past the fieldname.
5144 // Return NULL if no fieldname at all was found, or in the case of slash_ok
5145 // being true, we saw consecutive slashes (meaning we were looking for a
5146 // qualified path but found something that was badly-formed).
5147 static const char* skip_over_field_name(const char* name,
5148                                         bool slash_ok,
5149                                         unsigned int length) {
5150   const char* p;
5151   jboolean last_is_slash = false;
5152   jboolean not_first_ch = false;
5153 
5154   for (p = name; p != name + length; not_first_ch = true) {
5155     const char* old_p = p;
5156     jchar ch = *p;
5157     if (ch < 128) {
5158       p++;
5159       // quick check for ascii
5160       if ((ch >= 'a' && ch <= 'z') ||
5161         (ch >= 'A' && ch <= 'Z') ||
5162         (ch == '_' || ch == '$') ||
5163         (not_first_ch && ch >= '0' && ch <= '9')) {
5164         last_is_slash = false;
5165         continue;
5166       }
5167       if (slash_ok && ch == '/') {
5168         if (last_is_slash) {
5169           return NULL;  // Don't permit consecutive slashes
5170         }
5171         last_is_slash = true;
5172         continue;
5173       }
5174     }
5175     else {
5176       jint unicode_ch;
5177       char* tmp_p = UTF8::next_character(p, &unicode_ch);
5178       p = tmp_p;
5179       last_is_slash = false;
5180       // Check if ch is Java identifier start or is Java identifier part
5181       // 4672820: call java.lang.Character methods directly without generating separate tables.
5182       EXCEPTION_MARK;
5183 
5184       // return value
5185       JavaValue result(T_BOOLEAN);
5186       // Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart
5187       JavaCallArguments args;
5188       args.push_int(unicode_ch);
5189 
5190       // public static boolean isJavaIdentifierStart(char ch);
5191       JavaCalls::call_static(&result,
5192         SystemDictionary::Character_klass(),
5193         vmSymbols::isJavaIdentifierStart_name(),
5194         vmSymbols::int_bool_signature(),
5195         &args,
5196         THREAD);
5197 
5198       if (HAS_PENDING_EXCEPTION) {
5199         CLEAR_PENDING_EXCEPTION;
5200         return 0;
5201       }
5202       if (result.get_jboolean()) {
5203         continue;
5204       }
5205 
5206       if (not_first_ch) {
5207         // public static boolean isJavaIdentifierPart(char ch);
5208         JavaCalls::call_static(&result,
5209           SystemDictionary::Character_klass(),
5210           vmSymbols::isJavaIdentifierPart_name(),
5211           vmSymbols::int_bool_signature(),
5212           &args,
5213           THREAD);
5214 
5215         if (HAS_PENDING_EXCEPTION) {
5216           CLEAR_PENDING_EXCEPTION;
5217           return 0;
5218         }
5219 
5220         if (result.get_jboolean()) {
5221           continue;
5222         }
5223       }
5224     }
5225     return (not_first_ch) ? old_p : NULL;
5226   }
5227   return (not_first_ch) ? p : NULL;
5228 }
5229 
5230 // Take pointer to a string. Skip over the longest part of the string that could
5231 // be taken as a field signature. Allow "void" if void_ok.
5232 // Return a pointer to just past the signature.
5233 // Return NULL if no legal signature is found.
5234 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5235                                                        bool void_ok,
5236                                                        unsigned int length,
5237                                                        TRAPS) const {
5238   unsigned int array_dim = 0;
5239   while (length > 0) {
5240     switch (signature[0]) {
5241     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
5242     case JVM_SIGNATURE_BOOLEAN:
5243     case JVM_SIGNATURE_BYTE:
5244     case JVM_SIGNATURE_CHAR:
5245     case JVM_SIGNATURE_SHORT:
5246     case JVM_SIGNATURE_INT:
5247     case JVM_SIGNATURE_FLOAT:
5248     case JVM_SIGNATURE_LONG:
5249     case JVM_SIGNATURE_DOUBLE:
5250       return signature + 1;
5251     case JVM_SIGNATURE_CLASS:
5252     {
5253       if (_major_version < JAVA_1_5_VERSION) {
5254         // Skip over the class name if one is there
5255         const char* const p = skip_over_field_name(signature + 1, true, --length);
5256 
5257         // The next character better be a semicolon
5258         if (p && (p - signature) > 1 && p[0] == ';') {
5259           return p + 1;
5260         }
5261       }
5262       else {
5263         // Skip leading 'L' and ignore first appearance of ';'
5264         length--;
5265         signature++;
5266         char* c = strchr((char*) signature, ';');
5267         // Format check signature
5268         if (c != NULL) {
5269           ResourceMark rm(THREAD);
5270           int newlen = c - (char*) signature;
5271           char* sig = NEW_RESOURCE_ARRAY(char, newlen + 1);
5272           strncpy(sig, signature, newlen);
5273           sig[newlen] = '\0';
5274 
5275           bool legal = verify_unqualified_name(sig, newlen, LegalClass);
5276           if (!legal) {
5277             classfile_parse_error("Class name contains illegal character "
5278                                   "in descriptor in class file %s",
5279                                   CHECK_0);
5280             return NULL;
5281           }
5282           return signature + newlen + 1;
5283         }
5284       }
5285       return NULL;
5286     }
5287     case JVM_SIGNATURE_ARRAY:
5288       array_dim++;
5289       if (array_dim > 255) {
5290         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
5291         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
5292       }
5293       // The rest of what's there better be a legal signature
5294       signature++;
5295       length--;
5296       void_ok = false;
5297       break;
5298     default:
5299       return NULL;
5300     }
5301   }
5302   return NULL;
5303 }
5304 
5305 // Checks if name is a legal class name.
5306 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5307   if (!_need_verify || _relax_verify) { return; }
5308 
5309   char buf[fixed_buffer_size];
5310   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5311   unsigned int length = name->utf8_length();
5312   bool legal = false;
5313 
5314   if (length > 0) {
5315     const char* p;
5316     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5317       p = skip_over_field_signature(bytes, false, length, CHECK);
5318       legal = (p != NULL) && ((p - bytes) == (int)length);
5319     } else if (_major_version < JAVA_1_5_VERSION) {
5320       if (bytes[0] != '<') {
5321         p = skip_over_field_name(bytes, true, length);
5322         legal = (p != NULL) && ((p - bytes) == (int)length);
5323       }
5324     } else {
5325       // 4900761: relax the constraints based on JSR202 spec
5326       // Class names may be drawn from the entire Unicode character set.
5327       // Identifiers between '/' must be unqualified names.
5328       // The utf8 string has been verified when parsing cpool entries.
5329       legal = verify_unqualified_name(bytes, length, LegalClass);
5330     }
5331   }
5332   if (!legal) {
5333     ResourceMark rm(THREAD);
5334     assert(_class_name != NULL, "invariant");
5335     Exceptions::fthrow(
5336       THREAD_AND_LOCATION,
5337       vmSymbols::java_lang_ClassFormatError(),
5338       "Illegal class name \"%s\" in class file %s", bytes,
5339       _class_name->as_C_string()
5340     );
5341     return;
5342   }
5343 }
5344 
5345 // Checks if name is a legal field name.
5346 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5347   if (!_need_verify || _relax_verify) { return; }
5348 
5349   char buf[fixed_buffer_size];
5350   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5351   unsigned int length = name->utf8_length();
5352   bool legal = false;
5353 
5354   if (length > 0) {
5355     if (_major_version < JAVA_1_5_VERSION) {
5356       if (bytes[0] != '<') {
5357         const char* p = skip_over_field_name(bytes, false, length);
5358         legal = (p != NULL) && ((p - bytes) == (int)length);
5359       }
5360     } else {
5361       // 4881221: relax the constraints based on JSR202 spec
5362       legal = verify_unqualified_name(bytes, length, LegalField);
5363     }
5364   }
5365 
5366   if (!legal) {
5367     ResourceMark rm(THREAD);
5368     assert(_class_name != NULL, "invariant");
5369     Exceptions::fthrow(
5370       THREAD_AND_LOCATION,
5371       vmSymbols::java_lang_ClassFormatError(),
5372       "Illegal field name \"%s\" in class %s", bytes,
5373       _class_name->as_C_string()
5374     );
5375     return;
5376   }
5377 }
5378 
5379 // Checks if name is a legal method name.
5380 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5381   if (!_need_verify || _relax_verify) { return; }
5382 
5383   assert(name != NULL, "method name is null");
5384   char buf[fixed_buffer_size];
5385   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5386   unsigned int length = name->utf8_length();
5387   bool legal = false;
5388 
5389   if (length > 0) {
5390     if (bytes[0] == '<') {
5391       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5392         legal = true;
5393       }
5394     } else if (_major_version < JAVA_1_5_VERSION) {
5395       const char* p;
5396       p = skip_over_field_name(bytes, false, length);
5397       legal = (p != NULL) && ((p - bytes) == (int)length);
5398     } else {
5399       // 4881221: relax the constraints based on JSR202 spec
5400       legal = verify_unqualified_name(bytes, length, LegalMethod);
5401     }
5402   }
5403 
5404   if (!legal) {
5405     ResourceMark rm(THREAD);
5406     assert(_class_name != NULL, "invariant");
5407     Exceptions::fthrow(
5408       THREAD_AND_LOCATION,
5409       vmSymbols::java_lang_ClassFormatError(),
5410       "Illegal method name \"%s\" in class %s", bytes,
5411       _class_name->as_C_string()
5412     );
5413     return;
5414   }
5415 }
5416 
5417 
5418 // Checks if signature is a legal field signature.
5419 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5420                                                    const Symbol* signature,
5421                                                    TRAPS) const {
5422   if (!_need_verify) { return; }
5423 
5424   char buf[fixed_buffer_size];
5425   const char* const bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5426   const unsigned int length = signature->utf8_length();
5427   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5428 
5429   if (p == NULL || (p - bytes) != (int)length) {
5430     throwIllegalSignature("Field", name, signature, CHECK);
5431   }
5432 }
5433 
5434 // Checks if signature is a legal method signature.
5435 // Returns number of parameters
5436 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5437                                                    const Symbol* signature,
5438                                                    TRAPS) const {
5439   if (!_need_verify) {
5440     // make sure caller's args_size will be less than 0 even for non-static
5441     // method so it will be recomputed in compute_size_of_parameters().
5442     return -2;
5443   }
5444 
5445   // Class initializers cannot have args for class format version >= 51.
5446   if (name == vmSymbols::class_initializer_name() &&
5447       signature != vmSymbols::void_method_signature() &&
5448       _major_version >= JAVA_7_VERSION) {
5449     throwIllegalSignature("Method", name, signature, CHECK_0);
5450     return 0;
5451   }
5452 
5453   unsigned int args_size = 0;
5454   char buf[fixed_buffer_size];
5455   const char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5456   unsigned int length = signature->utf8_length();
5457   const char* nextp;
5458 
5459   // The first character must be a '('
5460   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5461     length--;
5462     // Skip over legal field signatures
5463     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5464     while ((length > 0) && (nextp != NULL)) {
5465       args_size++;
5466       if (p[0] == 'J' || p[0] == 'D') {
5467         args_size++;
5468       }
5469       length -= nextp - p;
5470       p = nextp;
5471       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5472     }
5473     // The first non-signature thing better be a ')'
5474     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5475       length--;
5476       if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
5477         // All internal methods must return void
5478         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
5479           return args_size;
5480         }
5481       } else {
5482         // Now we better just have a return value
5483         nextp = skip_over_field_signature(p, true, length, CHECK_0);
5484         if (nextp && ((int)length == (nextp - p))) {
5485           return args_size;
5486         }
5487       }
5488     }
5489   }
5490   // Report error
5491   throwIllegalSignature("Method", name, signature, CHECK_0);
5492   return 0;
5493 }
5494 
5495 int ClassFileParser::static_field_size() const {
5496   assert(_field_info != NULL, "invariant");
5497   return _field_info->static_field_size;
5498 }
5499 
5500 int ClassFileParser::total_oop_map_count() const {
5501   assert(_field_info != NULL, "invariant");
5502   return _field_info->oop_map_blocks->nonstatic_oop_map_count;
5503 }
5504 
5505 jint ClassFileParser::layout_size() const {
5506   assert(_field_info != NULL, "invariant");
5507   return _field_info->instance_size;
5508 }
5509 
5510 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5511                                          const Array<Method*>* methods) {
5512   assert(ik != NULL, "invariant");
5513   assert(methods != NULL, "invariant");
5514 
5515   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5516   // (We used to do this lazily, but now we query it in Rewriter,
5517   // which is eagerly done for every method, so we might as well do it now,
5518   // when everything is fresh in memory.)
5519   const vmSymbols::SID klass_id = Method::klass_id_for_intrinsics(ik);
5520 
5521   if (klass_id != vmSymbols::NO_SID) {
5522     for (int j = 0; j < methods->length(); ++j) {
5523       Method* method = methods->at(j);
5524       method->init_intrinsic_id();
5525 
5526       if (CheckIntrinsics) {
5527         // Check if an intrinsic is defined for method 'method',
5528         // but the method is not annotated with @HotSpotIntrinsicCandidate.
5529         if (method->intrinsic_id() != vmIntrinsics::_none &&
5530             !method->intrinsic_candidate()) {
5531               tty->print("Compiler intrinsic is defined for method [%s], "
5532               "but the method is not annotated with @HotSpotIntrinsicCandidate.%s",
5533               method->name_and_sig_as_C_string(),
5534               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5535             );
5536           tty->cr();
5537           DEBUG_ONLY(vm_exit(1));
5538         }
5539         // Check is the method 'method' is annotated with @HotSpotIntrinsicCandidate,
5540         // but there is no intrinsic available for it.
5541         if (method->intrinsic_candidate() &&
5542           method->intrinsic_id() == vmIntrinsics::_none) {
5543             tty->print("Method [%s] is annotated with @HotSpotIntrinsicCandidate, "
5544               "but no compiler intrinsic is defined for the method.%s",
5545               method->name_and_sig_as_C_string(),
5546               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5547             );
5548           tty->cr();
5549           DEBUG_ONLY(vm_exit(1));
5550         }
5551       }
5552     } // end for
5553 
5554 #ifdef ASSERT
5555     if (CheckIntrinsics) {
5556       // Check for orphan methods in the current class. A method m
5557       // of a class C is orphan if an intrinsic is defined for method m,
5558       // but class C does not declare m.
5559       // The check is potentially expensive, therefore it is available
5560       // only in debug builds.
5561 
5562       for (int id = vmIntrinsics::FIRST_ID; id < (int)vmIntrinsics::ID_LIMIT; ++id) {
5563         if (vmIntrinsics::_compiledLambdaForm == id) {
5564           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5565           // generated for the JVM from a LambdaForm and therefore no method
5566           // is defined for it.
5567           continue;
5568         }
5569 
5570         if (vmIntrinsics::class_for(vmIntrinsics::ID_from(id)) == klass_id) {
5571           // Check if the current class contains a method with the same
5572           // name, flags, signature.
5573           bool match = false;
5574           for (int j = 0; j < methods->length(); ++j) {
5575             const Method* method = methods->at(j);
5576             if (method->intrinsic_id() == id) {
5577               match = true;
5578               break;
5579             }
5580           }
5581 
5582           if (!match) {
5583             char buf[1000];
5584             tty->print("Compiler intrinsic is defined for method [%s], "
5585                        "but the method is not available in class [%s].%s",
5586                         vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID_from(id),
5587                                                              buf, sizeof(buf)),
5588                         ik->name()->as_C_string(),
5589                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5590             );
5591             tty->cr();
5592             DEBUG_ONLY(vm_exit(1));
5593           }
5594         }
5595       } // end for
5596     } // CheckIntrinsics
5597 #endif // ASSERT
5598   }
5599 }
5600 
5601 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook, TRAPS) {
5602   if (_klass != NULL) {
5603     return _klass;
5604   }
5605 
5606   InstanceKlass* const ik =
5607     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5608 
5609   fill_instance_klass(ik, changed_by_loadhook, CHECK_NULL);
5610 
5611   assert(_klass == ik, "invariant");
5612 
5613   ik->set_has_passed_fingerprint_check(false);
5614   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
5615     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
5616     if (aot_fp != 0 && aot_fp == _stream->compute_fingerprint()) {
5617       // This class matches with a class saved in an AOT library
5618       ik->set_has_passed_fingerprint_check(true);
5619     } else {
5620       ResourceMark rm;
5621       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT,
5622                                  ik->external_name(), aot_fp, _stream->compute_fingerprint());
5623     }
5624   }
5625 
5626   if (ik->is_value()) {
5627     ValueKlass* vk = ValueKlass::cast(ik);
5628     oop val = ik->allocate_instance(CHECK_NULL);
5629     vk->set_default_value(val);
5630   }
5631 
5632   return ik;
5633 }
5634 
5635 void ClassFileParser::fill_instance_klass(InstanceKlass* ik, bool changed_by_loadhook, TRAPS) {
5636   assert(ik != NULL, "invariant");
5637 
5638   set_klass_to_deallocate(ik);
5639 
5640   assert(_field_info != NULL, "invariant");
5641   assert(ik->static_field_size() == _field_info->static_field_size, "sanity");
5642   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->nonstatic_oop_map_count,
5643     "sanity");
5644 
5645   assert(ik->is_instance_klass(), "sanity");
5646   assert(ik->size_helper() == _field_info->instance_size, "sanity");
5647 
5648   // Fill in information already parsed
5649   ik->set_should_verify_class(_need_verify);
5650 
5651   // Not yet: supers are done below to support the new subtype-checking fields
5652   ik->set_class_loader_data(_loader_data);
5653   ik->set_nonstatic_field_size(_field_info->nonstatic_field_size);
5654   ik->set_has_nonstatic_fields(_field_info->has_nonstatic_fields);
5655   assert(_fac != NULL, "invariant");
5656   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_FLATTENABLE]);
5657 
5658   // this transfers ownership of a lot of arrays from
5659   // the parser onto the InstanceKlass*
5660   apply_parsed_class_metadata(ik, _java_fields_count, CHECK);
5661 
5662   // note that is not safe to use the fields in the parser from this point on
5663   assert(NULL == _cp, "invariant");
5664   assert(NULL == _fields, "invariant");
5665   assert(NULL == _methods, "invariant");
5666   assert(NULL == _inner_classes, "invariant");
5667   assert(NULL == _local_interfaces, "invariant");
5668   assert(NULL == _transitive_interfaces, "invariant");
5669   assert(NULL == _combined_annotations, "invariant");
5670 
5671   if (_has_final_method) {
5672     ik->set_has_final_method();
5673   }
5674 
5675   ik->copy_method_ordering(_method_ordering, CHECK);
5676   // The InstanceKlass::_methods_jmethod_ids cache
5677   // is managed on the assumption that the initial cache
5678   // size is equal to the number of methods in the class. If
5679   // that changes, then InstanceKlass::idnum_can_increment()
5680   // has to be changed accordingly.
5681   ik->set_initial_method_idnum(ik->methods()->length());
5682 
5683   ik->set_name(_class_name);
5684 
5685   if (is_anonymous()) {
5686     // _this_class_index is a CONSTANT_Class entry that refers to this
5687     // anonymous class itself. If this class needs to refer to its own methods or
5688     // fields, it would use a CONSTANT_MethodRef, etc, which would reference
5689     // _this_class_index. However, because this class is anonymous (it's
5690     // not stored in SystemDictionary), _this_class_index cannot be resolved
5691     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5692     // Therefore, we must eagerly resolve _this_class_index now.
5693     ik->constants()->klass_at_put(_this_class_index, ik);
5694   }
5695 
5696   ik->set_minor_version(_minor_version);
5697   ik->set_major_version(_major_version);
5698   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5699   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5700 
5701   if (_host_klass != NULL) {
5702     assert (ik->is_anonymous(), "should be the same");
5703     ik->set_host_klass(_host_klass);
5704   }
5705 
5706   // Set PackageEntry for this_klass
5707   oop cl = ik->class_loader();
5708   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5709   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5710   ik->set_package(cld, CHECK);
5711 
5712   const Array<Method*>* const methods = ik->methods();
5713   assert(methods != NULL, "invariant");
5714   const int methods_len = methods->length();
5715 
5716   check_methods_for_intrinsics(ik, methods);
5717 
5718   // Fill in field values obtained by parse_classfile_attributes
5719   if (_parsed_annotations->has_any_annotations()) {
5720     _parsed_annotations->apply_to(ik);
5721   }
5722 
5723   apply_parsed_class_attributes(ik);
5724 
5725   // Miranda methods
5726   if ((_num_miranda_methods > 0) ||
5727       // if this class introduced new miranda methods or
5728       (_super_klass != NULL && _super_klass->has_miranda_methods())
5729         // super class exists and this class inherited miranda methods
5730      ) {
5731        ik->set_has_miranda_methods(); // then set a flag
5732   }
5733 
5734   // Fill in information needed to compute superclasses.
5735   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), CHECK);
5736 
5737   // Initialize itable offset tables
5738   klassItable::setup_itable_offset_table(ik);
5739 
5740   // Compute transitive closure of interfaces this class implements
5741   // Do final class setup
5742   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5743   if (oop_map_blocks->nonstatic_oop_map_count > 0) {
5744     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5745   }
5746 
5747   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5748   set_precomputed_flags(ik, CHECK);
5749 
5750   // check if this class can access its super class
5751   check_super_class_access(ik, CHECK);
5752 
5753   // check if this class can access its superinterfaces
5754   check_super_interface_access(ik, CHECK);
5755 
5756   // check if this class overrides any final method
5757   check_final_method_override(ik, CHECK);
5758 
5759   // reject static interface methods prior to Java 8
5760   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5761     check_illegal_static_method(ik, CHECK);
5762   }
5763 
5764   // Obtain this_klass' module entry
5765   ModuleEntry* module_entry = ik->module();
5766   assert(module_entry != NULL, "module_entry should always be set");
5767 
5768   // Obtain java.lang.Module
5769   Handle module_handle(THREAD, module_entry->module());
5770 
5771   // Allocate mirror and initialize static fields
5772   // The create_mirror() call will also call compute_modifiers()
5773   java_lang_Class::create_mirror(ik,
5774                                  Handle(THREAD, _loader_data->class_loader()),
5775                                  module_handle,
5776                                  _protection_domain,
5777                                  CHECK);
5778 
5779   assert(_all_mirandas != NULL, "invariant");
5780 
5781   // Generate any default methods - default methods are public interface methods
5782   // that have a default implementation.  This is new with Java 8.
5783   if (_has_nonstatic_concrete_methods) {
5784     DefaultMethods::generate_default_methods(ik,
5785                                              _all_mirandas,
5786                                              CHECK);
5787   }
5788 
5789   if (is_value_type()) {
5790     ValueKlass* vk = ValueKlass::cast(ik);
5791     vk->set_if_bufferable();
5792     vk->initialize_calling_convention();
5793   }
5794 
5795   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5796   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5797       !module_entry->has_default_read_edges()) {
5798     if (!module_entry->set_has_default_read_edges()) {
5799       // We won a potential race
5800       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5801     }
5802   }
5803 
5804   int nfields = ik->java_fields_count();
5805   if (ik->is_value()) nfields++;
5806   for(int i = 0; i < nfields; i++) {
5807     if (ik->field_access_flags(i) & JVM_ACC_FLATTENABLE) {
5808       Klass* klass = SystemDictionary::resolve_or_fail(ik->field_signature(i),
5809                                                        Handle(THREAD, ik->class_loader()),
5810                                                        Handle(THREAD, ik->protection_domain()), true, CHECK);
5811       assert(klass != NULL, "Sanity check");
5812       assert(klass->access_flags().is_value_type(), "Value type expected");
5813       ik->set_value_field_klass(i, klass);
5814     } else if (is_value_type() && ((ik->field_access_flags(i) & JVM_ACC_FIELD_INTERNAL) != 0)
5815         && ((ik->field_access_flags(i) & JVM_ACC_STATIC) != 0)) {
5816       ValueKlass::cast(ik)->set_default_value_offset(ik->field_offset(i));
5817     }
5818   }
5819 
5820   // Update the loader_data graph.
5821   record_defined_class_dependencies(ik, CHECK);
5822 
5823   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5824 
5825   if (!is_internal()) {
5826     if (log_is_enabled(Info, class, load)) {
5827       ResourceMark rm;
5828       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
5829       ik->print_class_load_logging(_loader_data, module_name, _stream);
5830     }
5831 
5832     if (log_is_enabled(Debug, class, resolve))  {
5833       ResourceMark rm;
5834       // print out the superclass.
5835       const char * from = ik->external_name();
5836       if (ik->java_super() != NULL) {
5837         log_debug(class, resolve)("%s %s (super)",
5838                    from,
5839                    ik->java_super()->external_name());
5840       }
5841       // print out each of the interface classes referred to by this class.
5842       const Array<Klass*>* const local_interfaces = ik->local_interfaces();
5843       if (local_interfaces != NULL) {
5844         const int length = local_interfaces->length();
5845         for (int i = 0; i < length; i++) {
5846           const Klass* const k = local_interfaces->at(i);
5847           const char * to = k->external_name();
5848           log_debug(class, resolve)("%s %s (interface)", from, to);
5849         }
5850       }
5851     }
5852   }
5853 
5854   TRACE_INIT_ID(ik);
5855 
5856   // If we reach here, all is well.
5857   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5858   // in order for it to not be destroyed in the ClassFileParser destructor.
5859   set_klass_to_deallocate(NULL);
5860 
5861   // it's official
5862   set_klass(ik);
5863 
5864   debug_only(ik->verify();)
5865 }
5866 
5867 // For an anonymous class that is in the unnamed package, move it to its host class's
5868 // package by prepending its host class's package name to its class name and setting
5869 // its _class_name field.
5870 void ClassFileParser::prepend_host_package_name(const InstanceKlass* host_klass, TRAPS) {
5871   ResourceMark rm(THREAD);
5872   assert(strrchr(_class_name->as_C_string(), '/') == NULL,
5873          "Anonymous class should not be in a package");
5874   const char* host_pkg_name =
5875     ClassLoader::package_from_name(host_klass->name()->as_C_string(), NULL);
5876 
5877   if (host_pkg_name != NULL) {
5878     size_t host_pkg_len = strlen(host_pkg_name);
5879     int class_name_len = _class_name->utf8_length();
5880     char* new_anon_name =
5881       NEW_RESOURCE_ARRAY(char, host_pkg_len + 1 + class_name_len);
5882     // Copy host package name and trailing /.
5883     strncpy(new_anon_name, host_pkg_name, host_pkg_len);
5884     new_anon_name[host_pkg_len] = '/';
5885     // Append anonymous class name. The anonymous class name can contain odd
5886     // characters.  So, do a strncpy instead of using sprintf("%s...").
5887     strncpy(new_anon_name + host_pkg_len + 1, (char *)_class_name->base(), class_name_len);
5888 
5889     // Create a symbol and update the anonymous class name.
5890     _class_name = SymbolTable::new_symbol(new_anon_name,
5891                                           (int)host_pkg_len + 1 + class_name_len,
5892                                           CHECK);
5893   }
5894 }
5895 
5896 // If the host class and the anonymous class are in the same package then do
5897 // nothing.  If the anonymous class is in the unnamed package then move it to its
5898 // host's package.  If the classes are in different packages then throw an IAE
5899 // exception.
5900 void ClassFileParser::fix_anonymous_class_name(TRAPS) {
5901   assert(_host_klass != NULL, "Expected an anonymous class");
5902 
5903   const jbyte* anon_last_slash = UTF8::strrchr(_class_name->base(),
5904                                                _class_name->utf8_length(), '/');
5905   if (anon_last_slash == NULL) {  // Unnamed package
5906     prepend_host_package_name(_host_klass, CHECK);
5907   } else {
5908     if (!_host_klass->is_same_class_package(_host_klass->class_loader(), _class_name)) {
5909       ResourceMark rm(THREAD);
5910       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
5911         err_msg("Host class %s and anonymous class %s are in different packages",
5912         _host_klass->name()->as_C_string(), _class_name->as_C_string()));
5913     }
5914   }
5915 }
5916 
5917 static bool relax_format_check_for(ClassLoaderData* loader_data) {
5918   bool trusted = (loader_data->is_the_null_class_loader_data() ||
5919                   SystemDictionary::is_platform_class_loader(loader_data->class_loader()));
5920   bool need_verify =
5921     // verifyAll
5922     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
5923     // verifyRemote
5924     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
5925   return !need_verify;
5926 }
5927 
5928 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5929                                  Symbol* name,
5930                                  ClassLoaderData* loader_data,
5931                                  Handle protection_domain,
5932                                  const InstanceKlass* host_klass,
5933                                  GrowableArray<Handle>* cp_patches,
5934                                  Publicity pub_level,
5935                                  TRAPS) :
5936   _stream(stream),
5937   _requested_name(name),
5938   _loader_data(loader_data),
5939   _host_klass(host_klass),
5940   _cp_patches(cp_patches),
5941   _num_patched_klasses(0),
5942   _max_num_patched_klasses(0),
5943   _orig_cp_size(0),
5944   _first_patched_klass_resolved_index(0),
5945   _super_klass(),
5946   _cp(NULL),
5947   _fields(NULL),
5948   _methods(NULL),
5949   _inner_classes(NULL),
5950   _local_interfaces(NULL),
5951   _transitive_interfaces(NULL),
5952   _combined_annotations(NULL),
5953   _annotations(NULL),
5954   _type_annotations(NULL),
5955   _fields_annotations(NULL),
5956   _fields_type_annotations(NULL),
5957   _klass(NULL),
5958   _klass_to_deallocate(NULL),
5959   _parsed_annotations(NULL),
5960   _fac(NULL),
5961   _field_info(NULL),
5962   _method_ordering(NULL),
5963   _all_mirandas(NULL),
5964   _vtable_size(0),
5965   _itable_size(0),
5966   _num_miranda_methods(0),
5967   _rt(REF_NONE),
5968   _protection_domain(protection_domain),
5969   _access_flags(),
5970   _pub_level(pub_level),
5971   _bad_constant_seen(0),
5972   _synthetic_flag(false),
5973   _sde_length(false),
5974   _sde_buffer(NULL),
5975   _sourcefile_index(0),
5976   _generic_signature_index(0),
5977   _major_version(0),
5978   _minor_version(0),
5979   _this_class_index(0),
5980   _super_class_index(0),
5981   _itfs_len(0),
5982   _java_fields_count(0),
5983   _need_verify(false),
5984   _relax_verify(false),
5985   _has_nonstatic_concrete_methods(false),
5986   _declares_nonstatic_concrete_methods(false),
5987   _has_final_method(false),
5988   _has_finalizer(false),
5989   _has_empty_finalizer(false),
5990   _has_vanilla_constructor(false),
5991   _max_bootstrap_specifier_index(-1),
5992   _has_flattenable_fields(false) {
5993 
5994   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5995 
5996   assert(THREAD->is_Java_thread(), "invariant");
5997   assert(_loader_data != NULL, "invariant");
5998   assert(stream != NULL, "invariant");
5999   assert(_stream != NULL, "invariant");
6000   assert(_stream->buffer() == _stream->current(), "invariant");
6001   assert(_class_name != NULL, "invariant");
6002   assert(0 == _access_flags.as_int(), "invariant");
6003 
6004   // Figure out whether we can skip format checking (matching classic VM behavior)
6005   if (DumpSharedSpaces) {
6006     // verify == true means it's a 'remote' class (i.e., non-boot class)
6007     // Verification decision is based on BytecodeVerificationRemote flag
6008     // for those classes.
6009     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
6010                                               BytecodeVerificationLocal;
6011   }
6012   else {
6013     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
6014                                                stream->need_verify());
6015   }
6016   if (_cp_patches != NULL) {
6017     int len = _cp_patches->length();
6018     for (int i=0; i<len; i++) {
6019       if (has_cp_patch_at(i)) {
6020         Handle patch = cp_patch_at(i);
6021         if (java_lang_String::is_instance(patch()) || java_lang_Class::is_instance(patch())) {
6022           // We need to append the names of the patched classes to the end of the constant pool,
6023           // because a patched class may have a Utf8 name that's not already included in the
6024           // original constant pool. These class names are used when patch_constant_pool()
6025           // calls patch_class().
6026           //
6027           // Note that a String in cp_patch_at(i) may be used to patch a Utf8, a String, or a Class.
6028           // At this point, we don't know the tag for index i yet, because we haven't parsed the
6029           // constant pool. So we can only assume the worst -- every String is used to patch a Class.
6030           _max_num_patched_klasses++;
6031         }
6032       }
6033     }
6034   }
6035 
6036   // synch back verification state to stream
6037   stream->set_verify(_need_verify);
6038 
6039   // Check if verification needs to be relaxed for this class file
6040   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
6041   _relax_verify = relax_format_check_for(_loader_data);
6042 
6043   parse_stream(stream, CHECK);
6044 
6045   post_process_parsed_stream(stream, _cp, CHECK);
6046 }
6047 
6048 void ClassFileParser::clear_class_metadata() {
6049   // metadata created before the instance klass is created.  Must be
6050   // deallocated if classfile parsing returns an error.
6051   _cp = NULL;
6052   _fields = NULL;
6053   _methods = NULL;
6054   _inner_classes = NULL;
6055   _local_interfaces = NULL;
6056   _transitive_interfaces = NULL;
6057   _combined_annotations = NULL;
6058   _annotations = _type_annotations = NULL;
6059   _fields_annotations = _fields_type_annotations = NULL;
6060 }
6061 
6062 // Destructor to clean up
6063 ClassFileParser::~ClassFileParser() {
6064   if (_cp != NULL) {
6065     MetadataFactory::free_metadata(_loader_data, _cp);
6066   }
6067   if (_fields != NULL) {
6068     MetadataFactory::free_array<u2>(_loader_data, _fields);
6069   }
6070 
6071   if (_methods != NULL) {
6072     // Free methods
6073     InstanceKlass::deallocate_methods(_loader_data, _methods);
6074   }
6075 
6076   // beware of the Universe::empty_blah_array!!
6077   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
6078     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
6079   }
6080 
6081   // Free interfaces
6082   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6083                                        _local_interfaces, _transitive_interfaces);
6084 
6085   if (_combined_annotations != NULL) {
6086     // After all annotations arrays have been created, they are installed into the
6087     // Annotations object that will be assigned to the InstanceKlass being created.
6088 
6089     // Deallocate the Annotations object and the installed annotations arrays.
6090     _combined_annotations->deallocate_contents(_loader_data);
6091 
6092     // If the _combined_annotations pointer is non-NULL,
6093     // then the other annotations fields should have been cleared.
6094     assert(_annotations             == NULL, "Should have been cleared");
6095     assert(_type_annotations        == NULL, "Should have been cleared");
6096     assert(_fields_annotations      == NULL, "Should have been cleared");
6097     assert(_fields_type_annotations == NULL, "Should have been cleared");
6098   } else {
6099     // If the annotations arrays were not installed into the Annotations object,
6100     // then they have to be deallocated explicitly.
6101     MetadataFactory::free_array<u1>(_loader_data, _annotations);
6102     MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
6103     Annotations::free_contents(_loader_data, _fields_annotations);
6104     Annotations::free_contents(_loader_data, _fields_type_annotations);
6105   }
6106 
6107   clear_class_metadata();
6108 
6109   // deallocate the klass if already created.  Don't directly deallocate, but add
6110   // to the deallocate list so that the klass is removed from the CLD::_klasses list
6111   // at a safepoint.
6112   if (_klass_to_deallocate != NULL) {
6113     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
6114   }
6115 }
6116 
6117 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
6118                                    TRAPS) {
6119 
6120   assert(stream != NULL, "invariant");
6121   assert(_class_name != NULL, "invariant");
6122 
6123   // BEGIN STREAM PARSING
6124   stream->guarantee_more(8, CHECK);  // magic, major, minor
6125   // Magic value
6126   const u4 magic = stream->get_u4_fast();
6127   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
6128                      "Incompatible magic value %u in class file %s",
6129                      magic, CHECK);
6130 
6131   // Version numbers
6132   _minor_version = stream->get_u2_fast();
6133   _major_version = stream->get_u2_fast();
6134 
6135   if (DumpSharedSpaces && _major_version < JAVA_1_5_VERSION) {
6136     ResourceMark rm;
6137     warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
6138             _major_version,  _minor_version, _class_name->as_C_string());
6139     Exceptions::fthrow(
6140       THREAD_AND_LOCATION,
6141       vmSymbols::java_lang_UnsupportedClassVersionError(),
6142       "Unsupported major.minor version for dump time %u.%u",
6143       _major_version,
6144       _minor_version);
6145   }
6146 
6147   // Check version numbers - we check this even with verifier off
6148   if (!is_supported_version(_major_version, _minor_version)) {
6149     ResourceMark rm(THREAD);
6150     Exceptions::fthrow(
6151       THREAD_AND_LOCATION,
6152       vmSymbols::java_lang_UnsupportedClassVersionError(),
6153       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
6154       "this version of the Java Runtime only recognizes class file versions up to %u.%u",
6155       _class_name->as_C_string(),
6156       _major_version,
6157       _minor_version,
6158       JVM_CLASSFILE_MAJOR_VERSION,
6159       JVM_CLASSFILE_MINOR_VERSION);
6160     return;
6161   }
6162 
6163   stream->guarantee_more(3, CHECK); // length, first cp tag
6164   u2 cp_size = stream->get_u2_fast();
6165 
6166   guarantee_property(
6167     cp_size >= 1, "Illegal constant pool size %u in class file %s",
6168     cp_size, CHECK);
6169 
6170   _orig_cp_size = cp_size;
6171   if (int(cp_size) + _max_num_patched_klasses > 0xffff) {
6172     THROW_MSG(vmSymbols::java_lang_InternalError(), "not enough space for patched classes");
6173   }
6174   cp_size += _max_num_patched_klasses;
6175 
6176   _cp = ConstantPool::allocate(_loader_data,
6177                                cp_size,
6178                                CHECK);
6179 
6180   ConstantPool* const cp = _cp;
6181 
6182   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6183 
6184   assert(cp_size == (const u2)cp->length(), "invariant");
6185 
6186   // ACCESS FLAGS
6187   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6188 
6189   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;
6190   // JVM_ACC_MODULE is defined in JDK-9 and later.
6191   if (_major_version >= JAVA_9_VERSION) {
6192     recognized_modifiers |= JVM_ACC_MODULE;
6193   }
6194   // JVM_ACC_VALUE is defined for class file version 55 and later
6195   if (supports_value_types()) {
6196     recognized_modifiers |= JVM_ACC_VALUE;
6197   }
6198 
6199   // Access flags
6200   jint flags = stream->get_u2_fast() & recognized_modifiers;
6201 
6202   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6203     // Set abstract bit for old class files for backward compatibility
6204     flags |= JVM_ACC_ABSTRACT;
6205   }
6206 
6207   verify_legal_class_modifiers(flags, CHECK);
6208 
6209   short bad_constant = class_bad_constant_seen();
6210   if (bad_constant != 0) {
6211     // Do not throw CFE until after the access_flags are checked because if
6212     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6213     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, CHECK);
6214   }
6215 
6216   _access_flags.set_flags(flags);
6217 
6218   // This class and superclass
6219   _this_class_index = stream->get_u2_fast();
6220   check_property(
6221     valid_cp_range(_this_class_index, cp_size) &&
6222       cp->tag_at(_this_class_index).is_unresolved_klass(),
6223     "Invalid this class index %u in constant pool in class file %s",
6224     _this_class_index, CHECK);
6225 
6226   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6227   assert(class_name_in_cp != NULL, "class_name can't be null");
6228 
6229   // Update _class_name which could be null previously
6230   // to reflect the name in the constant pool
6231   _class_name = class_name_in_cp;
6232 
6233   // Don't need to check whether this class name is legal or not.
6234   // It has been checked when constant pool is parsed.
6235   // However, make sure it is not an array type.
6236   if (_need_verify) {
6237     guarantee_property(_class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
6238                        "Bad class name in class file %s",
6239                        CHECK);
6240   }
6241 
6242   // Checks if name in class file matches requested name
6243   if (_requested_name != NULL && _requested_name != _class_name) {
6244     ResourceMark rm(THREAD);
6245     Exceptions::fthrow(
6246       THREAD_AND_LOCATION,
6247       vmSymbols::java_lang_NoClassDefFoundError(),
6248       "%s (wrong name: %s)",
6249       _class_name->as_C_string(),
6250       _requested_name != NULL ? _requested_name->as_C_string() : "NoName"
6251     );
6252     return;
6253   }
6254 
6255   // if this is an anonymous class fix up its name if it's in the unnamed
6256   // package.  Otherwise, throw IAE if it is in a different package than
6257   // its host class.
6258   if (_host_klass != NULL) {
6259     fix_anonymous_class_name(CHECK);
6260   }
6261 
6262   // Verification prevents us from creating names with dots in them, this
6263   // asserts that that's the case.
6264   assert(is_internal_format(_class_name), "external class name format used internally");
6265 
6266   if (!is_internal()) {
6267     LogTarget(Debug, class, preorder) lt;
6268     if (lt.is_enabled()){
6269       ResourceMark rm(THREAD);
6270       LogStream ls(lt);
6271       ls.print("%s", _class_name->as_klass_external_name());
6272       if (stream->source() != NULL) {
6273         ls.print(" source: %s", stream->source());
6274       }
6275       ls.cr();
6276     }
6277 
6278 #if INCLUDE_CDS
6279     if (DumpLoadedClassList != NULL && stream->source() != NULL && classlist_file->is_open()) {
6280       if (!ClassLoader::has_jrt_entry()) {
6281         warning("DumpLoadedClassList and CDS are not supported in exploded build");
6282         DumpLoadedClassList = NULL;
6283       } else if (SystemDictionaryShared::is_sharing_possible(_loader_data) &&
6284           _host_klass == NULL) {
6285         // Only dump the classes that can be stored into CDS archive.
6286         // Anonymous classes such as generated LambdaForm classes are also not included.
6287         oop class_loader = _loader_data->class_loader();
6288         ResourceMark rm(THREAD);
6289         bool skip = false;
6290         if (class_loader == NULL || SystemDictionary::is_platform_class_loader(class_loader)) {
6291           // For the boot and platform class loaders, skip classes that are not found in the
6292           // java runtime image, such as those found in the --patch-module entries.
6293           // These classes can't be loaded from the archive during runtime.
6294           if (!ClassLoader::is_modules_image(stream->source()) && strncmp(stream->source(), "jrt:", 4) != 0) {
6295             skip = true;
6296           }
6297 
6298           if (class_loader == NULL && ClassLoader::contains_append_entry(stream->source())) {
6299             // .. but don't skip the boot classes that are loaded from -Xbootclasspath/a
6300             // as they can be loaded from the archive during runtime.
6301             skip = false;
6302           }
6303         }
6304         if (skip) {
6305           tty->print_cr("skip writing class %s from source %s to classlist file",
6306             _class_name->as_C_string(), stream->source());
6307         } else {
6308           classlist_file->print_cr("%s", _class_name->as_C_string());
6309           classlist_file->flush();
6310         }
6311       }
6312     }
6313 #endif
6314   }
6315 
6316   // SUPERKLASS
6317   _super_class_index = stream->get_u2_fast();
6318   _super_klass = parse_super_class(cp,
6319                                    _super_class_index,
6320                                    _need_verify,
6321                                    CHECK);
6322 
6323   // Interfaces
6324   _itfs_len = stream->get_u2_fast();
6325   parse_interfaces(stream,
6326                    _itfs_len,
6327                    cp,
6328                    &_has_nonstatic_concrete_methods,
6329                    CHECK);
6330 
6331   assert(_local_interfaces != NULL, "invariant");
6332 
6333   // Fields (offsets are filled in later)
6334   _fac = new FieldAllocationCount();
6335   parse_fields(stream,
6336                _access_flags.is_interface(),
6337                _access_flags.is_value_type(),
6338                _fac,
6339                cp,
6340                cp_size,
6341                &_java_fields_count,
6342                CHECK);
6343 
6344   assert(_fields != NULL, "invariant");
6345 
6346   // Methods
6347   AccessFlags promoted_flags;
6348   parse_methods(stream,
6349                 _access_flags.is_interface(),
6350                 _access_flags.is_value_type(),
6351                 &promoted_flags,
6352                 &_has_final_method,
6353                 &_declares_nonstatic_concrete_methods,
6354                 CHECK);
6355 
6356   assert(_methods != NULL, "invariant");
6357 
6358   // promote flags from parse_methods() to the klass' flags
6359   _access_flags.add_promoted_flags(promoted_flags.as_int());
6360 
6361   if (_declares_nonstatic_concrete_methods) {
6362     _has_nonstatic_concrete_methods = true;
6363   }
6364 
6365   // Additional attributes/annotations
6366   _parsed_annotations = new ClassAnnotationCollector();
6367   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6368 
6369   assert(_inner_classes != NULL, "invariant");
6370 
6371   // Finalize the Annotations metadata object,
6372   // now that all annotation arrays have been created.
6373   create_combined_annotations(CHECK);
6374 
6375   // Make sure this is the end of class file stream
6376   guarantee_property(stream->at_eos(),
6377                      "Extra bytes at the end of class file %s",
6378                      CHECK);
6379 
6380   // all bytes in stream read and parsed
6381 }
6382 
6383 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6384                                                  ConstantPool* cp,
6385                                                  TRAPS) {
6386   assert(stream != NULL, "invariant");
6387   assert(stream->at_eos(), "invariant");
6388   assert(cp != NULL, "invariant");
6389   assert(_loader_data != NULL, "invariant");
6390 
6391   if (_class_name == vmSymbols::java_lang_Object()) {
6392     check_property(_local_interfaces == Universe::the_empty_klass_array(),
6393                    "java.lang.Object cannot implement an interface in class file %s",
6394                    CHECK);
6395   }
6396   // We check super class after class file is parsed and format is checked
6397   if (_super_class_index > 0 && NULL ==_super_klass) {
6398     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6399     if (_access_flags.is_interface()) {
6400       // Before attempting to resolve the superclass, check for class format
6401       // errors not checked yet.
6402       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6403         "Interfaces must have java.lang.Object as superclass in class file %s",
6404         CHECK);
6405     }
6406     Handle loader(THREAD, _loader_data->class_loader());
6407     _super_klass = (const InstanceKlass*)
6408                        SystemDictionary::resolve_super_or_fail(_class_name,
6409                                                                super_class_name,
6410                                                                loader,
6411                                                                _protection_domain,
6412                                                                true,
6413                                                                CHECK);
6414   }
6415 
6416   if (_super_klass != NULL) {
6417     if (_super_klass->has_nonstatic_concrete_methods()) {
6418       _has_nonstatic_concrete_methods = true;
6419     }
6420 
6421     if (_super_klass->is_interface()) {
6422       ResourceMark rm(THREAD);
6423       Exceptions::fthrow(
6424         THREAD_AND_LOCATION,
6425         vmSymbols::java_lang_IncompatibleClassChangeError(),
6426         "class %s has interface %s as super class",
6427         _class_name->as_klass_external_name(),
6428         _super_klass->external_name()
6429       );
6430       return;
6431     }
6432 
6433     // For a value class, only java/lang/Object is an acceptable super class
6434     if (_access_flags.get_flags() & JVM_ACC_VALUE) {
6435       guarantee_property(_super_klass->name() == vmSymbols::java_lang_Object(),
6436         "Value type must have java.lang.Object as superclass in class file %s",
6437         CHECK);
6438     }
6439 
6440     // Make sure super class is not final
6441     if (_super_klass->is_final()) {
6442       THROW_MSG(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class");
6443     }
6444   }
6445 
6446   // Compute the transitive list of all unique interfaces implemented by this class
6447   _transitive_interfaces =
6448     compute_transitive_interfaces(_super_klass,
6449                                   _local_interfaces,
6450                                   _loader_data,
6451                                   CHECK);
6452 
6453   assert(_transitive_interfaces != NULL, "invariant");
6454 
6455   // sort methods
6456   _method_ordering = sort_methods(_methods);
6457 
6458   _all_mirandas = new GrowableArray<Method*>(20);
6459 
6460   Handle loader(THREAD, _loader_data->class_loader());
6461   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6462                                                     &_num_miranda_methods,
6463                                                     _all_mirandas,
6464                                                     _super_klass,
6465                                                     _methods,
6466                                                     _access_flags,
6467                                                     _major_version,
6468                                                     loader,
6469                                                     _class_name,
6470                                                     _local_interfaces,
6471                                                     CHECK);
6472 
6473   // Size of Java itable (in words)
6474   _itable_size = _access_flags.is_interface() ? 0 :
6475     klassItable::compute_itable_size(_transitive_interfaces);
6476 
6477   assert(_fac != NULL, "invariant");
6478   assert(_parsed_annotations != NULL, "invariant");
6479 
6480   _field_info = new FieldLayoutInfo();
6481   layout_fields(cp, _fac, _parsed_annotations, _field_info, CHECK);
6482 
6483   // Compute reference typ
6484   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();
6485 
6486 }
6487 
6488 void ClassFileParser::set_klass(InstanceKlass* klass) {
6489 
6490 #ifdef ASSERT
6491   if (klass != NULL) {
6492     assert(NULL == _klass, "leaking?");
6493   }
6494 #endif
6495 
6496   _klass = klass;
6497 }
6498 
6499 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6500 
6501 #ifdef ASSERT
6502   if (klass != NULL) {
6503     assert(NULL == _klass_to_deallocate, "leaking?");
6504   }
6505 #endif
6506 
6507   _klass_to_deallocate = klass;
6508 }
6509 
6510 // Caller responsible for ResourceMark
6511 // clone stream with rewound position
6512 const ClassFileStream* ClassFileParser::clone_stream() const {
6513   assert(_stream != NULL, "invariant");
6514 
6515   return _stream->clone();
6516 }
6517 
6518 // ----------------------------------------------------------------------------
6519 // debugging
6520 
6521 #ifdef ASSERT
6522 
6523 // return true if class_name contains no '.' (internal format is '/')
6524 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6525   if (class_name != NULL) {
6526     ResourceMark rm;
6527     char* name = class_name->as_C_string();
6528     return strchr(name, '.') == NULL;
6529   } else {
6530     return true;
6531   }
6532 }
6533 
6534 #endif