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