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 u2 ClassFileParser::parse_value_types_attribute(const ClassFileStream* const cfs,
3163                                                 const u1* const value_types_attribute_start,
3164                                                 TRAPS) {
3165   const u1* const current_mark = cfs->current();
3166   u2 length = 0;
3167   if (value_types_attribute_start != NULL) {
3168     cfs->set_current(value_types_attribute_start);
3169     cfs->guarantee_more(2, CHECK_0);  // length
3170     length = cfs->get_u2_fast();
3171   }
3172   Array<ValueTypes>* const value_types = MetadataFactory::new_array<ValueTypes>(_loader_data, length, CHECK_0);
3173 
3174   int index = 0;
3175   const int cp_size = _cp->length();
3176   cfs->guarantee_more(2 *length, CHECK_0);
3177   for (int n = 0; n < length; n++) {
3178       // Value types class index
3179       const u2 value_types_info_index = cfs->get_u2_fast();
3180       check_property(
3181         valid_klass_reference_at(value_types_info_index),
3182         "value_types_info_index %u has bad constant type in class file %s",
3183         value_types_info_index, CHECK_0);
3184       ValueTypes vt;
3185       vt._class_info_index = value_types_info_index;
3186       vt._class_name = NULL;
3187       value_types->at_put(index++, vt);
3188   }
3189   _value_types = value_types;
3190   // Restore buffer's current position.
3191   cfs->set_current(current_mark);
3192 
3193   return length;
3194 }
3195 
3196 // Return number of classes in the inner classes attribute table
3197 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
3198                                                             const u1* const inner_classes_attribute_start,
3199                                                             bool parsed_enclosingmethod_attribute,
3200                                                             u2 enclosing_method_class_index,
3201                                                             u2 enclosing_method_method_index,
3202                                                             TRAPS) {
3203   const u1* const current_mark = cfs->current();
3204   u2 length = 0;
3205   if (inner_classes_attribute_start != NULL) {
3206     cfs->set_current(inner_classes_attribute_start);
3207     cfs->guarantee_more(2, CHECK_0);  // length
3208     length = cfs->get_u2_fast();
3209   }
3210 
3211   // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
3212   // method data:
3213   //   [inner_class_info_index,
3214   //    outer_class_info_index,
3215   //    inner_name_index,
3216   //    inner_class_access_flags,
3217   //    ...
3218   //    enclosing_method_class_index,
3219   //    enclosing_method_method_index]
3220   const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
3221   Array<u2>* const inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3222   _inner_classes = inner_classes;
3223 
3224   int index = 0;
3225   const int cp_size = _cp->length();
3226   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
3227   for (int n = 0; n < length; n++) {
3228     // Inner class index
3229     const u2 inner_class_info_index = cfs->get_u2_fast();
3230     check_property(
3231       valid_klass_reference_at(inner_class_info_index),
3232       "inner_class_info_index %u has bad constant type in class file %s",
3233       inner_class_info_index, CHECK_0);
3234     // Outer class index
3235     const u2 outer_class_info_index = cfs->get_u2_fast();
3236     check_property(
3237       outer_class_info_index == 0 ||
3238         valid_klass_reference_at(outer_class_info_index),
3239       "outer_class_info_index %u has bad constant type in class file %s",
3240       outer_class_info_index, CHECK_0);
3241     // Inner class name
3242     const u2 inner_name_index = cfs->get_u2_fast();
3243     check_property(
3244       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3245       "inner_name_index %u has bad constant type in class file %s",
3246       inner_name_index, CHECK_0);
3247     if (_need_verify) {
3248       guarantee_property(inner_class_info_index != outer_class_info_index,
3249                          "Class is both outer and inner class in class file %s", CHECK_0);
3250     }
3251 
3252     jint recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3253     // JVM_ACC_MODULE is defined in JDK-9 and later.
3254     if (_major_version >= JAVA_9_VERSION) {
3255       recognized_modifiers |= JVM_ACC_MODULE;
3256     }
3257     // JVM_ACC_VALUE is defined for class file version 55 and later
3258     if (supports_value_types()) {
3259       recognized_modifiers |= JVM_ACC_VALUE;
3260     }
3261 
3262     // Access flags
3263     jint flags = cfs->get_u2_fast() & recognized_modifiers;
3264 
3265     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3266       // Set abstract bit for old class files for backward compatibility
3267       flags |= JVM_ACC_ABSTRACT;
3268     }
3269     verify_legal_class_modifiers(flags, CHECK_0);
3270     AccessFlags inner_access_flags(flags);
3271 
3272     inner_classes->at_put(index++, inner_class_info_index);
3273     inner_classes->at_put(index++, outer_class_info_index);
3274     inner_classes->at_put(index++, inner_name_index);
3275     inner_classes->at_put(index++, inner_access_flags.as_short());
3276   }
3277 
3278   // 4347400: make sure there's no duplicate entry in the classes array
3279   if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
3280     for(int i = 0; i < length * 4; i += 4) {
3281       for(int j = i + 4; j < length * 4; j += 4) {
3282         guarantee_property((inner_classes->at(i)   != inner_classes->at(j) ||
3283                             inner_classes->at(i+1) != inner_classes->at(j+1) ||
3284                             inner_classes->at(i+2) != inner_classes->at(j+2) ||
3285                             inner_classes->at(i+3) != inner_classes->at(j+3)),
3286                             "Duplicate entry in InnerClasses in class file %s",
3287                             CHECK_0);
3288       }
3289     }
3290   }
3291 
3292   // Set EnclosingMethod class and method indexes.
3293   if (parsed_enclosingmethod_attribute) {
3294     inner_classes->at_put(index++, enclosing_method_class_index);
3295     inner_classes->at_put(index++, enclosing_method_method_index);
3296   }
3297   assert(index == size, "wrong size");
3298 
3299   // Restore buffer's current position.
3300   cfs->set_current(current_mark);
3301 
3302   return length;
3303 }
3304 
3305 void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
3306   set_class_synthetic_flag(true);
3307 }
3308 
3309 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3310   assert(cfs != NULL, "invariant");
3311 
3312   const u2 signature_index = cfs->get_u2(CHECK);
3313   check_property(
3314     valid_symbol_at(signature_index),
3315     "Invalid constant pool index %u in Signature attribute in class file %s",
3316     signature_index, CHECK);
3317   set_class_generic_signature_index(signature_index);
3318 }
3319 
3320 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3321                                                                   ConstantPool* cp,
3322                                                                   u4 attribute_byte_length,
3323                                                                   TRAPS) {
3324   assert(cfs != NULL, "invariant");
3325   assert(cp != NULL, "invariant");
3326 
3327   const u1* const current_start = cfs->current();
3328 
3329   guarantee_property(attribute_byte_length >= sizeof(u2),
3330                      "Invalid BootstrapMethods attribute length %u in class file %s",
3331                      attribute_byte_length,
3332                      CHECK);
3333 
3334   cfs->guarantee_more(attribute_byte_length, CHECK);
3335 
3336   const int attribute_array_length = cfs->get_u2_fast();
3337 
3338   guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
3339                      "Short length on BootstrapMethods in class file %s",
3340                      CHECK);
3341 
3342 
3343   // The attribute contains a counted array of counted tuples of shorts,
3344   // represending bootstrap specifiers:
3345   //    length*{bootstrap_method_index, argument_count*{argument_index}}
3346   const int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3347   // operand_count = number of shorts in attr, except for leading length
3348 
3349   // The attribute is copied into a short[] array.
3350   // The array begins with a series of short[2] pairs, one for each tuple.
3351   const int index_size = (attribute_array_length * 2);
3352 
3353   Array<u2>* const operands =
3354     MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
3355 
3356   // Eagerly assign operands so they will be deallocated with the constant
3357   // pool if there is an error.
3358   cp->set_operands(operands);
3359 
3360   int operand_fill_index = index_size;
3361   const int cp_size = cp->length();
3362 
3363   for (int n = 0; n < attribute_array_length; n++) {
3364     // Store a 32-bit offset into the header of the operand array.
3365     ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
3366 
3367     // Read a bootstrap specifier.
3368     cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
3369     const u2 bootstrap_method_index = cfs->get_u2_fast();
3370     const u2 argument_count = cfs->get_u2_fast();
3371     check_property(
3372       valid_cp_range(bootstrap_method_index, cp_size) &&
3373       cp->tag_at(bootstrap_method_index).is_method_handle(),
3374       "bootstrap_method_index %u has bad constant type in class file %s",
3375       bootstrap_method_index,
3376       CHECK);
3377 
3378     guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
3379       "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
3380       CHECK);
3381 
3382     operands->at_put(operand_fill_index++, bootstrap_method_index);
3383     operands->at_put(operand_fill_index++, argument_count);
3384 
3385     cfs->guarantee_more(sizeof(u2) * argument_count, CHECK);  // argv[argc]
3386     for (int j = 0; j < argument_count; j++) {
3387       const u2 argument_index = cfs->get_u2_fast();
3388       check_property(
3389         valid_cp_range(argument_index, cp_size) &&
3390         cp->tag_at(argument_index).is_loadable_constant(),
3391         "argument_index %u has bad constant type in class file %s",
3392         argument_index,
3393         CHECK);
3394       operands->at_put(operand_fill_index++, argument_index);
3395     }
3396   }
3397   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3398                      "Bad length on BootstrapMethods in class file %s",
3399                      CHECK);
3400 }
3401 
3402 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3403                                                  ConstantPool* cp,
3404                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3405                                                  TRAPS) {
3406   assert(cfs != NULL, "invariant");
3407   assert(cp != NULL, "invariant");
3408   assert(parsed_annotations != NULL, "invariant");
3409 
3410   // Set inner classes attribute to default sentinel
3411   _inner_classes = Universe::the_empty_short_array();
3412   cfs->guarantee_more(2, CHECK);  // attributes_count
3413   u2 attributes_count = cfs->get_u2_fast();
3414   bool parsed_sourcefile_attribute = false;
3415   bool parsed_innerclasses_attribute = false;
3416   bool parsed_value_types_attribute = false;
3417   bool parsed_enclosingmethod_attribute = false;
3418   bool parsed_bootstrap_methods_attribute = false;
3419   const u1* runtime_visible_annotations = NULL;
3420   int runtime_visible_annotations_length = 0;
3421   const u1* runtime_invisible_annotations = NULL;
3422   int runtime_invisible_annotations_length = 0;
3423   const u1* runtime_visible_type_annotations = NULL;
3424   int runtime_visible_type_annotations_length = 0;
3425   const u1* runtime_invisible_type_annotations = NULL;
3426   int runtime_invisible_type_annotations_length = 0;
3427   bool runtime_invisible_type_annotations_exists = false;
3428   bool runtime_invisible_annotations_exists = false;
3429   bool parsed_source_debug_ext_annotations_exist = false;
3430   const u1* inner_classes_attribute_start = NULL;
3431   u4  inner_classes_attribute_length = 0;
3432   const u1* value_types_attribute_start = NULL;
3433   u4 value_types_attribute_length = 0;
3434   u2  enclosing_method_class_index = 0;
3435   u2  enclosing_method_method_index = 0;
3436   // Iterate over attributes
3437   while (attributes_count--) {
3438     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3439     const u2 attribute_name_index = cfs->get_u2_fast();
3440     const u4 attribute_length = cfs->get_u4_fast();
3441     check_property(
3442       valid_symbol_at(attribute_name_index),
3443       "Attribute name has bad constant pool index %u in class file %s",
3444       attribute_name_index, CHECK);
3445     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3446     if (tag == vmSymbols::tag_source_file()) {
3447       // Check for SourceFile tag
3448       if (_need_verify) {
3449         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3450       }
3451       if (parsed_sourcefile_attribute) {
3452         classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
3453       } else {
3454         parsed_sourcefile_attribute = true;
3455       }
3456       parse_classfile_sourcefile_attribute(cfs, CHECK);
3457     } else if (tag == vmSymbols::tag_source_debug_extension()) {
3458       // Check for SourceDebugExtension tag
3459       if (parsed_source_debug_ext_annotations_exist) {
3460           classfile_parse_error(
3461             "Multiple SourceDebugExtension attributes in class file %s", CHECK);
3462       }
3463       parsed_source_debug_ext_annotations_exist = true;
3464       parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3465     } else if (tag == vmSymbols::tag_inner_classes()) {
3466       // Check for InnerClasses tag
3467       if (parsed_innerclasses_attribute) {
3468         classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
3469       } else {
3470         parsed_innerclasses_attribute = true;
3471       }
3472       inner_classes_attribute_start = cfs->current();
3473       inner_classes_attribute_length = attribute_length;
3474       cfs->skip_u1(inner_classes_attribute_length, CHECK);
3475     } else if (tag == vmSymbols::tag_value_types()) {
3476       // Check for ValueTypes tag
3477       if (parsed_value_types_attribute) {
3478         classfile_parse_error("Multiple ValueTypes attributes in class file %s", CHECK);
3479       } else {
3480         parsed_value_types_attribute = true;
3481       }
3482       value_types_attribute_start = cfs->current();
3483       value_types_attribute_length = attribute_length;
3484       cfs->skip_u1(value_types_attribute_length, CHECK);
3485     } else if (tag == vmSymbols::tag_synthetic()) {
3486       // Check for Synthetic tag
3487       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3488       if (attribute_length != 0) {
3489         classfile_parse_error(
3490           "Invalid Synthetic classfile attribute length %u in class file %s",
3491           attribute_length, CHECK);
3492       }
3493       parse_classfile_synthetic_attribute(CHECK);
3494     } else if (tag == vmSymbols::tag_deprecated()) {
3495       // Check for Deprecatd tag - 4276120
3496       if (attribute_length != 0) {
3497         classfile_parse_error(
3498           "Invalid Deprecated classfile attribute length %u in class file %s",
3499           attribute_length, CHECK);
3500       }
3501     } else if (_major_version >= JAVA_1_5_VERSION) {
3502       if (tag == vmSymbols::tag_signature()) {
3503         if (_generic_signature_index != 0) {
3504           classfile_parse_error(
3505             "Multiple Signature attributes in class file %s", CHECK);
3506         }
3507         if (attribute_length != 2) {
3508           classfile_parse_error(
3509             "Wrong Signature attribute length %u in class file %s",
3510             attribute_length, CHECK);
3511         }
3512         parse_classfile_signature_attribute(cfs, CHECK);
3513       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3514         if (runtime_visible_annotations != NULL) {
3515           classfile_parse_error(
3516             "Multiple RuntimeVisibleAnnotations attributes in class file %s", CHECK);
3517         }
3518         runtime_visible_annotations_length = attribute_length;
3519         runtime_visible_annotations = cfs->current();
3520         assert(runtime_visible_annotations != NULL, "null visible annotations");
3521         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3522         parse_annotations(cp,
3523                           runtime_visible_annotations,
3524                           runtime_visible_annotations_length,
3525                           parsed_annotations,
3526                           _loader_data,
3527                           CHECK);
3528         cfs->skip_u1_fast(runtime_visible_annotations_length);
3529       } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3530         if (runtime_invisible_annotations_exists) {
3531           classfile_parse_error(
3532             "Multiple RuntimeInvisibleAnnotations attributes in class file %s", CHECK);
3533         }
3534         runtime_invisible_annotations_exists = true;
3535         if (PreserveAllAnnotations) {
3536           runtime_invisible_annotations_length = attribute_length;
3537           runtime_invisible_annotations = cfs->current();
3538           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
3539         }
3540         cfs->skip_u1(attribute_length, CHECK);
3541       } else if (tag == vmSymbols::tag_enclosing_method()) {
3542         if (parsed_enclosingmethod_attribute) {
3543           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
3544         } else {
3545           parsed_enclosingmethod_attribute = true;
3546         }
3547         guarantee_property(attribute_length == 4,
3548           "Wrong EnclosingMethod attribute length %u in class file %s",
3549           attribute_length, CHECK);
3550         cfs->guarantee_more(4, CHECK);  // class_index, method_index
3551         enclosing_method_class_index  = cfs->get_u2_fast();
3552         enclosing_method_method_index = cfs->get_u2_fast();
3553         if (enclosing_method_class_index == 0) {
3554           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
3555         }
3556         // Validate the constant pool indices and types
3557         check_property(valid_klass_reference_at(enclosing_method_class_index),
3558           "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3559         if (enclosing_method_method_index != 0 &&
3560             (!cp->is_within_bounds(enclosing_method_method_index) ||
3561              !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3562           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
3563         }
3564       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3565                  _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3566         if (parsed_bootstrap_methods_attribute) {
3567           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
3568         }
3569         parsed_bootstrap_methods_attribute = true;
3570         parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3571       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3572         if (runtime_visible_type_annotations != NULL) {
3573           classfile_parse_error(
3574             "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);
3575         }
3576         runtime_visible_type_annotations_length = attribute_length;
3577         runtime_visible_type_annotations = cfs->current();
3578         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
3579         // No need for the VM to parse Type annotations
3580         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3581       } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3582         if (runtime_invisible_type_annotations_exists) {
3583           classfile_parse_error(
3584             "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);
3585         } else {
3586           runtime_invisible_type_annotations_exists = true;
3587         }
3588         if (PreserveAllAnnotations) {
3589           runtime_invisible_type_annotations_length = attribute_length;
3590           runtime_invisible_type_annotations = cfs->current();
3591           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
3592         }
3593         cfs->skip_u1(attribute_length, CHECK);
3594       } else {
3595         // Unknown attribute
3596         cfs->skip_u1(attribute_length, CHECK);
3597       }
3598     } else {
3599       // Unknown attribute
3600       cfs->skip_u1(attribute_length, CHECK);
3601     }
3602   }
3603   _annotations = assemble_annotations(runtime_visible_annotations,
3604                                       runtime_visible_annotations_length,
3605                                       runtime_invisible_annotations,
3606                                       runtime_invisible_annotations_length,
3607                                       CHECK);
3608   _type_annotations = assemble_annotations(runtime_visible_type_annotations,
3609                                            runtime_visible_type_annotations_length,
3610                                            runtime_invisible_type_annotations,
3611                                            runtime_invisible_type_annotations_length,
3612                                            CHECK);
3613 
3614   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3615     const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3616                             cfs,
3617                             inner_classes_attribute_start,
3618                             parsed_innerclasses_attribute,
3619                             enclosing_method_class_index,
3620                             enclosing_method_method_index,
3621                             CHECK);
3622     if (parsed_innerclasses_attribute &&_need_verify && _major_version >= JAVA_1_5_VERSION) {
3623       guarantee_property(
3624         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3625         "Wrong InnerClasses attribute length in class file %s", CHECK);
3626     }
3627   }
3628 
3629   if (parsed_value_types_attribute) {
3630     parse_value_types_attribute(cfs, value_types_attribute_start, CHECK);
3631   }
3632 
3633   if (_max_bootstrap_specifier_index >= 0) {
3634     guarantee_property(parsed_bootstrap_methods_attribute,
3635                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3636   }
3637 }
3638 
3639 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3640   assert(k != NULL, "invariant");
3641 
3642   if (_synthetic_flag)
3643     k->set_is_synthetic();
3644   if (_sourcefile_index != 0) {
3645     k->set_source_file_name_index(_sourcefile_index);
3646   }
3647   if (_generic_signature_index != 0) {
3648     k->set_generic_signature_index(_generic_signature_index);
3649   }
3650   if (_sde_buffer != NULL) {
3651     k->set_source_debug_extension(_sde_buffer, _sde_length);
3652   }
3653 }
3654 
3655 // Create the Annotations object that will
3656 // hold the annotations array for the Klass.
3657 void ClassFileParser::create_combined_annotations(TRAPS) {
3658     if (_annotations == NULL &&
3659         _type_annotations == NULL &&
3660         _fields_annotations == NULL &&
3661         _fields_type_annotations == NULL) {
3662       // Don't create the Annotations object unnecessarily.
3663       return;
3664     }
3665 
3666     Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3667     annotations->set_class_annotations(_annotations);
3668     annotations->set_class_type_annotations(_type_annotations);
3669     annotations->set_fields_annotations(_fields_annotations);
3670     annotations->set_fields_type_annotations(_fields_type_annotations);
3671 
3672     // This is the Annotations object that will be
3673     // assigned to InstanceKlass being constructed.
3674     _combined_annotations = annotations;
3675 
3676     // The annotations arrays below has been transfered the
3677     // _combined_annotations so these fields can now be cleared.
3678     _annotations             = NULL;
3679     _type_annotations        = NULL;
3680     _fields_annotations      = NULL;
3681     _fields_type_annotations = NULL;
3682 }
3683 
3684 // Transfer ownership of metadata allocated to the InstanceKlass.
3685 void ClassFileParser::apply_parsed_class_metadata(
3686                                             InstanceKlass* this_klass,
3687                                             int java_fields_count, TRAPS) {
3688   assert(this_klass != NULL, "invariant");
3689 
3690   _cp->set_pool_holder(this_klass);
3691   this_klass->set_constants(_cp);
3692   this_klass->set_fields(_fields, java_fields_count);
3693   this_klass->set_methods(_methods);
3694   this_klass->set_inner_classes(_inner_classes);
3695   this_klass->set_value_types(_value_types);
3696   this_klass->set_local_interfaces(_local_interfaces);
3697   this_klass->set_transitive_interfaces(_transitive_interfaces);
3698   this_klass->set_annotations(_combined_annotations);
3699 
3700   // Clear out these fields so they don't get deallocated by the destructor
3701   clear_class_metadata();
3702 }
3703 
3704 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3705                                                        int runtime_visible_annotations_length,
3706                                                        const u1* const runtime_invisible_annotations,
3707                                                        int runtime_invisible_annotations_length,
3708                                                        TRAPS) {
3709   AnnotationArray* annotations = NULL;
3710   if (runtime_visible_annotations != NULL ||
3711       runtime_invisible_annotations != NULL) {
3712     annotations = MetadataFactory::new_array<u1>(_loader_data,
3713                                           runtime_visible_annotations_length +
3714                                           runtime_invisible_annotations_length,
3715                                           CHECK_(annotations));
3716     if (runtime_visible_annotations != NULL) {
3717       for (int i = 0; i < runtime_visible_annotations_length; i++) {
3718         annotations->at_put(i, runtime_visible_annotations[i]);
3719       }
3720     }
3721     if (runtime_invisible_annotations != NULL) {
3722       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3723         int append = runtime_visible_annotations_length+i;
3724         annotations->at_put(append, runtime_invisible_annotations[i]);
3725       }
3726     }
3727   }
3728   return annotations;
3729 }
3730 
3731 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3732                                                         const int super_class_index,
3733                                                         const bool need_verify,
3734                                                         TRAPS) {
3735   assert(cp != NULL, "invariant");
3736   const InstanceKlass* super_klass = NULL;
3737 
3738   if (super_class_index == 0) {
3739     check_property(_class_name == vmSymbols::java_lang_Object()
3740                    || (_access_flags.get_flags() & JVM_ACC_VALUE),
3741                    "Invalid superclass index %u in class file %s",
3742                    super_class_index,
3743                    CHECK_NULL);
3744   } else {
3745     check_property(valid_klass_reference_at(super_class_index),
3746                    "Invalid superclass index %u in class file %s",
3747                    super_class_index,
3748                    CHECK_NULL);
3749     // The class name should be legal because it is checked when parsing constant pool.
3750     // However, make sure it is not an array type.
3751     bool is_array = false;
3752     if (cp->tag_at(super_class_index).is_klass()) {
3753       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3754       if (need_verify)
3755         is_array = super_klass->is_array_klass();
3756     } else if (need_verify) {
3757       is_array = (cp->klass_name_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
3758     }
3759     if (need_verify) {
3760       guarantee_property(!is_array,
3761                         "Bad superclass name in class file %s", CHECK_NULL);
3762     }
3763   }
3764   return super_klass;
3765 }
3766 
3767 #ifndef PRODUCT
3768 static void print_field_layout(const Symbol* name,
3769                                Array<u2>* fields,
3770                                const constantPoolHandle& cp,
3771                                int instance_size,
3772                                int instance_fields_start,
3773                                int instance_fields_end,
3774                                int static_fields_end) {
3775 
3776   assert(name != NULL, "invariant");
3777 
3778   tty->print("%s: field layout\n", name->as_klass_external_name());
3779   tty->print("  @%3d %s\n", instance_fields_start, "--- instance fields start ---");
3780   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3781     if (!fs.access_flags().is_static()) {
3782       tty->print("  @%3d \"%s\" %s\n",
3783         fs.offset(),
3784         fs.name()->as_klass_external_name(),
3785         fs.signature()->as_klass_external_name());
3786     }
3787   }
3788   tty->print("  @%3d %s\n", instance_fields_end, "--- instance fields end ---");
3789   tty->print("  @%3d %s\n", instance_size * wordSize, "--- instance ends ---");
3790   tty->print("  @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");
3791   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3792     if (fs.access_flags().is_static()) {
3793       tty->print("  @%3d \"%s\" %s\n",
3794         fs.offset(),
3795         fs.name()->as_klass_external_name(),
3796         fs.signature()->as_klass_external_name());
3797     }
3798   }
3799   tty->print("  @%3d %s\n", static_fields_end, "--- static fields end ---");
3800   tty->print("\n");
3801 }
3802 #endif
3803 
3804 // Values needed for oopmap and InstanceKlass creation
3805 class ClassFileParser::FieldLayoutInfo : public ResourceObj {
3806  public:
3807   OopMapBlocksBuilder* oop_map_blocks;
3808   int           instance_size;
3809   int           nonstatic_field_size;
3810   int           static_field_size;
3811   bool          has_nonstatic_fields;
3812 };
3813 
3814 // Utility to collect and compact oop maps during layout
3815 class ClassFileParser::OopMapBlocksBuilder : public ResourceObj {
3816  public:
3817   OopMapBlock*  nonstatic_oop_maps;
3818   unsigned int  nonstatic_oop_map_count;
3819   unsigned int  max_nonstatic_oop_maps;
3820 
3821  public:
3822   OopMapBlocksBuilder(unsigned int  max_blocks, TRAPS) {
3823     max_nonstatic_oop_maps = max_blocks;
3824     nonstatic_oop_map_count = 0;
3825     if (max_blocks == 0) {
3826       nonstatic_oop_maps = NULL;
3827     } else {
3828       nonstatic_oop_maps = NEW_RESOURCE_ARRAY_IN_THREAD(
3829         THREAD, OopMapBlock, max_nonstatic_oop_maps);
3830       memset(nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3831     }
3832   }
3833 
3834   OopMapBlock* last_oop_map() const {
3835     assert(nonstatic_oop_map_count > 0, "Has no oop maps");
3836     return nonstatic_oop_maps + (nonstatic_oop_map_count - 1);
3837   }
3838 
3839   // addition of super oop maps
3840   void initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
3841     assert(nof_blocks && nonstatic_oop_map_count == 0 &&
3842         nof_blocks <= max_nonstatic_oop_maps, "invariant");
3843 
3844     memcpy(nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
3845     nonstatic_oop_map_count += nof_blocks;
3846   }
3847 
3848   // collection of oops
3849   void add(int offset, int count) {
3850     if (nonstatic_oop_map_count == 0) {
3851       nonstatic_oop_map_count++;
3852     }
3853     OopMapBlock*  nonstatic_oop_map = last_oop_map();
3854     if (nonstatic_oop_map->count() == 0) {  // Unused map, set it up
3855       nonstatic_oop_map->set_offset(offset);
3856       nonstatic_oop_map->set_count(count);
3857     } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
3858       nonstatic_oop_map->increment_count(count);
3859     } else { // Need a new one...
3860       nonstatic_oop_map_count++;
3861       assert(nonstatic_oop_map_count <= max_nonstatic_oop_maps, "range check");
3862       nonstatic_oop_map = last_oop_map();
3863       nonstatic_oop_map->set_offset(offset);
3864       nonstatic_oop_map->set_count(count);
3865     }
3866   }
3867 
3868   // general purpose copy, e.g. into allocated instanceKlass
3869   void copy(OopMapBlock* dst) {
3870     if (nonstatic_oop_map_count != 0) {
3871       memcpy(dst, nonstatic_oop_maps, sizeof(OopMapBlock) * nonstatic_oop_map_count);
3872     }
3873   }
3874 
3875   // Sort and compact adjacent blocks
3876   void compact(TRAPS) {
3877     if (nonstatic_oop_map_count <= 1) {
3878       return;
3879     }
3880     /*
3881      * Since field layout sneeks in oops before values, we will be able to condense
3882      * blocks. There is potential to compact between super, own refs and values
3883      * containing refs.
3884      *
3885      * Currently compaction is slightly limited due to values being 8 byte aligned.
3886      * This may well change: FixMe if doesn't, the code below is fairly general purpose
3887      * and maybe it doesn't need to be.
3888      */
3889     qsort(nonstatic_oop_maps, nonstatic_oop_map_count, sizeof(OopMapBlock),
3890         (_sort_Fn)OopMapBlock::compare_offset);
3891     if (nonstatic_oop_map_count < 2) {
3892       return;
3893     }
3894 
3895      //Make a temp copy, and iterate through and copy back into the orig
3896     ResourceMark rm(THREAD);
3897     OopMapBlock* oop_maps_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, OopMapBlock,
3898         nonstatic_oop_map_count);
3899     OopMapBlock* oop_maps_copy_end = oop_maps_copy + nonstatic_oop_map_count;
3900     copy(oop_maps_copy);
3901     OopMapBlock*  nonstatic_oop_map = nonstatic_oop_maps;
3902     unsigned int new_count = 1;
3903     oop_maps_copy++;
3904     while(oop_maps_copy < oop_maps_copy_end) {
3905       assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
3906       if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
3907         nonstatic_oop_map->increment_count(oop_maps_copy->count());
3908       } else {
3909         nonstatic_oop_map++;
3910         new_count++;
3911         nonstatic_oop_map->set_offset(oop_maps_copy->offset());
3912         nonstatic_oop_map->set_count(oop_maps_copy->count());
3913       }
3914       oop_maps_copy++;
3915     }
3916     assert(new_count <= nonstatic_oop_map_count, "end up with more maps after compact() ?");
3917     nonstatic_oop_map_count = new_count;
3918   }
3919 
3920   void print_on(outputStream* st) const {
3921     st->print_cr("  OopMapBlocks: %3d  /%3d", nonstatic_oop_map_count, max_nonstatic_oop_maps);
3922     if (nonstatic_oop_map_count > 0) {
3923       OopMapBlock* map = nonstatic_oop_maps;
3924       OopMapBlock* last_map = last_oop_map();
3925       assert(map <= last_map, "Last less than first");
3926       while (map <= last_map) {
3927         st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
3928             map->offset() + map->offset_span() - heapOopSize, map->count());
3929         map++;
3930       }
3931     }
3932   }
3933 
3934   void print_value_on(outputStream* st) const {
3935     print_on(st);
3936   }
3937 
3938 };
3939 
3940 void ClassFileParser::throwValueTypeLimitation(THREAD_AND_LOCATION_DECL,
3941                                                const char* msg,
3942                                                const Symbol* name,
3943                                                const Symbol* sig) const {
3944 
3945   ResourceMark rm(THREAD);
3946   if (name == NULL || sig == NULL) {
3947     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
3948         vmSymbols::java_lang_ClassFormatError(),
3949         "class: %s - %s", _class_name->as_C_string(), msg);
3950   }
3951   else {
3952     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
3953         vmSymbols::java_lang_ClassFormatError(),
3954         "\"%s\" sig: \"%s\" class: %s - %s", name->as_C_string(), sig->as_C_string(),
3955         _class_name->as_C_string(), msg);
3956   }
3957 }
3958 
3959 // Layout fields and fill in FieldLayoutInfo.  Could use more refactoring!
3960 void ClassFileParser::layout_fields(ConstantPool* cp,
3961                                     const FieldAllocationCount* fac,
3962                                     const ClassAnnotationCollector* parsed_annotations,
3963                                     FieldLayoutInfo* info,
3964                                     TRAPS) {
3965 
3966   assert(cp != NULL, "invariant");
3967 
3968   // Field size and offset computation
3969   int nonstatic_field_size = _super_klass == NULL ? 0 :
3970                                _super_klass->nonstatic_field_size();
3971   int next_nonstatic_valuetype_offset = 0;
3972   int first_nonstatic_valuetype_offset = 0;
3973 
3974   // Fields that are value types are handled differently depending if they are static or not:
3975   // - static fields are oops
3976   // - non-static fields are embedded
3977 
3978   // Count the contended fields by type.
3979   //
3980   // We ignore static fields, because @Contended is not supported for them.
3981   // The layout code below will also ignore the static fields.
3982   int nonstatic_contended_count = 0;
3983   FieldAllocationCount fac_contended;
3984   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
3985     FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
3986     if (fs.is_contended()) {
3987       fac_contended.count[atype]++;
3988       if (!fs.access_flags().is_static()) {
3989         nonstatic_contended_count++;
3990       }
3991     }
3992   }
3993 
3994 
3995   // Calculate the starting byte offsets
3996   int next_static_oop_offset    = InstanceMirrorKlass::offset_of_static_fields();
3997   // Value types in static fields are not embedded, they are handled with oops
3998   int next_static_double_offset = next_static_oop_offset +
3999                                   ((fac->count[STATIC_OOP] + fac->count[STATIC_FLATTENABLE]) * heapOopSize);
4000   if ( fac->count[STATIC_DOUBLE] &&
4001        (Universe::field_type_should_be_aligned(T_DOUBLE) ||
4002         Universe::field_type_should_be_aligned(T_LONG)) ) {
4003     next_static_double_offset = align_up(next_static_double_offset, BytesPerLong);
4004   }
4005 
4006   int next_static_word_offset   = next_static_double_offset +
4007                                     ((fac->count[STATIC_DOUBLE]) * BytesPerLong);
4008   int next_static_short_offset  = next_static_word_offset +
4009                                     ((fac->count[STATIC_WORD]) * BytesPerInt);
4010   int next_static_byte_offset   = next_static_short_offset +
4011                                   ((fac->count[STATIC_SHORT]) * BytesPerShort);
4012 
4013   int nonstatic_fields_start  = instanceOopDesc::base_offset_in_bytes() +
4014                                 nonstatic_field_size * heapOopSize;
4015 
4016   // First field of value types is aligned on a long boundary in order to ease
4017   // in-lining of value types (with header removal) in packed arrays and
4018   // flatten value types
4019   int initial_value_type_padding = 0;
4020   if (is_value_type()) {
4021     int old = nonstatic_fields_start;
4022     nonstatic_fields_start = align_up(nonstatic_fields_start, BytesPerLong);
4023     initial_value_type_padding = nonstatic_fields_start - old;
4024   }
4025 
4026   int next_nonstatic_field_offset = nonstatic_fields_start;
4027 
4028   const bool is_contended_class     = parsed_annotations->is_contended();
4029 
4030   // Class is contended, pad before all the fields
4031   if (is_contended_class) {
4032     next_nonstatic_field_offset += ContendedPaddingWidth;
4033   }
4034 
4035   // Temporary value types restrictions
4036   if (is_value_type()) {
4037     if (is_contended_class) {
4038       throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support @Contended annotation yet");
4039       return;
4040     }
4041   }
4042 
4043   // Compute the non-contended fields count.
4044   // The packing code below relies on these counts to determine if some field
4045   // can be squeezed into the alignment gap. Contended fields are obviously
4046   // exempt from that.
4047   unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
4048   unsigned int nonstatic_word_count   = fac->count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
4049   unsigned int nonstatic_short_count  = fac->count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
4050   unsigned int nonstatic_byte_count   = fac->count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
4051   unsigned int nonstatic_oop_count    = fac->count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];
4052 
4053   int static_value_type_count = 0;
4054   int nonstatic_value_type_count = 0;
4055   int* nonstatic_value_type_indexes = NULL;
4056   Klass** nonstatic_value_type_klasses = NULL;
4057   unsigned int value_type_oop_map_count = 0;
4058   int not_flattened_value_types = 0;
4059 
4060   int max_nonstatic_value_type = fac->count[NONSTATIC_FLATTENABLE] + 1;
4061 
4062   nonstatic_value_type_indexes = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, int,
4063                                                               max_nonstatic_value_type);
4064   for (int i = 0; i < max_nonstatic_value_type; i++) {
4065     nonstatic_value_type_indexes[i] = -1;
4066   }
4067   nonstatic_value_type_klasses = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, Klass*,
4068                                                               max_nonstatic_value_type);
4069 
4070   for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
4071     if (fs.allocation_type() == STATIC_FLATTENABLE) {
4072       // Pre-resolve the flattenable field and check for value type circularity
4073       // issues.  Note that super-class circularity checks are not needed here
4074       // because flattenable fields can only be in value types and value types
4075       // only have java.lang.Object as their super class.
4076       // Also, note that super-interface circularity checks are not needed
4077       // because interfaces cannot be value types.
4078       ResourceMark rm;
4079       Symbol* sig = fs.signature();
4080       Symbol* name = SymbolTable::lookup(sig->as_C_string() + 1,
4081                                          sig->utf8_length() - 2, CHECK);
4082       if (!InstanceKlass::is_declared_value_type(_cp, _value_types, name)) {
4083         name->decrement_refcount();
4084         THROW(vmSymbols::java_lang_ClassFormatError());
4085       }
4086       name->decrement_refcount();
4087       Klass* klass =
4088         SystemDictionary::resolve_flattenable_field_or_fail(&fs,
4089                                                             Handle(THREAD, _loader_data->class_loader()),
4090                                                             _protection_domain, true, CHECK);
4091       assert(klass != NULL, "Sanity check");
4092       if (!klass->access_flags().is_value_type()) {
4093         THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
4094       }
4095       static_value_type_count++;
4096     } else if (fs.allocation_type() == NONSTATIC_FLATTENABLE) {
4097       // Pre-resolve the flattenable field and check for value type circularity issues.
4098       ResourceMark rm;
4099       Symbol* sig = fs.signature();
4100       Symbol* name = SymbolTable::lookup(sig->as_C_string() + 1,
4101                                          sig->utf8_length() - 2, CHECK);
4102       if (!InstanceKlass::is_declared_value_type(_cp, _value_types, name)) {
4103         name->decrement_refcount();
4104         char* name = fs.name()->as_C_string();
4105         char* signature = fs.signature()->as_C_string();
4106         THROW(vmSymbols::java_lang_ClassFormatError());
4107       }
4108       name->decrement_refcount();
4109       Klass* klass =
4110         SystemDictionary::resolve_flattenable_field_or_fail(&fs,
4111                                                             Handle(THREAD, _loader_data->class_loader()),
4112                                                             _protection_domain, true, CHECK);
4113       assert(klass != NULL, "Sanity check");
4114       if (!klass->access_flags().is_value_type()) {
4115         THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
4116       }
4117       ValueKlass* vk = ValueKlass::cast(klass);
4118       // Conditions to apply flattening or not should be defined in a single place
4119       if ((ValueFieldMaxFlatSize < 0) || (vk->size_helper() * HeapWordSize) <= ValueFieldMaxFlatSize) {
4120         nonstatic_value_type_indexes[nonstatic_value_type_count] = fs.index();
4121         nonstatic_value_type_klasses[nonstatic_value_type_count] = klass;
4122         nonstatic_value_type_count++;
4123 
4124         ValueKlass* vklass = ValueKlass::cast(klass);
4125         if (vklass->contains_oops()) {
4126           value_type_oop_map_count += vklass->nonstatic_oop_map_count();
4127         }
4128         fs.set_flattened(true);
4129       } else {
4130         not_flattened_value_types++;
4131         fs.set_flattened(false);
4132       }
4133     }
4134   }
4135 
4136   // Adjusting non_static_oop_count to take into account not flattened value types;
4137   nonstatic_oop_count += not_flattened_value_types;
4138 
4139   // Total non-static fields count, including every contended field
4140   unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +
4141                                         fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +
4142                                         fac->count[NONSTATIC_OOP] + fac->count[NONSTATIC_FLATTENABLE];
4143 
4144   const bool super_has_nonstatic_fields =
4145           (_super_klass != NULL && _super_klass->has_nonstatic_fields());
4146   const bool has_nonstatic_fields =
4147     super_has_nonstatic_fields || (nonstatic_fields_count != 0);
4148   const bool has_nonstatic_value_fields = nonstatic_value_type_count > 0;
4149 
4150   if (is_value_type() && (!has_nonstatic_fields)) {
4151     // There are a number of fixes required throughout the type system and JIT
4152     throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support zero instance size yet");
4153   }
4154 
4155   // Prepare list of oops for oop map generation.
4156   //
4157   // "offset" and "count" lists are describing the set of contiguous oop
4158   // regions. offset[i] is the start of the i-th region, which then has
4159   // count[i] oops following. Before we know how many regions are required,
4160   // we pessimistically allocate the maps to fit all the oops into the
4161   // distinct regions.
4162   //
4163   int super_oop_map_count = (_super_klass == NULL) ? 0 :_super_klass->nonstatic_oop_map_count();
4164   int max_oop_map_count =
4165       super_oop_map_count +
4166       fac->count[NONSTATIC_OOP] +
4167       value_type_oop_map_count +
4168       not_flattened_value_types;
4169 
4170   OopMapBlocksBuilder* nonstatic_oop_maps = new OopMapBlocksBuilder(max_oop_map_count, THREAD);
4171   if (super_oop_map_count > 0) {
4172     nonstatic_oop_maps->initialize_inherited_blocks(_super_klass->start_of_nonstatic_oop_maps(),
4173                                                     _super_klass->nonstatic_oop_map_count());
4174   }
4175 
4176   int first_nonstatic_oop_offset = 0; // will be set for first oop field
4177 
4178   bool compact_fields   = CompactFields;
4179   int allocation_style = FieldsAllocationStyle;
4180   if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
4181     assert(false, "0 <= FieldsAllocationStyle <= 2");
4182     allocation_style = 1; // Optimistic
4183   }
4184 
4185   // The next classes have predefined hard-coded fields offsets
4186   // (see in JavaClasses::compute_hard_coded_offsets()).
4187   // Use default fields allocation order for them.
4188   if( (allocation_style != 0 || compact_fields ) && _loader_data->class_loader() == NULL &&
4189       (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
4190        _class_name == vmSymbols::java_lang_Class() ||
4191        _class_name == vmSymbols::java_lang_ClassLoader() ||
4192        _class_name == vmSymbols::java_lang_ref_Reference() ||
4193        _class_name == vmSymbols::java_lang_ref_SoftReference() ||
4194        _class_name == vmSymbols::java_lang_StackTraceElement() ||
4195        _class_name == vmSymbols::java_lang_String() ||
4196        _class_name == vmSymbols::java_lang_Throwable() ||
4197        _class_name == vmSymbols::java_lang_Boolean() ||
4198        _class_name == vmSymbols::java_lang_Character() ||
4199        _class_name == vmSymbols::java_lang_Float() ||
4200        _class_name == vmSymbols::java_lang_Double() ||
4201        _class_name == vmSymbols::java_lang_Byte() ||
4202        _class_name == vmSymbols::java_lang_Short() ||
4203        _class_name == vmSymbols::java_lang_Integer() ||
4204        _class_name == vmSymbols::java_lang_Long())) {
4205     allocation_style = 0;     // Allocate oops first
4206     compact_fields   = false; // Don't compact fields
4207   }
4208 
4209   int next_nonstatic_oop_offset = 0;
4210   int next_nonstatic_double_offset = 0;
4211 
4212   // Rearrange fields for a given allocation style
4213   if( allocation_style == 0 ) {
4214     // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
4215     next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4216     next_nonstatic_double_offset = next_nonstatic_oop_offset +
4217                                     (nonstatic_oop_count * heapOopSize);
4218   } else if( allocation_style == 1 ) {
4219     // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
4220     next_nonstatic_double_offset = next_nonstatic_field_offset;
4221   } else if( allocation_style == 2 ) {
4222     // Fields allocation: oops fields in super and sub classes are together.
4223     if( nonstatic_field_size > 0 && super_oop_map_count > 0 ) {
4224       if (next_nonstatic_field_offset == nonstatic_oop_maps->last_oop_map()->end_offset()) {
4225         allocation_style = 0;   // allocate oops first
4226         next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4227         next_nonstatic_double_offset = next_nonstatic_oop_offset +
4228                                        (nonstatic_oop_count * heapOopSize);
4229       }
4230     }
4231     if( allocation_style == 2 ) {
4232       allocation_style = 1;     // allocate oops last
4233       next_nonstatic_double_offset = next_nonstatic_field_offset;
4234     }
4235   } else {
4236     ShouldNotReachHere();
4237   }
4238 
4239   int nonstatic_oop_space_count   = 0;
4240   int nonstatic_word_space_count  = 0;
4241   int nonstatic_short_space_count = 0;
4242   int nonstatic_byte_space_count  = 0;
4243   int nonstatic_oop_space_offset = 0;
4244   int nonstatic_word_space_offset = 0;
4245   int nonstatic_short_space_offset = 0;
4246   int nonstatic_byte_space_offset = 0;
4247 
4248   // Try to squeeze some of the fields into the gaps due to
4249   // long/double alignment.
4250   if (nonstatic_double_count > 0) {
4251     int offset = next_nonstatic_double_offset;
4252     next_nonstatic_double_offset = align_up(offset, BytesPerLong);
4253     if (compact_fields && offset != next_nonstatic_double_offset) {
4254       // Allocate available fields into the gap before double field.
4255       int length = next_nonstatic_double_offset - offset;
4256       assert(length == BytesPerInt, "");
4257       nonstatic_word_space_offset = offset;
4258       if (nonstatic_word_count > 0) {
4259         nonstatic_word_count      -= 1;
4260         nonstatic_word_space_count = 1; // Only one will fit
4261         length -= BytesPerInt;
4262         offset += BytesPerInt;
4263       }
4264       nonstatic_short_space_offset = offset;
4265       while (length >= BytesPerShort && nonstatic_short_count > 0) {
4266         nonstatic_short_count       -= 1;
4267         nonstatic_short_space_count += 1;
4268         length -= BytesPerShort;
4269         offset += BytesPerShort;
4270       }
4271       nonstatic_byte_space_offset = offset;
4272       while (length > 0 && nonstatic_byte_count > 0) {
4273         nonstatic_byte_count       -= 1;
4274         nonstatic_byte_space_count += 1;
4275         length -= 1;
4276       }
4277       // Allocate oop field in the gap if there are no other fields for that.
4278       nonstatic_oop_space_offset = offset;
4279       if (length >= heapOopSize && nonstatic_oop_count > 0 &&
4280           allocation_style != 0) { // when oop fields not first
4281         nonstatic_oop_count      -= 1;
4282         nonstatic_oop_space_count = 1; // Only one will fit
4283         length -= heapOopSize;
4284         offset += heapOopSize;
4285       }
4286     }
4287   }
4288 
4289   int next_nonstatic_word_offset = next_nonstatic_double_offset +
4290                                      (nonstatic_double_count * BytesPerLong);
4291   int next_nonstatic_short_offset = next_nonstatic_word_offset +
4292                                       (nonstatic_word_count * BytesPerInt);
4293   int next_nonstatic_byte_offset = next_nonstatic_short_offset +
4294                                      (nonstatic_short_count * BytesPerShort);
4295   int next_nonstatic_padded_offset = next_nonstatic_byte_offset +
4296                                        nonstatic_byte_count;
4297 
4298   // let oops jump before padding with this allocation style
4299   if( allocation_style == 1 ) {
4300     next_nonstatic_oop_offset = next_nonstatic_padded_offset;
4301     if( nonstatic_oop_count > 0 ) {
4302       next_nonstatic_oop_offset = align_up(next_nonstatic_oop_offset, heapOopSize);
4303     }
4304     next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
4305   }
4306 
4307   // Aligning embedded value types
4308   // bug below, the current algorithm to layout embedded value types always put them at the
4309   // end of the layout, which doesn't match the different allocation policies the VM is
4310   // supposed to provide => FixMe
4311   // Note also that the current alignment policy is to make each value type starting on a
4312   // 64 bits boundary. This could be optimized later. For instance, it could be nice to
4313   // align value types according to their most constrained internal type.
4314   next_nonstatic_valuetype_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4315   int next_value_type_index = 0;
4316 
4317   // Iterate over fields again and compute correct offsets.
4318   // The field allocation type was temporarily stored in the offset slot.
4319   // oop fields are located before non-oop fields (static and non-static).
4320   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4321 
4322     // skip already laid out fields
4323     if (fs.is_offset_set()) continue;
4324 
4325     // contended instance fields are handled below
4326     if (fs.is_contended() && !fs.access_flags().is_static()) continue;
4327 
4328     int real_offset = 0;
4329     const FieldAllocationType atype = (const FieldAllocationType) fs.allocation_type();
4330 
4331     // pack the rest of the fields
4332     switch (atype) {
4333       // Value types in static fields are handled with oops
4334       case STATIC_FLATTENABLE:   // Fallthrough
4335       case STATIC_OOP:
4336         real_offset = next_static_oop_offset;
4337         next_static_oop_offset += heapOopSize;
4338         break;
4339       case STATIC_BYTE:
4340         real_offset = next_static_byte_offset;
4341         next_static_byte_offset += 1;
4342         break;
4343       case STATIC_SHORT:
4344         real_offset = next_static_short_offset;
4345         next_static_short_offset += BytesPerShort;
4346         break;
4347       case STATIC_WORD:
4348         real_offset = next_static_word_offset;
4349         next_static_word_offset += BytesPerInt;
4350         break;
4351       case STATIC_DOUBLE:
4352         real_offset = next_static_double_offset;
4353         next_static_double_offset += BytesPerLong;
4354         break;
4355       case NONSTATIC_FLATTENABLE:
4356         if (fs.is_flattened()) {
4357           Klass* klass = nonstatic_value_type_klasses[next_value_type_index];
4358           assert(klass != NULL, "Klass should have been loaded and resolved earlier");
4359           assert(klass->access_flags().is_value_type(),"Must be a value type");
4360           ValueKlass* vklass = ValueKlass::cast(klass);
4361           real_offset = next_nonstatic_valuetype_offset;
4362           next_nonstatic_valuetype_offset += (vklass->size_helper()) * wordSize - vklass->first_field_offset();
4363           // aligning next value type on a 64 bits boundary
4364           next_nonstatic_valuetype_offset = align_up(next_nonstatic_valuetype_offset, BytesPerLong);
4365           next_value_type_index += 1;
4366 
4367           if (vklass->contains_oops()) { // add flatten oop maps
4368             int diff = real_offset - vklass->first_field_offset();
4369             const OopMapBlock* map = vklass->start_of_nonstatic_oop_maps();
4370             const OopMapBlock* const last_map = map + vklass->nonstatic_oop_map_count();
4371             while (map < last_map) {
4372               nonstatic_oop_maps->add(map->offset() + diff, map->count());
4373               map++;
4374             }
4375           }
4376           break;
4377         } else {
4378           // Fall through
4379         }
4380       case NONSTATIC_OOP:
4381         if( nonstatic_oop_space_count > 0 ) {
4382           real_offset = nonstatic_oop_space_offset;
4383           nonstatic_oop_space_offset += heapOopSize;
4384           nonstatic_oop_space_count  -= 1;
4385         } else {
4386           real_offset = next_nonstatic_oop_offset;
4387           next_nonstatic_oop_offset += heapOopSize;
4388         }
4389         nonstatic_oop_maps->add(real_offset, 1);
4390         break;
4391       case NONSTATIC_BYTE:
4392         if( nonstatic_byte_space_count > 0 ) {
4393           real_offset = nonstatic_byte_space_offset;
4394           nonstatic_byte_space_offset += 1;
4395           nonstatic_byte_space_count  -= 1;
4396         } else {
4397           real_offset = next_nonstatic_byte_offset;
4398           next_nonstatic_byte_offset += 1;
4399         }
4400         break;
4401       case NONSTATIC_SHORT:
4402         if( nonstatic_short_space_count > 0 ) {
4403           real_offset = nonstatic_short_space_offset;
4404           nonstatic_short_space_offset += BytesPerShort;
4405           nonstatic_short_space_count  -= 1;
4406         } else {
4407           real_offset = next_nonstatic_short_offset;
4408           next_nonstatic_short_offset += BytesPerShort;
4409         }
4410         break;
4411       case NONSTATIC_WORD:
4412         if( nonstatic_word_space_count > 0 ) {
4413           real_offset = nonstatic_word_space_offset;
4414           nonstatic_word_space_offset += BytesPerInt;
4415           nonstatic_word_space_count  -= 1;
4416         } else {
4417           real_offset = next_nonstatic_word_offset;
4418           next_nonstatic_word_offset += BytesPerInt;
4419         }
4420         break;
4421       case NONSTATIC_DOUBLE:
4422         real_offset = next_nonstatic_double_offset;
4423         next_nonstatic_double_offset += BytesPerLong;
4424         break;
4425       default:
4426         ShouldNotReachHere();
4427     }
4428     fs.set_offset(real_offset);
4429   }
4430 
4431 
4432   // Handle the contended cases.
4433   //
4434   // Each contended field should not intersect the cache line with another contended field.
4435   // In the absence of alignment information, we end up with pessimistically separating
4436   // the fields with full-width padding.
4437   //
4438   // Additionally, this should not break alignment for the fields, so we round the alignment up
4439   // for each field.
4440   if (nonstatic_contended_count > 0) {
4441 
4442     // if there is at least one contended field, we need to have pre-padding for them
4443     next_nonstatic_padded_offset += ContendedPaddingWidth;
4444 
4445     // collect all contended groups
4446     ResourceBitMap bm(cp->size());
4447     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4448       // skip already laid out fields
4449       if (fs.is_offset_set()) continue;
4450 
4451       if (fs.is_contended()) {
4452         bm.set_bit(fs.contended_group());
4453       }
4454     }
4455 
4456     int current_group = -1;
4457     while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
4458 
4459       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4460 
4461         // skip already laid out fields
4462         if (fs.is_offset_set()) continue;
4463 
4464         // skip non-contended fields and fields from different group
4465         if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
4466 
4467         // handle statics below
4468         if (fs.access_flags().is_static()) continue;
4469 
4470         int real_offset = 0;
4471         FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
4472 
4473         switch (atype) {
4474           case NONSTATIC_BYTE:
4475             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, 1);
4476             real_offset = next_nonstatic_padded_offset;
4477             next_nonstatic_padded_offset += 1;
4478             break;
4479 
4480           case NONSTATIC_SHORT:
4481             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerShort);
4482             real_offset = next_nonstatic_padded_offset;
4483             next_nonstatic_padded_offset += BytesPerShort;
4484             break;
4485 
4486           case NONSTATIC_WORD:
4487             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerInt);
4488             real_offset = next_nonstatic_padded_offset;
4489             next_nonstatic_padded_offset += BytesPerInt;
4490             break;
4491 
4492           case NONSTATIC_DOUBLE:
4493             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4494             real_offset = next_nonstatic_padded_offset;
4495             next_nonstatic_padded_offset += BytesPerLong;
4496             break;
4497 
4498             // Value types in static fields are handled with oops
4499           case NONSTATIC_FLATTENABLE:
4500             throwValueTypeLimitation(THREAD_AND_LOCATION,
4501                                      "@Contended annotation not supported for value types yet", fs.name(), fs.signature());
4502             return;
4503 
4504           case NONSTATIC_OOP:
4505             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, heapOopSize);
4506             real_offset = next_nonstatic_padded_offset;
4507             next_nonstatic_padded_offset += heapOopSize;
4508             nonstatic_oop_maps->add(real_offset, 1);
4509             break;
4510 
4511           default:
4512             ShouldNotReachHere();
4513         }
4514 
4515         if (fs.contended_group() == 0) {
4516           // Contended group defines the equivalence class over the fields:
4517           // the fields within the same contended group are not inter-padded.
4518           // The only exception is default group, which does not incur the
4519           // equivalence, and so requires intra-padding.
4520           next_nonstatic_padded_offset += ContendedPaddingWidth;
4521         }
4522 
4523         fs.set_offset(real_offset);
4524       } // for
4525 
4526       // Start laying out the next group.
4527       // Note that this will effectively pad the last group in the back;
4528       // this is expected to alleviate memory contention effects for
4529       // subclass fields and/or adjacent object.
4530       // If this was the default group, the padding is already in place.
4531       if (current_group != 0) {
4532         next_nonstatic_padded_offset += ContendedPaddingWidth;
4533       }
4534     }
4535 
4536     // handle static fields
4537   }
4538 
4539   // Entire class is contended, pad in the back.
4540   // This helps to alleviate memory contention effects for subclass fields
4541   // and/or adjacent object.
4542   if (is_contended_class) {
4543     assert(!is_value_type(), "@Contended not supported for value types yet");
4544     next_nonstatic_padded_offset += ContendedPaddingWidth;
4545   }
4546 
4547   int notaligned_nonstatic_fields_end;
4548   if (nonstatic_value_type_count != 0) {
4549     notaligned_nonstatic_fields_end = next_nonstatic_valuetype_offset;
4550   } else {
4551     notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;
4552   }
4553 
4554   int nonstatic_field_sz_align = heapOopSize;
4555   if (is_value_type()) {
4556     if ((notaligned_nonstatic_fields_end - nonstatic_fields_start) > heapOopSize) {
4557       nonstatic_field_sz_align = BytesPerLong; // value copy of fields only uses jlong copy
4558     }
4559   }
4560   int nonstatic_fields_end      = align_up(notaligned_nonstatic_fields_end, nonstatic_field_sz_align);
4561   int instance_end              = align_up(notaligned_nonstatic_fields_end, wordSize);
4562   int static_fields_end         = align_up(next_static_byte_offset, wordSize);
4563 
4564   int static_field_size         = (static_fields_end -
4565                                    InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
4566   nonstatic_field_size          = nonstatic_field_size +
4567                                   (nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
4568 
4569   int instance_size             = align_object_size(instance_end / wordSize);
4570 
4571   assert(instance_size == align_object_size(align_up(
4572          (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize)
4573          + initial_value_type_padding, wordSize) / wordSize), "consistent layout helper value");
4574 
4575 
4576   // Invariant: nonstatic_field end/start should only change if there are
4577   // nonstatic fields in the class, or if the class is contended. We compare
4578   // against the non-aligned value, so that end alignment will not fail the
4579   // assert without actually having the fields.
4580   assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
4581          is_contended_class ||
4582          (nonstatic_fields_count > 0), "double-check nonstatic start/end");
4583 
4584   // Number of non-static oop map blocks allocated at end of klass.
4585   nonstatic_oop_maps->compact(THREAD);
4586 
4587 #ifndef PRODUCT
4588   if ((PrintFieldLayout && !is_value_type()) ||
4589       (PrintValueLayout && (is_value_type() || has_nonstatic_value_fields))) {
4590     print_field_layout(_class_name,
4591           _fields,
4592           cp,
4593           instance_size,
4594           nonstatic_fields_start,
4595           nonstatic_fields_end,
4596           static_fields_end);
4597     nonstatic_oop_maps->print_on(tty);
4598     tty->print("\n");
4599   }
4600 
4601 #endif
4602   // Pass back information needed for InstanceKlass creation
4603   info->oop_map_blocks = nonstatic_oop_maps;
4604   info->instance_size = instance_size;
4605   info->static_field_size = static_field_size;
4606   info->nonstatic_field_size = nonstatic_field_size;
4607   info->has_nonstatic_fields = has_nonstatic_fields;
4608 }
4609 
4610 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4611   assert(ik != NULL, "invariant");
4612 
4613   const Klass* const super = ik->super();
4614 
4615   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4616   // in which case we don't have to register objects as finalizable
4617   if (!_has_empty_finalizer) {
4618     if (_has_finalizer ||
4619         (super != NULL && super->has_finalizer())) {
4620       ik->set_has_finalizer();
4621     }
4622   }
4623 
4624 #ifdef ASSERT
4625   bool f = false;
4626   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4627                                            vmSymbols::void_method_signature());
4628   if (m != NULL && !m->is_empty_method()) {
4629       f = true;
4630   }
4631 
4632   // Spec doesn't prevent agent from redefinition of empty finalizer.
4633   // Despite the fact that it's generally bad idea and redefined finalizer
4634   // will not work as expected we shouldn't abort vm in this case
4635   if (!ik->has_redefined_this_or_super()) {
4636     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4637   }
4638 #endif
4639 
4640   // Check if this klass supports the java.lang.Cloneable interface
4641   if (SystemDictionary::Cloneable_klass_loaded()) {
4642     if (ik->is_subtype_of(SystemDictionary::Cloneable_klass())) {
4643       ik->set_is_cloneable();
4644     }
4645   }
4646 
4647   // Check if this klass has a vanilla default constructor
4648   if (super == NULL) {
4649     // java.lang.Object has empty default constructor
4650     ik->set_has_vanilla_constructor();
4651   } else {
4652     if (super->has_vanilla_constructor() &&
4653         _has_vanilla_constructor) {
4654       ik->set_has_vanilla_constructor();
4655     }
4656 #ifdef ASSERT
4657     bool v = false;
4658     if (super->has_vanilla_constructor()) {
4659       const Method* const constructor =
4660         ik->find_method(vmSymbols::object_initializer_name(),
4661                        vmSymbols::void_method_signature());
4662       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4663         v = true;
4664       }
4665     }
4666     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4667 #endif
4668   }
4669 
4670   // If it cannot be fast-path allocated, set a bit in the layout helper.
4671   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4672   assert(ik->size_helper() > 0, "layout_helper is initialized");
4673   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4674       || ik->is_abstract() || ik->is_interface()
4675       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4676       || ik->size_helper() >= FastAllocateSizeLimit) {
4677     // Forbid fast-path allocation.
4678     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4679     ik->set_layout_helper(lh);
4680   }
4681 }
4682 
4683 bool ClassFileParser::supports_value_types() const {
4684   // Value types are only supported by class file version 55 and later
4685   return _major_version >= JAVA_11_VERSION;
4686 }
4687 
4688 // Attach super classes and interface classes to class loader data
4689 static void record_defined_class_dependencies(const InstanceKlass* defined_klass,
4690                                               TRAPS) {
4691   assert(defined_klass != NULL, "invariant");
4692 
4693   ClassLoaderData* const defining_loader_data = defined_klass->class_loader_data();
4694   if (defining_loader_data->is_the_null_class_loader_data()) {
4695       // Dependencies to null class loader data are implicit.
4696       return;
4697   } else {
4698     // add super class dependency
4699     Klass* const super = defined_klass->super();
4700     if (super != NULL) {
4701       defining_loader_data->record_dependency(super, CHECK);
4702     }
4703 
4704     // add super interface dependencies
4705     const Array<Klass*>* const local_interfaces = defined_klass->local_interfaces();
4706     if (local_interfaces != NULL) {
4707       const int length = local_interfaces->length();
4708       for (int i = 0; i < length; i++) {
4709         defining_loader_data->record_dependency(local_interfaces->at(i), CHECK);
4710       }
4711     }
4712 
4713     for(int i = 0; i < defined_klass->java_fields_count(); i++) {
4714       if ((defined_klass->field_access_flags(i) & JVM_ACC_FLATTENABLE) != 0) {
4715         const Klass* klass = defined_klass->get_value_field_klass(i);
4716         defining_loader_data->record_dependency(klass, CHECK);
4717       }
4718     }
4719   }
4720 }
4721 
4722 // utility methods for appending an array with check for duplicates
4723 
4724 static void append_interfaces(GrowableArray<Klass*>* result,
4725                               const Array<Klass*>* const ifs) {
4726   // iterate over new interfaces
4727   for (int i = 0; i < ifs->length(); i++) {
4728     Klass* const e = ifs->at(i);
4729     assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");
4730     // add new interface
4731     result->append_if_missing(e);
4732   }
4733 }
4734 
4735 static Array<Klass*>* compute_transitive_interfaces(const InstanceKlass* super,
4736                                                     Array<Klass*>* local_ifs,
4737                                                     ClassLoaderData* loader_data,
4738                                                     TRAPS) {
4739   assert(local_ifs != NULL, "invariant");
4740   assert(loader_data != NULL, "invariant");
4741 
4742   // Compute maximum size for transitive interfaces
4743   int max_transitive_size = 0;
4744   int super_size = 0;
4745   // Add superclass transitive interfaces size
4746   if (super != NULL) {
4747     super_size = super->transitive_interfaces()->length();
4748     max_transitive_size += super_size;
4749   }
4750   // Add local interfaces' super interfaces
4751   const int local_size = local_ifs->length();
4752   for (int i = 0; i < local_size; i++) {
4753     Klass* const l = local_ifs->at(i);
4754     max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();
4755   }
4756   // Finally add local interfaces
4757   max_transitive_size += local_size;
4758   // Construct array
4759   if (max_transitive_size == 0) {
4760     // no interfaces, use canonicalized array
4761     return Universe::the_empty_klass_array();
4762   } else if (max_transitive_size == super_size) {
4763     // no new local interfaces added, share superklass' transitive interface array
4764     return super->transitive_interfaces();
4765   } else if (max_transitive_size == local_size) {
4766     // only local interfaces added, share local interface array
4767     return local_ifs;
4768   } else {
4769     ResourceMark rm;
4770     GrowableArray<Klass*>* const result = new GrowableArray<Klass*>(max_transitive_size);
4771 
4772     // Copy down from superclass
4773     if (super != NULL) {
4774       append_interfaces(result, super->transitive_interfaces());
4775     }
4776 
4777     // Copy down from local interfaces' superinterfaces
4778     for (int i = 0; i < local_size; i++) {
4779       Klass* const l = local_ifs->at(i);
4780       append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());
4781     }
4782     // Finally add local interfaces
4783     append_interfaces(result, local_ifs);
4784 
4785     // length will be less than the max_transitive_size if duplicates were removed
4786     const int length = result->length();
4787     assert(length <= max_transitive_size, "just checking");
4788     Array<Klass*>* const new_result =
4789       MetadataFactory::new_array<Klass*>(loader_data, length, CHECK_NULL);
4790     for (int i = 0; i < length; i++) {
4791       Klass* const e = result->at(i);
4792       assert(e != NULL, "just checking");
4793       new_result->at_put(i, e);
4794     }
4795     return new_result;
4796   }
4797 }
4798 
4799 static void check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4800   assert(this_klass != NULL, "invariant");
4801   const Klass* const super = this_klass->super();
4802   if (super != NULL) {
4803 
4804     // If the loader is not the boot loader then throw an exception if its
4805     // superclass is in package jdk.internal.reflect and its loader is not a
4806     // special reflection class loader
4807     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4808       assert(super->is_instance_klass(), "super is not instance klass");
4809       PackageEntry* super_package = super->package();
4810       if (super_package != NULL &&
4811           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4812           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4813         ResourceMark rm(THREAD);
4814         Exceptions::fthrow(
4815           THREAD_AND_LOCATION,
4816           vmSymbols::java_lang_IllegalAccessError(),
4817           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4818           this_klass->external_name(),
4819           this_klass->class_loader_data()->loader_name(),
4820           super->external_name());
4821         return;
4822       }
4823     }
4824 
4825     Reflection::VerifyClassAccessResults vca_result =
4826       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4827     if (vca_result != Reflection::ACCESS_OK) {
4828       ResourceMark rm(THREAD);
4829       char* msg = Reflection::verify_class_access_msg(this_klass,
4830                                                       InstanceKlass::cast(super),
4831                                                       vca_result);
4832       if (msg == NULL) {
4833         Exceptions::fthrow(
4834           THREAD_AND_LOCATION,
4835           vmSymbols::java_lang_IllegalAccessError(),
4836           "class %s cannot access its superclass %s",
4837           this_klass->external_name(),
4838           super->external_name());
4839       } else {
4840         // Add additional message content.
4841         Exceptions::fthrow(
4842           THREAD_AND_LOCATION,
4843           vmSymbols::java_lang_IllegalAccessError(),
4844           "superclass access check failed: %s",
4845           msg);
4846       }
4847     }
4848   }
4849 }
4850 
4851 
4852 static void check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4853   assert(this_klass != NULL, "invariant");
4854   const Array<Klass*>* const local_interfaces = this_klass->local_interfaces();
4855   const int lng = local_interfaces->length();
4856   for (int i = lng - 1; i >= 0; i--) {
4857     Klass* const k = local_interfaces->at(i);
4858     assert (k != NULL && k->is_interface(), "invalid interface");
4859     Reflection::VerifyClassAccessResults vca_result =
4860       Reflection::verify_class_access(this_klass, InstanceKlass::cast(k), false);
4861     if (vca_result != Reflection::ACCESS_OK) {
4862       ResourceMark rm(THREAD);
4863       char* msg = Reflection::verify_class_access_msg(this_klass,
4864                                                       InstanceKlass::cast(k),
4865                                                       vca_result);
4866       if (msg == NULL) {
4867         Exceptions::fthrow(
4868           THREAD_AND_LOCATION,
4869           vmSymbols::java_lang_IllegalAccessError(),
4870           "class %s cannot access its superinterface %s",
4871           this_klass->external_name(),
4872           k->external_name());
4873       } else {
4874         // Add additional message content.
4875         Exceptions::fthrow(
4876           THREAD_AND_LOCATION,
4877           vmSymbols::java_lang_IllegalAccessError(),
4878           "superinterface check failed: %s",
4879           msg);
4880       }
4881     }
4882   }
4883 }
4884 
4885 
4886 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4887   assert(this_klass != NULL, "invariant");
4888   const Array<Method*>* const methods = this_klass->methods();
4889   const int num_methods = methods->length();
4890 
4891   // go thru each method and check if it overrides a final method
4892   for (int index = 0; index < num_methods; index++) {
4893     const Method* const m = methods->at(index);
4894 
4895     // skip private, static, and <init> methods
4896     if ((!m->is_private() && !m->is_static()) &&
4897         (m->name() != vmSymbols::object_initializer_name())) {
4898 
4899       const Symbol* const name = m->name();
4900       const Symbol* const signature = m->signature();
4901       const Klass* k = this_klass->super();
4902       const Method* super_m = NULL;
4903       while (k != NULL) {
4904         // skip supers that don't have final methods.
4905         if (k->has_final_method()) {
4906           // lookup a matching method in the super class hierarchy
4907           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4908           if (super_m == NULL) {
4909             break; // didn't find any match; get out
4910           }
4911 
4912           if (super_m->is_final() && !super_m->is_static() &&
4913               // matching method in super is final, and not static
4914               (Reflection::verify_field_access(this_klass,
4915                                                super_m->method_holder(),
4916                                                super_m->method_holder(),
4917                                                super_m->access_flags(), false))
4918             // this class can access super final method and therefore override
4919             ) {
4920             ResourceMark rm(THREAD);
4921             Exceptions::fthrow(
4922               THREAD_AND_LOCATION,
4923               vmSymbols::java_lang_VerifyError(),
4924               "class %s overrides final method %s.%s%s",
4925               this_klass->external_name(),
4926               super_m->method_holder()->external_name(),
4927               name->as_C_string(),
4928               signature->as_C_string()
4929             );
4930             return;
4931           }
4932 
4933           // continue to look from super_m's holder's super.
4934           k = super_m->method_holder()->super();
4935           continue;
4936         }
4937 
4938         k = k->super();
4939       }
4940     }
4941   }
4942 }
4943 
4944 
4945 // assumes that this_klass is an interface
4946 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4947   assert(this_klass != NULL, "invariant");
4948   assert(this_klass->is_interface(), "not an interface");
4949   const Array<Method*>* methods = this_klass->methods();
4950   const int num_methods = methods->length();
4951 
4952   for (int index = 0; index < num_methods; index++) {
4953     const Method* const m = methods->at(index);
4954     // if m is static and not the init method, throw a verify error
4955     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4956       ResourceMark rm(THREAD);
4957       Exceptions::fthrow(
4958         THREAD_AND_LOCATION,
4959         vmSymbols::java_lang_VerifyError(),
4960         "Illegal static method %s in interface %s",
4961         m->name()->as_C_string(),
4962         this_klass->external_name()
4963       );
4964       return;
4965     }
4966   }
4967 }
4968 
4969 // utility methods for format checking
4970 
4971 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4972   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4973   const bool is_value_type = (flags & JVM_ACC_VALUE) != 0;
4974   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4975   assert(supports_value_types() || !is_value_type, "JVM_ACC_VALUE should not be set");
4976   if (is_module) {
4977     ResourceMark rm(THREAD);
4978     Exceptions::fthrow(
4979       THREAD_AND_LOCATION,
4980       vmSymbols::java_lang_NoClassDefFoundError(),
4981       "%s is not a class because access_flag ACC_MODULE is set",
4982       _class_name->as_C_string());
4983     return;
4984   }
4985 
4986   if (!_need_verify) { return; }
4987 
4988   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4989   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4990   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4991   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4992   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4993   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4994   const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;
4995 
4996   if ((is_abstract && is_final) ||
4997       (is_interface && !is_abstract) ||
4998       (is_interface && major_gte_15 && (is_super || is_enum)) ||
4999       (!is_interface && major_gte_15 && is_annotation) ||
5000       (is_value_type && (is_interface || is_abstract || is_enum || !is_final))) {
5001     ResourceMark rm(THREAD);
5002     Exceptions::fthrow(
5003       THREAD_AND_LOCATION,
5004       vmSymbols::java_lang_ClassFormatError(),
5005       "Illegal class modifiers in class %s: 0x%X",
5006       _class_name->as_C_string(), flags
5007     );
5008     return;
5009   }
5010 }
5011 
5012 static bool has_illegal_visibility(jint flags) {
5013   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
5014   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
5015   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
5016 
5017   return ((is_public && is_protected) ||
5018           (is_public && is_private) ||
5019           (is_protected && is_private));
5020 }
5021 
5022 static bool is_supported_version(u2 major, u2 minor) {
5023   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
5024   return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
5025          (major <= max_version) &&
5026          ((major != max_version) ||
5027           (minor <= JVM_CLASSFILE_MINOR_VERSION));
5028 }
5029 
5030 void ClassFileParser::verify_legal_field_modifiers(jint flags,
5031                                                    bool is_interface,
5032                                                    bool is_value_type,
5033                                                    TRAPS) const {
5034   if (!_need_verify) { return; }
5035 
5036   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
5037   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
5038   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
5039   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
5040   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
5041   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
5042   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
5043   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
5044   const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
5045 
5046   bool is_illegal = false;
5047 
5048   if (is_interface) {
5049     if (!is_public || !is_static || !is_final || is_private ||
5050         is_protected || is_volatile || is_transient ||
5051         (major_gte_15 && is_enum)) {
5052       is_illegal = true;
5053     }
5054   } else { // not interface
5055     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
5056       is_illegal = true;
5057     } else {
5058       if (is_value_type && !is_static && !is_final) {
5059         is_illegal = true;
5060       }
5061     }
5062   }
5063 
5064   if (is_illegal) {
5065     ResourceMark rm(THREAD);
5066     Exceptions::fthrow(
5067       THREAD_AND_LOCATION,
5068       vmSymbols::java_lang_ClassFormatError(),
5069       "Illegal field modifiers in class %s: 0x%X",
5070       _class_name->as_C_string(), flags);
5071     return;
5072   }
5073 }
5074 
5075 void ClassFileParser::verify_legal_method_modifiers(jint flags,
5076                                                     bool is_interface,
5077                                                     bool is_value_type,
5078                                                     const Symbol* name,
5079                                                     TRAPS) const {
5080   if (!_need_verify) { return; }
5081 
5082   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
5083   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
5084   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
5085   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
5086   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
5087   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
5088   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
5089   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
5090   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
5091   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
5092   const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
5093   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
5094   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
5095 
5096   bool is_illegal = false;
5097 
5098   if (is_interface) {
5099     if (major_gte_8) {
5100       // Class file version is JAVA_8_VERSION or later Methods of
5101       // interfaces may set any of the flags except ACC_PROTECTED,
5102       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
5103       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
5104       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
5105           (is_native || is_protected || is_final || is_synchronized) ||
5106           // If a specific method of a class or interface has its
5107           // ACC_ABSTRACT flag set, it must not have any of its
5108           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
5109           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
5110           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
5111           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
5112           (is_abstract && (is_private || is_static || is_strict))) {
5113         is_illegal = true;
5114       }
5115     } else if (major_gte_15) {
5116       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
5117       if (!is_public || is_private || is_protected || is_static || is_final ||
5118           is_synchronized || is_native || !is_abstract || is_strict) {
5119         is_illegal = true;
5120       }
5121     } else {
5122       // Class file version is pre-JAVA_1_5_VERSION
5123       if (!is_public || is_static || is_final || is_native || !is_abstract) {
5124         is_illegal = true;
5125       }
5126     }
5127   } else { // not interface
5128     if (has_illegal_visibility(flags)) {
5129       is_illegal = true;
5130     } else {
5131       if (is_initializer) {
5132         if (is_static || is_final || is_synchronized || is_native ||
5133             is_abstract || (major_gte_15 && is_bridge)) {
5134           is_illegal = true;
5135         }
5136       } else { // not initializer
5137         if (is_value_type && is_synchronized && !is_static) {
5138           is_illegal = true;
5139         } else {
5140           if (is_abstract) {
5141             if ((is_final || is_native || is_private || is_static ||
5142                 (major_gte_15 && (is_synchronized || is_strict)))) {
5143               is_illegal = true;
5144             }
5145           }
5146         }
5147       }
5148     }
5149   }
5150 
5151   if (is_illegal) {
5152     ResourceMark rm(THREAD);
5153     Exceptions::fthrow(
5154       THREAD_AND_LOCATION,
5155       vmSymbols::java_lang_ClassFormatError(),
5156       "Method %s in class %s has illegal modifiers: 0x%X",
5157       name->as_C_string(), _class_name->as_C_string(), flags);
5158     return;
5159   }
5160 }
5161 
5162 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
5163                                         int length,
5164                                         TRAPS) const {
5165   assert(_need_verify, "only called when _need_verify is true");
5166   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
5167     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
5168   }
5169 }
5170 
5171 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
5172 // In class names, '/' separates unqualified names.  This is verified in this function also.
5173 // Method names also may not contain the characters '<' or '>', unless <init>
5174 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
5175 // method.  Because these names have been checked as special cases before
5176 // calling this method in verify_legal_method_name.
5177 //
5178 // This method is also called from the modular system APIs in modules.cpp
5179 // to verify the validity of module and package names.
5180 bool ClassFileParser::verify_unqualified_name(const char* name,
5181                                               unsigned int length,
5182                                               int type) {
5183   for (const char* p = name; p != name + length;) {
5184     jchar ch = *p;
5185     if (ch < 128) {
5186       if (ch == '.' || ch == ';' || ch == '[' ) {
5187         return false;   // do not permit '.', ';', or '['
5188       }
5189       if (ch == '/') {
5190         // check for '//' or leading or trailing '/' which are not legal
5191         // unqualified name must not be empty
5192         if (type == ClassFileParser::LegalClass) {
5193           if (p == name || p+1 >= name+length || *(p+1) == '/') {
5194            return false;
5195           }
5196         } else {
5197           return false;   // do not permit '/' unless it's class name
5198         }
5199       }
5200       if (type == ClassFileParser::LegalMethod && (ch == '<' || ch == '>')) {
5201         return false;   // do not permit '<' or '>' in method names
5202       }
5203       p++;
5204     } else {
5205       char* tmp_p = UTF8::next(p, &ch);
5206       p = tmp_p;
5207     }
5208   }
5209   return true;
5210 }
5211 
5212 // Take pointer to a string. Skip over the longest part of the string that could
5213 // be taken as a fieldname. Allow '/' if slash_ok is true.
5214 // Return a pointer to just past the fieldname.
5215 // Return NULL if no fieldname at all was found, or in the case of slash_ok
5216 // being true, we saw consecutive slashes (meaning we were looking for a
5217 // qualified path but found something that was badly-formed).
5218 static const char* skip_over_field_name(const char* name,
5219                                         bool slash_ok,
5220                                         unsigned int length) {
5221   const char* p;
5222   jboolean last_is_slash = false;
5223   jboolean not_first_ch = false;
5224 
5225   for (p = name; p != name + length; not_first_ch = true) {
5226     const char* old_p = p;
5227     jchar ch = *p;
5228     if (ch < 128) {
5229       p++;
5230       // quick check for ascii
5231       if ((ch >= 'a' && ch <= 'z') ||
5232         (ch >= 'A' && ch <= 'Z') ||
5233         (ch == '_' || ch == '$') ||
5234         (not_first_ch && ch >= '0' && ch <= '9')) {
5235         last_is_slash = false;
5236         continue;
5237       }
5238       if (slash_ok && ch == '/') {
5239         if (last_is_slash) {
5240           return NULL;  // Don't permit consecutive slashes
5241         }
5242         last_is_slash = true;
5243         continue;
5244       }
5245     }
5246     else {
5247       jint unicode_ch;
5248       char* tmp_p = UTF8::next_character(p, &unicode_ch);
5249       p = tmp_p;
5250       last_is_slash = false;
5251       // Check if ch is Java identifier start or is Java identifier part
5252       // 4672820: call java.lang.Character methods directly without generating separate tables.
5253       EXCEPTION_MARK;
5254 
5255       // return value
5256       JavaValue result(T_BOOLEAN);
5257       // Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart
5258       JavaCallArguments args;
5259       args.push_int(unicode_ch);
5260 
5261       // public static boolean isJavaIdentifierStart(char ch);
5262       JavaCalls::call_static(&result,
5263         SystemDictionary::Character_klass(),
5264         vmSymbols::isJavaIdentifierStart_name(),
5265         vmSymbols::int_bool_signature(),
5266         &args,
5267         THREAD);
5268 
5269       if (HAS_PENDING_EXCEPTION) {
5270         CLEAR_PENDING_EXCEPTION;
5271         return 0;
5272       }
5273       if (result.get_jboolean()) {
5274         continue;
5275       }
5276 
5277       if (not_first_ch) {
5278         // public static boolean isJavaIdentifierPart(char ch);
5279         JavaCalls::call_static(&result,
5280           SystemDictionary::Character_klass(),
5281           vmSymbols::isJavaIdentifierPart_name(),
5282           vmSymbols::int_bool_signature(),
5283           &args,
5284           THREAD);
5285 
5286         if (HAS_PENDING_EXCEPTION) {
5287           CLEAR_PENDING_EXCEPTION;
5288           return 0;
5289         }
5290 
5291         if (result.get_jboolean()) {
5292           continue;
5293         }
5294       }
5295     }
5296     return (not_first_ch) ? old_p : NULL;
5297   }
5298   return (not_first_ch) ? p : NULL;
5299 }
5300 
5301 // Take pointer to a string. Skip over the longest part of the string that could
5302 // be taken as a field signature. Allow "void" if void_ok.
5303 // Return a pointer to just past the signature.
5304 // Return NULL if no legal signature is found.
5305 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5306                                                        bool void_ok,
5307                                                        unsigned int length,
5308                                                        TRAPS) const {
5309   unsigned int array_dim = 0;
5310   while (length > 0) {
5311     switch (signature[0]) {
5312     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
5313     case JVM_SIGNATURE_BOOLEAN:
5314     case JVM_SIGNATURE_BYTE:
5315     case JVM_SIGNATURE_CHAR:
5316     case JVM_SIGNATURE_SHORT:
5317     case JVM_SIGNATURE_INT:
5318     case JVM_SIGNATURE_FLOAT:
5319     case JVM_SIGNATURE_LONG:
5320     case JVM_SIGNATURE_DOUBLE:
5321       return signature + 1;
5322     case JVM_SIGNATURE_CLASS:
5323     {
5324       if (_major_version < JAVA_1_5_VERSION) {
5325         // Skip over the class name if one is there
5326         const char* const p = skip_over_field_name(signature + 1, true, --length);
5327 
5328         // The next character better be a semicolon
5329         if (p && (p - signature) > 1 && p[0] == ';') {
5330           return p + 1;
5331         }
5332       }
5333       else {
5334         // Skip leading 'L' and ignore first appearance of ';'
5335         length--;
5336         signature++;
5337         char* c = strchr((char*) signature, ';');
5338         // Format check signature
5339         if (c != NULL) {
5340           ResourceMark rm(THREAD);
5341           int newlen = c - (char*) signature;
5342           char* sig = NEW_RESOURCE_ARRAY(char, newlen + 1);
5343           strncpy(sig, signature, newlen);
5344           sig[newlen] = '\0';
5345 
5346           bool legal = verify_unqualified_name(sig, newlen, LegalClass);
5347           if (!legal) {
5348             classfile_parse_error("Class name contains illegal character "
5349                                   "in descriptor in class file %s",
5350                                   CHECK_0);
5351             return NULL;
5352           }
5353           return signature + newlen + 1;
5354         }
5355       }
5356       return NULL;
5357     }
5358     case JVM_SIGNATURE_ARRAY:
5359       array_dim++;
5360       if (array_dim > 255) {
5361         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
5362         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
5363       }
5364       // The rest of what's there better be a legal signature
5365       signature++;
5366       length--;
5367       void_ok = false;
5368       break;
5369     default:
5370       return NULL;
5371     }
5372   }
5373   return NULL;
5374 }
5375 
5376 // Checks if name is a legal class name.
5377 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5378   if (!_need_verify || _relax_verify) { return; }
5379 
5380   char buf[fixed_buffer_size];
5381   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5382   unsigned int length = name->utf8_length();
5383   bool legal = false;
5384 
5385   if (length > 0) {
5386     const char* p;
5387     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5388       p = skip_over_field_signature(bytes, false, length, CHECK);
5389       legal = (p != NULL) && ((p - bytes) == (int)length);
5390     } else if (_major_version < JAVA_1_5_VERSION) {
5391       if (bytes[0] != '<') {
5392         p = skip_over_field_name(bytes, true, length);
5393         legal = (p != NULL) && ((p - bytes) == (int)length);
5394       }
5395     } else {
5396       // 4900761: relax the constraints based on JSR202 spec
5397       // Class names may be drawn from the entire Unicode character set.
5398       // Identifiers between '/' must be unqualified names.
5399       // The utf8 string has been verified when parsing cpool entries.
5400       legal = verify_unqualified_name(bytes, length, LegalClass);
5401     }
5402   }
5403   if (!legal) {
5404     ResourceMark rm(THREAD);
5405     assert(_class_name != NULL, "invariant");
5406     Exceptions::fthrow(
5407       THREAD_AND_LOCATION,
5408       vmSymbols::java_lang_ClassFormatError(),
5409       "Illegal class name \"%s\" in class file %s", bytes,
5410       _class_name->as_C_string()
5411     );
5412     return;
5413   }
5414 }
5415 
5416 // Checks if name is a legal field name.
5417 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5418   if (!_need_verify || _relax_verify) { return; }
5419 
5420   char buf[fixed_buffer_size];
5421   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5422   unsigned int length = name->utf8_length();
5423   bool legal = false;
5424 
5425   if (length > 0) {
5426     if (_major_version < JAVA_1_5_VERSION) {
5427       if (bytes[0] != '<') {
5428         const char* p = skip_over_field_name(bytes, false, length);
5429         legal = (p != NULL) && ((p - bytes) == (int)length);
5430       }
5431     } else {
5432       // 4881221: relax the constraints based on JSR202 spec
5433       legal = verify_unqualified_name(bytes, length, LegalField);
5434     }
5435   }
5436 
5437   if (!legal) {
5438     ResourceMark rm(THREAD);
5439     assert(_class_name != NULL, "invariant");
5440     Exceptions::fthrow(
5441       THREAD_AND_LOCATION,
5442       vmSymbols::java_lang_ClassFormatError(),
5443       "Illegal field name \"%s\" in class %s", bytes,
5444       _class_name->as_C_string()
5445     );
5446     return;
5447   }
5448 }
5449 
5450 // Checks if name is a legal method name.
5451 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5452   if (!_need_verify || _relax_verify) { return; }
5453 
5454   assert(name != NULL, "method name is null");
5455   char buf[fixed_buffer_size];
5456   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5457   unsigned int length = name->utf8_length();
5458   bool legal = false;
5459 
5460   if (length > 0) {
5461     if (bytes[0] == '<') {
5462       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5463         legal = true;
5464       }
5465     } else if (_major_version < JAVA_1_5_VERSION) {
5466       const char* p;
5467       p = skip_over_field_name(bytes, false, length);
5468       legal = (p != NULL) && ((p - bytes) == (int)length);
5469     } else {
5470       // 4881221: relax the constraints based on JSR202 spec
5471       legal = verify_unqualified_name(bytes, length, LegalMethod);
5472     }
5473   }
5474 
5475   if (!legal) {
5476     ResourceMark rm(THREAD);
5477     assert(_class_name != NULL, "invariant");
5478     Exceptions::fthrow(
5479       THREAD_AND_LOCATION,
5480       vmSymbols::java_lang_ClassFormatError(),
5481       "Illegal method name \"%s\" in class %s", bytes,
5482       _class_name->as_C_string()
5483     );
5484     return;
5485   }
5486 }
5487 
5488 
5489 // Checks if signature is a legal field signature.
5490 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5491                                                    const Symbol* signature,
5492                                                    TRAPS) const {
5493   if (!_need_verify) { return; }
5494 
5495   char buf[fixed_buffer_size];
5496   const char* const bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5497   const unsigned int length = signature->utf8_length();
5498   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5499 
5500   if (p == NULL || (p - bytes) != (int)length) {
5501     throwIllegalSignature("Field", name, signature, CHECK);
5502   }
5503 }
5504 
5505 // Checks if signature is a legal method signature.
5506 // Returns number of parameters
5507 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5508                                                    const Symbol* signature,
5509                                                    TRAPS) const {
5510   if (!_need_verify) {
5511     // make sure caller's args_size will be less than 0 even for non-static
5512     // method so it will be recomputed in compute_size_of_parameters().
5513     return -2;
5514   }
5515 
5516   // Class initializers cannot have args for class format version >= 51.
5517   if (name == vmSymbols::class_initializer_name() &&
5518       signature != vmSymbols::void_method_signature() &&
5519       _major_version >= JAVA_7_VERSION) {
5520     throwIllegalSignature("Method", name, signature, CHECK_0);
5521     return 0;
5522   }
5523 
5524   unsigned int args_size = 0;
5525   char buf[fixed_buffer_size];
5526   const char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5527   unsigned int length = signature->utf8_length();
5528   const char* nextp;
5529 
5530   // The first character must be a '('
5531   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5532     length--;
5533     // Skip over legal field signatures
5534     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5535     while ((length > 0) && (nextp != NULL)) {
5536       args_size++;
5537       if (p[0] == 'J' || p[0] == 'D') {
5538         args_size++;
5539       }
5540       length -= nextp - p;
5541       p = nextp;
5542       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5543     }
5544     // The first non-signature thing better be a ')'
5545     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5546       length--;
5547       if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
5548         // All internal methods must return void
5549         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
5550           return args_size;
5551         }
5552       } else {
5553         // Now we better just have a return value
5554         nextp = skip_over_field_signature(p, true, length, CHECK_0);
5555         if (nextp && ((int)length == (nextp - p))) {
5556           return args_size;
5557         }
5558       }
5559     }
5560   }
5561   // Report error
5562   throwIllegalSignature("Method", name, signature, CHECK_0);
5563   return 0;
5564 }
5565 
5566 int ClassFileParser::static_field_size() const {
5567   assert(_field_info != NULL, "invariant");
5568   return _field_info->static_field_size;
5569 }
5570 
5571 int ClassFileParser::total_oop_map_count() const {
5572   assert(_field_info != NULL, "invariant");
5573   return _field_info->oop_map_blocks->nonstatic_oop_map_count;
5574 }
5575 
5576 jint ClassFileParser::layout_size() const {
5577   assert(_field_info != NULL, "invariant");
5578   return _field_info->instance_size;
5579 }
5580 
5581 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5582                                          const Array<Method*>* methods) {
5583   assert(ik != NULL, "invariant");
5584   assert(methods != NULL, "invariant");
5585 
5586   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5587   // (We used to do this lazily, but now we query it in Rewriter,
5588   // which is eagerly done for every method, so we might as well do it now,
5589   // when everything is fresh in memory.)
5590   const vmSymbols::SID klass_id = Method::klass_id_for_intrinsics(ik);
5591 
5592   if (klass_id != vmSymbols::NO_SID) {
5593     for (int j = 0; j < methods->length(); ++j) {
5594       Method* method = methods->at(j);
5595       method->init_intrinsic_id();
5596 
5597       if (CheckIntrinsics) {
5598         // Check if an intrinsic is defined for method 'method',
5599         // but the method is not annotated with @HotSpotIntrinsicCandidate.
5600         if (method->intrinsic_id() != vmIntrinsics::_none &&
5601             !method->intrinsic_candidate()) {
5602               tty->print("Compiler intrinsic is defined for method [%s], "
5603               "but the method is not annotated with @HotSpotIntrinsicCandidate.%s",
5604               method->name_and_sig_as_C_string(),
5605               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5606             );
5607           tty->cr();
5608           DEBUG_ONLY(vm_exit(1));
5609         }
5610         // Check is the method 'method' is annotated with @HotSpotIntrinsicCandidate,
5611         // but there is no intrinsic available for it.
5612         if (method->intrinsic_candidate() &&
5613           method->intrinsic_id() == vmIntrinsics::_none) {
5614             tty->print("Method [%s] is annotated with @HotSpotIntrinsicCandidate, "
5615               "but no compiler intrinsic is defined for the method.%s",
5616               method->name_and_sig_as_C_string(),
5617               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5618             );
5619           tty->cr();
5620           DEBUG_ONLY(vm_exit(1));
5621         }
5622       }
5623     } // end for
5624 
5625 #ifdef ASSERT
5626     if (CheckIntrinsics) {
5627       // Check for orphan methods in the current class. A method m
5628       // of a class C is orphan if an intrinsic is defined for method m,
5629       // but class C does not declare m.
5630       // The check is potentially expensive, therefore it is available
5631       // only in debug builds.
5632 
5633       for (int id = vmIntrinsics::FIRST_ID; id < (int)vmIntrinsics::ID_LIMIT; ++id) {
5634         if (vmIntrinsics::_compiledLambdaForm == id) {
5635           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5636           // generated for the JVM from a LambdaForm and therefore no method
5637           // is defined for it.
5638           continue;
5639         }
5640 
5641         if (vmIntrinsics::class_for(vmIntrinsics::ID_from(id)) == klass_id) {
5642           // Check if the current class contains a method with the same
5643           // name, flags, signature.
5644           bool match = false;
5645           for (int j = 0; j < methods->length(); ++j) {
5646             const Method* method = methods->at(j);
5647             if (method->intrinsic_id() == id) {
5648               match = true;
5649               break;
5650             }
5651           }
5652 
5653           if (!match) {
5654             char buf[1000];
5655             tty->print("Compiler intrinsic is defined for method [%s], "
5656                        "but the method is not available in class [%s].%s",
5657                         vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID_from(id),
5658                                                              buf, sizeof(buf)),
5659                         ik->name()->as_C_string(),
5660                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5661             );
5662             tty->cr();
5663             DEBUG_ONLY(vm_exit(1));
5664           }
5665         }
5666       } // end for
5667     } // CheckIntrinsics
5668 #endif // ASSERT
5669   }
5670 }
5671 
5672 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook, TRAPS) {
5673   if (_klass != NULL) {
5674     return _klass;
5675   }
5676 
5677   InstanceKlass* const ik =
5678     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5679 
5680   fill_instance_klass(ik, changed_by_loadhook, CHECK_NULL);
5681 
5682   assert(_klass == ik, "invariant");
5683 
5684   ik->set_has_passed_fingerprint_check(false);
5685   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
5686     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
5687     if (aot_fp != 0 && aot_fp == _stream->compute_fingerprint()) {
5688       // This class matches with a class saved in an AOT library
5689       ik->set_has_passed_fingerprint_check(true);
5690     } else {
5691       ResourceMark rm;
5692       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT,
5693                                  ik->external_name(), aot_fp, _stream->compute_fingerprint());
5694     }
5695   }
5696 
5697   if (ik->is_value()) {
5698     ValueKlass* vk = ValueKlass::cast(ik);
5699     oop val = ik->allocate_instance(CHECK_NULL);
5700     vk->set_default_value(val);
5701   }
5702 
5703   return ik;
5704 }
5705 
5706 void ClassFileParser::fill_instance_klass(InstanceKlass* ik, bool changed_by_loadhook, TRAPS) {
5707   assert(ik != NULL, "invariant");
5708 
5709   set_klass_to_deallocate(ik);
5710 
5711   assert(_field_info != NULL, "invariant");
5712   assert(ik->static_field_size() == _field_info->static_field_size, "sanity");
5713   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->nonstatic_oop_map_count,
5714     "sanity");
5715 
5716   assert(ik->is_instance_klass(), "sanity");
5717   assert(ik->size_helper() == _field_info->instance_size, "sanity");
5718 
5719   // Fill in information already parsed
5720   ik->set_should_verify_class(_need_verify);
5721 
5722   // Not yet: supers are done below to support the new subtype-checking fields
5723   ik->set_class_loader_data(_loader_data);
5724   ik->set_nonstatic_field_size(_field_info->nonstatic_field_size);
5725   ik->set_has_nonstatic_fields(_field_info->has_nonstatic_fields);
5726   assert(_fac != NULL, "invariant");
5727   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_FLATTENABLE]);
5728 
5729   // this transfers ownership of a lot of arrays from
5730   // the parser onto the InstanceKlass*
5731   apply_parsed_class_metadata(ik, _java_fields_count, CHECK);
5732 
5733   // note that is not safe to use the fields in the parser from this point on
5734   assert(NULL == _cp, "invariant");
5735   assert(NULL == _fields, "invariant");
5736   assert(NULL == _methods, "invariant");
5737   assert(NULL == _inner_classes, "invariant");
5738   assert(NULL == _local_interfaces, "invariant");
5739   assert(NULL == _transitive_interfaces, "invariant");
5740   assert(NULL == _combined_annotations, "invariant");
5741 
5742   if (_has_final_method) {
5743     ik->set_has_final_method();
5744   }
5745 
5746   ik->copy_method_ordering(_method_ordering, CHECK);
5747   // The InstanceKlass::_methods_jmethod_ids cache
5748   // is managed on the assumption that the initial cache
5749   // size is equal to the number of methods in the class. If
5750   // that changes, then InstanceKlass::idnum_can_increment()
5751   // has to be changed accordingly.
5752   ik->set_initial_method_idnum(ik->methods()->length());
5753 
5754   ik->set_name(_class_name);
5755 
5756   if (is_anonymous()) {
5757     // _this_class_index is a CONSTANT_Class entry that refers to this
5758     // anonymous class itself. If this class needs to refer to its own methods or
5759     // fields, it would use a CONSTANT_MethodRef, etc, which would reference
5760     // _this_class_index. However, because this class is anonymous (it's
5761     // not stored in SystemDictionary), _this_class_index cannot be resolved
5762     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5763     // Therefore, we must eagerly resolve _this_class_index now.
5764     ik->constants()->klass_at_put(_this_class_index, ik);
5765   }
5766 
5767   ik->set_minor_version(_minor_version);
5768   ik->set_major_version(_major_version);
5769   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5770   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5771 
5772   if (_host_klass != NULL) {
5773     assert (ik->is_anonymous(), "should be the same");
5774     ik->set_host_klass(_host_klass);
5775   }
5776 
5777   // Set PackageEntry for this_klass
5778   oop cl = ik->class_loader();
5779   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5780   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5781   ik->set_package(cld, CHECK);
5782 
5783   const Array<Method*>* const methods = ik->methods();
5784   assert(methods != NULL, "invariant");
5785   const int methods_len = methods->length();
5786 
5787   check_methods_for_intrinsics(ik, methods);
5788 
5789   // Fill in field values obtained by parse_classfile_attributes
5790   if (_parsed_annotations->has_any_annotations()) {
5791     _parsed_annotations->apply_to(ik);
5792   }
5793 
5794   apply_parsed_class_attributes(ik);
5795 
5796   // Miranda methods
5797   if ((_num_miranda_methods > 0) ||
5798       // if this class introduced new miranda methods or
5799       (_super_klass != NULL && _super_klass->has_miranda_methods())
5800         // super class exists and this class inherited miranda methods
5801      ) {
5802        ik->set_has_miranda_methods(); // then set a flag
5803   }
5804 
5805   // Fill in information needed to compute superclasses.
5806   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), CHECK);
5807 
5808   // Initialize itable offset tables
5809   klassItable::setup_itable_offset_table(ik);
5810 
5811   // Compute transitive closure of interfaces this class implements
5812   // Do final class setup
5813   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5814   if (oop_map_blocks->nonstatic_oop_map_count > 0) {
5815     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5816   }
5817 
5818   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5819   set_precomputed_flags(ik);
5820 
5821   // check if this class can access its super class
5822   check_super_class_access(ik, CHECK);
5823 
5824   // check if this class can access its superinterfaces
5825   check_super_interface_access(ik, CHECK);
5826 
5827   // check if this class overrides any final method
5828   check_final_method_override(ik, CHECK);
5829 
5830   // reject static interface methods prior to Java 8
5831   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5832     check_illegal_static_method(ik, CHECK);
5833   }
5834 
5835   // Obtain this_klass' module entry
5836   ModuleEntry* module_entry = ik->module();
5837   assert(module_entry != NULL, "module_entry should always be set");
5838 
5839   // Obtain java.lang.Module
5840   Handle module_handle(THREAD, module_entry->module());
5841 
5842   // Allocate mirror and initialize static fields
5843   // The create_mirror() call will also call compute_modifiers()
5844   java_lang_Class::create_mirror(ik,
5845                                  Handle(THREAD, _loader_data->class_loader()),
5846                                  module_handle,
5847                                  _protection_domain,
5848                                  CHECK);
5849 
5850   assert(_all_mirandas != NULL, "invariant");
5851 
5852   // Generate any default methods - default methods are public interface methods
5853   // that have a default implementation.  This is new with Java 8.
5854   if (_has_nonstatic_concrete_methods) {
5855     DefaultMethods::generate_default_methods(ik,
5856                                              _all_mirandas,
5857                                              CHECK);
5858   }
5859 
5860   if (is_value_type()) {
5861     ValueKlass* vk = ValueKlass::cast(ik);
5862     vk->set_if_bufferable();
5863     vk->initialize_calling_convention();
5864   }
5865 
5866   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5867   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5868       !module_entry->has_default_read_edges()) {
5869     if (!module_entry->set_has_default_read_edges()) {
5870       // We won a potential race
5871       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5872     }
5873   }
5874 
5875   int nfields = ik->java_fields_count();
5876   if (ik->is_value()) nfields++;
5877   for(int i = 0; i < nfields; i++) {
5878     if (ik->field_access_flags(i) & JVM_ACC_FLATTENABLE) {
5879       Klass* klass = SystemDictionary::resolve_or_fail(ik->field_signature(i),
5880                                                        Handle(THREAD, ik->class_loader()),
5881                                                        Handle(THREAD, ik->protection_domain()), true, CHECK);
5882       assert(klass != NULL, "Sanity check");
5883       assert(klass->access_flags().is_value_type(), "Value type expected");
5884       ik->set_value_field_klass(i, klass);
5885     } else if (is_value_type() && ((ik->field_access_flags(i) & JVM_ACC_FIELD_INTERNAL) != 0)
5886         && ((ik->field_access_flags(i) & JVM_ACC_STATIC) != 0)) {
5887       ValueKlass::cast(ik)->set_default_value_offset(ik->field_offset(i));
5888     }
5889   }
5890 
5891   // Update the loader_data graph.
5892   record_defined_class_dependencies(ik, CHECK);
5893 
5894   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5895 
5896   if (!is_internal()) {
5897     if (log_is_enabled(Info, class, load)) {
5898       ResourceMark rm;
5899       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
5900       ik->print_class_load_logging(_loader_data, module_name, _stream);
5901     }
5902 
5903     if (log_is_enabled(Debug, class, resolve))  {
5904       ResourceMark rm;
5905       // print out the superclass.
5906       const char * from = ik->external_name();
5907       if (ik->java_super() != NULL) {
5908         log_debug(class, resolve)("%s %s (super)",
5909                    from,
5910                    ik->java_super()->external_name());
5911       }
5912       // print out each of the interface classes referred to by this class.
5913       const Array<Klass*>* const local_interfaces = ik->local_interfaces();
5914       if (local_interfaces != NULL) {
5915         const int length = local_interfaces->length();
5916         for (int i = 0; i < length; i++) {
5917           const Klass* const k = local_interfaces->at(i);
5918           const char * to = k->external_name();
5919           log_debug(class, resolve)("%s %s (interface)", from, to);
5920         }
5921       }
5922     }
5923   }
5924 
5925   TRACE_INIT_ID(ik);
5926 
5927   // If we reach here, all is well.
5928   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5929   // in order for it to not be destroyed in the ClassFileParser destructor.
5930   set_klass_to_deallocate(NULL);
5931 
5932   // it's official
5933   set_klass(ik);
5934 
5935   debug_only(ik->verify();)
5936 }
5937 
5938 // For an anonymous class that is in the unnamed package, move it to its host class's
5939 // package by prepending its host class's package name to its class name and setting
5940 // its _class_name field.
5941 void ClassFileParser::prepend_host_package_name(const InstanceKlass* host_klass, TRAPS) {
5942   ResourceMark rm(THREAD);
5943   assert(strrchr(_class_name->as_C_string(), '/') == NULL,
5944          "Anonymous class should not be in a package");
5945   const char* host_pkg_name =
5946     ClassLoader::package_from_name(host_klass->name()->as_C_string(), NULL);
5947 
5948   if (host_pkg_name != NULL) {
5949     size_t host_pkg_len = strlen(host_pkg_name);
5950     int class_name_len = _class_name->utf8_length();
5951     char* new_anon_name =
5952       NEW_RESOURCE_ARRAY(char, host_pkg_len + 1 + class_name_len);
5953     // Copy host package name and trailing /.
5954     strncpy(new_anon_name, host_pkg_name, host_pkg_len);
5955     new_anon_name[host_pkg_len] = '/';
5956     // Append anonymous class name. The anonymous class name can contain odd
5957     // characters.  So, do a strncpy instead of using sprintf("%s...").
5958     strncpy(new_anon_name + host_pkg_len + 1, (char *)_class_name->base(), class_name_len);
5959 
5960     // Create a symbol and update the anonymous class name.
5961     _class_name = SymbolTable::new_symbol(new_anon_name,
5962                                           (int)host_pkg_len + 1 + class_name_len,
5963                                           CHECK);
5964   }
5965 }
5966 
5967 // If the host class and the anonymous class are in the same package then do
5968 // nothing.  If the anonymous class is in the unnamed package then move it to its
5969 // host's package.  If the classes are in different packages then throw an IAE
5970 // exception.
5971 void ClassFileParser::fix_anonymous_class_name(TRAPS) {
5972   assert(_host_klass != NULL, "Expected an anonymous class");
5973 
5974   const jbyte* anon_last_slash = UTF8::strrchr(_class_name->base(),
5975                                                _class_name->utf8_length(), '/');
5976   if (anon_last_slash == NULL) {  // Unnamed package
5977     prepend_host_package_name(_host_klass, CHECK);
5978   } else {
5979     if (!_host_klass->is_same_class_package(_host_klass->class_loader(), _class_name)) {
5980       ResourceMark rm(THREAD);
5981       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
5982         err_msg("Host class %s and anonymous class %s are in different packages",
5983         _host_klass->name()->as_C_string(), _class_name->as_C_string()));
5984     }
5985   }
5986 }
5987 
5988 static bool relax_format_check_for(ClassLoaderData* loader_data) {
5989   bool trusted = (loader_data->is_the_null_class_loader_data() ||
5990                   SystemDictionary::is_platform_class_loader(loader_data->class_loader()));
5991   bool need_verify =
5992     // verifyAll
5993     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
5994     // verifyRemote
5995     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
5996   return !need_verify;
5997 }
5998 
5999 ClassFileParser::ClassFileParser(ClassFileStream* stream,
6000                                  Symbol* name,
6001                                  ClassLoaderData* loader_data,
6002                                  Handle protection_domain,
6003                                  const InstanceKlass* host_klass,
6004                                  GrowableArray<Handle>* cp_patches,
6005                                  Publicity pub_level,
6006                                  TRAPS) :
6007   _stream(stream),
6008   _requested_name(name),
6009   _loader_data(loader_data),
6010   _host_klass(host_klass),
6011   _cp_patches(cp_patches),
6012   _num_patched_klasses(0),
6013   _max_num_patched_klasses(0),
6014   _orig_cp_size(0),
6015   _first_patched_klass_resolved_index(0),
6016   _super_klass(),
6017   _cp(NULL),
6018   _fields(NULL),
6019   _methods(NULL),
6020   _inner_classes(NULL),
6021   _value_types(NULL),
6022   _local_interfaces(NULL),
6023   _transitive_interfaces(NULL),
6024   _combined_annotations(NULL),
6025   _annotations(NULL),
6026   _type_annotations(NULL),
6027   _fields_annotations(NULL),
6028   _fields_type_annotations(NULL),
6029   _klass(NULL),
6030   _klass_to_deallocate(NULL),
6031   _parsed_annotations(NULL),
6032   _fac(NULL),
6033   _field_info(NULL),
6034   _method_ordering(NULL),
6035   _all_mirandas(NULL),
6036   _vtable_size(0),
6037   _itable_size(0),
6038   _num_miranda_methods(0),
6039   _rt(REF_NONE),
6040   _protection_domain(protection_domain),
6041   _access_flags(),
6042   _pub_level(pub_level),
6043   _bad_constant_seen(0),
6044   _synthetic_flag(false),
6045   _sde_length(false),
6046   _sde_buffer(NULL),
6047   _sourcefile_index(0),
6048   _generic_signature_index(0),
6049   _major_version(0),
6050   _minor_version(0),
6051   _this_class_index(0),
6052   _super_class_index(0),
6053   _itfs_len(0),
6054   _java_fields_count(0),
6055   _need_verify(false),
6056   _relax_verify(false),
6057   _has_nonstatic_concrete_methods(false),
6058   _declares_nonstatic_concrete_methods(false),
6059   _has_final_method(false),
6060   _has_finalizer(false),
6061   _has_empty_finalizer(false),
6062   _has_vanilla_constructor(false),
6063   _max_bootstrap_specifier_index(-1),
6064   _has_flattenable_fields(false) {
6065 
6066   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
6067 
6068   assert(THREAD->is_Java_thread(), "invariant");
6069   assert(_loader_data != NULL, "invariant");
6070   assert(stream != NULL, "invariant");
6071   assert(_stream != NULL, "invariant");
6072   assert(_stream->buffer() == _stream->current(), "invariant");
6073   assert(_class_name != NULL, "invariant");
6074   assert(0 == _access_flags.as_int(), "invariant");
6075 
6076   // Figure out whether we can skip format checking (matching classic VM behavior)
6077   if (DumpSharedSpaces) {
6078     // verify == true means it's a 'remote' class (i.e., non-boot class)
6079     // Verification decision is based on BytecodeVerificationRemote flag
6080     // for those classes.
6081     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
6082                                               BytecodeVerificationLocal;
6083   }
6084   else {
6085     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
6086                                                stream->need_verify());
6087   }
6088   if (_cp_patches != NULL) {
6089     int len = _cp_patches->length();
6090     for (int i=0; i<len; i++) {
6091       if (has_cp_patch_at(i)) {
6092         Handle patch = cp_patch_at(i);
6093         if (java_lang_String::is_instance(patch()) || java_lang_Class::is_instance(patch())) {
6094           // We need to append the names of the patched classes to the end of the constant pool,
6095           // because a patched class may have a Utf8 name that's not already included in the
6096           // original constant pool. These class names are used when patch_constant_pool()
6097           // calls patch_class().
6098           //
6099           // Note that a String in cp_patch_at(i) may be used to patch a Utf8, a String, or a Class.
6100           // At this point, we don't know the tag for index i yet, because we haven't parsed the
6101           // constant pool. So we can only assume the worst -- every String is used to patch a Class.
6102           _max_num_patched_klasses++;
6103         }
6104       }
6105     }
6106   }
6107 
6108   // synch back verification state to stream
6109   stream->set_verify(_need_verify);
6110 
6111   // Check if verification needs to be relaxed for this class file
6112   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
6113   _relax_verify = relax_format_check_for(_loader_data);
6114 
6115   parse_stream(stream, CHECK);
6116 
6117   post_process_parsed_stream(stream, _cp, CHECK);
6118 }
6119 
6120 void ClassFileParser::clear_class_metadata() {
6121   // metadata created before the instance klass is created.  Must be
6122   // deallocated if classfile parsing returns an error.
6123   _cp = NULL;
6124   _fields = NULL;
6125   _methods = NULL;
6126   _inner_classes = NULL;
6127   _local_interfaces = NULL;
6128   _transitive_interfaces = NULL;
6129   _combined_annotations = NULL;
6130   _annotations = _type_annotations = NULL;
6131   _fields_annotations = _fields_type_annotations = NULL;
6132 }
6133 
6134 // Destructor to clean up
6135 ClassFileParser::~ClassFileParser() {
6136   if (_cp != NULL) {
6137     MetadataFactory::free_metadata(_loader_data, _cp);
6138   }
6139   if (_fields != NULL) {
6140     MetadataFactory::free_array<u2>(_loader_data, _fields);
6141   }
6142 
6143   if (_methods != NULL) {
6144     // Free methods
6145     InstanceKlass::deallocate_methods(_loader_data, _methods);
6146   }
6147 
6148   // beware of the Universe::empty_blah_array!!
6149   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
6150     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
6151   }
6152 
6153   // Free interfaces
6154   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6155                                        _local_interfaces, _transitive_interfaces);
6156 
6157   if (_combined_annotations != NULL) {
6158     // After all annotations arrays have been created, they are installed into the
6159     // Annotations object that will be assigned to the InstanceKlass being created.
6160 
6161     // Deallocate the Annotations object and the installed annotations arrays.
6162     _combined_annotations->deallocate_contents(_loader_data);
6163 
6164     // If the _combined_annotations pointer is non-NULL,
6165     // then the other annotations fields should have been cleared.
6166     assert(_annotations             == NULL, "Should have been cleared");
6167     assert(_type_annotations        == NULL, "Should have been cleared");
6168     assert(_fields_annotations      == NULL, "Should have been cleared");
6169     assert(_fields_type_annotations == NULL, "Should have been cleared");
6170   } else {
6171     // If the annotations arrays were not installed into the Annotations object,
6172     // then they have to be deallocated explicitly.
6173     MetadataFactory::free_array<u1>(_loader_data, _annotations);
6174     MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
6175     Annotations::free_contents(_loader_data, _fields_annotations);
6176     Annotations::free_contents(_loader_data, _fields_type_annotations);
6177   }
6178 
6179   clear_class_metadata();
6180 
6181   // deallocate the klass if already created.  Don't directly deallocate, but add
6182   // to the deallocate list so that the klass is removed from the CLD::_klasses list
6183   // at a safepoint.
6184   if (_klass_to_deallocate != NULL) {
6185     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
6186   }
6187 }
6188 
6189 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
6190                                    TRAPS) {
6191 
6192   assert(stream != NULL, "invariant");
6193   assert(_class_name != NULL, "invariant");
6194 
6195   // BEGIN STREAM PARSING
6196   stream->guarantee_more(8, CHECK);  // magic, major, minor
6197   // Magic value
6198   const u4 magic = stream->get_u4_fast();
6199   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
6200                      "Incompatible magic value %u in class file %s",
6201                      magic, CHECK);
6202 
6203   // Version numbers
6204   _minor_version = stream->get_u2_fast();
6205   _major_version = stream->get_u2_fast();
6206 
6207   if (DumpSharedSpaces && _major_version < JAVA_1_5_VERSION) {
6208     ResourceMark rm;
6209     warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
6210             _major_version,  _minor_version, _class_name->as_C_string());
6211     Exceptions::fthrow(
6212       THREAD_AND_LOCATION,
6213       vmSymbols::java_lang_UnsupportedClassVersionError(),
6214       "Unsupported major.minor version for dump time %u.%u",
6215       _major_version,
6216       _minor_version);
6217   }
6218 
6219   // Check version numbers - we check this even with verifier off
6220   if (!is_supported_version(_major_version, _minor_version)) {
6221     ResourceMark rm(THREAD);
6222     Exceptions::fthrow(
6223       THREAD_AND_LOCATION,
6224       vmSymbols::java_lang_UnsupportedClassVersionError(),
6225       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
6226       "this version of the Java Runtime only recognizes class file versions up to %u.%u",
6227       _class_name->as_C_string(),
6228       _major_version,
6229       _minor_version,
6230       JVM_CLASSFILE_MAJOR_VERSION,
6231       JVM_CLASSFILE_MINOR_VERSION);
6232     return;
6233   }
6234 
6235   stream->guarantee_more(3, CHECK); // length, first cp tag
6236   u2 cp_size = stream->get_u2_fast();
6237 
6238   guarantee_property(
6239     cp_size >= 1, "Illegal constant pool size %u in class file %s",
6240     cp_size, CHECK);
6241 
6242   _orig_cp_size = cp_size;
6243   if (int(cp_size) + _max_num_patched_klasses > 0xffff) {
6244     THROW_MSG(vmSymbols::java_lang_InternalError(), "not enough space for patched classes");
6245   }
6246   cp_size += _max_num_patched_klasses;
6247 
6248   _cp = ConstantPool::allocate(_loader_data,
6249                                cp_size,
6250                                CHECK);
6251 
6252   ConstantPool* const cp = _cp;
6253 
6254   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6255 
6256   assert(cp_size == (const u2)cp->length(), "invariant");
6257 
6258   // ACCESS FLAGS
6259   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6260 
6261   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;
6262   // JVM_ACC_MODULE is defined in JDK-9 and later.
6263   if (_major_version >= JAVA_9_VERSION) {
6264     recognized_modifiers |= JVM_ACC_MODULE;
6265   }
6266   // JVM_ACC_VALUE is defined for class file version 55 and later
6267   if (supports_value_types()) {
6268     recognized_modifiers |= JVM_ACC_VALUE;
6269   }
6270 
6271   // Access flags
6272   jint flags = stream->get_u2_fast() & recognized_modifiers;
6273 
6274   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6275     // Set abstract bit for old class files for backward compatibility
6276     flags |= JVM_ACC_ABSTRACT;
6277   }
6278 
6279   verify_legal_class_modifiers(flags, CHECK);
6280 
6281   short bad_constant = class_bad_constant_seen();
6282   if (bad_constant != 0) {
6283     // Do not throw CFE until after the access_flags are checked because if
6284     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6285     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, CHECK);
6286   }
6287 
6288   _access_flags.set_flags(flags);
6289 
6290   // This class and superclass
6291   _this_class_index = stream->get_u2_fast();
6292   check_property(
6293     valid_cp_range(_this_class_index, cp_size) &&
6294       cp->tag_at(_this_class_index).is_unresolved_klass(),
6295     "Invalid this class index %u in constant pool in class file %s",
6296     _this_class_index, CHECK);
6297 
6298   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6299   assert(class_name_in_cp != NULL, "class_name can't be null");
6300 
6301   // Update _class_name which could be null previously
6302   // to reflect the name in the constant pool
6303   _class_name = class_name_in_cp;
6304 
6305   // Don't need to check whether this class name is legal or not.
6306   // It has been checked when constant pool is parsed.
6307   // However, make sure it is not an array type.
6308   if (_need_verify) {
6309     guarantee_property(_class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
6310                        "Bad class name in class file %s",
6311                        CHECK);
6312   }
6313 
6314   // Checks if name in class file matches requested name
6315   if (_requested_name != NULL && _requested_name != _class_name) {
6316     ResourceMark rm(THREAD);
6317     Exceptions::fthrow(
6318       THREAD_AND_LOCATION,
6319       vmSymbols::java_lang_NoClassDefFoundError(),
6320       "%s (wrong name: %s)",
6321       _class_name->as_C_string(),
6322       _requested_name != NULL ? _requested_name->as_C_string() : "NoName"
6323     );
6324     return;
6325   }
6326 
6327   // if this is an anonymous class fix up its name if it's in the unnamed
6328   // package.  Otherwise, throw IAE if it is in a different package than
6329   // its host class.
6330   if (_host_klass != NULL) {
6331     fix_anonymous_class_name(CHECK);
6332   }
6333 
6334   // Verification prevents us from creating names with dots in them, this
6335   // asserts that that's the case.
6336   assert(is_internal_format(_class_name), "external class name format used internally");
6337 
6338   if (!is_internal()) {
6339     LogTarget(Debug, class, preorder) lt;
6340     if (lt.is_enabled()){
6341       ResourceMark rm(THREAD);
6342       LogStream ls(lt);
6343       ls.print("%s", _class_name->as_klass_external_name());
6344       if (stream->source() != NULL) {
6345         ls.print(" source: %s", stream->source());
6346       }
6347       ls.cr();
6348     }
6349 
6350 #if INCLUDE_CDS
6351     if (DumpLoadedClassList != NULL && stream->source() != NULL && classlist_file->is_open()) {
6352       if (!ClassLoader::has_jrt_entry()) {
6353         warning("DumpLoadedClassList and CDS are not supported in exploded build");
6354         DumpLoadedClassList = NULL;
6355       } else if (SystemDictionaryShared::is_sharing_possible(_loader_data) &&
6356           _host_klass == NULL) {
6357         // Only dump the classes that can be stored into CDS archive.
6358         // Anonymous classes such as generated LambdaForm classes are also not included.
6359         oop class_loader = _loader_data->class_loader();
6360         ResourceMark rm(THREAD);
6361         bool skip = false;
6362         if (class_loader == NULL || SystemDictionary::is_platform_class_loader(class_loader)) {
6363           // For the boot and platform class loaders, skip classes that are not found in the
6364           // java runtime image, such as those found in the --patch-module entries.
6365           // These classes can't be loaded from the archive during runtime.
6366           if (!ClassLoader::is_modules_image(stream->source()) && strncmp(stream->source(), "jrt:", 4) != 0) {
6367             skip = true;
6368           }
6369 
6370           if (class_loader == NULL && ClassLoader::contains_append_entry(stream->source())) {
6371             // .. but don't skip the boot classes that are loaded from -Xbootclasspath/a
6372             // as they can be loaded from the archive during runtime.
6373             skip = false;
6374           }
6375         }
6376         if (skip) {
6377           tty->print_cr("skip writing class %s from source %s to classlist file",
6378             _class_name->as_C_string(), stream->source());
6379         } else {
6380           classlist_file->print_cr("%s", _class_name->as_C_string());
6381           classlist_file->flush();
6382         }
6383       }
6384     }
6385 #endif
6386   }
6387 
6388   // SUPERKLASS
6389   _super_class_index = stream->get_u2_fast();
6390   _super_klass = parse_super_class(cp,
6391                                    _super_class_index,
6392                                    _need_verify,
6393                                    CHECK);
6394 
6395   // Interfaces
6396   _itfs_len = stream->get_u2_fast();
6397   parse_interfaces(stream,
6398                    _itfs_len,
6399                    cp,
6400                    &_has_nonstatic_concrete_methods,
6401                    CHECK);
6402 
6403   assert(_local_interfaces != NULL, "invariant");
6404 
6405   // Fields (offsets are filled in later)
6406   _fac = new FieldAllocationCount();
6407   parse_fields(stream,
6408                _access_flags.is_interface(),
6409                _access_flags.is_value_type(),
6410                _fac,
6411                cp,
6412                cp_size,
6413                &_java_fields_count,
6414                CHECK);
6415 
6416   assert(_fields != NULL, "invariant");
6417 
6418   // Methods
6419   AccessFlags promoted_flags;
6420   parse_methods(stream,
6421                 _access_flags.is_interface(),
6422                 _access_flags.is_value_type(),
6423                 &promoted_flags,
6424                 &_has_final_method,
6425                 &_declares_nonstatic_concrete_methods,
6426                 CHECK);
6427 
6428   assert(_methods != NULL, "invariant");
6429 
6430   // promote flags from parse_methods() to the klass' flags
6431   _access_flags.add_promoted_flags(promoted_flags.as_int());
6432 
6433   if (_declares_nonstatic_concrete_methods) {
6434     _has_nonstatic_concrete_methods = true;
6435   }
6436 
6437   // Additional attributes/annotations
6438   _parsed_annotations = new ClassAnnotationCollector();
6439   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6440 
6441   assert(_inner_classes != NULL, "invariant");
6442 
6443   // Finalize the Annotations metadata object,
6444   // now that all annotation arrays have been created.
6445   create_combined_annotations(CHECK);
6446 
6447   // Make sure this is the end of class file stream
6448   guarantee_property(stream->at_eos(),
6449                      "Extra bytes at the end of class file %s",
6450                      CHECK);
6451 
6452   // all bytes in stream read and parsed
6453 }
6454 
6455 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6456                                                  ConstantPool* cp,
6457                                                  TRAPS) {
6458   assert(stream != NULL, "invariant");
6459   assert(stream->at_eos(), "invariant");
6460   assert(cp != NULL, "invariant");
6461   assert(_loader_data != NULL, "invariant");
6462 
6463   if (_class_name == vmSymbols::java_lang_Object()) {
6464     check_property(_local_interfaces == Universe::the_empty_klass_array(),
6465                    "java.lang.Object cannot implement an interface in class file %s",
6466                    CHECK);
6467   }
6468   // We check super class after class file is parsed and format is checked
6469   if (_super_class_index > 0 && NULL ==_super_klass) {
6470     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6471     if (_access_flags.is_interface()) {
6472       // Before attempting to resolve the superclass, check for class format
6473       // errors not checked yet.
6474       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6475         "Interfaces must have java.lang.Object as superclass in class file %s",
6476         CHECK);
6477     }
6478     Handle loader(THREAD, _loader_data->class_loader());
6479     _super_klass = (const InstanceKlass*)
6480                        SystemDictionary::resolve_super_or_fail(_class_name,
6481                                                                super_class_name,
6482                                                                loader,
6483                                                                _protection_domain,
6484                                                                true,
6485                                                                CHECK);
6486   }
6487 
6488   if (_super_klass != NULL) {
6489     if (_super_klass->has_nonstatic_concrete_methods()) {
6490       _has_nonstatic_concrete_methods = true;
6491     }
6492 
6493     if (_super_klass->is_interface()) {
6494       ResourceMark rm(THREAD);
6495       Exceptions::fthrow(
6496         THREAD_AND_LOCATION,
6497         vmSymbols::java_lang_IncompatibleClassChangeError(),
6498         "class %s has interface %s as super class",
6499         _class_name->as_klass_external_name(),
6500         _super_klass->external_name()
6501       );
6502       return;
6503     }
6504 
6505     // For a value class, only java/lang/Object is an acceptable super class
6506     if (_access_flags.get_flags() & JVM_ACC_VALUE) {
6507       guarantee_property(_super_klass->name() == vmSymbols::java_lang_Object(),
6508         "Value type must have java.lang.Object as superclass in class file %s",
6509         CHECK);
6510     }
6511 
6512     // Make sure super class is not final
6513     if (_super_klass->is_final()) {
6514       THROW_MSG(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class");
6515     }
6516   }
6517 
6518   // Compute the transitive list of all unique interfaces implemented by this class
6519   _transitive_interfaces =
6520     compute_transitive_interfaces(_super_klass,
6521                                   _local_interfaces,
6522                                   _loader_data,
6523                                   CHECK);
6524 
6525   assert(_transitive_interfaces != NULL, "invariant");
6526 
6527   // sort methods
6528   _method_ordering = sort_methods(_methods);
6529 
6530   _all_mirandas = new GrowableArray<Method*>(20);
6531 
6532   Handle loader(THREAD, _loader_data->class_loader());
6533   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6534                                                     &_num_miranda_methods,
6535                                                     _all_mirandas,
6536                                                     _super_klass,
6537                                                     _methods,
6538                                                     _access_flags,
6539                                                     _major_version,
6540                                                     loader,
6541                                                     _class_name,
6542                                                     _local_interfaces,
6543                                                     CHECK);
6544 
6545   // Size of Java itable (in words)
6546   _itable_size = _access_flags.is_interface() ? 0 :
6547     klassItable::compute_itable_size(_transitive_interfaces);
6548 
6549   assert(_fac != NULL, "invariant");
6550   assert(_parsed_annotations != NULL, "invariant");
6551 
6552   _field_info = new FieldLayoutInfo();
6553   layout_fields(cp, _fac, _parsed_annotations, _field_info, CHECK);
6554 
6555   // Compute reference typ
6556   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();
6557 
6558 }
6559 
6560 void ClassFileParser::set_klass(InstanceKlass* klass) {
6561 
6562 #ifdef ASSERT
6563   if (klass != NULL) {
6564     assert(NULL == _klass, "leaking?");
6565   }
6566 #endif
6567 
6568   _klass = klass;
6569 }
6570 
6571 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6572 
6573 #ifdef ASSERT
6574   if (klass != NULL) {
6575     assert(NULL == _klass_to_deallocate, "leaking?");
6576   }
6577 #endif
6578 
6579   _klass_to_deallocate = klass;
6580 }
6581 
6582 // Caller responsible for ResourceMark
6583 // clone stream with rewound position
6584 const ClassFileStream* ClassFileParser::clone_stream() const {
6585   assert(_stream != NULL, "invariant");
6586 
6587   return _stream->clone();
6588 }
6589 
6590 // ----------------------------------------------------------------------------
6591 // debugging
6592 
6593 #ifdef ASSERT
6594 
6595 // return true if class_name contains no '.' (internal format is '/')
6596 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6597   if (class_name != NULL) {
6598     ResourceMark rm;
6599     char* name = class_name->as_C_string();
6600     return strchr(name, '.') == NULL;
6601   } else {
6602     return true;
6603   }
6604 }
6605 
6606 #endif