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, bool is_flattenable) {
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   if (is_flattenable) {
1528     result = is_static ? STATIC_FLATTENABLE : NONSTATIC_FLATTENABLE;
1529   }
1530   return result;
1531 }
1532 
1533 class ClassFileParser::FieldAllocationCount : public ResourceObj {
1534  public:
1535   u2 count[MAX_FIELD_ALLOCATION_TYPE];
1536 
1537   FieldAllocationCount() {
1538     for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
1539       count[i] = 0;
1540     }
1541   }
1542 
1543   FieldAllocationType update(bool is_static, BasicType type, bool is_flattenable) {
1544     FieldAllocationType atype = basic_type_to_atype(is_static, type, is_flattenable);
1545     if (atype != BAD_ALLOCATION_TYPE) {
1546       // Make sure there is no overflow with injected fields.
1547       assert(count[atype] < 0xFFFF, "More than 65535 fields");
1548       count[atype]++;
1549     }
1550     return atype;
1551   }
1552 };
1553 
1554 // Side-effects: populates the _fields, _fields_annotations,
1555 // _fields_type_annotations fields
1556 void ClassFileParser::parse_fields(const ClassFileStream* const cfs,
1557                                    bool is_interface,
1558                                    bool is_concrete_value_type,
1559                                    FieldAllocationCount* const fac,
1560                                    ConstantPool* cp,
1561                                    const int cp_size,
1562                                    u2* const java_fields_count_ptr,
1563                                    TRAPS) {
1564 
1565   assert(cfs != NULL, "invariant");
1566   assert(fac != NULL, "invariant");
1567   assert(cp != NULL, "invariant");
1568   assert(java_fields_count_ptr != NULL, "invariant");
1569 
1570   assert(NULL == _fields, "invariant");
1571   assert(NULL == _fields_annotations, "invariant");
1572   assert(NULL == _fields_type_annotations, "invariant");
1573 
1574   cfs->guarantee_more(2, CHECK);  // length
1575   const u2 length = cfs->get_u2_fast();
1576   *java_fields_count_ptr = length;
1577 
1578   int num_injected = 0;
1579   const InjectedField* const injected = JavaClasses::get_injected(_class_name,
1580                                                                   &num_injected);
1581 
1582   const int total_fields = length + num_injected + (is_concrete_value_type ? 1 : 0);
1583 
1584   // The field array starts with tuples of shorts
1585   // [access, name index, sig index, initial value index, byte offset].
1586   // A generic signature slot only exists for field with generic
1587   // signature attribute. And the access flag is set with
1588   // JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE for that field. The generic
1589   // signature slots are at the end of the field array and after all
1590   // other fields data.
1591   //
1592   //   f1: [access, name index, sig index, initial value index, low_offset, high_offset]
1593   //   f2: [access, name index, sig index, initial value index, low_offset, high_offset]
1594   //       ...
1595   //   fn: [access, name index, sig index, initial value index, low_offset, high_offset]
1596   //       [generic signature index]
1597   //       [generic signature index]
1598   //       ...
1599   //
1600   // Allocate a temporary resource array for field data. For each field,
1601   // a slot is reserved in the temporary array for the generic signature
1602   // index. After parsing all fields, the data are copied to a permanent
1603   // array and any unused slots will be discarded.
1604   ResourceMark rm(THREAD);
1605   u2* const fa = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD,
1606                                               u2,
1607                                               total_fields * (FieldInfo::field_slots + 1));
1608 
1609   // The generic signature slots start after all other fields' data.
1610   int generic_signature_slot = total_fields * FieldInfo::field_slots;
1611   int num_generic_signature = 0;
1612   for (int n = 0; n < length; n++) {
1613     // access_flags, name_index, descriptor_index, attributes_count
1614     cfs->guarantee_more(8, CHECK);
1615 
1616     AccessFlags access_flags;
1617     const jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1618     verify_legal_field_modifiers(flags, is_interface, CHECK);
1619     access_flags.set_flags(flags);
1620 
1621     const u2 name_index = cfs->get_u2_fast();
1622     check_property(valid_symbol_at(name_index),
1623       "Invalid constant pool index %u for field name in class file %s",
1624       name_index, CHECK);
1625     const Symbol* const name = cp->symbol_at(name_index);
1626     verify_legal_field_name(name, CHECK);
1627 
1628     const u2 signature_index = cfs->get_u2_fast();
1629     check_property(valid_symbol_at(signature_index),
1630       "Invalid constant pool index %u for field signature in class file %s",
1631       signature_index, CHECK);
1632     const Symbol* const sig = cp->symbol_at(signature_index);
1633     verify_legal_field_signature(name, sig, CHECK);
1634     if (access_flags.is_flattenable()) {
1635       _has_flattenable_fields = true;
1636     }
1637 
1638     u2 constantvalue_index = 0;
1639     bool is_synthetic = false;
1640     u2 generic_signature_index = 0;
1641     const bool is_static = access_flags.is_static();
1642     FieldAnnotationCollector parsed_annotations(_loader_data);
1643 
1644     const u2 attributes_count = cfs->get_u2_fast();
1645     if (attributes_count > 0) {
1646       parse_field_attributes(cfs,
1647                              attributes_count,
1648                              is_static,
1649                              signature_index,
1650                              &constantvalue_index,
1651                              &is_synthetic,
1652                              &generic_signature_index,
1653                              &parsed_annotations,
1654                              CHECK);
1655 
1656       if (parsed_annotations.field_annotations() != NULL) {
1657         if (_fields_annotations == NULL) {
1658           _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
1659                                              _loader_data, length, NULL,
1660                                              CHECK);
1661         }
1662         _fields_annotations->at_put(n, parsed_annotations.field_annotations());
1663         parsed_annotations.set_field_annotations(NULL);
1664       }
1665       if (parsed_annotations.field_type_annotations() != NULL) {
1666         if (_fields_type_annotations == NULL) {
1667           _fields_type_annotations =
1668             MetadataFactory::new_array<AnnotationArray*>(_loader_data,
1669                                                          length,
1670                                                          NULL,
1671                                                          CHECK);
1672         }
1673         _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
1674         parsed_annotations.set_field_type_annotations(NULL);
1675       }
1676 
1677       if (is_synthetic) {
1678         access_flags.set_is_synthetic();
1679       }
1680       if (generic_signature_index != 0) {
1681         access_flags.set_field_has_generic_signature();
1682         fa[generic_signature_slot] = generic_signature_index;
1683         generic_signature_slot ++;
1684         num_generic_signature ++;
1685       }
1686     }
1687 
1688     FieldInfo* const field = FieldInfo::from_field_array(fa, n);
1689     field->initialize(access_flags.as_short(),
1690                       name_index,
1691                       signature_index,
1692                       constantvalue_index);
1693     const BasicType type = cp->basic_type_for_signature_at(signature_index);
1694 
1695     // Remember how many oops we encountered and compute allocation type
1696     const FieldAllocationType atype = fac->update(is_static, type, access_flags.is_flattenable());
1697     field->set_allocation_type(atype);
1698 
1699     // After field is initialized with type, we can augment it with aux info
1700     if (parsed_annotations.has_any_annotations())
1701       parsed_annotations.apply_to(field);
1702   }
1703 
1704   int index = length;
1705   if (num_injected != 0) {
1706     for (int n = 0; n < num_injected; n++) {
1707       // Check for duplicates
1708       if (injected[n].may_be_java) {
1709         const Symbol* const name      = injected[n].name();
1710         const Symbol* const signature = injected[n].signature();
1711         bool duplicate = false;
1712         for (int i = 0; i < length; i++) {
1713           const FieldInfo* const f = FieldInfo::from_field_array(fa, i);
1714           if (name      == cp->symbol_at(f->name_index()) &&
1715               signature == cp->symbol_at(f->signature_index())) {
1716             // Symbol is desclared in Java so skip this one
1717             duplicate = true;
1718             break;
1719           }
1720         }
1721         if (duplicate) {
1722           // These will be removed from the field array at the end
1723           continue;
1724         }
1725       }
1726 
1727       // Injected field
1728       FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1729       field->initialize(JVM_ACC_FIELD_INTERNAL,
1730                         injected[n].name_index,
1731                         injected[n].signature_index,
1732                         0);
1733 
1734       const BasicType type = FieldType::basic_type(injected[n].signature());
1735 
1736       // Remember how many oops we encountered and compute allocation type
1737       const FieldAllocationType atype = fac->update(false, type, false);
1738       field->set_allocation_type(atype);
1739       index++;
1740     }
1741   }
1742 
1743   if (is_concrete_value_type) {
1744     index = length + num_injected;
1745     FieldInfo* const field = FieldInfo::from_field_array(fa, index);
1746     field->initialize(JVM_ACC_FIELD_INTERNAL | JVM_ACC_STATIC,
1747                       vmSymbols::default_value_name_enum,
1748                       vmSymbols::java_lang_Object_enum,
1749                       0);
1750     const BasicType type = FieldType::basic_type(vmSymbols::object_signature());
1751     const FieldAllocationType atype = fac->update(true, type, false);
1752     field->set_allocation_type(atype);
1753     index++;
1754   }
1755 
1756   assert(NULL == _fields, "invariant");
1757 
1758   _fields =
1759     MetadataFactory::new_array<u2>(_loader_data,
1760                                    index * FieldInfo::field_slots + num_generic_signature,
1761                                    CHECK);
1762   // Sometimes injected fields already exist in the Java source so
1763   // the fields array could be too long.  In that case the
1764   // fields array is trimed. Also unused slots that were reserved
1765   // for generic signature indexes are discarded.
1766   {
1767     int i = 0;
1768     for (; i < index * FieldInfo::field_slots; i++) {
1769       _fields->at_put(i, fa[i]);
1770     }
1771     for (int j = total_fields * FieldInfo::field_slots;
1772          j < generic_signature_slot; j++) {
1773       _fields->at_put(i++, fa[j]);
1774     }
1775     assert(_fields->length() == i, "");
1776   }
1777 
1778   if (_need_verify && length > 1) {
1779     // Check duplicated fields
1780     ResourceMark rm(THREAD);
1781     NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
1782       THREAD, NameSigHash*, HASH_ROW_SIZE);
1783     initialize_hashtable(names_and_sigs);
1784     bool dup = false;
1785     const Symbol* name = NULL;
1786     const Symbol* sig = NULL;
1787     {
1788       debug_only(NoSafepointVerifier nsv;)
1789       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
1790         name = fs.name();
1791         sig = fs.signature();
1792         // If no duplicates, add name/signature in hashtable names_and_sigs.
1793         if (!put_after_lookup(name, sig, names_and_sigs)) {
1794           dup = true;
1795           break;
1796         }
1797       }
1798     }
1799     if (dup) {
1800       classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
1801                              name->as_C_string(), sig->as_klass_external_name(), CHECK);
1802     }
1803   }
1804 }
1805 
1806 
1807 const ClassFileParser::unsafe_u2* ClassFileParser::parse_exception_table(const ClassFileStream* const cfs,
1808                                                                          u4 code_length,
1809                                                                          u4 exception_table_length,
1810                                                                          TRAPS) {
1811   assert(cfs != NULL, "invariant");
1812 
1813   const unsafe_u2* const exception_table_start = cfs->current();
1814   assert(exception_table_start != NULL, "null exception table");
1815 
1816   cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc,
1817                                                                // end_pc,
1818                                                                // handler_pc,
1819                                                                // catch_type_index
1820 
1821   // Will check legal target after parsing code array in verifier.
1822   if (_need_verify) {
1823     for (unsigned int i = 0; i < exception_table_length; i++) {
1824       const u2 start_pc = cfs->get_u2_fast();
1825       const u2 end_pc = cfs->get_u2_fast();
1826       const u2 handler_pc = cfs->get_u2_fast();
1827       const u2 catch_type_index = cfs->get_u2_fast();
1828       guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1829                          "Illegal exception table range in class file %s",
1830                          CHECK_NULL);
1831       guarantee_property(handler_pc < code_length,
1832                          "Illegal exception table handler in class file %s",
1833                          CHECK_NULL);
1834       if (catch_type_index != 0) {
1835         guarantee_property(valid_klass_reference_at(catch_type_index),
1836                            "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
1837       }
1838     }
1839   } else {
1840     cfs->skip_u2_fast(exception_table_length * 4);
1841   }
1842   return exception_table_start;
1843 }
1844 
1845 void ClassFileParser::parse_linenumber_table(u4 code_attribute_length,
1846                                              u4 code_length,
1847                                              CompressedLineNumberWriteStream**const write_stream,
1848                                              TRAPS) {
1849 
1850   const ClassFileStream* const cfs = _stream;
1851   unsigned int num_entries = cfs->get_u2(CHECK);
1852 
1853   // Each entry is a u2 start_pc, and a u2 line_number
1854   const unsigned int length_in_bytes = num_entries * (sizeof(u2) * 2);
1855 
1856   // Verify line number attribute and table length
1857   check_property(
1858     code_attribute_length == sizeof(u2) + length_in_bytes,
1859     "LineNumberTable attribute has wrong length in class file %s", CHECK);
1860 
1861   cfs->guarantee_more(length_in_bytes, CHECK);
1862 
1863   if ((*write_stream) == NULL) {
1864     if (length_in_bytes > fixed_buffer_size) {
1865       (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1866     } else {
1867       (*write_stream) = new CompressedLineNumberWriteStream(
1868         _linenumbertable_buffer, fixed_buffer_size);
1869     }
1870   }
1871 
1872   while (num_entries-- > 0) {
1873     const u2 bci  = cfs->get_u2_fast(); // start_pc
1874     const u2 line = cfs->get_u2_fast(); // line_number
1875     guarantee_property(bci < code_length,
1876         "Invalid pc in LineNumberTable in class file %s", CHECK);
1877     (*write_stream)->write_pair(bci, line);
1878   }
1879 }
1880 
1881 
1882 class LVT_Hash : public AllStatic {
1883  public:
1884 
1885   static bool equals(LocalVariableTableElement const& e0, LocalVariableTableElement const& e1) {
1886   /*
1887    * 3-tuple start_bci/length/slot has to be unique key,
1888    * so the following comparison seems to be redundant:
1889    *       && elem->name_cp_index == entry->_elem->name_cp_index
1890    */
1891     return (e0.start_bci     == e1.start_bci &&
1892             e0.length        == e1.length &&
1893             e0.name_cp_index == e1.name_cp_index &&
1894             e0.slot          == e1.slot);
1895   }
1896 
1897   static unsigned int hash(LocalVariableTableElement const& e0) {
1898     unsigned int raw_hash = e0.start_bci;
1899 
1900     raw_hash = e0.length        + raw_hash * 37;
1901     raw_hash = e0.name_cp_index + raw_hash * 37;
1902     raw_hash = e0.slot          + raw_hash * 37;
1903 
1904     return raw_hash;
1905   }
1906 };
1907 
1908 
1909 // Class file LocalVariableTable elements.
1910 class Classfile_LVT_Element VALUE_OBJ_CLASS_SPEC {
1911  public:
1912   u2 start_bci;
1913   u2 length;
1914   u2 name_cp_index;
1915   u2 descriptor_cp_index;
1916   u2 slot;
1917 };
1918 
1919 static void copy_lvt_element(const Classfile_LVT_Element* const src,
1920                              LocalVariableTableElement* const lvt) {
1921   lvt->start_bci           = Bytes::get_Java_u2((u1*) &src->start_bci);
1922   lvt->length              = Bytes::get_Java_u2((u1*) &src->length);
1923   lvt->name_cp_index       = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1924   lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1925   lvt->signature_cp_index  = 0;
1926   lvt->slot                = Bytes::get_Java_u2((u1*) &src->slot);
1927 }
1928 
1929 // Function is used to parse both attributes:
1930 // LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1931 const ClassFileParser::unsafe_u2* ClassFileParser::parse_localvariable_table(const ClassFileStream* cfs,
1932                                                                              u4 code_length,
1933                                                                              u2 max_locals,
1934                                                                              u4 code_attribute_length,
1935                                                                              u2* const localvariable_table_length,
1936                                                                              bool isLVTT,
1937                                                                              TRAPS) {
1938   const char* const tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1939   *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1940   const unsigned int size =
1941     (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);
1942 
1943   const ConstantPool* const cp = _cp;
1944 
1945   // Verify local variable table attribute has right length
1946   if (_need_verify) {
1947     guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1948                        "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1949   }
1950 
1951   const unsafe_u2* const localvariable_table_start = cfs->current();
1952   assert(localvariable_table_start != NULL, "null local variable table");
1953   if (!_need_verify) {
1954     cfs->skip_u2_fast(size);
1955   } else {
1956     cfs->guarantee_more(size * 2, CHECK_NULL);
1957     for(int i = 0; i < (*localvariable_table_length); i++) {
1958       const u2 start_pc = cfs->get_u2_fast();
1959       const u2 length = cfs->get_u2_fast();
1960       const u2 name_index = cfs->get_u2_fast();
1961       const u2 descriptor_index = cfs->get_u2_fast();
1962       const u2 index = cfs->get_u2_fast();
1963       // Assign to a u4 to avoid overflow
1964       const u4 end_pc = (u4)start_pc + (u4)length;
1965 
1966       if (start_pc >= code_length) {
1967         classfile_parse_error(
1968           "Invalid start_pc %u in %s in class file %s",
1969           start_pc, tbl_name, CHECK_NULL);
1970       }
1971       if (end_pc > code_length) {
1972         classfile_parse_error(
1973           "Invalid length %u in %s in class file %s",
1974           length, tbl_name, CHECK_NULL);
1975       }
1976       const int cp_size = cp->length();
1977       guarantee_property(valid_symbol_at(name_index),
1978         "Name index %u in %s has bad constant type in class file %s",
1979         name_index, tbl_name, CHECK_NULL);
1980       guarantee_property(valid_symbol_at(descriptor_index),
1981         "Signature index %u in %s has bad constant type in class file %s",
1982         descriptor_index, tbl_name, CHECK_NULL);
1983 
1984       const Symbol* const name = cp->symbol_at(name_index);
1985       const Symbol* const sig = cp->symbol_at(descriptor_index);
1986       verify_legal_field_name(name, CHECK_NULL);
1987       u2 extra_slot = 0;
1988       if (!isLVTT) {
1989         verify_legal_field_signature(name, sig, CHECK_NULL);
1990 
1991         // 4894874: check special cases for double and long local variables
1992         if (sig == vmSymbols::type_signature(T_DOUBLE) ||
1993             sig == vmSymbols::type_signature(T_LONG)) {
1994           extra_slot = 1;
1995         }
1996       }
1997       guarantee_property((index + extra_slot) < max_locals,
1998                           "Invalid index %u in %s in class file %s",
1999                           index, tbl_name, CHECK_NULL);
2000     }
2001   }
2002   return localvariable_table_start;
2003 }
2004 
2005 
2006 void ClassFileParser::parse_type_array(u2 array_length,
2007                                        u4 code_length,
2008                                        u4* const u1_index,
2009                                        u4* const u2_index,
2010                                        u1* const u1_array,
2011                                        u2* const u2_array,
2012                                        TRAPS) {
2013   const ClassFileStream* const cfs = _stream;
2014   u2 index = 0; // index in the array with long/double occupying two slots
2015   u4 i1 = *u1_index;
2016   u4 i2 = *u2_index + 1;
2017   for(int i = 0; i < array_length; i++) {
2018     const u1 tag = u1_array[i1++] = cfs->get_u1(CHECK);
2019     index++;
2020     if (tag == ITEM_Long || tag == ITEM_Double) {
2021       index++;
2022     } else if (tag == ITEM_Object) {
2023       const u2 class_index = u2_array[i2++] = cfs->get_u2(CHECK);
2024       guarantee_property(valid_klass_reference_at(class_index),
2025                          "Bad class index %u in StackMap in class file %s",
2026                          class_index, CHECK);
2027     } else if (tag == ITEM_Uninitialized) {
2028       const u2 offset = u2_array[i2++] = cfs->get_u2(CHECK);
2029       guarantee_property(
2030         offset < code_length,
2031         "Bad uninitialized type offset %u in StackMap in class file %s",
2032         offset, CHECK);
2033     } else {
2034       guarantee_property(
2035         tag <= (u1)ITEM_Uninitialized,
2036         "Unknown variable type %u in StackMap in class file %s",
2037         tag, CHECK);
2038     }
2039   }
2040   u2_array[*u2_index] = index;
2041   *u1_index = i1;
2042   *u2_index = i2;
2043 }
2044 
2045 static const u1* parse_stackmap_table(const ClassFileStream* const cfs,
2046                                       u4 code_attribute_length,
2047                                       bool need_verify,
2048                                       TRAPS) {
2049   assert(cfs != NULL, "invariant");
2050 
2051   if (0 == code_attribute_length) {
2052     return NULL;
2053   }
2054 
2055   const u1* const stackmap_table_start = cfs->current();
2056   assert(stackmap_table_start != NULL, "null stackmap table");
2057 
2058   // check code_attribute_length first
2059   cfs->skip_u1(code_attribute_length, CHECK_NULL);
2060 
2061   if (!need_verify && !DumpSharedSpaces) {
2062     return NULL;
2063   }
2064   return stackmap_table_start;
2065 }
2066 
2067 const ClassFileParser::unsafe_u2* ClassFileParser::parse_checked_exceptions(const ClassFileStream* const cfs,
2068                                                                             u2* const checked_exceptions_length,
2069                                                                             u4 method_attribute_length,
2070                                                                             TRAPS) {
2071   assert(cfs != NULL, "invariant");
2072   assert(checked_exceptions_length != NULL, "invariant");
2073 
2074   cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
2075   *checked_exceptions_length = cfs->get_u2_fast();
2076   const unsigned int size =
2077     (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
2078   const unsafe_u2* const checked_exceptions_start = cfs->current();
2079   assert(checked_exceptions_start != NULL, "null checked exceptions");
2080   if (!_need_verify) {
2081     cfs->skip_u2_fast(size);
2082   } else {
2083     // Verify each value in the checked exception table
2084     u2 checked_exception;
2085     const u2 len = *checked_exceptions_length;
2086     cfs->guarantee_more(2 * len, CHECK_NULL);
2087     for (int i = 0; i < len; i++) {
2088       checked_exception = cfs->get_u2_fast();
2089       check_property(
2090         valid_klass_reference_at(checked_exception),
2091         "Exception name has bad type at constant pool %u in class file %s",
2092         checked_exception, CHECK_NULL);
2093     }
2094   }
2095   // check exceptions attribute length
2096   if (_need_verify) {
2097     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
2098                                                    sizeof(u2) * size),
2099                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
2100   }
2101   return checked_exceptions_start;
2102 }
2103 
2104 void ClassFileParser::throwIllegalSignature(const char* type,
2105                                             const Symbol* name,
2106                                             const Symbol* sig,
2107                                             TRAPS) const {
2108   assert(name != NULL, "invariant");
2109   assert(sig != NULL, "invariant");
2110 
2111   ResourceMark rm(THREAD);
2112   Exceptions::fthrow(THREAD_AND_LOCATION,
2113       vmSymbols::java_lang_ClassFormatError(),
2114       "%s \"%s\" in class %s has illegal signature \"%s\"", type,
2115       name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
2116 }
2117 
2118 AnnotationCollector::ID
2119 AnnotationCollector::annotation_index(const ClassLoaderData* loader_data,
2120                                       const Symbol* name) {
2121   const vmSymbols::SID sid = vmSymbols::find_sid(name);
2122   // Privileged code can use all annotations.  Other code silently drops some.
2123   const bool privileged = loader_data->is_the_null_class_loader_data() ||
2124                           loader_data->is_platform_class_loader_data() ||
2125                           loader_data->is_anonymous();
2126   switch (sid) {
2127     case vmSymbols::VM_SYMBOL_ENUM_NAME(reflect_CallerSensitive_signature): {
2128       if (_location != _in_method)  break;  // only allow for methods
2129       if (!privileged)              break;  // only allow in privileged code
2130       return _method_CallerSensitive;
2131     }
2132     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ForceInline_signature): {
2133       if (_location != _in_method)  break;  // only allow for methods
2134       if (!privileged)              break;  // only allow in privileged code
2135       return _method_ForceInline;
2136     }
2137     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_DontInline_signature): {
2138       if (_location != _in_method)  break;  // only allow for methods
2139       if (!privileged)              break;  // only allow in privileged code
2140       return _method_DontInline;
2141     }
2142     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature): {
2143       if (_location != _in_method)  break;  // only allow for methods
2144       if (!privileged)              break;  // only allow in privileged code
2145       return _method_InjectedProfile;
2146     }
2147     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature): {
2148       if (_location != _in_method)  break;  // only allow for methods
2149       if (!privileged)              break;  // only allow in privileged code
2150       return _method_LambdaForm_Compiled;
2151     }
2152     case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Hidden_signature): {
2153       if (_location != _in_method)  break;  // only allow for methods
2154       if (!privileged)              break;  // only allow in privileged code
2155       return _method_LambdaForm_Hidden;
2156     }
2157     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_HotSpotIntrinsicCandidate_signature): {
2158       if (_location != _in_method)  break;  // only allow for methods
2159       if (!privileged)              break;  // only allow in privileged code
2160       return _method_HotSpotIntrinsicCandidate;
2161     }
2162     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Stable_signature): {
2163       if (_location != _in_field)   break;  // only allow for fields
2164       if (!privileged)              break;  // only allow in privileged code
2165       return _field_Stable;
2166     }
2167     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_Contended_signature): {
2168       if (_location != _in_field && _location != _in_class) {
2169         break;  // only allow for fields and classes
2170       }
2171       if (!EnableContended || (RestrictContended && !privileged)) {
2172         break;  // honor privileges
2173       }
2174       return _jdk_internal_vm_annotation_Contended;
2175     }
2176     case vmSymbols::VM_SYMBOL_ENUM_NAME(jdk_internal_vm_annotation_ReservedStackAccess_signature): {
2177       if (_location != _in_method)  break;  // only allow for methods
2178       if (RestrictReservedStack && !privileged) break; // honor privileges
2179       return _jdk_internal_vm_annotation_ReservedStackAccess;
2180     }
2181     default: {
2182       break;
2183     }
2184   }
2185   return AnnotationCollector::_unknown;
2186 }
2187 
2188 void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
2189   if (is_contended())
2190     f->set_contended_group(contended_group());
2191   if (is_stable())
2192     f->set_stable(true);
2193 }
2194 
2195 ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
2196   // If there's an error deallocate metadata for field annotations
2197   MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
2198   MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
2199 }
2200 
2201 void MethodAnnotationCollector::apply_to(const methodHandle& m) {
2202   if (has_annotation(_method_CallerSensitive))
2203     m->set_caller_sensitive(true);
2204   if (has_annotation(_method_ForceInline))
2205     m->set_force_inline(true);
2206   if (has_annotation(_method_DontInline))
2207     m->set_dont_inline(true);
2208   if (has_annotation(_method_InjectedProfile))
2209     m->set_has_injected_profile(true);
2210   if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
2211     m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
2212   if (has_annotation(_method_LambdaForm_Hidden))
2213     m->set_hidden(true);
2214   if (has_annotation(_method_HotSpotIntrinsicCandidate) && !m->is_synthetic())
2215     m->set_intrinsic_candidate(true);
2216   if (has_annotation(_jdk_internal_vm_annotation_ReservedStackAccess))
2217     m->set_has_reserved_stack_access(true);
2218 }
2219 
2220 void ClassFileParser::ClassAnnotationCollector::apply_to(InstanceKlass* ik) {
2221   assert(ik != NULL, "invariant");
2222   ik->set_is_contended(is_contended());
2223 }
2224 
2225 #define MAX_ARGS_SIZE 255
2226 #define MAX_CODE_SIZE 65535
2227 #define INITIAL_MAX_LVT_NUMBER 256
2228 
2229 /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2230  *
2231  * Rules for LVT's and LVTT's are:
2232  *   - There can be any number of LVT's and LVTT's.
2233  *   - If there are n LVT's, it is the same as if there was just
2234  *     one LVT containing all the entries from the n LVT's.
2235  *   - There may be no more than one LVT entry per local variable.
2236  *     Two LVT entries are 'equal' if these fields are the same:
2237  *        start_pc, length, name, slot
2238  *   - There may be no more than one LVTT entry per each LVT entry.
2239  *     Each LVTT entry has to match some LVT entry.
2240  *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
2241  */
2242 void ClassFileParser::copy_localvariable_table(const ConstMethod* cm,
2243                                                int lvt_cnt,
2244                                                u2* const localvariable_table_length,
2245                                                const unsafe_u2** const localvariable_table_start,
2246                                                int lvtt_cnt,
2247                                                u2* const localvariable_type_table_length,
2248                                                const unsafe_u2** const localvariable_type_table_start,
2249                                                TRAPS) {
2250 
2251   ResourceMark rm(THREAD);
2252 
2253   typedef ResourceHashtable<LocalVariableTableElement, LocalVariableTableElement*,
2254                             &LVT_Hash::hash, &LVT_Hash::equals> LVT_HashTable;
2255 
2256   LVT_HashTable* const table = new LVT_HashTable();
2257 
2258   // To fill LocalVariableTable in
2259   const Classfile_LVT_Element* cf_lvt;
2260   LocalVariableTableElement* lvt = cm->localvariable_table_start();
2261 
2262   for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
2263     cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
2264     for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
2265       copy_lvt_element(&cf_lvt[idx], lvt);
2266       // If no duplicates, add LVT elem in hashtable.
2267       if (table->put(*lvt, lvt) == false
2268           && _need_verify
2269           && _major_version >= JAVA_1_5_VERSION) {
2270         classfile_parse_error("Duplicated LocalVariableTable attribute "
2271                               "entry for '%s' in class file %s",
2272                                _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
2273                                CHECK);
2274       }
2275     }
2276   }
2277 
2278   // To merge LocalVariableTable and LocalVariableTypeTable
2279   const Classfile_LVT_Element* cf_lvtt;
2280   LocalVariableTableElement lvtt_elem;
2281 
2282   for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2283     cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2284     for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2285       copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2286       LocalVariableTableElement** entry = table->get(lvtt_elem);
2287       if (entry == NULL) {
2288         if (_need_verify) {
2289           classfile_parse_error("LVTT entry for '%s' in class file %s "
2290                                 "does not match any LVT entry",
2291                                  _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2292                                  CHECK);
2293         }
2294       } else if ((*entry)->signature_cp_index != 0 && _need_verify) {
2295         classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2296                               "entry for '%s' in class file %s",
2297                                _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2298                                CHECK);
2299       } else {
2300         // to add generic signatures into LocalVariableTable
2301         (*entry)->signature_cp_index = lvtt_elem.descriptor_cp_index;
2302       }
2303     }
2304   }
2305 }
2306 
2307 
2308 void ClassFileParser::copy_method_annotations(ConstMethod* cm,
2309                                        const u1* runtime_visible_annotations,
2310                                        int runtime_visible_annotations_length,
2311                                        const u1* runtime_invisible_annotations,
2312                                        int runtime_invisible_annotations_length,
2313                                        const u1* runtime_visible_parameter_annotations,
2314                                        int runtime_visible_parameter_annotations_length,
2315                                        const u1* runtime_invisible_parameter_annotations,
2316                                        int runtime_invisible_parameter_annotations_length,
2317                                        const u1* runtime_visible_type_annotations,
2318                                        int runtime_visible_type_annotations_length,
2319                                        const u1* runtime_invisible_type_annotations,
2320                                        int runtime_invisible_type_annotations_length,
2321                                        const u1* annotation_default,
2322                                        int annotation_default_length,
2323                                        TRAPS) {
2324 
2325   AnnotationArray* a;
2326 
2327   if (runtime_visible_annotations_length +
2328       runtime_invisible_annotations_length > 0) {
2329      a = assemble_annotations(runtime_visible_annotations,
2330                               runtime_visible_annotations_length,
2331                               runtime_invisible_annotations,
2332                               runtime_invisible_annotations_length,
2333                               CHECK);
2334      cm->set_method_annotations(a);
2335   }
2336 
2337   if (runtime_visible_parameter_annotations_length +
2338       runtime_invisible_parameter_annotations_length > 0) {
2339     a = assemble_annotations(runtime_visible_parameter_annotations,
2340                              runtime_visible_parameter_annotations_length,
2341                              runtime_invisible_parameter_annotations,
2342                              runtime_invisible_parameter_annotations_length,
2343                              CHECK);
2344     cm->set_parameter_annotations(a);
2345   }
2346 
2347   if (annotation_default_length > 0) {
2348     a = assemble_annotations(annotation_default,
2349                              annotation_default_length,
2350                              NULL,
2351                              0,
2352                              CHECK);
2353     cm->set_default_annotations(a);
2354   }
2355 
2356   if (runtime_visible_type_annotations_length +
2357       runtime_invisible_type_annotations_length > 0) {
2358     a = assemble_annotations(runtime_visible_type_annotations,
2359                              runtime_visible_type_annotations_length,
2360                              runtime_invisible_type_annotations,
2361                              runtime_invisible_type_annotations_length,
2362                              CHECK);
2363     cm->set_type_annotations(a);
2364   }
2365 }
2366 
2367 
2368 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2369 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2370 // Method* to save footprint, so we only know the size of the resulting Method* when the
2371 // entire method attribute is parsed.
2372 //
2373 // The promoted_flags parameter is used to pass relevant access_flags
2374 // from the method back up to the containing klass. These flag values
2375 // are added to klass's access_flags.
2376 
2377 Method* ClassFileParser::parse_method(const ClassFileStream* const cfs,
2378                                       bool is_interface,
2379                                       const ConstantPool* cp,
2380                                       AccessFlags* const promoted_flags,
2381                                       TRAPS) {
2382   assert(cfs != NULL, "invariant");
2383   assert(cp != NULL, "invariant");
2384   assert(promoted_flags != NULL, "invariant");
2385 
2386   ResourceMark rm(THREAD);
2387   // Parse fixed parts:
2388   // access_flags, name_index, descriptor_index, attributes_count
2389   cfs->guarantee_more(8, CHECK_NULL);
2390 
2391   int flags = cfs->get_u2_fast();
2392   const u2 name_index = cfs->get_u2_fast();
2393   const int cp_size = cp->length();
2394   check_property(
2395     valid_symbol_at(name_index),
2396     "Illegal constant pool index %u for method name in class file %s",
2397     name_index, CHECK_NULL);
2398   const Symbol* const name = cp->symbol_at(name_index);
2399   verify_legal_method_name(name, CHECK_NULL);
2400 
2401   const u2 signature_index = cfs->get_u2_fast();
2402   guarantee_property(
2403     valid_symbol_at(signature_index),
2404     "Illegal constant pool index %u for method signature in class file %s",
2405     signature_index, CHECK_NULL);
2406   const Symbol* const signature = cp->symbol_at(signature_index);
2407 
2408   if (name == vmSymbols::class_initializer_name()) {
2409     // We ignore the other access flags for a valid class initializer.
2410     // (JVM Spec 2nd ed., chapter 4.6)
2411     if (_major_version < 51) { // backward compatibility
2412       flags = JVM_ACC_STATIC;
2413     } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
2414       flags &= JVM_ACC_STATIC | JVM_ACC_STRICT;
2415     } else {
2416       classfile_parse_error("Method <clinit> is not static in class file %s", CHECK_NULL);
2417     }
2418   } else {
2419     verify_legal_method_modifiers(flags, is_interface, name, CHECK_NULL);
2420   }
2421 
2422   if (name == vmSymbols::object_initializer_name() && is_interface) {
2423     classfile_parse_error("Interface cannot have a method named <init>, class file %s", CHECK_NULL);
2424   }
2425 
2426   int args_size = -1;  // only used when _need_verify is true
2427   if (_need_verify) {
2428     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
2429                  verify_legal_method_signature(name, signature, CHECK_NULL);
2430     if (args_size > MAX_ARGS_SIZE) {
2431       classfile_parse_error("Too many arguments in method signature in class file %s", CHECK_NULL);
2432     }
2433   }
2434 
2435   AccessFlags access_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
2436 
2437   // Default values for code and exceptions attribute elements
2438   u2 max_stack = 0;
2439   u2 max_locals = 0;
2440   u4 code_length = 0;
2441   const u1* code_start = 0;
2442   u2 exception_table_length = 0;
2443   const unsafe_u2* exception_table_start = NULL; // (potentially unaligned) pointer to array of u2 elements
2444   Array<int>* exception_handlers = Universe::the_empty_int_array();
2445   u2 checked_exceptions_length = 0;
2446   const unsafe_u2* checked_exceptions_start = NULL; // (potentially unaligned) pointer to array of u2 elements
2447   CompressedLineNumberWriteStream* linenumber_table = NULL;
2448   int linenumber_table_length = 0;
2449   int total_lvt_length = 0;
2450   u2 lvt_cnt = 0;
2451   u2 lvtt_cnt = 0;
2452   bool lvt_allocated = false;
2453   u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
2454   u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
2455   u2* localvariable_table_length = NULL;
2456   const unsafe_u2** localvariable_table_start = NULL; // (potentially unaligned) pointer to array of LVT attributes
2457   u2* localvariable_type_table_length = NULL;
2458   const unsafe_u2** localvariable_type_table_start = NULL; // (potentially unaligned) pointer to LVTT attributes
2459   int method_parameters_length = -1;
2460   const u1* method_parameters_data = NULL;
2461   bool method_parameters_seen = false;
2462   bool parsed_code_attribute = false;
2463   bool parsed_checked_exceptions_attribute = false;
2464   bool parsed_stackmap_attribute = false;
2465   // stackmap attribute - JDK1.5
2466   const u1* stackmap_data = NULL;
2467   int stackmap_data_length = 0;
2468   u2 generic_signature_index = 0;
2469   MethodAnnotationCollector parsed_annotations;
2470   const u1* runtime_visible_annotations = NULL;
2471   int runtime_visible_annotations_length = 0;
2472   const u1* runtime_invisible_annotations = NULL;
2473   int runtime_invisible_annotations_length = 0;
2474   const u1* runtime_visible_parameter_annotations = NULL;
2475   int runtime_visible_parameter_annotations_length = 0;
2476   const u1* runtime_invisible_parameter_annotations = NULL;
2477   int runtime_invisible_parameter_annotations_length = 0;
2478   const u1* runtime_visible_type_annotations = NULL;
2479   int runtime_visible_type_annotations_length = 0;
2480   const u1* runtime_invisible_type_annotations = NULL;
2481   int runtime_invisible_type_annotations_length = 0;
2482   bool runtime_invisible_annotations_exists = false;
2483   bool runtime_invisible_type_annotations_exists = false;
2484   bool runtime_invisible_parameter_annotations_exists = false;
2485   const u1* annotation_default = NULL;
2486   int annotation_default_length = 0;
2487 
2488   // Parse code and exceptions attribute
2489   u2 method_attributes_count = cfs->get_u2_fast();
2490   while (method_attributes_count--) {
2491     cfs->guarantee_more(6, CHECK_NULL);  // method_attribute_name_index, method_attribute_length
2492     const u2 method_attribute_name_index = cfs->get_u2_fast();
2493     const u4 method_attribute_length = cfs->get_u4_fast();
2494     check_property(
2495       valid_symbol_at(method_attribute_name_index),
2496       "Invalid method attribute name index %u in class file %s",
2497       method_attribute_name_index, CHECK_NULL);
2498 
2499     const Symbol* const method_attribute_name = cp->symbol_at(method_attribute_name_index);
2500     if (method_attribute_name == vmSymbols::tag_code()) {
2501       // Parse Code attribute
2502       if (_need_verify) {
2503         guarantee_property(
2504             !access_flags.is_native() && !access_flags.is_abstract(),
2505                         "Code attribute in native or abstract methods in class file %s",
2506                          CHECK_NULL);
2507       }
2508       if (parsed_code_attribute) {
2509         classfile_parse_error("Multiple Code attributes in class file %s",
2510                               CHECK_NULL);
2511       }
2512       parsed_code_attribute = true;
2513 
2514       // Stack size, locals size, and code size
2515       if (_major_version == 45 && _minor_version <= 2) {
2516         cfs->guarantee_more(4, CHECK_NULL);
2517         max_stack = cfs->get_u1_fast();
2518         max_locals = cfs->get_u1_fast();
2519         code_length = cfs->get_u2_fast();
2520       } else {
2521         cfs->guarantee_more(8, CHECK_NULL);
2522         max_stack = cfs->get_u2_fast();
2523         max_locals = cfs->get_u2_fast();
2524         code_length = cfs->get_u4_fast();
2525       }
2526       if (_need_verify) {
2527         guarantee_property(args_size <= max_locals,
2528                            "Arguments can't fit into locals in class file %s",
2529                            CHECK_NULL);
2530         guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
2531                            "Invalid method Code length %u in class file %s",
2532                            code_length, CHECK_NULL);
2533       }
2534       // Code pointer
2535       code_start = cfs->current();
2536       assert(code_start != NULL, "null code start");
2537       cfs->guarantee_more(code_length, CHECK_NULL);
2538       cfs->skip_u1_fast(code_length);
2539 
2540       // Exception handler table
2541       cfs->guarantee_more(2, CHECK_NULL);  // exception_table_length
2542       exception_table_length = cfs->get_u2_fast();
2543       if (exception_table_length > 0) {
2544         exception_table_start = parse_exception_table(cfs,
2545                                                       code_length,
2546                                                       exception_table_length,
2547                                                       CHECK_NULL);
2548       }
2549 
2550       // Parse additional attributes in code attribute
2551       cfs->guarantee_more(2, CHECK_NULL);  // code_attributes_count
2552       u2 code_attributes_count = cfs->get_u2_fast();
2553 
2554       unsigned int calculated_attribute_length = 0;
2555 
2556       if (_major_version > 45 || (_major_version == 45 && _minor_version > 2)) {
2557         calculated_attribute_length =
2558             sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
2559       } else {
2560         // max_stack, locals and length are smaller in pre-version 45.2 classes
2561         calculated_attribute_length = sizeof(u1) + sizeof(u1) + sizeof(u2);
2562       }
2563       calculated_attribute_length +=
2564         code_length +
2565         sizeof(exception_table_length) +
2566         sizeof(code_attributes_count) +
2567         exception_table_length *
2568             ( sizeof(u2) +   // start_pc
2569               sizeof(u2) +   // end_pc
2570               sizeof(u2) +   // handler_pc
2571               sizeof(u2) );  // catch_type_index
2572 
2573       while (code_attributes_count--) {
2574         cfs->guarantee_more(6, CHECK_NULL);  // code_attribute_name_index, code_attribute_length
2575         const u2 code_attribute_name_index = cfs->get_u2_fast();
2576         const u4 code_attribute_length = cfs->get_u4_fast();
2577         calculated_attribute_length += code_attribute_length +
2578                                        sizeof(code_attribute_name_index) +
2579                                        sizeof(code_attribute_length);
2580         check_property(valid_symbol_at(code_attribute_name_index),
2581                        "Invalid code attribute name index %u in class file %s",
2582                        code_attribute_name_index,
2583                        CHECK_NULL);
2584         if (LoadLineNumberTables &&
2585             cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
2586           // Parse and compress line number table
2587           parse_linenumber_table(code_attribute_length,
2588                                  code_length,
2589                                  &linenumber_table,
2590                                  CHECK_NULL);
2591 
2592         } else if (LoadLocalVariableTables &&
2593                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
2594           // Parse local variable table
2595           if (!lvt_allocated) {
2596             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2597               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2598             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2599               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2600             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2601               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2602             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2603               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2604             lvt_allocated = true;
2605           }
2606           if (lvt_cnt == max_lvt_cnt) {
2607             max_lvt_cnt <<= 1;
2608             localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
2609             localvariable_table_start  = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
2610           }
2611           localvariable_table_start[lvt_cnt] =
2612             parse_localvariable_table(cfs,
2613                                       code_length,
2614                                       max_locals,
2615                                       code_attribute_length,
2616                                       &localvariable_table_length[lvt_cnt],
2617                                       false,    // is not LVTT
2618                                       CHECK_NULL);
2619           total_lvt_length += localvariable_table_length[lvt_cnt];
2620           lvt_cnt++;
2621         } else if (LoadLocalVariableTypeTables &&
2622                    _major_version >= JAVA_1_5_VERSION &&
2623                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
2624           if (!lvt_allocated) {
2625             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2626               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2627             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2628               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2629             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
2630               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
2631             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
2632               THREAD, const unsafe_u2*, INITIAL_MAX_LVT_NUMBER);
2633             lvt_allocated = true;
2634           }
2635           // Parse local variable type table
2636           if (lvtt_cnt == max_lvtt_cnt) {
2637             max_lvtt_cnt <<= 1;
2638             localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
2639             localvariable_type_table_start  = REALLOC_RESOURCE_ARRAY(const unsafe_u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
2640           }
2641           localvariable_type_table_start[lvtt_cnt] =
2642             parse_localvariable_table(cfs,
2643                                       code_length,
2644                                       max_locals,
2645                                       code_attribute_length,
2646                                       &localvariable_type_table_length[lvtt_cnt],
2647                                       true,     // is LVTT
2648                                       CHECK_NULL);
2649           lvtt_cnt++;
2650         } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2651                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
2652           // Stack map is only needed by the new verifier in JDK1.5.
2653           if (parsed_stackmap_attribute) {
2654             classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_NULL);
2655           }
2656           stackmap_data = parse_stackmap_table(cfs, code_attribute_length, _need_verify, CHECK_NULL);
2657           stackmap_data_length = code_attribute_length;
2658           parsed_stackmap_attribute = true;
2659         } else {
2660           // Skip unknown attributes
2661           cfs->skip_u1(code_attribute_length, CHECK_NULL);
2662         }
2663       }
2664       // check method attribute length
2665       if (_need_verify) {
2666         guarantee_property(method_attribute_length == calculated_attribute_length,
2667                            "Code segment has wrong length in class file %s",
2668                            CHECK_NULL);
2669       }
2670     } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
2671       // Parse Exceptions attribute
2672       if (parsed_checked_exceptions_attribute) {
2673         classfile_parse_error("Multiple Exceptions attributes in class file %s",
2674                               CHECK_NULL);
2675       }
2676       parsed_checked_exceptions_attribute = true;
2677       checked_exceptions_start =
2678             parse_checked_exceptions(cfs,
2679                                      &checked_exceptions_length,
2680                                      method_attribute_length,
2681                                      CHECK_NULL);
2682     } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2683       // reject multiple method parameters
2684       if (method_parameters_seen) {
2685         classfile_parse_error("Multiple MethodParameters attributes in class file %s",
2686                               CHECK_NULL);
2687       }
2688       method_parameters_seen = true;
2689       method_parameters_length = cfs->get_u1_fast();
2690       const u2 real_length = (method_parameters_length * 4u) + 1u;
2691       if (method_attribute_length != real_length) {
2692         classfile_parse_error(
2693           "Invalid MethodParameters method attribute length %u in class file",
2694           method_attribute_length, CHECK_NULL);
2695       }
2696       method_parameters_data = cfs->current();
2697       cfs->skip_u2_fast(method_parameters_length);
2698       cfs->skip_u2_fast(method_parameters_length);
2699       // ignore this attribute if it cannot be reflected
2700       if (!SystemDictionary::Parameter_klass_loaded())
2701         method_parameters_length = -1;
2702     } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
2703       if (method_attribute_length != 0) {
2704         classfile_parse_error(
2705           "Invalid Synthetic method attribute length %u in class file %s",
2706           method_attribute_length, CHECK_NULL);
2707       }
2708       // Should we check that there hasn't already been a synthetic attribute?
2709       access_flags.set_is_synthetic();
2710     } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
2711       if (method_attribute_length != 0) {
2712         classfile_parse_error(
2713           "Invalid Deprecated method attribute length %u in class file %s",
2714           method_attribute_length, CHECK_NULL);
2715       }
2716     } else if (_major_version >= JAVA_1_5_VERSION) {
2717       if (method_attribute_name == vmSymbols::tag_signature()) {
2718         if (generic_signature_index != 0) {
2719           classfile_parse_error(
2720             "Multiple Signature attributes for method in class file %s",
2721             CHECK_NULL);
2722         }
2723         if (method_attribute_length != 2) {
2724           classfile_parse_error(
2725             "Invalid Signature attribute length %u in class file %s",
2726             method_attribute_length, CHECK_NULL);
2727         }
2728         generic_signature_index = parse_generic_signature_attribute(cfs, CHECK_NULL);
2729       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
2730         if (runtime_visible_annotations != NULL) {
2731           classfile_parse_error(
2732             "Multiple RuntimeVisibleAnnotations attributes for method in class file %s",
2733             CHECK_NULL);
2734         }
2735         runtime_visible_annotations_length = method_attribute_length;
2736         runtime_visible_annotations = cfs->current();
2737         assert(runtime_visible_annotations != NULL, "null visible annotations");
2738         cfs->guarantee_more(runtime_visible_annotations_length, CHECK_NULL);
2739         parse_annotations(cp,
2740                           runtime_visible_annotations,
2741                           runtime_visible_annotations_length,
2742                           &parsed_annotations,
2743                           _loader_data,
2744                           CHECK_NULL);
2745         cfs->skip_u1_fast(runtime_visible_annotations_length);
2746       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
2747         if (runtime_invisible_annotations_exists) {
2748           classfile_parse_error(
2749             "Multiple RuntimeInvisibleAnnotations attributes for method in class file %s",
2750             CHECK_NULL);
2751         }
2752         runtime_invisible_annotations_exists = true;
2753         if (PreserveAllAnnotations) {
2754           runtime_invisible_annotations_length = method_attribute_length;
2755           runtime_invisible_annotations = cfs->current();
2756           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
2757         }
2758         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2759       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
2760         if (runtime_visible_parameter_annotations != NULL) {
2761           classfile_parse_error(
2762             "Multiple RuntimeVisibleParameterAnnotations attributes for method in class file %s",
2763             CHECK_NULL);
2764         }
2765         runtime_visible_parameter_annotations_length = method_attribute_length;
2766         runtime_visible_parameter_annotations = cfs->current();
2767         assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");
2768         cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_NULL);
2769       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
2770         if (runtime_invisible_parameter_annotations_exists) {
2771           classfile_parse_error(
2772             "Multiple RuntimeInvisibleParameterAnnotations attributes for method in class file %s",
2773             CHECK_NULL);
2774         }
2775         runtime_invisible_parameter_annotations_exists = true;
2776         if (PreserveAllAnnotations) {
2777           runtime_invisible_parameter_annotations_length = method_attribute_length;
2778           runtime_invisible_parameter_annotations = cfs->current();
2779           assert(runtime_invisible_parameter_annotations != NULL,
2780             "null invisible parameter annotations");
2781         }
2782         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2783       } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
2784         if (annotation_default != NULL) {
2785           classfile_parse_error(
2786             "Multiple AnnotationDefault attributes for method in class file %s",
2787             CHECK_NULL);
2788         }
2789         annotation_default_length = method_attribute_length;
2790         annotation_default = cfs->current();
2791         assert(annotation_default != NULL, "null annotation default");
2792         cfs->skip_u1(annotation_default_length, CHECK_NULL);
2793       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2794         if (runtime_visible_type_annotations != NULL) {
2795           classfile_parse_error(
2796             "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
2797             CHECK_NULL);
2798         }
2799         runtime_visible_type_annotations_length = method_attribute_length;
2800         runtime_visible_type_annotations = cfs->current();
2801         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
2802         // No need for the VM to parse Type annotations
2803         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_NULL);
2804       } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
2805         if (runtime_invisible_type_annotations_exists) {
2806           classfile_parse_error(
2807             "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
2808             CHECK_NULL);
2809         } else {
2810           runtime_invisible_type_annotations_exists = true;
2811         }
2812         if (PreserveAllAnnotations) {
2813           runtime_invisible_type_annotations_length = method_attribute_length;
2814           runtime_invisible_type_annotations = cfs->current();
2815           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
2816         }
2817         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2818       } else {
2819         // Skip unknown attributes
2820         cfs->skip_u1(method_attribute_length, CHECK_NULL);
2821       }
2822     } else {
2823       // Skip unknown attributes
2824       cfs->skip_u1(method_attribute_length, CHECK_NULL);
2825     }
2826   }
2827 
2828   if (linenumber_table != NULL) {
2829     linenumber_table->write_terminator();
2830     linenumber_table_length = linenumber_table->position();
2831   }
2832 
2833   // Make sure there's at least one Code attribute in non-native/non-abstract method
2834   if (_need_verify) {
2835     guarantee_property(access_flags.is_native() ||
2836                        access_flags.is_abstract() ||
2837                        parsed_code_attribute,
2838                        "Absent Code attribute in method that is not native or abstract in class file %s",
2839                        CHECK_NULL);
2840   }
2841 
2842   // All sizing information for a Method* is finally available, now create it
2843   InlineTableSizes sizes(
2844       total_lvt_length,
2845       linenumber_table_length,
2846       exception_table_length,
2847       checked_exceptions_length,
2848       method_parameters_length,
2849       generic_signature_index,
2850       runtime_visible_annotations_length +
2851            runtime_invisible_annotations_length,
2852       runtime_visible_parameter_annotations_length +
2853            runtime_invisible_parameter_annotations_length,
2854       runtime_visible_type_annotations_length +
2855            runtime_invisible_type_annotations_length,
2856       annotation_default_length,
2857       0);
2858 
2859   Method* const m = Method::allocate(_loader_data,
2860                                      code_length,
2861                                      access_flags,
2862                                      &sizes,
2863                                      ConstMethod::NORMAL,
2864                                      CHECK_NULL);
2865 
2866   ClassLoadingService::add_class_method_size(m->size()*wordSize);
2867 
2868   // Fill in information from fixed part (access_flags already set)
2869   m->set_constants(_cp);
2870   m->set_name_index(name_index);
2871   m->set_signature_index(signature_index);
2872 
2873   ResultTypeFinder rtf(cp->symbol_at(signature_index));
2874   m->constMethod()->set_result_type(rtf.type());
2875 
2876   if (args_size >= 0) {
2877     m->set_size_of_parameters(args_size);
2878   } else {
2879     m->compute_size_of_parameters(THREAD);
2880   }
2881 #ifdef ASSERT
2882   if (args_size >= 0) {
2883     m->compute_size_of_parameters(THREAD);
2884     assert(args_size == m->size_of_parameters(), "");
2885   }
2886 #endif
2887 
2888   // Fill in code attribute information
2889   m->set_max_stack(max_stack);
2890   m->set_max_locals(max_locals);
2891   if (stackmap_data != NULL) {
2892     m->constMethod()->copy_stackmap_data(_loader_data,
2893                                          (u1*)stackmap_data,
2894                                          stackmap_data_length,
2895                                          CHECK_NULL);
2896   }
2897 
2898   // Copy byte codes
2899   m->set_code((u1*)code_start);
2900 
2901   // Copy line number table
2902   if (linenumber_table != NULL) {
2903     memcpy(m->compressed_linenumber_table(),
2904            linenumber_table->buffer(),
2905            linenumber_table_length);
2906   }
2907 
2908   // Copy exception table
2909   if (exception_table_length > 0) {
2910     Copy::conjoint_swap_if_needed<Endian::JAVA>(exception_table_start,
2911                                                 m->exception_table_start(),
2912                                                 exception_table_length * sizeof(ExceptionTableElement),
2913                                                 sizeof(u2));
2914   }
2915 
2916   // Copy method parameters
2917   if (method_parameters_length > 0) {
2918     MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2919     for (int i = 0; i < method_parameters_length; i++) {
2920       elem[i].name_cp_index = Bytes::get_Java_u2((address)method_parameters_data);
2921       method_parameters_data += 2;
2922       elem[i].flags = Bytes::get_Java_u2((address)method_parameters_data);
2923       method_parameters_data += 2;
2924     }
2925   }
2926 
2927   // Copy checked exceptions
2928   if (checked_exceptions_length > 0) {
2929     Copy::conjoint_swap_if_needed<Endian::JAVA>(checked_exceptions_start,
2930                                                 m->checked_exceptions_start(),
2931                                                 checked_exceptions_length * sizeof(CheckedExceptionElement),
2932                                                 sizeof(u2));
2933   }
2934 
2935   // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
2936   if (total_lvt_length > 0) {
2937     promoted_flags->set_has_localvariable_table();
2938     copy_localvariable_table(m->constMethod(),
2939                              lvt_cnt,
2940                              localvariable_table_length,
2941                              localvariable_table_start,
2942                              lvtt_cnt,
2943                              localvariable_type_table_length,
2944                              localvariable_type_table_start,
2945                              CHECK_NULL);
2946   }
2947 
2948   if (parsed_annotations.has_any_annotations())
2949     parsed_annotations.apply_to(m);
2950 
2951   // Copy annotations
2952   copy_method_annotations(m->constMethod(),
2953                           runtime_visible_annotations,
2954                           runtime_visible_annotations_length,
2955                           runtime_invisible_annotations,
2956                           runtime_invisible_annotations_length,
2957                           runtime_visible_parameter_annotations,
2958                           runtime_visible_parameter_annotations_length,
2959                           runtime_invisible_parameter_annotations,
2960                           runtime_invisible_parameter_annotations_length,
2961                           runtime_visible_type_annotations,
2962                           runtime_visible_type_annotations_length,
2963                           runtime_invisible_type_annotations,
2964                           runtime_invisible_type_annotations_length,
2965                           annotation_default,
2966                           annotation_default_length,
2967                           CHECK_NULL);
2968 
2969   if (name == vmSymbols::finalize_method_name() &&
2970       signature == vmSymbols::void_method_signature()) {
2971     if (m->is_empty_method()) {
2972       _has_empty_finalizer = true;
2973     } else {
2974       _has_finalizer = true;
2975     }
2976   }
2977   if (name == vmSymbols::object_initializer_name() &&
2978       signature == vmSymbols::void_method_signature() &&
2979       m->is_vanilla_constructor()) {
2980     _has_vanilla_constructor = true;
2981   }
2982 
2983   NOT_PRODUCT(m->verify());
2984   return m;
2985 }
2986 
2987 
2988 // The promoted_flags parameter is used to pass relevant access_flags
2989 // from the methods back up to the containing klass. These flag values
2990 // are added to klass's access_flags.
2991 // Side-effects: populates the _methods field in the parser
2992 void ClassFileParser::parse_methods(const ClassFileStream* const cfs,
2993                                     bool is_interface,
2994                                     AccessFlags* promoted_flags,
2995                                     bool* has_final_method,
2996                                     bool* declares_nonstatic_concrete_methods,
2997                                     TRAPS) {
2998   assert(cfs != NULL, "invariant");
2999   assert(promoted_flags != NULL, "invariant");
3000   assert(has_final_method != NULL, "invariant");
3001   assert(declares_nonstatic_concrete_methods != NULL, "invariant");
3002 
3003   assert(NULL == _methods, "invariant");
3004 
3005   cfs->guarantee_more(2, CHECK);  // length
3006   const u2 length = cfs->get_u2_fast();
3007   if (length == 0) {
3008     _methods = Universe::the_empty_method_array();
3009   } else {
3010     _methods = MetadataFactory::new_array<Method*>(_loader_data,
3011                                                    length,
3012                                                    NULL,
3013                                                    CHECK);
3014 
3015     for (int index = 0; index < length; index++) {
3016       Method* method = parse_method(cfs,
3017                                     is_interface,
3018                                     _cp,
3019                                     promoted_flags,
3020                                     CHECK);
3021 
3022       if (method->is_final()) {
3023         *has_final_method = true;
3024       }
3025       // declares_nonstatic_concrete_methods: declares concrete instance methods, any access flags
3026       // used for interface initialization, and default method inheritance analysis
3027       if (is_interface && !(*declares_nonstatic_concrete_methods)
3028         && !method->is_abstract() && !method->is_static()) {
3029         *declares_nonstatic_concrete_methods = true;
3030       }
3031       _methods->at_put(index, method);
3032     }
3033 
3034     if (_need_verify && length > 1) {
3035       // Check duplicated methods
3036       ResourceMark rm(THREAD);
3037       NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
3038         THREAD, NameSigHash*, HASH_ROW_SIZE);
3039       initialize_hashtable(names_and_sigs);
3040       bool dup = false;
3041       const Symbol* name = NULL;
3042       const Symbol* sig = NULL;
3043       {
3044         debug_only(NoSafepointVerifier nsv;)
3045         for (int i = 0; i < length; i++) {
3046           const Method* const m = _methods->at(i);
3047           name = m->name();
3048           sig = m->signature();
3049           // If no duplicates, add name/signature in hashtable names_and_sigs.
3050           if (!put_after_lookup(name, sig, names_and_sigs)) {
3051             dup = true;
3052             break;
3053           }
3054         }
3055       }
3056       if (dup) {
3057         classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
3058                                name->as_C_string(), sig->as_klass_external_name(), CHECK);
3059       }
3060     }
3061   }
3062 }
3063 
3064 static const intArray* sort_methods(Array<Method*>* methods) {
3065   const int length = methods->length();
3066   // If JVMTI original method ordering or sharing is enabled we have to
3067   // remember the original class file ordering.
3068   // We temporarily use the vtable_index field in the Method* to store the
3069   // class file index, so we can read in after calling qsort.
3070   // Put the method ordering in the shared archive.
3071   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
3072     for (int index = 0; index < length; index++) {
3073       Method* const m = methods->at(index);
3074       assert(!m->valid_vtable_index(), "vtable index should not be set");
3075       m->set_vtable_index(index);
3076     }
3077   }
3078   // Sort method array by ascending method name (for faster lookups & vtable construction)
3079   // Note that the ordering is not alphabetical, see Symbol::fast_compare
3080   Method::sort_methods(methods);
3081 
3082   intArray* method_ordering = NULL;
3083   // If JVMTI original method ordering or sharing is enabled construct int
3084   // array remembering the original ordering
3085   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
3086     method_ordering = new intArray(length, length, -1);
3087     for (int index = 0; index < length; index++) {
3088       Method* const m = methods->at(index);
3089       const int old_index = m->vtable_index();
3090       assert(old_index >= 0 && old_index < length, "invalid method index");
3091       method_ordering->at_put(index, old_index);
3092       m->set_vtable_index(Method::invalid_vtable_index);
3093     }
3094   }
3095   return method_ordering;
3096 }
3097 
3098 // Parse generic_signature attribute for methods and fields
3099 u2 ClassFileParser::parse_generic_signature_attribute(const ClassFileStream* const cfs,
3100                                                       TRAPS) {
3101   assert(cfs != NULL, "invariant");
3102 
3103   cfs->guarantee_more(2, CHECK_0);  // generic_signature_index
3104   const u2 generic_signature_index = cfs->get_u2_fast();
3105   check_property(
3106     valid_symbol_at(generic_signature_index),
3107     "Invalid Signature attribute at constant pool index %u in class file %s",
3108     generic_signature_index, CHECK_0);
3109   return generic_signature_index;
3110 }
3111 
3112 void ClassFileParser::parse_classfile_sourcefile_attribute(const ClassFileStream* const cfs,
3113                                                            TRAPS) {
3114 
3115   assert(cfs != NULL, "invariant");
3116 
3117   cfs->guarantee_more(2, CHECK);  // sourcefile_index
3118   const u2 sourcefile_index = cfs->get_u2_fast();
3119   check_property(
3120     valid_symbol_at(sourcefile_index),
3121     "Invalid SourceFile attribute at constant pool index %u in class file %s",
3122     sourcefile_index, CHECK);
3123   set_class_sourcefile_index(sourcefile_index);
3124 }
3125 
3126 void ClassFileParser::parse_classfile_source_debug_extension_attribute(const ClassFileStream* const cfs,
3127                                                                        int length,
3128                                                                        TRAPS) {
3129   assert(cfs != NULL, "invariant");
3130 
3131   const u1* const sde_buffer = cfs->current();
3132   assert(sde_buffer != NULL, "null sde buffer");
3133 
3134   // Don't bother storing it if there is no way to retrieve it
3135   if (JvmtiExport::can_get_source_debug_extension()) {
3136     assert((length+1) > length, "Overflow checking");
3137     u1* const sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
3138     for (int i = 0; i < length; i++) {
3139       sde[i] = sde_buffer[i];
3140     }
3141     sde[length] = '\0';
3142     set_class_sde_buffer((const char*)sde, length);
3143   }
3144   // Got utf8 string, set stream position forward
3145   cfs->skip_u1(length, CHECK);
3146 }
3147 
3148 
3149 // Inner classes can be static, private or protected (classic VM does this)
3150 #define RECOGNIZED_INNER_CLASS_MODIFIERS ( JVM_RECOGNIZED_CLASS_MODIFIERS | \
3151                                            JVM_ACC_PRIVATE |                \
3152                                            JVM_ACC_PROTECTED |              \
3153                                            JVM_ACC_STATIC                   \
3154                                          )
3155 
3156 // Return number of classes in the inner classes attribute table
3157 u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ClassFileStream* const cfs,
3158                                                             const u1* const inner_classes_attribute_start,
3159                                                             bool parsed_enclosingmethod_attribute,
3160                                                             u2 enclosing_method_class_index,
3161                                                             u2 enclosing_method_method_index,
3162                                                             TRAPS) {
3163   const u1* const current_mark = cfs->current();
3164   u2 length = 0;
3165   if (inner_classes_attribute_start != NULL) {
3166     cfs->set_current(inner_classes_attribute_start);
3167     cfs->guarantee_more(2, CHECK_0);  // length
3168     length = cfs->get_u2_fast();
3169   }
3170 
3171   // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
3172   // method data:
3173   //   [inner_class_info_index,
3174   //    outer_class_info_index,
3175   //    inner_name_index,
3176   //    inner_class_access_flags,
3177   //    ...
3178   //    enclosing_method_class_index,
3179   //    enclosing_method_method_index]
3180   const int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
3181   Array<u2>* const inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
3182   _inner_classes = inner_classes;
3183 
3184   int index = 0;
3185   const int cp_size = _cp->length();
3186   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
3187   for (int n = 0; n < length; n++) {
3188     // Inner class index
3189     const u2 inner_class_info_index = cfs->get_u2_fast();
3190     check_property(
3191       (valid_klass_reference_at(inner_class_info_index) ||
3192        (EnableValhalla && valid_value_type_reference_at(inner_class_info_index))),
3193       "inner_class_info_index %u has bad constant type in class file %s",
3194       inner_class_info_index, CHECK_0);
3195     // Outer class index
3196     const u2 outer_class_info_index = cfs->get_u2_fast();
3197     check_property(
3198       outer_class_info_index == 0 ||
3199         (valid_klass_reference_at(outer_class_info_index) ||
3200          (EnableValhalla && valid_value_type_reference_at(outer_class_info_index))),
3201       "outer_class_info_index %u has bad constant type in class file %s",
3202       outer_class_info_index, CHECK_0);
3203     // Inner class name
3204     const u2 inner_name_index = cfs->get_u2_fast();
3205     check_property(
3206       inner_name_index == 0 || valid_symbol_at(inner_name_index),
3207       "inner_name_index %u has bad constant type in class file %s",
3208       inner_name_index, CHECK_0);
3209     if (_need_verify) {
3210       guarantee_property(inner_class_info_index != outer_class_info_index,
3211                          "Class is both outer and inner class in class file %s", CHECK_0);
3212     }
3213 
3214     jint recognized_modifiers = RECOGNIZED_INNER_CLASS_MODIFIERS;
3215     // JVM_ACC_MODULE is defined in JDK-9 and later.
3216     if (_major_version >= JAVA_9_VERSION) {
3217       recognized_modifiers |= JVM_ACC_MODULE;
3218     }
3219     // JVM_ACC_VALUE is defined for class file version 53.1 and later
3220     if (supports_value_types()) {
3221       recognized_modifiers |= JVM_ACC_VALUE;
3222     }
3223 
3224     // Access flags
3225     jint flags = cfs->get_u2_fast() & recognized_modifiers;
3226 
3227     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
3228       // Set abstract bit for old class files for backward compatibility
3229       flags |= JVM_ACC_ABSTRACT;
3230     }
3231     verify_legal_class_modifiers(flags, CHECK_0);
3232     AccessFlags inner_access_flags(flags);
3233 
3234     inner_classes->at_put(index++, inner_class_info_index);
3235     inner_classes->at_put(index++, outer_class_info_index);
3236     inner_classes->at_put(index++, inner_name_index);
3237     inner_classes->at_put(index++, inner_access_flags.as_short());
3238   }
3239 
3240   // 4347400: make sure there's no duplicate entry in the classes array
3241   if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
3242     for(int i = 0; i < length * 4; i += 4) {
3243       for(int j = i + 4; j < length * 4; j += 4) {
3244         guarantee_property((inner_classes->at(i)   != inner_classes->at(j) ||
3245                             inner_classes->at(i+1) != inner_classes->at(j+1) ||
3246                             inner_classes->at(i+2) != inner_classes->at(j+2) ||
3247                             inner_classes->at(i+3) != inner_classes->at(j+3)),
3248                             "Duplicate entry in InnerClasses in class file %s",
3249                             CHECK_0);
3250       }
3251     }
3252   }
3253 
3254   // Set EnclosingMethod class and method indexes.
3255   if (parsed_enclosingmethod_attribute) {
3256     inner_classes->at_put(index++, enclosing_method_class_index);
3257     inner_classes->at_put(index++, enclosing_method_method_index);
3258   }
3259   assert(index == size, "wrong size");
3260 
3261   // Restore buffer's current position.
3262   cfs->set_current(current_mark);
3263 
3264   return length;
3265 }
3266 
3267 void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
3268   set_class_synthetic_flag(true);
3269 }
3270 
3271 void ClassFileParser::parse_classfile_signature_attribute(const ClassFileStream* const cfs, TRAPS) {
3272   assert(cfs != NULL, "invariant");
3273 
3274   const u2 signature_index = cfs->get_u2(CHECK);
3275   check_property(
3276     valid_symbol_at(signature_index),
3277     "Invalid constant pool index %u in Signature attribute in class file %s",
3278     signature_index, CHECK);
3279   set_class_generic_signature_index(signature_index);
3280 }
3281 
3282 void ClassFileParser::parse_classfile_bootstrap_methods_attribute(const ClassFileStream* const cfs,
3283                                                                   ConstantPool* cp,
3284                                                                   u4 attribute_byte_length,
3285                                                                   TRAPS) {
3286   assert(cfs != NULL, "invariant");
3287   assert(cp != NULL, "invariant");
3288 
3289   const u1* const current_start = cfs->current();
3290 
3291   guarantee_property(attribute_byte_length >= sizeof(u2),
3292                      "Invalid BootstrapMethods attribute length %u in class file %s",
3293                      attribute_byte_length,
3294                      CHECK);
3295 
3296   cfs->guarantee_more(attribute_byte_length, CHECK);
3297 
3298   const int attribute_array_length = cfs->get_u2_fast();
3299 
3300   guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
3301                      "Short length on BootstrapMethods in class file %s",
3302                      CHECK);
3303 
3304 
3305   // The attribute contains a counted array of counted tuples of shorts,
3306   // represending bootstrap specifiers:
3307   //    length*{bootstrap_method_index, argument_count*{argument_index}}
3308   const int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
3309   // operand_count = number of shorts in attr, except for leading length
3310 
3311   // The attribute is copied into a short[] array.
3312   // The array begins with a series of short[2] pairs, one for each tuple.
3313   const int index_size = (attribute_array_length * 2);
3314 
3315   Array<u2>* const operands =
3316     MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
3317 
3318   // Eagerly assign operands so they will be deallocated with the constant
3319   // pool if there is an error.
3320   cp->set_operands(operands);
3321 
3322   int operand_fill_index = index_size;
3323   const int cp_size = cp->length();
3324 
3325   for (int n = 0; n < attribute_array_length; n++) {
3326     // Store a 32-bit offset into the header of the operand array.
3327     ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
3328 
3329     // Read a bootstrap specifier.
3330     cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
3331     const u2 bootstrap_method_index = cfs->get_u2_fast();
3332     const u2 argument_count = cfs->get_u2_fast();
3333     check_property(
3334       valid_cp_range(bootstrap_method_index, cp_size) &&
3335       cp->tag_at(bootstrap_method_index).is_method_handle(),
3336       "bootstrap_method_index %u has bad constant type in class file %s",
3337       bootstrap_method_index,
3338       CHECK);
3339 
3340     guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
3341       "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
3342       CHECK);
3343 
3344     operands->at_put(operand_fill_index++, bootstrap_method_index);
3345     operands->at_put(operand_fill_index++, argument_count);
3346 
3347     cfs->guarantee_more(sizeof(u2) * argument_count, CHECK);  // argv[argc]
3348     for (int j = 0; j < argument_count; j++) {
3349       const u2 argument_index = cfs->get_u2_fast();
3350       check_property(
3351         valid_cp_range(argument_index, cp_size) &&
3352         cp->tag_at(argument_index).is_loadable_constant(),
3353         "argument_index %u has bad constant type in class file %s",
3354         argument_index,
3355         CHECK);
3356       operands->at_put(operand_fill_index++, argument_index);
3357     }
3358   }
3359   guarantee_property(current_start + attribute_byte_length == cfs->current(),
3360                      "Bad length on BootstrapMethods in class file %s",
3361                      CHECK);
3362 }
3363 
3364 void ClassFileParser::parse_classfile_attributes(const ClassFileStream* const cfs,
3365                                                  ConstantPool* cp,
3366                  ClassFileParser::ClassAnnotationCollector* parsed_annotations,
3367                                                  TRAPS) {
3368   assert(cfs != NULL, "invariant");
3369   assert(cp != NULL, "invariant");
3370   assert(parsed_annotations != NULL, "invariant");
3371 
3372   // Set inner classes attribute to default sentinel
3373   _inner_classes = Universe::the_empty_short_array();
3374   cfs->guarantee_more(2, CHECK);  // attributes_count
3375   u2 attributes_count = cfs->get_u2_fast();
3376   bool parsed_sourcefile_attribute = false;
3377   bool parsed_innerclasses_attribute = false;
3378   bool parsed_enclosingmethod_attribute = false;
3379   bool parsed_bootstrap_methods_attribute = false;
3380   const u1* runtime_visible_annotations = NULL;
3381   int runtime_visible_annotations_length = 0;
3382   const u1* runtime_invisible_annotations = NULL;
3383   int runtime_invisible_annotations_length = 0;
3384   const u1* runtime_visible_type_annotations = NULL;
3385   int runtime_visible_type_annotations_length = 0;
3386   const u1* runtime_invisible_type_annotations = NULL;
3387   int runtime_invisible_type_annotations_length = 0;
3388   bool runtime_invisible_type_annotations_exists = false;
3389   bool runtime_invisible_annotations_exists = false;
3390   bool parsed_source_debug_ext_annotations_exist = false;
3391   const u1* inner_classes_attribute_start = NULL;
3392   u4  inner_classes_attribute_length = 0;
3393   u2  enclosing_method_class_index = 0;
3394   u2  enclosing_method_method_index = 0;
3395   // Iterate over attributes
3396   while (attributes_count--) {
3397     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
3398     const u2 attribute_name_index = cfs->get_u2_fast();
3399     const u4 attribute_length = cfs->get_u4_fast();
3400     check_property(
3401       valid_symbol_at(attribute_name_index),
3402       "Attribute name has bad constant pool index %u in class file %s",
3403       attribute_name_index, CHECK);
3404     const Symbol* const tag = cp->symbol_at(attribute_name_index);
3405     if (tag == vmSymbols::tag_source_file()) {
3406       // Check for SourceFile tag
3407       if (_need_verify) {
3408         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
3409       }
3410       if (parsed_sourcefile_attribute) {
3411         classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
3412       } else {
3413         parsed_sourcefile_attribute = true;
3414       }
3415       parse_classfile_sourcefile_attribute(cfs, CHECK);
3416     } else if (tag == vmSymbols::tag_source_debug_extension()) {
3417       // Check for SourceDebugExtension tag
3418       if (parsed_source_debug_ext_annotations_exist) {
3419           classfile_parse_error(
3420             "Multiple SourceDebugExtension attributes in class file %s", CHECK);
3421       }
3422       parsed_source_debug_ext_annotations_exist = true;
3423       parse_classfile_source_debug_extension_attribute(cfs, (int)attribute_length, CHECK);
3424     } else if (tag == vmSymbols::tag_inner_classes()) {
3425       // Check for InnerClasses tag
3426       if (parsed_innerclasses_attribute) {
3427         classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
3428       } else {
3429         parsed_innerclasses_attribute = true;
3430       }
3431       inner_classes_attribute_start = cfs->current();
3432       inner_classes_attribute_length = attribute_length;
3433       cfs->skip_u1(inner_classes_attribute_length, CHECK);
3434     } else if (tag == vmSymbols::tag_synthetic()) {
3435       // Check for Synthetic tag
3436       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
3437       if (attribute_length != 0) {
3438         classfile_parse_error(
3439           "Invalid Synthetic classfile attribute length %u in class file %s",
3440           attribute_length, CHECK);
3441       }
3442       parse_classfile_synthetic_attribute(CHECK);
3443     } else if (tag == vmSymbols::tag_deprecated()) {
3444       // Check for Deprecatd tag - 4276120
3445       if (attribute_length != 0) {
3446         classfile_parse_error(
3447           "Invalid Deprecated classfile attribute length %u in class file %s",
3448           attribute_length, CHECK);
3449       }
3450     } else if (_major_version >= JAVA_1_5_VERSION) {
3451       if (tag == vmSymbols::tag_signature()) {
3452         if (_generic_signature_index != 0) {
3453           classfile_parse_error(
3454             "Multiple Signature attributes in class file %s", CHECK);
3455         }
3456         if (attribute_length != 2) {
3457           classfile_parse_error(
3458             "Wrong Signature attribute length %u in class file %s",
3459             attribute_length, CHECK);
3460         }
3461         parse_classfile_signature_attribute(cfs, CHECK);
3462       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
3463         if (runtime_visible_annotations != NULL) {
3464           classfile_parse_error(
3465             "Multiple RuntimeVisibleAnnotations attributes in class file %s", CHECK);
3466         }
3467         runtime_visible_annotations_length = attribute_length;
3468         runtime_visible_annotations = cfs->current();
3469         assert(runtime_visible_annotations != NULL, "null visible annotations");
3470         cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
3471         parse_annotations(cp,
3472                           runtime_visible_annotations,
3473                           runtime_visible_annotations_length,
3474                           parsed_annotations,
3475                           _loader_data,
3476                           CHECK);
3477         cfs->skip_u1_fast(runtime_visible_annotations_length);
3478       } else if (tag == vmSymbols::tag_runtime_invisible_annotations()) {
3479         if (runtime_invisible_annotations_exists) {
3480           classfile_parse_error(
3481             "Multiple RuntimeInvisibleAnnotations attributes in class file %s", CHECK);
3482         }
3483         runtime_invisible_annotations_exists = true;
3484         if (PreserveAllAnnotations) {
3485           runtime_invisible_annotations_length = attribute_length;
3486           runtime_invisible_annotations = cfs->current();
3487           assert(runtime_invisible_annotations != NULL, "null invisible annotations");
3488         }
3489         cfs->skip_u1(attribute_length, CHECK);
3490       } else if (tag == vmSymbols::tag_enclosing_method()) {
3491         if (parsed_enclosingmethod_attribute) {
3492           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
3493         } else {
3494           parsed_enclosingmethod_attribute = true;
3495         }
3496         guarantee_property(attribute_length == 4,
3497           "Wrong EnclosingMethod attribute length %u in class file %s",
3498           attribute_length, CHECK);
3499         cfs->guarantee_more(4, CHECK);  // class_index, method_index
3500         enclosing_method_class_index  = cfs->get_u2_fast();
3501         enclosing_method_method_index = cfs->get_u2_fast();
3502         if (enclosing_method_class_index == 0) {
3503           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
3504         }
3505         // Validate the constant pool indices and types
3506         check_property(valid_klass_reference_at(enclosing_method_class_index),
3507           "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
3508         if (enclosing_method_method_index != 0 &&
3509             (!cp->is_within_bounds(enclosing_method_method_index) ||
3510              !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
3511           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
3512         }
3513       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
3514                  _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
3515         if (parsed_bootstrap_methods_attribute) {
3516           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
3517         }
3518         parsed_bootstrap_methods_attribute = true;
3519         parse_classfile_bootstrap_methods_attribute(cfs, cp, attribute_length, CHECK);
3520       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3521         if (runtime_visible_type_annotations != NULL) {
3522           classfile_parse_error(
3523             "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);
3524         }
3525         runtime_visible_type_annotations_length = attribute_length;
3526         runtime_visible_type_annotations = cfs->current();
3527         assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
3528         // No need for the VM to parse Type annotations
3529         cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3530       } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
3531         if (runtime_invisible_type_annotations_exists) {
3532           classfile_parse_error(
3533             "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);
3534         } else {
3535           runtime_invisible_type_annotations_exists = true;
3536         }
3537         if (PreserveAllAnnotations) {
3538           runtime_invisible_type_annotations_length = attribute_length;
3539           runtime_invisible_type_annotations = cfs->current();
3540           assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
3541         }
3542         cfs->skip_u1(attribute_length, CHECK);
3543       } else {
3544         // Unknown attribute
3545         cfs->skip_u1(attribute_length, CHECK);
3546       }
3547     } else {
3548       // Unknown attribute
3549       cfs->skip_u1(attribute_length, CHECK);
3550     }
3551   }
3552   _annotations = assemble_annotations(runtime_visible_annotations,
3553                                       runtime_visible_annotations_length,
3554                                       runtime_invisible_annotations,
3555                                       runtime_invisible_annotations_length,
3556                                       CHECK);
3557   _type_annotations = assemble_annotations(runtime_visible_type_annotations,
3558                                            runtime_visible_type_annotations_length,
3559                                            runtime_invisible_type_annotations,
3560                                            runtime_invisible_type_annotations_length,
3561                                            CHECK);
3562 
3563   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
3564     const u2 num_of_classes = parse_classfile_inner_classes_attribute(
3565                             cfs,
3566                             inner_classes_attribute_start,
3567                             parsed_innerclasses_attribute,
3568                             enclosing_method_class_index,
3569                             enclosing_method_method_index,
3570                             CHECK);
3571     if (parsed_innerclasses_attribute &&_need_verify && _major_version >= JAVA_1_5_VERSION) {
3572       guarantee_property(
3573         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
3574         "Wrong InnerClasses attribute length in class file %s", CHECK);
3575     }
3576   }
3577 
3578   if (_max_bootstrap_specifier_index >= 0) {
3579     guarantee_property(parsed_bootstrap_methods_attribute,
3580                        "Missing BootstrapMethods attribute in class file %s", CHECK);
3581   }
3582 }
3583 
3584 void ClassFileParser::apply_parsed_class_attributes(InstanceKlass* k) {
3585   assert(k != NULL, "invariant");
3586 
3587   if (_synthetic_flag)
3588     k->set_is_synthetic();
3589   if (_sourcefile_index != 0) {
3590     k->set_source_file_name_index(_sourcefile_index);
3591   }
3592   if (_generic_signature_index != 0) {
3593     k->set_generic_signature_index(_generic_signature_index);
3594   }
3595   if (_sde_buffer != NULL) {
3596     k->set_source_debug_extension(_sde_buffer, _sde_length);
3597   }
3598 }
3599 
3600 // Create the Annotations object that will
3601 // hold the annotations array for the Klass.
3602 void ClassFileParser::create_combined_annotations(TRAPS) {
3603     if (_annotations == NULL &&
3604         _type_annotations == NULL &&
3605         _fields_annotations == NULL &&
3606         _fields_type_annotations == NULL) {
3607       // Don't create the Annotations object unnecessarily.
3608       return;
3609     }
3610 
3611     Annotations* const annotations = Annotations::allocate(_loader_data, CHECK);
3612     annotations->set_class_annotations(_annotations);
3613     annotations->set_class_type_annotations(_type_annotations);
3614     annotations->set_fields_annotations(_fields_annotations);
3615     annotations->set_fields_type_annotations(_fields_type_annotations);
3616 
3617     // This is the Annotations object that will be
3618     // assigned to InstanceKlass being constructed.
3619     _combined_annotations = annotations;
3620 
3621     // The annotations arrays below has been transfered the
3622     // _combined_annotations so these fields can now be cleared.
3623     _annotations             = NULL;
3624     _type_annotations        = NULL;
3625     _fields_annotations      = NULL;
3626     _fields_type_annotations = NULL;
3627 }
3628 
3629 // Transfer ownership of metadata allocated to the InstanceKlass.
3630 void ClassFileParser::apply_parsed_class_metadata(
3631                                             InstanceKlass* this_klass,
3632                                             int java_fields_count, TRAPS) {
3633   assert(this_klass != NULL, "invariant");
3634 
3635   _cp->set_pool_holder(this_klass);
3636   this_klass->set_constants(_cp);
3637   this_klass->set_fields(_fields, java_fields_count);
3638   this_klass->set_methods(_methods);
3639   this_klass->set_inner_classes(_inner_classes);
3640   this_klass->set_local_interfaces(_local_interfaces);
3641   this_klass->set_transitive_interfaces(_transitive_interfaces);
3642   this_klass->set_annotations(_combined_annotations);
3643 
3644   // Clear out these fields so they don't get deallocated by the destructor
3645   clear_class_metadata();
3646 }
3647 
3648 AnnotationArray* ClassFileParser::assemble_annotations(const u1* const runtime_visible_annotations,
3649                                                        int runtime_visible_annotations_length,
3650                                                        const u1* const runtime_invisible_annotations,
3651                                                        int runtime_invisible_annotations_length,
3652                                                        TRAPS) {
3653   AnnotationArray* annotations = NULL;
3654   if (runtime_visible_annotations != NULL ||
3655       runtime_invisible_annotations != NULL) {
3656     annotations = MetadataFactory::new_array<u1>(_loader_data,
3657                                           runtime_visible_annotations_length +
3658                                           runtime_invisible_annotations_length,
3659                                           CHECK_(annotations));
3660     if (runtime_visible_annotations != NULL) {
3661       for (int i = 0; i < runtime_visible_annotations_length; i++) {
3662         annotations->at_put(i, runtime_visible_annotations[i]);
3663       }
3664     }
3665     if (runtime_invisible_annotations != NULL) {
3666       for (int i = 0; i < runtime_invisible_annotations_length; i++) {
3667         int append = runtime_visible_annotations_length+i;
3668         annotations->at_put(append, runtime_invisible_annotations[i]);
3669       }
3670     }
3671   }
3672   return annotations;
3673 }
3674 
3675 const InstanceKlass* ClassFileParser::parse_super_class(ConstantPool* const cp,
3676                                                         const int super_class_index,
3677                                                         const bool need_verify,
3678                                                         TRAPS) {
3679   assert(cp != NULL, "invariant");
3680   const InstanceKlass* super_klass = NULL;
3681 
3682   if (super_class_index == 0) {
3683     check_property(_class_name == vmSymbols::java_lang_Object()
3684                    || (_access_flags.get_flags() & JVM_ACC_VALUE),
3685                    "Invalid superclass index %u in class file %s",
3686                    super_class_index,
3687                    CHECK_NULL);
3688   } else {
3689     check_property((valid_klass_reference_at(super_class_index) ||
3690                     ((EnableValhalla || EnableMVT) && valid_value_type_reference_at(super_class_index))),
3691                    "Invalid superclass index %u in class file %s",
3692                    super_class_index,
3693                    CHECK_NULL);
3694     // The class name should be legal because it is checked when parsing constant pool.
3695     // However, make sure it is not an array type.
3696     bool is_array = false;
3697     if (cp->tag_at(super_class_index).is_klass() || cp->tag_at(super_class_index).is_value_type()) {
3698       super_klass = InstanceKlass::cast(cp->resolved_klass_at(super_class_index));
3699       if (need_verify)
3700         is_array = super_klass->is_array_klass();
3701     } else if (need_verify) {
3702       is_array = (cp->klass_name_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
3703     }
3704     if (need_verify) {
3705       guarantee_property(!is_array,
3706                         "Bad superclass name in class file %s", CHECK_NULL);
3707     }
3708   }
3709   return super_klass;
3710 }
3711 
3712 #ifndef PRODUCT
3713 static void print_field_layout(const Symbol* name,
3714                                Array<u2>* fields,
3715                                const constantPoolHandle& cp,
3716                                int instance_size,
3717                                int instance_fields_start,
3718                                int instance_fields_end,
3719                                int static_fields_end) {
3720 
3721   assert(name != NULL, "invariant");
3722 
3723   tty->print("%s: field layout\n", name->as_klass_external_name());
3724   tty->print("  @%3d %s\n", instance_fields_start, "--- instance fields start ---");
3725   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3726     if (!fs.access_flags().is_static()) {
3727       tty->print("  @%3d \"%s\" %s\n",
3728         fs.offset(),
3729         fs.name()->as_klass_external_name(),
3730         fs.signature()->as_klass_external_name());
3731     }
3732   }
3733   tty->print("  @%3d %s\n", instance_fields_end, "--- instance fields end ---");
3734   tty->print("  @%3d %s\n", instance_size * wordSize, "--- instance ends ---");
3735   tty->print("  @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");
3736   for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
3737     if (fs.access_flags().is_static()) {
3738       tty->print("  @%3d \"%s\" %s\n",
3739         fs.offset(),
3740         fs.name()->as_klass_external_name(),
3741         fs.signature()->as_klass_external_name());
3742     }
3743   }
3744   tty->print("  @%3d %s\n", static_fields_end, "--- static fields end ---");
3745   tty->print("\n");
3746 }
3747 #endif
3748 
3749 // Values needed for oopmap and InstanceKlass creation
3750 class ClassFileParser::FieldLayoutInfo : public ResourceObj {
3751  public:
3752   OopMapBlocksBuilder* oop_map_blocks;
3753   int           instance_size;
3754   int           nonstatic_field_size;
3755   int           static_field_size;
3756   bool          has_nonstatic_fields;
3757 };
3758 
3759 // Utility to collect and compact oop maps during layout
3760 class ClassFileParser::OopMapBlocksBuilder : public ResourceObj {
3761  public:
3762   OopMapBlock*  nonstatic_oop_maps;
3763   unsigned int  nonstatic_oop_map_count;
3764   unsigned int  max_nonstatic_oop_maps;
3765 
3766  public:
3767   OopMapBlocksBuilder(unsigned int  max_blocks, TRAPS) {
3768     max_nonstatic_oop_maps = max_blocks;
3769     nonstatic_oop_map_count = 0;
3770     if (max_blocks == 0) {
3771       nonstatic_oop_maps = NULL;
3772     } else {
3773       nonstatic_oop_maps = NEW_RESOURCE_ARRAY_IN_THREAD(
3774         THREAD, OopMapBlock, max_nonstatic_oop_maps);
3775       memset(nonstatic_oop_maps, 0, sizeof(OopMapBlock) * max_blocks);
3776     }
3777   }
3778 
3779   OopMapBlock* last_oop_map() const {
3780     assert(nonstatic_oop_map_count > 0, "Has no oop maps");
3781     return nonstatic_oop_maps + (nonstatic_oop_map_count - 1);
3782   }
3783 
3784   // addition of super oop maps
3785   void initialize_inherited_blocks(OopMapBlock* blocks, unsigned int nof_blocks) {
3786     assert(nof_blocks && nonstatic_oop_map_count == 0 &&
3787         nof_blocks <= max_nonstatic_oop_maps, "invariant");
3788 
3789     memcpy(nonstatic_oop_maps, blocks, sizeof(OopMapBlock) * nof_blocks);
3790     nonstatic_oop_map_count += nof_blocks;
3791   }
3792 
3793   // collection of oops
3794   void add(int offset, int count) {
3795     if (nonstatic_oop_map_count == 0) {
3796       nonstatic_oop_map_count++;
3797     }
3798     OopMapBlock*  nonstatic_oop_map = last_oop_map();
3799     if (nonstatic_oop_map->count() == 0) {  // Unused map, set it up
3800       nonstatic_oop_map->set_offset(offset);
3801       nonstatic_oop_map->set_count(count);
3802     } else if (nonstatic_oop_map->is_contiguous(offset)) { // contiguous, add
3803       nonstatic_oop_map->increment_count(count);
3804     } else { // Need a new one...
3805       nonstatic_oop_map_count++;
3806       assert(nonstatic_oop_map_count <= max_nonstatic_oop_maps, "range check");
3807       nonstatic_oop_map = last_oop_map();
3808       nonstatic_oop_map->set_offset(offset);
3809       nonstatic_oop_map->set_count(count);
3810     }
3811   }
3812 
3813   // general purpose copy, e.g. into allocated instanceKlass
3814   void copy(OopMapBlock* dst) {
3815     if (nonstatic_oop_map_count != 0) {
3816       memcpy(dst, nonstatic_oop_maps, sizeof(OopMapBlock) * nonstatic_oop_map_count);
3817     }
3818   }
3819 
3820   // Sort and compact adjacent blocks
3821   void compact(TRAPS) {
3822     if (nonstatic_oop_map_count <= 1) {
3823       return;
3824     }
3825     /*
3826      * Since field layout sneeks in oops before values, we will be able to condense
3827      * blocks. There is potential to compact between super, own refs and values
3828      * containing refs.
3829      *
3830      * Currently compaction is slightly limited due to values being 8 byte aligned.
3831      * This may well change: FixMe if doesn't, the code below is fairly general purpose
3832      * and maybe it doesn't need to be.
3833      */
3834     qsort(nonstatic_oop_maps, nonstatic_oop_map_count, sizeof(OopMapBlock),
3835         (_sort_Fn)OopMapBlock::compare_offset);
3836     if (nonstatic_oop_map_count < 2) {
3837       return;
3838     }
3839 
3840      //Make a temp copy, and iterate through and copy back into the orig
3841     ResourceMark rm(THREAD);
3842     OopMapBlock* oop_maps_copy = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, OopMapBlock,
3843         nonstatic_oop_map_count);
3844     OopMapBlock* oop_maps_copy_end = oop_maps_copy + nonstatic_oop_map_count;
3845     copy(oop_maps_copy);
3846     OopMapBlock*  nonstatic_oop_map = nonstatic_oop_maps;
3847     unsigned int new_count = 1;
3848     oop_maps_copy++;
3849     while(oop_maps_copy < oop_maps_copy_end) {
3850       assert(nonstatic_oop_map->offset() < oop_maps_copy->offset(), "invariant");
3851       if (nonstatic_oop_map->is_contiguous(oop_maps_copy->offset())) {
3852         nonstatic_oop_map->increment_count(oop_maps_copy->count());
3853       } else {
3854         nonstatic_oop_map++;
3855         new_count++;
3856         nonstatic_oop_map->set_offset(oop_maps_copy->offset());
3857         nonstatic_oop_map->set_count(oop_maps_copy->count());
3858       }
3859       oop_maps_copy++;
3860     }
3861     assert(new_count <= nonstatic_oop_map_count, "end up with more maps after compact() ?");
3862     nonstatic_oop_map_count = new_count;
3863   }
3864 
3865   void print_on(outputStream* st) const {
3866     st->print_cr("  OopMapBlocks: %3d  /%3d", nonstatic_oop_map_count, max_nonstatic_oop_maps);
3867     if (nonstatic_oop_map_count > 0) {
3868       OopMapBlock* map = nonstatic_oop_maps;
3869       OopMapBlock* last_map = last_oop_map();
3870       assert(map <= last_map, "Last less than first");
3871       while (map <= last_map) {
3872         st->print_cr("    Offset: %3d  -%3d Count: %3d", map->offset(),
3873             map->offset() + map->offset_span() - heapOopSize, map->count());
3874         map++;
3875       }
3876     }
3877   }
3878 
3879   void print_value_on(outputStream* st) const {
3880     print_on(st);
3881   }
3882 
3883 };
3884 
3885 void ClassFileParser::throwValueTypeLimitation(THREAD_AND_LOCATION_DECL,
3886                                                const char* msg,
3887                                                const Symbol* name,
3888                                                const Symbol* sig) const {
3889 
3890   ResourceMark rm(THREAD);
3891   if (name == NULL || sig == NULL) {
3892     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
3893         vmSymbols::java_lang_ClassFormatError(),
3894         "class: %s - %s", _class_name->as_C_string(), msg);
3895   }
3896   else {
3897     Exceptions::fthrow(THREAD_AND_LOCATION_ARGS,
3898         vmSymbols::java_lang_ClassFormatError(),
3899         "\"%s\" sig: \"%s\" class: %s - %s", name->as_C_string(), sig->as_C_string(),
3900         _class_name->as_C_string(), msg);
3901   }
3902 }
3903 
3904 // Layout fields and fill in FieldLayoutInfo.  Could use more refactoring!
3905 void ClassFileParser::layout_fields(ConstantPool* cp,
3906                                     const FieldAllocationCount* fac,
3907                                     const ClassAnnotationCollector* parsed_annotations,
3908                                     FieldLayoutInfo* info,
3909                                     TRAPS) {
3910 
3911   assert(cp != NULL, "invariant");
3912 
3913   // Field size and offset computation
3914   int nonstatic_field_size = _super_klass == NULL ? 0 :
3915                                _super_klass->nonstatic_field_size();
3916   int next_nonstatic_valuetype_offset = 0;
3917   int first_nonstatic_valuetype_offset = 0;
3918 
3919   // Fields that are value types are handled differently depending if they are static or not:
3920   // - static fields are oops
3921   // - non-static fields are embedded
3922 
3923   // Count the contended fields by type.
3924   //
3925   // We ignore static fields, because @Contended is not supported for them.
3926   // The layout code below will also ignore the static fields.
3927   int nonstatic_contended_count = 0;
3928   FieldAllocationCount fac_contended;
3929   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
3930     FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
3931     if (fs.is_contended()) {
3932       fac_contended.count[atype]++;
3933       if (!fs.access_flags().is_static()) {
3934         nonstatic_contended_count++;
3935       }
3936     }
3937   }
3938 
3939 
3940   // Calculate the starting byte offsets
3941   int next_static_oop_offset    = InstanceMirrorKlass::offset_of_static_fields();
3942   // Value types in static fields are not embedded, they are handled with oops
3943   int next_static_double_offset = next_static_oop_offset +
3944                                   ((fac->count[STATIC_OOP] + fac->count[STATIC_FLATTENABLE]) * heapOopSize);
3945   if ( fac->count[STATIC_DOUBLE] &&
3946        (Universe::field_type_should_be_aligned(T_DOUBLE) ||
3947         Universe::field_type_should_be_aligned(T_LONG)) ) {
3948     next_static_double_offset = align_up(next_static_double_offset, BytesPerLong);
3949   }
3950 
3951   int next_static_word_offset   = next_static_double_offset +
3952                                     ((fac->count[STATIC_DOUBLE]) * BytesPerLong);
3953   int next_static_short_offset  = next_static_word_offset +
3954                                     ((fac->count[STATIC_WORD]) * BytesPerInt);
3955   int next_static_byte_offset   = next_static_short_offset +
3956                                   ((fac->count[STATIC_SHORT]) * BytesPerShort);
3957 
3958   int nonstatic_fields_start  = instanceOopDesc::base_offset_in_bytes() +
3959                                 nonstatic_field_size * heapOopSize;
3960 
3961   // First field of value types is aligned on a long boundary in order to ease
3962   // in-lining of value types (with header removal) in packed arrays and
3963   // flatten value types
3964   int initial_value_type_padding = 0;
3965   if (is_value_type()) {
3966     int old = nonstatic_fields_start;
3967     nonstatic_fields_start = align_up(nonstatic_fields_start, BytesPerLong);
3968     initial_value_type_padding = nonstatic_fields_start - old;
3969   }
3970 
3971   int next_nonstatic_field_offset = nonstatic_fields_start;
3972 
3973   const bool is_contended_class     = parsed_annotations->is_contended();
3974 
3975   // Class is contended, pad before all the fields
3976   if (is_contended_class) {
3977     next_nonstatic_field_offset += ContendedPaddingWidth;
3978   }
3979 
3980   // Temporary value types restrictions
3981   if (is_value_type()) {
3982     if (is_contended_class) {
3983       throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support @Contended annotation yet");
3984       return;
3985     }
3986   }
3987 
3988   // Compute the non-contended fields count.
3989   // The packing code below relies on these counts to determine if some field
3990   // can be squeezed into the alignment gap. Contended fields are obviously
3991   // exempt from that.
3992   unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
3993   unsigned int nonstatic_word_count   = fac->count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
3994   unsigned int nonstatic_short_count  = fac->count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
3995   unsigned int nonstatic_byte_count   = fac->count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
3996   unsigned int nonstatic_oop_count    = fac->count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];
3997 
3998   int static_value_type_count = 0;
3999   int nonstatic_value_type_count = 0;
4000   int* nonstatic_value_type_indexes = NULL;
4001   Klass** nonstatic_value_type_klasses = NULL;
4002   unsigned int value_type_oop_map_count = 0;
4003   int not_flattened_value_types = 0;
4004 
4005   int max_nonstatic_value_type = fac->count[NONSTATIC_FLATTENABLE] + 1;
4006 
4007   nonstatic_value_type_indexes = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, int,
4008                                                               max_nonstatic_value_type);
4009   for (int i = 0; i < max_nonstatic_value_type; i++) {
4010     nonstatic_value_type_indexes[i] = -1;
4011   }
4012   nonstatic_value_type_klasses = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, Klass*,
4013                                                               max_nonstatic_value_type);
4014 
4015   for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
4016     if (fs.allocation_type() == STATIC_FLATTENABLE) {
4017       static_value_type_count++;
4018     } else if (fs.allocation_type() == NONSTATIC_FLATTENABLE) {
4019       Symbol* signature = fs.signature();
4020       Klass* klass = SystemDictionary::resolve_or_fail(signature,
4021                                                        Handle(THREAD, _loader_data->class_loader()),
4022                                                        _protection_domain, true, CHECK);
4023       assert(klass != NULL, "Sanity check");
4024       assert(klass->access_flags().is_value_type(), "Value type expected");
4025       ValueKlass* vk = ValueKlass::cast(klass);
4026       // Conditions to apply flattening or not should be defined in a single place
4027       if ((ValueFieldMaxFlatSize < 0) || (vk->size_helper() * HeapWordSize) <= ValueFieldMaxFlatSize) {
4028         nonstatic_value_type_indexes[nonstatic_value_type_count] = fs.index();
4029         nonstatic_value_type_klasses[nonstatic_value_type_count] = klass;
4030         nonstatic_value_type_count++;
4031 
4032         ValueKlass* vklass = ValueKlass::cast(klass);
4033         if (vklass->contains_oops()) {
4034           value_type_oop_map_count += vklass->nonstatic_oop_map_count();
4035         }
4036         fs.set_flattened(true);
4037       } else {
4038         not_flattened_value_types++;
4039         fs.set_flattened(false);
4040       }
4041     }
4042   }
4043 
4044   // Adjusting non_static_oop_count to take into account not flattened value types;
4045   nonstatic_oop_count += not_flattened_value_types;
4046 
4047   // Total non-static fields count, including every contended field
4048   unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +
4049                                         fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +
4050                                         fac->count[NONSTATIC_OOP] + fac->count[NONSTATIC_FLATTENABLE];
4051 
4052   const bool super_has_nonstatic_fields =
4053           (_super_klass != NULL && _super_klass->has_nonstatic_fields());
4054   const bool has_nonstatic_fields =
4055     super_has_nonstatic_fields || (nonstatic_fields_count != 0);
4056   const bool has_nonstatic_value_fields = nonstatic_value_type_count > 0;
4057 
4058   if (is_value_type() && (!has_nonstatic_fields)) {
4059     // There are a number of fixes required throughout the type system and JIT
4060     throwValueTypeLimitation(THREAD_AND_LOCATION, "Value Types do not support zero instance size yet");
4061   }
4062 
4063   // Prepare list of oops for oop map generation.
4064   //
4065   // "offset" and "count" lists are describing the set of contiguous oop
4066   // regions. offset[i] is the start of the i-th region, which then has
4067   // count[i] oops following. Before we know how many regions are required,
4068   // we pessimistically allocate the maps to fit all the oops into the
4069   // distinct regions.
4070   //
4071   int super_oop_map_count = (_super_klass == NULL) ? 0 :_super_klass->nonstatic_oop_map_count();
4072   int max_oop_map_count =
4073       super_oop_map_count +
4074       fac->count[NONSTATIC_OOP] +
4075       value_type_oop_map_count +
4076       not_flattened_value_types;
4077 
4078   OopMapBlocksBuilder* nonstatic_oop_maps = new OopMapBlocksBuilder(max_oop_map_count, THREAD);
4079   if (super_oop_map_count > 0) {
4080     nonstatic_oop_maps->initialize_inherited_blocks(_super_klass->start_of_nonstatic_oop_maps(),
4081                                                     _super_klass->nonstatic_oop_map_count());
4082   }
4083 
4084   int first_nonstatic_oop_offset = 0; // will be set for first oop field
4085 
4086   bool compact_fields   = CompactFields;
4087   int allocation_style = FieldsAllocationStyle;
4088   if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
4089     assert(false, "0 <= FieldsAllocationStyle <= 2");
4090     allocation_style = 1; // Optimistic
4091   }
4092 
4093   // The next classes have predefined hard-coded fields offsets
4094   // (see in JavaClasses::compute_hard_coded_offsets()).
4095   // Use default fields allocation order for them.
4096   if( (allocation_style != 0 || compact_fields ) && _loader_data->class_loader() == NULL &&
4097       (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
4098        _class_name == vmSymbols::java_lang_Class() ||
4099        _class_name == vmSymbols::java_lang_ClassLoader() ||
4100        _class_name == vmSymbols::java_lang_ref_Reference() ||
4101        _class_name == vmSymbols::java_lang_ref_SoftReference() ||
4102        _class_name == vmSymbols::java_lang_StackTraceElement() ||
4103        _class_name == vmSymbols::java_lang_String() ||
4104        _class_name == vmSymbols::java_lang_Throwable() ||
4105        _class_name == vmSymbols::java_lang_Boolean() ||
4106        _class_name == vmSymbols::java_lang_Character() ||
4107        _class_name == vmSymbols::java_lang_Float() ||
4108        _class_name == vmSymbols::java_lang_Double() ||
4109        _class_name == vmSymbols::java_lang_Byte() ||
4110        _class_name == vmSymbols::java_lang_Short() ||
4111        _class_name == vmSymbols::java_lang_Integer() ||
4112        _class_name == vmSymbols::java_lang_Long())) {
4113     allocation_style = 0;     // Allocate oops first
4114     compact_fields   = false; // Don't compact fields
4115   }
4116 
4117   int next_nonstatic_oop_offset = 0;
4118   int next_nonstatic_double_offset = 0;
4119 
4120   // Rearrange fields for a given allocation style
4121   if( allocation_style == 0 ) {
4122     // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
4123     next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4124     next_nonstatic_double_offset = next_nonstatic_oop_offset +
4125                                     (nonstatic_oop_count * heapOopSize);
4126   } else if( allocation_style == 1 ) {
4127     // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
4128     next_nonstatic_double_offset = next_nonstatic_field_offset;
4129   } else if( allocation_style == 2 ) {
4130     // Fields allocation: oops fields in super and sub classes are together.
4131     if( nonstatic_field_size > 0 && super_oop_map_count > 0 ) {
4132       if (next_nonstatic_field_offset == nonstatic_oop_maps->last_oop_map()->end_offset()) {
4133         allocation_style = 0;   // allocate oops first
4134         next_nonstatic_oop_offset    = next_nonstatic_field_offset;
4135         next_nonstatic_double_offset = next_nonstatic_oop_offset +
4136                                        (nonstatic_oop_count * heapOopSize);
4137       }
4138     }
4139     if( allocation_style == 2 ) {
4140       allocation_style = 1;     // allocate oops last
4141       next_nonstatic_double_offset = next_nonstatic_field_offset;
4142     }
4143   } else {
4144     ShouldNotReachHere();
4145   }
4146 
4147   int nonstatic_oop_space_count   = 0;
4148   int nonstatic_word_space_count  = 0;
4149   int nonstatic_short_space_count = 0;
4150   int nonstatic_byte_space_count  = 0;
4151   int nonstatic_oop_space_offset = 0;
4152   int nonstatic_word_space_offset = 0;
4153   int nonstatic_short_space_offset = 0;
4154   int nonstatic_byte_space_offset = 0;
4155 
4156   // Try to squeeze some of the fields into the gaps due to
4157   // long/double alignment.
4158   if (nonstatic_double_count > 0) {
4159     int offset = next_nonstatic_double_offset;
4160     next_nonstatic_double_offset = align_up(offset, BytesPerLong);
4161     if (compact_fields && offset != next_nonstatic_double_offset) {
4162       // Allocate available fields into the gap before double field.
4163       int length = next_nonstatic_double_offset - offset;
4164       assert(length == BytesPerInt, "");
4165       nonstatic_word_space_offset = offset;
4166       if (nonstatic_word_count > 0) {
4167         nonstatic_word_count      -= 1;
4168         nonstatic_word_space_count = 1; // Only one will fit
4169         length -= BytesPerInt;
4170         offset += BytesPerInt;
4171       }
4172       nonstatic_short_space_offset = offset;
4173       while (length >= BytesPerShort && nonstatic_short_count > 0) {
4174         nonstatic_short_count       -= 1;
4175         nonstatic_short_space_count += 1;
4176         length -= BytesPerShort;
4177         offset += BytesPerShort;
4178       }
4179       nonstatic_byte_space_offset = offset;
4180       while (length > 0 && nonstatic_byte_count > 0) {
4181         nonstatic_byte_count       -= 1;
4182         nonstatic_byte_space_count += 1;
4183         length -= 1;
4184       }
4185       // Allocate oop field in the gap if there are no other fields for that.
4186       nonstatic_oop_space_offset = offset;
4187       if (length >= heapOopSize && nonstatic_oop_count > 0 &&
4188           allocation_style != 0) { // when oop fields not first
4189         nonstatic_oop_count      -= 1;
4190         nonstatic_oop_space_count = 1; // Only one will fit
4191         length -= heapOopSize;
4192         offset += heapOopSize;
4193       }
4194     }
4195   }
4196 
4197   int next_nonstatic_word_offset = next_nonstatic_double_offset +
4198                                      (nonstatic_double_count * BytesPerLong);
4199   int next_nonstatic_short_offset = next_nonstatic_word_offset +
4200                                       (nonstatic_word_count * BytesPerInt);
4201   int next_nonstatic_byte_offset = next_nonstatic_short_offset +
4202                                      (nonstatic_short_count * BytesPerShort);
4203   int next_nonstatic_padded_offset = next_nonstatic_byte_offset +
4204                                        nonstatic_byte_count;
4205 
4206   // let oops jump before padding with this allocation style
4207   if( allocation_style == 1 ) {
4208     next_nonstatic_oop_offset = next_nonstatic_padded_offset;
4209     if( nonstatic_oop_count > 0 ) {
4210       next_nonstatic_oop_offset = align_up(next_nonstatic_oop_offset, heapOopSize);
4211     }
4212     next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
4213   }
4214 
4215   // Aligning embedded value types
4216   // bug below, the current algorithm to layout embedded value types always put them at the
4217   // end of the layout, which doesn't match the different allocation policies the VM is
4218   // supposed to provide => FixMe
4219   // Note also that the current alignment policy is to make each value type starting on a
4220   // 64 bits boundary. This could be optimized later. For instance, it could be nice to
4221   // align value types according to their most constrained internal type.
4222   next_nonstatic_valuetype_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4223   int next_value_type_index = 0;
4224 
4225   // Iterate over fields again and compute correct offsets.
4226   // The field allocation type was temporarily stored in the offset slot.
4227   // oop fields are located before non-oop fields (static and non-static).
4228   for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4229 
4230     // skip already laid out fields
4231     if (fs.is_offset_set()) continue;
4232 
4233     // contended instance fields are handled below
4234     if (fs.is_contended() && !fs.access_flags().is_static()) continue;
4235 
4236     int real_offset = 0;
4237     const FieldAllocationType atype = (const FieldAllocationType) fs.allocation_type();
4238 
4239     // pack the rest of the fields
4240     switch (atype) {
4241       // Value types in static fields are handled with oops
4242       case STATIC_FLATTENABLE:   // Fallthrough
4243       case STATIC_OOP:
4244         real_offset = next_static_oop_offset;
4245         next_static_oop_offset += heapOopSize;
4246         break;
4247       case STATIC_BYTE:
4248         real_offset = next_static_byte_offset;
4249         next_static_byte_offset += 1;
4250         break;
4251       case STATIC_SHORT:
4252         real_offset = next_static_short_offset;
4253         next_static_short_offset += BytesPerShort;
4254         break;
4255       case STATIC_WORD:
4256         real_offset = next_static_word_offset;
4257         next_static_word_offset += BytesPerInt;
4258         break;
4259       case STATIC_DOUBLE:
4260         real_offset = next_static_double_offset;
4261         next_static_double_offset += BytesPerLong;
4262         break;
4263       case NONSTATIC_FLATTENABLE:
4264         if (fs.is_flattened()) {
4265           Klass* klass = nonstatic_value_type_klasses[next_value_type_index];
4266           assert(klass != NULL, "Klass should have been loaded and resolved earlier");
4267           assert(klass->access_flags().is_value_type(),"Must be a value type");
4268           ValueKlass* vklass = ValueKlass::cast(klass);
4269           real_offset = next_nonstatic_valuetype_offset;
4270           next_nonstatic_valuetype_offset += (vklass->size_helper()) * wordSize - vklass->first_field_offset();
4271           // aligning next value type on a 64 bits boundary
4272           next_nonstatic_valuetype_offset = align_up(next_nonstatic_valuetype_offset, BytesPerLong);
4273           next_value_type_index += 1;
4274 
4275           if (vklass->contains_oops()) { // add flatten oop maps
4276             int diff = real_offset - vklass->first_field_offset();
4277             const OopMapBlock* map = vklass->start_of_nonstatic_oop_maps();
4278             const OopMapBlock* const last_map = map + vklass->nonstatic_oop_map_count();
4279             while (map < last_map) {
4280               nonstatic_oop_maps->add(map->offset() + diff, map->count());
4281               map++;
4282             }
4283           }
4284           break;
4285         } else {
4286           // Fall through
4287         }
4288       case NONSTATIC_OOP:
4289         if( nonstatic_oop_space_count > 0 ) {
4290           real_offset = nonstatic_oop_space_offset;
4291           nonstatic_oop_space_offset += heapOopSize;
4292           nonstatic_oop_space_count  -= 1;
4293         } else {
4294           real_offset = next_nonstatic_oop_offset;
4295           next_nonstatic_oop_offset += heapOopSize;
4296         }
4297         nonstatic_oop_maps->add(real_offset, 1);
4298         break;
4299       case NONSTATIC_BYTE:
4300         if( nonstatic_byte_space_count > 0 ) {
4301           real_offset = nonstatic_byte_space_offset;
4302           nonstatic_byte_space_offset += 1;
4303           nonstatic_byte_space_count  -= 1;
4304         } else {
4305           real_offset = next_nonstatic_byte_offset;
4306           next_nonstatic_byte_offset += 1;
4307         }
4308         break;
4309       case NONSTATIC_SHORT:
4310         if( nonstatic_short_space_count > 0 ) {
4311           real_offset = nonstatic_short_space_offset;
4312           nonstatic_short_space_offset += BytesPerShort;
4313           nonstatic_short_space_count  -= 1;
4314         } else {
4315           real_offset = next_nonstatic_short_offset;
4316           next_nonstatic_short_offset += BytesPerShort;
4317         }
4318         break;
4319       case NONSTATIC_WORD:
4320         if( nonstatic_word_space_count > 0 ) {
4321           real_offset = nonstatic_word_space_offset;
4322           nonstatic_word_space_offset += BytesPerInt;
4323           nonstatic_word_space_count  -= 1;
4324         } else {
4325           real_offset = next_nonstatic_word_offset;
4326           next_nonstatic_word_offset += BytesPerInt;
4327         }
4328         break;
4329       case NONSTATIC_DOUBLE:
4330         real_offset = next_nonstatic_double_offset;
4331         next_nonstatic_double_offset += BytesPerLong;
4332         break;
4333       default:
4334         ShouldNotReachHere();
4335     }
4336     fs.set_offset(real_offset);
4337   }
4338 
4339 
4340   // Handle the contended cases.
4341   //
4342   // Each contended field should not intersect the cache line with another contended field.
4343   // In the absence of alignment information, we end up with pessimistically separating
4344   // the fields with full-width padding.
4345   //
4346   // Additionally, this should not break alignment for the fields, so we round the alignment up
4347   // for each field.
4348   if (nonstatic_contended_count > 0) {
4349 
4350     // if there is at least one contended field, we need to have pre-padding for them
4351     next_nonstatic_padded_offset += ContendedPaddingWidth;
4352 
4353     // collect all contended groups
4354     ResourceBitMap bm(cp->size());
4355     for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4356       // skip already laid out fields
4357       if (fs.is_offset_set()) continue;
4358 
4359       if (fs.is_contended()) {
4360         bm.set_bit(fs.contended_group());
4361       }
4362     }
4363 
4364     int current_group = -1;
4365     while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
4366 
4367       for (AllFieldStream fs(_fields, cp); !fs.done(); fs.next()) {
4368 
4369         // skip already laid out fields
4370         if (fs.is_offset_set()) continue;
4371 
4372         // skip non-contended fields and fields from different group
4373         if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
4374 
4375         // handle statics below
4376         if (fs.access_flags().is_static()) continue;
4377 
4378         int real_offset = 0;
4379         FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
4380 
4381         switch (atype) {
4382           case NONSTATIC_BYTE:
4383             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, 1);
4384             real_offset = next_nonstatic_padded_offset;
4385             next_nonstatic_padded_offset += 1;
4386             break;
4387 
4388           case NONSTATIC_SHORT:
4389             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerShort);
4390             real_offset = next_nonstatic_padded_offset;
4391             next_nonstatic_padded_offset += BytesPerShort;
4392             break;
4393 
4394           case NONSTATIC_WORD:
4395             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerInt);
4396             real_offset = next_nonstatic_padded_offset;
4397             next_nonstatic_padded_offset += BytesPerInt;
4398             break;
4399 
4400           case NONSTATIC_DOUBLE:
4401             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, BytesPerLong);
4402             real_offset = next_nonstatic_padded_offset;
4403             next_nonstatic_padded_offset += BytesPerLong;
4404             break;
4405 
4406             // Value types in static fields are handled with oops
4407           case NONSTATIC_FLATTENABLE:
4408             throwValueTypeLimitation(THREAD_AND_LOCATION,
4409                                      "@Contended annotation not supported for value types yet", fs.name(), fs.signature());
4410             return;
4411 
4412           case NONSTATIC_OOP:
4413             next_nonstatic_padded_offset = align_up(next_nonstatic_padded_offset, heapOopSize);
4414             real_offset = next_nonstatic_padded_offset;
4415             next_nonstatic_padded_offset += heapOopSize;
4416             nonstatic_oop_maps->add(real_offset, 1);
4417             break;
4418 
4419           default:
4420             ShouldNotReachHere();
4421         }
4422 
4423         if (fs.contended_group() == 0) {
4424           // Contended group defines the equivalence class over the fields:
4425           // the fields within the same contended group are not inter-padded.
4426           // The only exception is default group, which does not incur the
4427           // equivalence, and so requires intra-padding.
4428           next_nonstatic_padded_offset += ContendedPaddingWidth;
4429         }
4430 
4431         fs.set_offset(real_offset);
4432       } // for
4433 
4434       // Start laying out the next group.
4435       // Note that this will effectively pad the last group in the back;
4436       // this is expected to alleviate memory contention effects for
4437       // subclass fields and/or adjacent object.
4438       // If this was the default group, the padding is already in place.
4439       if (current_group != 0) {
4440         next_nonstatic_padded_offset += ContendedPaddingWidth;
4441       }
4442     }
4443 
4444     // handle static fields
4445   }
4446 
4447   // Entire class is contended, pad in the back.
4448   // This helps to alleviate memory contention effects for subclass fields
4449   // and/or adjacent object.
4450   if (is_contended_class) {
4451     assert(!is_value_type(), "@Contended not supported for value types yet");
4452     next_nonstatic_padded_offset += ContendedPaddingWidth;
4453   }
4454 
4455   int notaligned_nonstatic_fields_end;
4456   if (nonstatic_value_type_count != 0) {
4457     notaligned_nonstatic_fields_end = next_nonstatic_valuetype_offset;
4458   } else {
4459     notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;
4460   }
4461 
4462   int nonstatic_field_sz_align = heapOopSize;
4463   if (is_value_type()) {
4464     if ((notaligned_nonstatic_fields_end - nonstatic_fields_start) > heapOopSize) {
4465       nonstatic_field_sz_align = BytesPerLong; // value copy of fields only uses jlong copy
4466     }
4467   }
4468   int nonstatic_fields_end      = align_up(notaligned_nonstatic_fields_end, nonstatic_field_sz_align);
4469   int instance_end              = align_up(notaligned_nonstatic_fields_end, wordSize);
4470   int static_fields_end         = align_up(next_static_byte_offset, wordSize);
4471 
4472   int static_field_size         = (static_fields_end -
4473                                    InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
4474   nonstatic_field_size          = nonstatic_field_size +
4475                                   (nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
4476 
4477   int instance_size             = align_object_size(instance_end / wordSize);
4478 
4479   assert(instance_size == align_object_size(align_up(
4480          (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize)
4481          + initial_value_type_padding, wordSize) / wordSize), "consistent layout helper value");
4482 
4483 
4484   // Invariant: nonstatic_field end/start should only change if there are
4485   // nonstatic fields in the class, or if the class is contended. We compare
4486   // against the non-aligned value, so that end alignment will not fail the
4487   // assert without actually having the fields.
4488   assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
4489          is_contended_class ||
4490          (nonstatic_fields_count > 0), "double-check nonstatic start/end");
4491 
4492   // Number of non-static oop map blocks allocated at end of klass.
4493   nonstatic_oop_maps->compact(THREAD);
4494 
4495 #ifndef PRODUCT
4496   if ((PrintFieldLayout && !is_value_type()) ||
4497       (PrintValueLayout && (is_value_type() || has_nonstatic_value_fields))) {
4498     print_field_layout(_class_name,
4499           _fields,
4500           cp,
4501           instance_size,
4502           nonstatic_fields_start,
4503           nonstatic_fields_end,
4504           static_fields_end);
4505     nonstatic_oop_maps->print_on(tty);
4506     tty->print("\n");
4507   }
4508 
4509 #endif
4510   // Pass back information needed for InstanceKlass creation
4511   info->oop_map_blocks = nonstatic_oop_maps;
4512   info->instance_size = instance_size;
4513   info->static_field_size = static_field_size;
4514   info->nonstatic_field_size = nonstatic_field_size;
4515   info->has_nonstatic_fields = has_nonstatic_fields;
4516 }
4517 
4518 void ClassFileParser::set_precomputed_flags(InstanceKlass* ik) {
4519   assert(ik != NULL, "invariant");
4520 
4521   const Klass* const super = ik->super();
4522 
4523   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
4524   // in which case we don't have to register objects as finalizable
4525   if (!_has_empty_finalizer) {
4526     if (_has_finalizer ||
4527         (super != NULL && super->has_finalizer())) {
4528       ik->set_has_finalizer();
4529     }
4530   }
4531 
4532 #ifdef ASSERT
4533   bool f = false;
4534   const Method* const m = ik->lookup_method(vmSymbols::finalize_method_name(),
4535                                            vmSymbols::void_method_signature());
4536   if (m != NULL && !m->is_empty_method()) {
4537       f = true;
4538   }
4539 
4540   // Spec doesn't prevent agent from redefinition of empty finalizer.
4541   // Despite the fact that it's generally bad idea and redefined finalizer
4542   // will not work as expected we shouldn't abort vm in this case
4543   if (!ik->has_redefined_this_or_super()) {
4544     assert(ik->has_finalizer() == f, "inconsistent has_finalizer");
4545   }
4546 #endif
4547 
4548   // Check if this klass supports the java.lang.Cloneable interface
4549   if (SystemDictionary::Cloneable_klass_loaded()) {
4550     if (ik->is_subtype_of(SystemDictionary::Cloneable_klass())) {
4551       ik->set_is_cloneable();
4552     }
4553   }
4554 
4555   // Check if this klass has a vanilla default constructor
4556   if (super == NULL) {
4557     // java.lang.Object has empty default constructor
4558     ik->set_has_vanilla_constructor();
4559   } else {
4560     if (super->has_vanilla_constructor() &&
4561         _has_vanilla_constructor) {
4562       ik->set_has_vanilla_constructor();
4563     }
4564 #ifdef ASSERT
4565     bool v = false;
4566     if (super->has_vanilla_constructor()) {
4567       const Method* const constructor =
4568         ik->find_method(vmSymbols::object_initializer_name(),
4569                        vmSymbols::void_method_signature());
4570       if (constructor != NULL && constructor->is_vanilla_constructor()) {
4571         v = true;
4572       }
4573     }
4574     assert(v == ik->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
4575 #endif
4576   }
4577 
4578   // If it cannot be fast-path allocated, set a bit in the layout helper.
4579   // See documentation of InstanceKlass::can_be_fastpath_allocated().
4580   assert(ik->size_helper() > 0, "layout_helper is initialized");
4581   if ((!RegisterFinalizersAtInit && ik->has_finalizer())
4582       || ik->is_abstract() || ik->is_interface()
4583       || (ik->name() == vmSymbols::java_lang_Class() && ik->class_loader() == NULL)
4584       || ik->size_helper() >= FastAllocateSizeLimit) {
4585     // Forbid fast-path allocation.
4586     const jint lh = Klass::instance_layout_helper(ik->size_helper(), true);
4587     ik->set_layout_helper(lh);
4588   }
4589 }
4590 
4591 bool ClassFileParser::supports_value_types() const {
4592   // Value types are only supported by class file version 53.1 and later
4593   return _major_version > JAVA_9_VERSION || (_major_version == JAVA_9_VERSION && _minor_version >= 1);
4594 }
4595 
4596 // Attach super classes and interface classes to class loader data
4597 static void record_defined_class_dependencies(const InstanceKlass* defined_klass,
4598                                               TRAPS) {
4599   assert(defined_klass != NULL, "invariant");
4600 
4601   ClassLoaderData* const defining_loader_data = defined_klass->class_loader_data();
4602   if (defining_loader_data->is_the_null_class_loader_data()) {
4603       // Dependencies to null class loader data are implicit.
4604       return;
4605   } else {
4606     // add super class dependency
4607     Klass* const super = defined_klass->super();
4608     if (super != NULL) {
4609       defining_loader_data->record_dependency(super, CHECK);
4610     }
4611 
4612     // add super interface dependencies
4613     const Array<Klass*>* const local_interfaces = defined_klass->local_interfaces();
4614     if (local_interfaces != NULL) {
4615       const int length = local_interfaces->length();
4616       for (int i = 0; i < length; i++) {
4617         defining_loader_data->record_dependency(local_interfaces->at(i), CHECK);
4618       }
4619     }
4620 
4621     for(int i = 0; i < defined_klass->java_fields_count(); i++) {
4622       if ((defined_klass->field_access_flags(i) & JVM_ACC_FLATTENABLE) != 0) {
4623         const Klass* klass = defined_klass->get_value_field_klass(i);
4624         defining_loader_data->record_dependency(klass, CHECK);
4625       }
4626     }
4627   }
4628 }
4629 
4630 // utility methods for appending an array with check for duplicates
4631 
4632 static void append_interfaces(GrowableArray<Klass*>* result,
4633                               const Array<Klass*>* const ifs) {
4634   // iterate over new interfaces
4635   for (int i = 0; i < ifs->length(); i++) {
4636     Klass* const e = ifs->at(i);
4637     assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");
4638     // add new interface
4639     result->append_if_missing(e);
4640   }
4641 }
4642 
4643 static Array<Klass*>* compute_transitive_interfaces(const InstanceKlass* super,
4644                                                     Array<Klass*>* local_ifs,
4645                                                     ClassLoaderData* loader_data,
4646                                                     TRAPS) {
4647   assert(local_ifs != NULL, "invariant");
4648   assert(loader_data != NULL, "invariant");
4649 
4650   // Compute maximum size for transitive interfaces
4651   int max_transitive_size = 0;
4652   int super_size = 0;
4653   // Add superclass transitive interfaces size
4654   if (super != NULL) {
4655     super_size = super->transitive_interfaces()->length();
4656     max_transitive_size += super_size;
4657   }
4658   // Add local interfaces' super interfaces
4659   const int local_size = local_ifs->length();
4660   for (int i = 0; i < local_size; i++) {
4661     Klass* const l = local_ifs->at(i);
4662     max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();
4663   }
4664   // Finally add local interfaces
4665   max_transitive_size += local_size;
4666   // Construct array
4667   if (max_transitive_size == 0) {
4668     // no interfaces, use canonicalized array
4669     return Universe::the_empty_klass_array();
4670   } else if (max_transitive_size == super_size) {
4671     // no new local interfaces added, share superklass' transitive interface array
4672     return super->transitive_interfaces();
4673   } else if (max_transitive_size == local_size) {
4674     // only local interfaces added, share local interface array
4675     return local_ifs;
4676   } else {
4677     ResourceMark rm;
4678     GrowableArray<Klass*>* const result = new GrowableArray<Klass*>(max_transitive_size);
4679 
4680     // Copy down from superclass
4681     if (super != NULL) {
4682       append_interfaces(result, super->transitive_interfaces());
4683     }
4684 
4685     // Copy down from local interfaces' superinterfaces
4686     for (int i = 0; i < local_size; i++) {
4687       Klass* const l = local_ifs->at(i);
4688       append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());
4689     }
4690     // Finally add local interfaces
4691     append_interfaces(result, local_ifs);
4692 
4693     // length will be less than the max_transitive_size if duplicates were removed
4694     const int length = result->length();
4695     assert(length <= max_transitive_size, "just checking");
4696     Array<Klass*>* const new_result =
4697       MetadataFactory::new_array<Klass*>(loader_data, length, CHECK_NULL);
4698     for (int i = 0; i < length; i++) {
4699       Klass* const e = result->at(i);
4700       assert(e != NULL, "just checking");
4701       new_result->at_put(i, e);
4702     }
4703     return new_result;
4704   }
4705 }
4706 
4707 static void check_super_class_access(const InstanceKlass* this_klass, TRAPS) {
4708   assert(this_klass != NULL, "invariant");
4709   const Klass* const super = this_klass->super();
4710   if (super != NULL) {
4711 
4712     // If the loader is not the boot loader then throw an exception if its
4713     // superclass is in package jdk.internal.reflect and its loader is not a
4714     // special reflection class loader
4715     if (!this_klass->class_loader_data()->is_the_null_class_loader_data()) {
4716       assert(super->is_instance_klass(), "super is not instance klass");
4717       PackageEntry* super_package = super->package();
4718       if (super_package != NULL &&
4719           super_package->name()->fast_compare(vmSymbols::jdk_internal_reflect()) == 0 &&
4720           !java_lang_ClassLoader::is_reflection_class_loader(this_klass->class_loader())) {
4721         ResourceMark rm(THREAD);
4722         Exceptions::fthrow(
4723           THREAD_AND_LOCATION,
4724           vmSymbols::java_lang_IllegalAccessError(),
4725           "class %s loaded by %s cannot access jdk/internal/reflect superclass %s",
4726           this_klass->external_name(),
4727           this_klass->class_loader_data()->loader_name(),
4728           super->external_name());
4729         return;
4730       }
4731     }
4732 
4733     Reflection::VerifyClassAccessResults vca_result =
4734       Reflection::verify_class_access(this_klass, InstanceKlass::cast(super), false);
4735     if (vca_result != Reflection::ACCESS_OK) {
4736       ResourceMark rm(THREAD);
4737       char* msg = Reflection::verify_class_access_msg(this_klass,
4738                                                       InstanceKlass::cast(super),
4739                                                       vca_result);
4740       if (msg == NULL) {
4741         Exceptions::fthrow(
4742           THREAD_AND_LOCATION,
4743           vmSymbols::java_lang_IllegalAccessError(),
4744           "class %s cannot access its superclass %s",
4745           this_klass->external_name(),
4746           super->external_name());
4747       } else {
4748         // Add additional message content.
4749         Exceptions::fthrow(
4750           THREAD_AND_LOCATION,
4751           vmSymbols::java_lang_IllegalAccessError(),
4752           "superclass access check failed: %s",
4753           msg);
4754       }
4755     }
4756   }
4757 }
4758 
4759 
4760 static void check_super_interface_access(const InstanceKlass* this_klass, TRAPS) {
4761   assert(this_klass != NULL, "invariant");
4762   const Array<Klass*>* const local_interfaces = this_klass->local_interfaces();
4763   const int lng = local_interfaces->length();
4764   for (int i = lng - 1; i >= 0; i--) {
4765     Klass* const k = local_interfaces->at(i);
4766     assert (k != NULL && k->is_interface(), "invalid interface");
4767     Reflection::VerifyClassAccessResults vca_result =
4768       Reflection::verify_class_access(this_klass, InstanceKlass::cast(k), false);
4769     if (vca_result != Reflection::ACCESS_OK) {
4770       ResourceMark rm(THREAD);
4771       char* msg = Reflection::verify_class_access_msg(this_klass,
4772                                                       InstanceKlass::cast(k),
4773                                                       vca_result);
4774       if (msg == NULL) {
4775         Exceptions::fthrow(
4776           THREAD_AND_LOCATION,
4777           vmSymbols::java_lang_IllegalAccessError(),
4778           "class %s cannot access its superinterface %s",
4779           this_klass->external_name(),
4780           k->external_name());
4781       } else {
4782         // Add additional message content.
4783         Exceptions::fthrow(
4784           THREAD_AND_LOCATION,
4785           vmSymbols::java_lang_IllegalAccessError(),
4786           "superinterface check failed: %s",
4787           msg);
4788       }
4789     }
4790   }
4791 }
4792 
4793 
4794 static void check_final_method_override(const InstanceKlass* this_klass, TRAPS) {
4795   assert(this_klass != NULL, "invariant");
4796   const Array<Method*>* const methods = this_klass->methods();
4797   const int num_methods = methods->length();
4798 
4799   // go thru each method and check if it overrides a final method
4800   for (int index = 0; index < num_methods; index++) {
4801     const Method* const m = methods->at(index);
4802 
4803     // skip private, static, and <init> methods
4804     if ((!m->is_private() && !m->is_static()) &&
4805         (m->name() != vmSymbols::object_initializer_name())) {
4806 
4807       const Symbol* const name = m->name();
4808       const Symbol* const signature = m->signature();
4809       const Klass* k = this_klass->super();
4810       const Method* super_m = NULL;
4811       while (k != NULL) {
4812         // skip supers that don't have final methods.
4813         if (k->has_final_method()) {
4814           // lookup a matching method in the super class hierarchy
4815           super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
4816           if (super_m == NULL) {
4817             break; // didn't find any match; get out
4818           }
4819 
4820           if (super_m->is_final() && !super_m->is_static() &&
4821               // matching method in super is final, and not static
4822               (Reflection::verify_field_access(this_klass,
4823                                                super_m->method_holder(),
4824                                                super_m->method_holder(),
4825                                                super_m->access_flags(), false))
4826             // this class can access super final method and therefore override
4827             ) {
4828             ResourceMark rm(THREAD);
4829             Exceptions::fthrow(
4830               THREAD_AND_LOCATION,
4831               vmSymbols::java_lang_VerifyError(),
4832               "class %s overrides final method %s.%s%s",
4833               this_klass->external_name(),
4834               super_m->method_holder()->external_name(),
4835               name->as_C_string(),
4836               signature->as_C_string()
4837             );
4838             return;
4839           }
4840 
4841           // continue to look from super_m's holder's super.
4842           k = super_m->method_holder()->super();
4843           continue;
4844         }
4845 
4846         k = k->super();
4847       }
4848     }
4849   }
4850 }
4851 
4852 
4853 // assumes that this_klass is an interface
4854 static void check_illegal_static_method(const InstanceKlass* this_klass, TRAPS) {
4855   assert(this_klass != NULL, "invariant");
4856   assert(this_klass->is_interface(), "not an interface");
4857   const Array<Method*>* methods = this_klass->methods();
4858   const int num_methods = methods->length();
4859 
4860   for (int index = 0; index < num_methods; index++) {
4861     const Method* const m = methods->at(index);
4862     // if m is static and not the init method, throw a verify error
4863     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
4864       ResourceMark rm(THREAD);
4865       Exceptions::fthrow(
4866         THREAD_AND_LOCATION,
4867         vmSymbols::java_lang_VerifyError(),
4868         "Illegal static method %s in interface %s",
4869         m->name()->as_C_string(),
4870         this_klass->external_name()
4871       );
4872       return;
4873     }
4874   }
4875 }
4876 
4877 // utility methods for format checking
4878 
4879 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) const {
4880   const bool is_module = (flags & JVM_ACC_MODULE) != 0;
4881   const bool is_value_type = (flags & JVM_ACC_VALUE) != 0;
4882   assert(_major_version >= JAVA_9_VERSION || !is_module, "JVM_ACC_MODULE should not be set");
4883   assert(supports_value_types() || !is_value_type, "JVM_ACC_VALUE should not be set");
4884   if (is_module) {
4885     ResourceMark rm(THREAD);
4886     Exceptions::fthrow(
4887       THREAD_AND_LOCATION,
4888       vmSymbols::java_lang_NoClassDefFoundError(),
4889       "%s is not a class because access_flag ACC_MODULE is set",
4890       _class_name->as_C_string());
4891     return;
4892   }
4893 
4894   if (!_need_verify) { return; }
4895 
4896   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
4897   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
4898   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
4899   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
4900   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
4901   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
4902   const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;
4903 
4904   if ((is_abstract && is_final) ||
4905       (is_interface && !is_abstract) ||
4906       (is_interface && major_gte_15 && (is_super || is_enum)) ||
4907       (!is_interface && major_gte_15 && is_annotation)) {
4908     ResourceMark rm(THREAD);
4909     Exceptions::fthrow(
4910       THREAD_AND_LOCATION,
4911       vmSymbols::java_lang_ClassFormatError(),
4912       "Illegal class modifiers in class %s: 0x%X",
4913       _class_name->as_C_string(), flags
4914     );
4915     return;
4916   }
4917 }
4918 
4919 static bool has_illegal_visibility(jint flags) {
4920   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4921   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4922   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4923 
4924   return ((is_public && is_protected) ||
4925           (is_public && is_private) ||
4926           (is_protected && is_private));
4927 }
4928 
4929 static bool is_supported_version(u2 major, u2 minor) {
4930   const u2 max_version = JVM_CLASSFILE_MAJOR_VERSION;
4931   return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
4932          (major <= max_version) &&
4933          ((major != max_version) ||
4934           (minor <= JVM_CLASSFILE_MINOR_VERSION));
4935 }
4936 
4937 void ClassFileParser::verify_legal_field_modifiers(jint flags,
4938                                                    bool is_interface,
4939                                                    TRAPS) const {
4940   if (!_need_verify) { return; }
4941 
4942   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4943   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4944   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4945   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4946   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4947   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4948   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4949   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4950   const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
4951 
4952   bool is_illegal = false;
4953 
4954   if (is_interface) {
4955     if (!is_public || !is_static || !is_final || is_private ||
4956         is_protected || is_volatile || is_transient ||
4957         (major_gte_15 && is_enum)) {
4958       is_illegal = true;
4959     }
4960   } else { // not interface
4961     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4962       is_illegal = true;
4963     }
4964   }
4965 
4966   if (is_illegal) {
4967     ResourceMark rm(THREAD);
4968     Exceptions::fthrow(
4969       THREAD_AND_LOCATION,
4970       vmSymbols::java_lang_ClassFormatError(),
4971       "Illegal field modifiers in class %s: 0x%X",
4972       _class_name->as_C_string(), flags);
4973     return;
4974   }
4975 }
4976 
4977 void ClassFileParser::verify_legal_method_modifiers(jint flags,
4978                                                     bool is_interface,
4979                                                     const Symbol* name,
4980                                                     TRAPS) const {
4981   if (!_need_verify) { return; }
4982 
4983   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4984   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4985   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4986   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4987   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4988   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4989   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4990   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4991   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4992   const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
4993   const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
4994   const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
4995   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4996 
4997   bool is_illegal = false;
4998 
4999   if (is_interface) {
5000     if (major_gte_8) {
5001       // Class file version is JAVA_8_VERSION or later Methods of
5002       // interfaces may set any of the flags except ACC_PROTECTED,
5003       // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
5004       // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
5005       if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
5006           (is_native || is_protected || is_final || is_synchronized) ||
5007           // If a specific method of a class or interface has its
5008           // ACC_ABSTRACT flag set, it must not have any of its
5009           // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
5010           // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
5011           // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
5012           // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
5013           (is_abstract && (is_private || is_static || is_strict))) {
5014         is_illegal = true;
5015       }
5016     } else if (major_gte_15) {
5017       // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
5018       if (!is_public || is_private || is_protected || is_static || is_final ||
5019           is_synchronized || is_native || !is_abstract || is_strict) {
5020         is_illegal = true;
5021       }
5022     } else {
5023       // Class file version is pre-JAVA_1_5_VERSION
5024       if (!is_public || is_static || is_final || is_native || !is_abstract) {
5025         is_illegal = true;
5026       }
5027     }
5028   } else { // not interface
5029     if (has_illegal_visibility(flags)) {
5030       is_illegal = true;
5031     } else {
5032       if (is_initializer) {
5033         if (is_static || is_final || is_synchronized || is_native ||
5034             is_abstract || (major_gte_15 && is_bridge)) {
5035           is_illegal = true;
5036         }
5037       } else { // not initializer
5038         if (is_abstract) {
5039           if ((is_final || is_native || is_private || is_static ||
5040               (major_gte_15 && (is_synchronized || is_strict)))) {
5041             is_illegal = true;
5042           }
5043         }
5044       }
5045     }
5046   }
5047 
5048   if (is_illegal) {
5049     ResourceMark rm(THREAD);
5050     Exceptions::fthrow(
5051       THREAD_AND_LOCATION,
5052       vmSymbols::java_lang_ClassFormatError(),
5053       "Method %s in class %s has illegal modifiers: 0x%X",
5054       name->as_C_string(), _class_name->as_C_string(), flags);
5055     return;
5056   }
5057 }
5058 
5059 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer,
5060                                         int length,
5061                                         TRAPS) const {
5062   assert(_need_verify, "only called when _need_verify is true");
5063   if (!UTF8::is_legal_utf8(buffer, length, _major_version <= 47)) {
5064     classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
5065   }
5066 }
5067 
5068 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
5069 // In class names, '/' separates unqualified names.  This is verified in this function also.
5070 // Method names also may not contain the characters '<' or '>', unless <init>
5071 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
5072 // method.  Because these names have been checked as special cases before
5073 // calling this method in verify_legal_method_name.
5074 //
5075 // This method is also called from the modular system APIs in modules.cpp
5076 // to verify the validity of module and package names.
5077 bool ClassFileParser::verify_unqualified_name(const char* name,
5078                                               unsigned int length,
5079                                               int type) {
5080   for (const char* p = name; p != name + length;) {
5081     jchar ch = *p;
5082     if (ch < 128) {
5083       if (ch == '.' || ch == ';' || ch == '[' ) {
5084         return false;   // do not permit '.', ';', or '['
5085       }
5086       if (ch == '/') {
5087         // check for '//' or leading or trailing '/' which are not legal
5088         // unqualified name must not be empty
5089         if (type == ClassFileParser::LegalClass) {
5090           if (p == name || p+1 >= name+length || *(p+1) == '/') {
5091            return false;
5092           }
5093         } else {
5094           return false;   // do not permit '/' unless it's class name
5095         }
5096       }
5097       if (type == ClassFileParser::LegalMethod && (ch == '<' || ch == '>')) {
5098         return false;   // do not permit '<' or '>' in method names
5099       }
5100       p++;
5101     } else {
5102       char* tmp_p = UTF8::next(p, &ch);
5103       p = tmp_p;
5104     }
5105   }
5106   return true;
5107 }
5108 
5109 // Take pointer to a string. Skip over the longest part of the string that could
5110 // be taken as a fieldname. Allow '/' if slash_ok is true.
5111 // Return a pointer to just past the fieldname.
5112 // Return NULL if no fieldname at all was found, or in the case of slash_ok
5113 // being true, we saw consecutive slashes (meaning we were looking for a
5114 // qualified path but found something that was badly-formed).
5115 static const char* skip_over_field_name(const char* name,
5116                                         bool slash_ok,
5117                                         unsigned int length) {
5118   const char* p;
5119   jboolean last_is_slash = false;
5120   jboolean not_first_ch = false;
5121 
5122   for (p = name; p != name + length; not_first_ch = true) {
5123     const char* old_p = p;
5124     jchar ch = *p;
5125     if (ch < 128) {
5126       p++;
5127       // quick check for ascii
5128       if ((ch >= 'a' && ch <= 'z') ||
5129         (ch >= 'A' && ch <= 'Z') ||
5130         (ch == '_' || ch == '$') ||
5131         (not_first_ch && ch >= '0' && ch <= '9')) {
5132         last_is_slash = false;
5133         continue;
5134       }
5135       if (slash_ok && ch == '/') {
5136         if (last_is_slash) {
5137           return NULL;  // Don't permit consecutive slashes
5138         }
5139         last_is_slash = true;
5140         continue;
5141       }
5142     }
5143     else {
5144       jint unicode_ch;
5145       char* tmp_p = UTF8::next_character(p, &unicode_ch);
5146       p = tmp_p;
5147       last_is_slash = false;
5148       // Check if ch is Java identifier start or is Java identifier part
5149       // 4672820: call java.lang.Character methods directly without generating separate tables.
5150       EXCEPTION_MARK;
5151 
5152       // return value
5153       JavaValue result(T_BOOLEAN);
5154       // Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart
5155       JavaCallArguments args;
5156       args.push_int(unicode_ch);
5157 
5158       // public static boolean isJavaIdentifierStart(char ch);
5159       JavaCalls::call_static(&result,
5160         SystemDictionary::Character_klass(),
5161         vmSymbols::isJavaIdentifierStart_name(),
5162         vmSymbols::int_bool_signature(),
5163         &args,
5164         THREAD);
5165 
5166       if (HAS_PENDING_EXCEPTION) {
5167         CLEAR_PENDING_EXCEPTION;
5168         return 0;
5169       }
5170       if (result.get_jboolean()) {
5171         continue;
5172       }
5173 
5174       if (not_first_ch) {
5175         // public static boolean isJavaIdentifierPart(char ch);
5176         JavaCalls::call_static(&result,
5177           SystemDictionary::Character_klass(),
5178           vmSymbols::isJavaIdentifierPart_name(),
5179           vmSymbols::int_bool_signature(),
5180           &args,
5181           THREAD);
5182 
5183         if (HAS_PENDING_EXCEPTION) {
5184           CLEAR_PENDING_EXCEPTION;
5185           return 0;
5186         }
5187 
5188         if (result.get_jboolean()) {
5189           continue;
5190         }
5191       }
5192     }
5193     return (not_first_ch) ? old_p : NULL;
5194   }
5195   return (not_first_ch) ? p : NULL;
5196 }
5197 
5198 // Take pointer to a string. Skip over the longest part of the string that could
5199 // be taken as a field signature. Allow "void" if void_ok.
5200 // Return a pointer to just past the signature.
5201 // Return NULL if no legal signature is found.
5202 const char* ClassFileParser::skip_over_field_signature(const char* signature,
5203                                                        bool void_ok,
5204                                                        unsigned int length,
5205                                                        TRAPS) const {
5206   unsigned int array_dim = 0;
5207   while (length > 0) {
5208     switch (signature[0]) {
5209     case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
5210     case JVM_SIGNATURE_BOOLEAN:
5211     case JVM_SIGNATURE_BYTE:
5212     case JVM_SIGNATURE_CHAR:
5213     case JVM_SIGNATURE_SHORT:
5214     case JVM_SIGNATURE_INT:
5215     case JVM_SIGNATURE_FLOAT:
5216     case JVM_SIGNATURE_LONG:
5217     case JVM_SIGNATURE_DOUBLE:
5218       return signature + 1;
5219     case JVM_SIGNATURE_CLASS:
5220     {
5221       if (_major_version < JAVA_1_5_VERSION) {
5222         // Skip over the class name if one is there
5223         const char* const p = skip_over_field_name(signature + 1, true, --length);
5224 
5225         // The next character better be a semicolon
5226         if (p && (p - signature) > 1 && p[0] == ';') {
5227           return p + 1;
5228         }
5229       }
5230       else {
5231         // Skip leading 'L' and ignore first appearance of ';'
5232         length--;
5233         signature++;
5234         char* c = strchr((char*) signature, ';');
5235         // Format check signature
5236         if (c != NULL) {
5237           ResourceMark rm(THREAD);
5238           int newlen = c - (char*) signature;
5239           char* sig = NEW_RESOURCE_ARRAY(char, newlen + 1);
5240           strncpy(sig, signature, newlen);
5241           sig[newlen] = '\0';
5242 
5243           bool legal = verify_unqualified_name(sig, newlen, LegalClass);
5244           if (!legal) {
5245             classfile_parse_error("Class name contains illegal character "
5246                                   "in descriptor in class file %s",
5247                                   CHECK_0);
5248             return NULL;
5249           }
5250           return signature + newlen + 1;
5251         }
5252       }
5253       return NULL;
5254     }
5255     case JVM_SIGNATURE_ARRAY:
5256       array_dim++;
5257       if (array_dim > 255) {
5258         // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
5259         classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
5260       }
5261       // The rest of what's there better be a legal signature
5262       signature++;
5263       length--;
5264       void_ok = false;
5265       break;
5266     default:
5267       return NULL;
5268     }
5269   }
5270   return NULL;
5271 }
5272 
5273 // Checks if name is a legal class name.
5274 void ClassFileParser::verify_legal_class_name(const Symbol* name, TRAPS) const {
5275   if (!_need_verify || _relax_verify) { return; }
5276 
5277   char buf[fixed_buffer_size];
5278   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5279   unsigned int length = name->utf8_length();
5280   bool legal = false;
5281 
5282   if (length > 0) {
5283     const char* p;
5284     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
5285       p = skip_over_field_signature(bytes, false, length, CHECK);
5286       legal = (p != NULL) && ((p - bytes) == (int)length);
5287     } else if (_major_version < JAVA_1_5_VERSION) {
5288       if (bytes[0] != '<') {
5289         p = skip_over_field_name(bytes, true, length);
5290         legal = (p != NULL) && ((p - bytes) == (int)length);
5291       }
5292     } else {
5293       // 4900761: relax the constraints based on JSR202 spec
5294       // Class names may be drawn from the entire Unicode character set.
5295       // Identifiers between '/' must be unqualified names.
5296       // The utf8 string has been verified when parsing cpool entries.
5297       legal = verify_unqualified_name(bytes, length, LegalClass);
5298     }
5299   }
5300   if (!legal) {
5301     ResourceMark rm(THREAD);
5302     assert(_class_name != NULL, "invariant");
5303     Exceptions::fthrow(
5304       THREAD_AND_LOCATION,
5305       vmSymbols::java_lang_ClassFormatError(),
5306       "Illegal class name \"%s\" in class file %s", bytes,
5307       _class_name->as_C_string()
5308     );
5309     return;
5310   }
5311 }
5312 
5313 // Checks if name is a legal field name.
5314 void ClassFileParser::verify_legal_field_name(const Symbol* name, TRAPS) const {
5315   if (!_need_verify || _relax_verify) { return; }
5316 
5317   char buf[fixed_buffer_size];
5318   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5319   unsigned int length = name->utf8_length();
5320   bool legal = false;
5321 
5322   if (length > 0) {
5323     if (_major_version < JAVA_1_5_VERSION) {
5324       if (bytes[0] != '<') {
5325         const char* p = skip_over_field_name(bytes, false, length);
5326         legal = (p != NULL) && ((p - bytes) == (int)length);
5327       }
5328     } else {
5329       // 4881221: relax the constraints based on JSR202 spec
5330       legal = verify_unqualified_name(bytes, length, LegalField);
5331     }
5332   }
5333 
5334   if (!legal) {
5335     ResourceMark rm(THREAD);
5336     assert(_class_name != NULL, "invariant");
5337     Exceptions::fthrow(
5338       THREAD_AND_LOCATION,
5339       vmSymbols::java_lang_ClassFormatError(),
5340       "Illegal field name \"%s\" in class %s", bytes,
5341       _class_name->as_C_string()
5342     );
5343     return;
5344   }
5345 }
5346 
5347 // Checks if name is a legal method name.
5348 void ClassFileParser::verify_legal_method_name(const Symbol* name, TRAPS) const {
5349   if (!_need_verify || _relax_verify) { return; }
5350 
5351   assert(name != NULL, "method name is null");
5352   char buf[fixed_buffer_size];
5353   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5354   unsigned int length = name->utf8_length();
5355   bool legal = false;
5356 
5357   if (length > 0) {
5358     if (bytes[0] == '<') {
5359       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
5360         legal = true;
5361       }
5362     } else if (_major_version < JAVA_1_5_VERSION) {
5363       const char* p;
5364       p = skip_over_field_name(bytes, false, length);
5365       legal = (p != NULL) && ((p - bytes) == (int)length);
5366     } else {
5367       // 4881221: relax the constraints based on JSR202 spec
5368       legal = verify_unqualified_name(bytes, length, LegalMethod);
5369     }
5370   }
5371 
5372   if (!legal) {
5373     ResourceMark rm(THREAD);
5374     assert(_class_name != NULL, "invariant");
5375     Exceptions::fthrow(
5376       THREAD_AND_LOCATION,
5377       vmSymbols::java_lang_ClassFormatError(),
5378       "Illegal method name \"%s\" in class %s", bytes,
5379       _class_name->as_C_string()
5380     );
5381     return;
5382   }
5383 }
5384 
5385 
5386 // Checks if signature is a legal field signature.
5387 void ClassFileParser::verify_legal_field_signature(const Symbol* name,
5388                                                    const Symbol* signature,
5389                                                    TRAPS) const {
5390   if (!_need_verify) { return; }
5391 
5392   char buf[fixed_buffer_size];
5393   const char* const bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5394   const unsigned int length = signature->utf8_length();
5395   const char* const p = skip_over_field_signature(bytes, false, length, CHECK);
5396 
5397   if (p == NULL || (p - bytes) != (int)length) {
5398     throwIllegalSignature("Field", name, signature, CHECK);
5399   }
5400 }
5401 
5402 // Checks if signature is a legal method signature.
5403 // Returns number of parameters
5404 int ClassFileParser::verify_legal_method_signature(const Symbol* name,
5405                                                    const Symbol* signature,
5406                                                    TRAPS) const {
5407   if (!_need_verify) {
5408     // make sure caller's args_size will be less than 0 even for non-static
5409     // method so it will be recomputed in compute_size_of_parameters().
5410     return -2;
5411   }
5412 
5413   // Class initializers cannot have args for class format version >= 51.
5414   if (name == vmSymbols::class_initializer_name() &&
5415       signature != vmSymbols::void_method_signature() &&
5416       _major_version >= JAVA_7_VERSION) {
5417     throwIllegalSignature("Method", name, signature, CHECK_0);
5418     return 0;
5419   }
5420 
5421   unsigned int args_size = 0;
5422   char buf[fixed_buffer_size];
5423   const char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
5424   unsigned int length = signature->utf8_length();
5425   const char* nextp;
5426 
5427   // The first character must be a '('
5428   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
5429     length--;
5430     // Skip over legal field signatures
5431     nextp = skip_over_field_signature(p, false, length, CHECK_0);
5432     while ((length > 0) && (nextp != NULL)) {
5433       args_size++;
5434       if (p[0] == 'J' || p[0] == 'D') {
5435         args_size++;
5436       }
5437       length -= nextp - p;
5438       p = nextp;
5439       nextp = skip_over_field_signature(p, false, length, CHECK_0);
5440     }
5441     // The first non-signature thing better be a ')'
5442     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
5443       length--;
5444       if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
5445         // All internal methods must return void
5446         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
5447           return args_size;
5448         }
5449       } else {
5450         // Now we better just have a return value
5451         nextp = skip_over_field_signature(p, true, length, CHECK_0);
5452         if (nextp && ((int)length == (nextp - p))) {
5453           return args_size;
5454         }
5455       }
5456     }
5457   }
5458   // Report error
5459   throwIllegalSignature("Method", name, signature, CHECK_0);
5460   return 0;
5461 }
5462 
5463 int ClassFileParser::static_field_size() const {
5464   assert(_field_info != NULL, "invariant");
5465   return _field_info->static_field_size;
5466 }
5467 
5468 int ClassFileParser::total_oop_map_count() const {
5469   assert(_field_info != NULL, "invariant");
5470   return _field_info->oop_map_blocks->nonstatic_oop_map_count;
5471 }
5472 
5473 jint ClassFileParser::layout_size() const {
5474   assert(_field_info != NULL, "invariant");
5475   return _field_info->instance_size;
5476 }
5477 
5478 static void check_methods_for_intrinsics(const InstanceKlass* ik,
5479                                          const Array<Method*>* methods) {
5480   assert(ik != NULL, "invariant");
5481   assert(methods != NULL, "invariant");
5482 
5483   // Set up Method*::intrinsic_id as soon as we know the names of methods.
5484   // (We used to do this lazily, but now we query it in Rewriter,
5485   // which is eagerly done for every method, so we might as well do it now,
5486   // when everything is fresh in memory.)
5487   const vmSymbols::SID klass_id = Method::klass_id_for_intrinsics(ik);
5488 
5489   if (klass_id != vmSymbols::NO_SID) {
5490     for (int j = 0; j < methods->length(); ++j) {
5491       Method* method = methods->at(j);
5492       method->init_intrinsic_id();
5493 
5494       if (CheckIntrinsics) {
5495         // Check if an intrinsic is defined for method 'method',
5496         // but the method is not annotated with @HotSpotIntrinsicCandidate.
5497         if (method->intrinsic_id() != vmIntrinsics::_none &&
5498             !method->intrinsic_candidate()) {
5499               tty->print("Compiler intrinsic is defined for method [%s], "
5500               "but the method is not annotated with @HotSpotIntrinsicCandidate.%s",
5501               method->name_and_sig_as_C_string(),
5502               NOT_DEBUG(" Method will not be inlined.") DEBUG_ONLY(" Exiting.")
5503             );
5504           tty->cr();
5505           DEBUG_ONLY(vm_exit(1));
5506         }
5507         // Check is the method 'method' is annotated with @HotSpotIntrinsicCandidate,
5508         // but there is no intrinsic available for it.
5509         if (method->intrinsic_candidate() &&
5510           method->intrinsic_id() == vmIntrinsics::_none) {
5511             tty->print("Method [%s] is annotated with @HotSpotIntrinsicCandidate, "
5512               "but no compiler intrinsic is defined for the method.%s",
5513               method->name_and_sig_as_C_string(),
5514               NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5515             );
5516           tty->cr();
5517           DEBUG_ONLY(vm_exit(1));
5518         }
5519       }
5520     } // end for
5521 
5522 #ifdef ASSERT
5523     if (CheckIntrinsics) {
5524       // Check for orphan methods in the current class. A method m
5525       // of a class C is orphan if an intrinsic is defined for method m,
5526       // but class C does not declare m.
5527       // The check is potentially expensive, therefore it is available
5528       // only in debug builds.
5529 
5530       for (int id = vmIntrinsics::FIRST_ID; id < (int)vmIntrinsics::ID_LIMIT; ++id) {
5531         if (vmIntrinsics::_compiledLambdaForm == id) {
5532           // The _compiledLamdbdaForm intrinsic is a special marker for bytecode
5533           // generated for the JVM from a LambdaForm and therefore no method
5534           // is defined for it.
5535           continue;
5536         }
5537 
5538         if (vmIntrinsics::class_for(vmIntrinsics::ID_from(id)) == klass_id) {
5539           // Check if the current class contains a method with the same
5540           // name, flags, signature.
5541           bool match = false;
5542           for (int j = 0; j < methods->length(); ++j) {
5543             const Method* method = methods->at(j);
5544             if (method->intrinsic_id() == id) {
5545               match = true;
5546               break;
5547             }
5548           }
5549 
5550           if (!match) {
5551             char buf[1000];
5552             tty->print("Compiler intrinsic is defined for method [%s], "
5553                        "but the method is not available in class [%s].%s",
5554                         vmIntrinsics::short_name_as_C_string(vmIntrinsics::ID_from(id),
5555                                                              buf, sizeof(buf)),
5556                         ik->name()->as_C_string(),
5557                         NOT_DEBUG("") DEBUG_ONLY(" Exiting.")
5558             );
5559             tty->cr();
5560             DEBUG_ONLY(vm_exit(1));
5561           }
5562         }
5563       } // end for
5564     } // CheckIntrinsics
5565 #endif // ASSERT
5566   }
5567 }
5568 
5569 InstanceKlass* ClassFileParser::create_instance_klass(bool changed_by_loadhook, TRAPS) {
5570   if (_klass != NULL) {
5571     return _klass;
5572   }
5573 
5574   InstanceKlass* const ik =
5575     InstanceKlass::allocate_instance_klass(*this, CHECK_NULL);
5576 
5577   fill_instance_klass(ik, changed_by_loadhook, CHECK_NULL);
5578 
5579   assert(_klass == ik, "invariant");
5580 
5581   ik->set_has_passed_fingerprint_check(false);
5582   if (UseAOT && ik->supers_have_passed_fingerprint_checks()) {
5583     uint64_t aot_fp = AOTLoader::get_saved_fingerprint(ik);
5584     if (aot_fp != 0 && aot_fp == _stream->compute_fingerprint()) {
5585       // This class matches with a class saved in an AOT library
5586       ik->set_has_passed_fingerprint_check(true);
5587     } else {
5588       ResourceMark rm;
5589       log_info(class, fingerprint)("%s :  expected = " PTR64_FORMAT " actual = " PTR64_FORMAT,
5590                                  ik->external_name(), aot_fp, _stream->compute_fingerprint());
5591     }
5592   }
5593 
5594   if (ik->is_value()) {
5595     ValueKlass* vk = ValueKlass::cast(ik);
5596     oop val = ik->allocate_instance(CHECK_NULL);
5597     vk->set_default_value(val);
5598   }
5599 
5600   return ik;
5601 }
5602 
5603 void ClassFileParser::fill_instance_klass(InstanceKlass* ik, bool changed_by_loadhook, TRAPS) {
5604   assert(ik != NULL, "invariant");
5605 
5606   set_klass_to_deallocate(ik);
5607 
5608   assert(_field_info != NULL, "invariant");
5609   assert(ik->static_field_size() == _field_info->static_field_size, "sanity");
5610   assert(ik->nonstatic_oop_map_count() == _field_info->oop_map_blocks->nonstatic_oop_map_count,
5611     "sanity");
5612 
5613   assert(ik->is_instance_klass(), "sanity");
5614   assert(ik->size_helper() == _field_info->instance_size, "sanity");
5615 
5616   // Fill in information already parsed
5617   ik->set_should_verify_class(_need_verify);
5618 
5619   // Not yet: supers are done below to support the new subtype-checking fields
5620   ik->set_class_loader_data(_loader_data);
5621   ik->set_nonstatic_field_size(_field_info->nonstatic_field_size);
5622   ik->set_has_nonstatic_fields(_field_info->has_nonstatic_fields);
5623   assert(_fac != NULL, "invariant");
5624   ik->set_static_oop_field_count(_fac->count[STATIC_OOP] + _fac->count[STATIC_FLATTENABLE]);
5625 
5626   // this transfers ownership of a lot of arrays from
5627   // the parser onto the InstanceKlass*
5628   apply_parsed_class_metadata(ik, _java_fields_count, CHECK);
5629 
5630   // note that is not safe to use the fields in the parser from this point on
5631   assert(NULL == _cp, "invariant");
5632   assert(NULL == _fields, "invariant");
5633   assert(NULL == _methods, "invariant");
5634   assert(NULL == _inner_classes, "invariant");
5635   assert(NULL == _local_interfaces, "invariant");
5636   assert(NULL == _transitive_interfaces, "invariant");
5637   assert(NULL == _combined_annotations, "invariant");
5638 
5639   if (_has_final_method) {
5640     ik->set_has_final_method();
5641   }
5642 
5643   ik->copy_method_ordering(_method_ordering, CHECK);
5644   // The InstanceKlass::_methods_jmethod_ids cache
5645   // is managed on the assumption that the initial cache
5646   // size is equal to the number of methods in the class. If
5647   // that changes, then InstanceKlass::idnum_can_increment()
5648   // has to be changed accordingly.
5649   ik->set_initial_method_idnum(ik->methods()->length());
5650 
5651   ik->set_name(_class_name);
5652 
5653   if (is_anonymous()) {
5654     // _this_class_index is a CONSTANT_Class entry that refers to this
5655     // anonymous class itself. If this class needs to refer to its own methods or
5656     // fields, it would use a CONSTANT_MethodRef, etc, which would reference
5657     // _this_class_index. However, because this class is anonymous (it's
5658     // not stored in SystemDictionary), _this_class_index cannot be resolved
5659     // with ConstantPool::klass_at_impl, which does a SystemDictionary lookup.
5660     // Therefore, we must eagerly resolve _this_class_index now.
5661     ik->constants()->klass_at_put(_this_class_index, ik);
5662   }
5663 
5664   ik->set_minor_version(_minor_version);
5665   ik->set_major_version(_major_version);
5666   ik->set_has_nonstatic_concrete_methods(_has_nonstatic_concrete_methods);
5667   ik->set_declares_nonstatic_concrete_methods(_declares_nonstatic_concrete_methods);
5668 
5669   if (_host_klass != NULL) {
5670     assert (ik->is_anonymous(), "should be the same");
5671     ik->set_host_klass(_host_klass);
5672   }
5673 
5674   // Set PackageEntry for this_klass
5675   oop cl = ik->class_loader();
5676   Handle clh = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(cl));
5677   ClassLoaderData* cld = ClassLoaderData::class_loader_data_or_null(clh());
5678   ik->set_package(cld, CHECK);
5679 
5680   const Array<Method*>* const methods = ik->methods();
5681   assert(methods != NULL, "invariant");
5682   const int methods_len = methods->length();
5683 
5684   check_methods_for_intrinsics(ik, methods);
5685 
5686   // Fill in field values obtained by parse_classfile_attributes
5687   if (_parsed_annotations->has_any_annotations()) {
5688     _parsed_annotations->apply_to(ik);
5689   }
5690 
5691   apply_parsed_class_attributes(ik);
5692 
5693   // Miranda methods
5694   if ((_num_miranda_methods > 0) ||
5695       // if this class introduced new miranda methods or
5696       (_super_klass != NULL && _super_klass->has_miranda_methods())
5697         // super class exists and this class inherited miranda methods
5698      ) {
5699        ik->set_has_miranda_methods(); // then set a flag
5700   }
5701 
5702   // Fill in information needed to compute superclasses.
5703   ik->initialize_supers(const_cast<InstanceKlass*>(_super_klass), CHECK);
5704 
5705   // Initialize itable offset tables
5706   klassItable::setup_itable_offset_table(ik);
5707 
5708   // Compute transitive closure of interfaces this class implements
5709   // Do final class setup
5710   OopMapBlocksBuilder* oop_map_blocks = _field_info->oop_map_blocks;
5711   if (oop_map_blocks->nonstatic_oop_map_count > 0) {
5712     oop_map_blocks->copy(ik->start_of_nonstatic_oop_maps());
5713   }
5714 
5715   // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
5716   set_precomputed_flags(ik);
5717 
5718   // check if this class can access its super class
5719   check_super_class_access(ik, CHECK);
5720 
5721   // check if this class can access its superinterfaces
5722   check_super_interface_access(ik, CHECK);
5723 
5724   // check if this class overrides any final method
5725   check_final_method_override(ik, CHECK);
5726 
5727   // reject static interface methods prior to Java 8
5728   if (ik->is_interface() && _major_version < JAVA_8_VERSION) {
5729     check_illegal_static_method(ik, CHECK);
5730   }
5731 
5732   // Obtain this_klass' module entry
5733   ModuleEntry* module_entry = ik->module();
5734   assert(module_entry != NULL, "module_entry should always be set");
5735 
5736   // Obtain java.lang.Module
5737   Handle module_handle(THREAD, module_entry->module());
5738 
5739   // Allocate mirror and initialize static fields
5740   // The create_mirror() call will also call compute_modifiers()
5741   java_lang_Class::create_mirror(ik,
5742                                  Handle(THREAD, _loader_data->class_loader()),
5743                                  module_handle,
5744                                  _protection_domain,
5745                                  CHECK);
5746 
5747   assert(_all_mirandas != NULL, "invariant");
5748 
5749   // Generate any default methods - default methods are public interface methods
5750   // that have a default implementation.  This is new with Java 8.
5751   if (_has_nonstatic_concrete_methods) {
5752     DefaultMethods::generate_default_methods(ik,
5753                                              _all_mirandas,
5754                                              CHECK);
5755   }
5756 
5757   if (is_value_type()) {
5758     ValueKlass* vk = ValueKlass::cast(ik);
5759     vk->set_if_bufferable();
5760     vk->initialize_calling_convention();
5761   }
5762 
5763   // Add read edges to the unnamed modules of the bootstrap and app class loaders.
5764   if (changed_by_loadhook && !module_handle.is_null() && module_entry->is_named() &&
5765       !module_entry->has_default_read_edges()) {
5766     if (!module_entry->set_has_default_read_edges()) {
5767       // We won a potential race
5768       JvmtiExport::add_default_read_edges(module_handle, THREAD);
5769     }
5770   }
5771 
5772   int nfields = ik->java_fields_count();
5773   if (ik->is_value()) nfields++;
5774   for(int i = 0; i < nfields; i++) {
5775     if (ik->field_access_flags(i) & JVM_ACC_FLATTENABLE) {
5776       Klass* klass = SystemDictionary::resolve_or_fail(ik->field_signature(i),
5777                                                        Handle(THREAD, ik->class_loader()),
5778                                                        Handle(THREAD, ik->protection_domain()), true, CHECK);
5779       assert(klass != NULL, "Sanity check");
5780       assert(klass->access_flags().is_value_type(), "Value type expected");
5781       ik->set_value_field_klass(i, klass);
5782     } else if (is_value_type() && ((ik->field_access_flags(i) & JVM_ACC_FIELD_INTERNAL) != 0)
5783         && ((ik->field_access_flags(i) & JVM_ACC_STATIC) != 0)) {
5784       ValueKlass::cast(ik)->set_default_value_offset(ik->field_offset(i));
5785     }
5786   }
5787 
5788   // Update the loader_data graph.
5789   record_defined_class_dependencies(ik, CHECK);
5790 
5791   ClassLoadingService::notify_class_loaded(ik, false /* not shared class */);
5792 
5793   if (!is_internal()) {
5794     if (log_is_enabled(Info, class, load)) {
5795       ResourceMark rm;
5796       const char* module_name = (module_entry->name() == NULL) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
5797       ik->print_class_load_logging(_loader_data, module_name, _stream);
5798     }
5799 
5800     if (log_is_enabled(Debug, class, resolve))  {
5801       ResourceMark rm;
5802       // print out the superclass.
5803       const char * from = ik->external_name();
5804       if (ik->java_super() != NULL) {
5805         log_debug(class, resolve)("%s %s (super)",
5806                    from,
5807                    ik->java_super()->external_name());
5808       }
5809       // print out each of the interface classes referred to by this class.
5810       const Array<Klass*>* const local_interfaces = ik->local_interfaces();
5811       if (local_interfaces != NULL) {
5812         const int length = local_interfaces->length();
5813         for (int i = 0; i < length; i++) {
5814           const Klass* const k = local_interfaces->at(i);
5815           const char * to = k->external_name();
5816           log_debug(class, resolve)("%s %s (interface)", from, to);
5817         }
5818       }
5819     }
5820   }
5821 
5822   TRACE_INIT_ID(ik);
5823 
5824   // If we reach here, all is well.
5825   // Now remove the InstanceKlass* from the _klass_to_deallocate field
5826   // in order for it to not be destroyed in the ClassFileParser destructor.
5827   set_klass_to_deallocate(NULL);
5828 
5829   // it's official
5830   set_klass(ik);
5831 
5832   debug_only(ik->verify();)
5833 }
5834 
5835 // For an anonymous class that is in the unnamed package, move it to its host class's
5836 // package by prepending its host class's package name to its class name and setting
5837 // its _class_name field.
5838 void ClassFileParser::prepend_host_package_name(const InstanceKlass* host_klass, TRAPS) {
5839   ResourceMark rm(THREAD);
5840   assert(strrchr(_class_name->as_C_string(), '/') == NULL,
5841          "Anonymous class should not be in a package");
5842   const char* host_pkg_name =
5843     ClassLoader::package_from_name(host_klass->name()->as_C_string(), NULL);
5844 
5845   if (host_pkg_name != NULL) {
5846     size_t host_pkg_len = strlen(host_pkg_name);
5847     int class_name_len = _class_name->utf8_length();
5848     char* new_anon_name =
5849       NEW_RESOURCE_ARRAY(char, host_pkg_len + 1 + class_name_len);
5850     // Copy host package name and trailing /.
5851     strncpy(new_anon_name, host_pkg_name, host_pkg_len);
5852     new_anon_name[host_pkg_len] = '/';
5853     // Append anonymous class name. The anonymous class name can contain odd
5854     // characters.  So, do a strncpy instead of using sprintf("%s...").
5855     strncpy(new_anon_name + host_pkg_len + 1, (char *)_class_name->base(), class_name_len);
5856 
5857     // Create a symbol and update the anonymous class name.
5858     _class_name = SymbolTable::new_symbol(new_anon_name,
5859                                           (int)host_pkg_len + 1 + class_name_len,
5860                                           CHECK);
5861   }
5862 }
5863 
5864 // If the host class and the anonymous class are in the same package then do
5865 // nothing.  If the anonymous class is in the unnamed package then move it to its
5866 // host's package.  If the classes are in different packages then throw an IAE
5867 // exception.
5868 void ClassFileParser::fix_anonymous_class_name(TRAPS) {
5869   assert(_host_klass != NULL, "Expected an anonymous class");
5870 
5871   const jbyte* anon_last_slash = UTF8::strrchr(_class_name->base(),
5872                                                _class_name->utf8_length(), '/');
5873   if (anon_last_slash == NULL) {  // Unnamed package
5874     prepend_host_package_name(_host_klass, CHECK);
5875   } else {
5876     if (!_host_klass->is_same_class_package(_host_klass->class_loader(), _class_name)) {
5877       ResourceMark rm(THREAD);
5878       THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(),
5879         err_msg("Host class %s and anonymous class %s are in different packages",
5880         _host_klass->name()->as_C_string(), _class_name->as_C_string()));
5881     }
5882   }
5883 }
5884 
5885 static bool relax_format_check_for(ClassLoaderData* loader_data) {
5886   bool trusted = (loader_data->is_the_null_class_loader_data() ||
5887                   SystemDictionary::is_platform_class_loader(loader_data->class_loader()));
5888   bool need_verify =
5889     // verifyAll
5890     (BytecodeVerificationLocal && BytecodeVerificationRemote) ||
5891     // verifyRemote
5892     (!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);
5893   return !need_verify;
5894 }
5895 
5896 ClassFileParser::ClassFileParser(ClassFileStream* stream,
5897                                  Symbol* name,
5898                                  ClassLoaderData* loader_data,
5899                                  Handle protection_domain,
5900                                  const InstanceKlass* host_klass,
5901                                  GrowableArray<Handle>* cp_patches,
5902                                  Publicity pub_level,
5903                                  TRAPS) :
5904   _stream(stream),
5905   _requested_name(name),
5906   _loader_data(loader_data),
5907   _host_klass(host_klass),
5908   _cp_patches(cp_patches),
5909   _num_patched_klasses(0),
5910   _max_num_patched_klasses(0),
5911   _orig_cp_size(0),
5912   _first_patched_klass_resolved_index(0),
5913   _super_klass(),
5914   _cp(NULL),
5915   _fields(NULL),
5916   _methods(NULL),
5917   _inner_classes(NULL),
5918   _local_interfaces(NULL),
5919   _transitive_interfaces(NULL),
5920   _combined_annotations(NULL),
5921   _annotations(NULL),
5922   _type_annotations(NULL),
5923   _fields_annotations(NULL),
5924   _fields_type_annotations(NULL),
5925   _klass(NULL),
5926   _klass_to_deallocate(NULL),
5927   _parsed_annotations(NULL),
5928   _fac(NULL),
5929   _field_info(NULL),
5930   _method_ordering(NULL),
5931   _all_mirandas(NULL),
5932   _vtable_size(0),
5933   _itable_size(0),
5934   _num_miranda_methods(0),
5935   _rt(REF_NONE),
5936   _protection_domain(protection_domain),
5937   _access_flags(),
5938   _pub_level(pub_level),
5939   _bad_constant_seen(0),
5940   _synthetic_flag(false),
5941   _sde_length(false),
5942   _sde_buffer(NULL),
5943   _sourcefile_index(0),
5944   _generic_signature_index(0),
5945   _major_version(0),
5946   _minor_version(0),
5947   _this_class_index(0),
5948   _super_class_index(0),
5949   _itfs_len(0),
5950   _java_fields_count(0),
5951   _need_verify(false),
5952   _relax_verify(false),
5953   _has_nonstatic_concrete_methods(false),
5954   _declares_nonstatic_concrete_methods(false),
5955   _has_final_method(false),
5956   _has_finalizer(false),
5957   _has_empty_finalizer(false),
5958   _has_vanilla_constructor(false),
5959   _max_bootstrap_specifier_index(-1),
5960   _has_flattenable_fields(false) {
5961 
5962   _class_name = name != NULL ? name : vmSymbols::unknown_class_name();
5963 
5964   assert(THREAD->is_Java_thread(), "invariant");
5965   assert(_loader_data != NULL, "invariant");
5966   assert(stream != NULL, "invariant");
5967   assert(_stream != NULL, "invariant");
5968   assert(_stream->buffer() == _stream->current(), "invariant");
5969   assert(_class_name != NULL, "invariant");
5970   assert(0 == _access_flags.as_int(), "invariant");
5971 
5972   // Figure out whether we can skip format checking (matching classic VM behavior)
5973   if (DumpSharedSpaces) {
5974     // verify == true means it's a 'remote' class (i.e., non-boot class)
5975     // Verification decision is based on BytecodeVerificationRemote flag
5976     // for those classes.
5977     _need_verify = (stream->need_verify()) ? BytecodeVerificationRemote :
5978                                               BytecodeVerificationLocal;
5979   }
5980   else {
5981     _need_verify = Verifier::should_verify_for(_loader_data->class_loader(),
5982                                                stream->need_verify());
5983   }
5984   if (_cp_patches != NULL) {
5985     int len = _cp_patches->length();
5986     for (int i=0; i<len; i++) {
5987       if (has_cp_patch_at(i)) {
5988         Handle patch = cp_patch_at(i);
5989         if (java_lang_String::is_instance(patch()) || java_lang_Class::is_instance(patch())) {
5990           // We need to append the names of the patched classes to the end of the constant pool,
5991           // because a patched class may have a Utf8 name that's not already included in the
5992           // original constant pool. These class names are used when patch_constant_pool()
5993           // calls patch_class().
5994           //
5995           // Note that a String in cp_patch_at(i) may be used to patch a Utf8, a String, or a Class.
5996           // At this point, we don't know the tag for index i yet, because we haven't parsed the
5997           // constant pool. So we can only assume the worst -- every String is used to patch a Class.
5998           _max_num_patched_klasses++;
5999         }
6000       }
6001     }
6002   }
6003 
6004   // synch back verification state to stream
6005   stream->set_verify(_need_verify);
6006 
6007   // Check if verification needs to be relaxed for this class file
6008   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
6009   _relax_verify = relax_format_check_for(_loader_data);
6010 
6011   parse_stream(stream, CHECK);
6012 
6013   post_process_parsed_stream(stream, _cp, CHECK);
6014 }
6015 
6016 void ClassFileParser::clear_class_metadata() {
6017   // metadata created before the instance klass is created.  Must be
6018   // deallocated if classfile parsing returns an error.
6019   _cp = NULL;
6020   _fields = NULL;
6021   _methods = NULL;
6022   _inner_classes = NULL;
6023   _local_interfaces = NULL;
6024   _transitive_interfaces = NULL;
6025   _combined_annotations = NULL;
6026   _annotations = _type_annotations = NULL;
6027   _fields_annotations = _fields_type_annotations = NULL;
6028 }
6029 
6030 // Destructor to clean up
6031 ClassFileParser::~ClassFileParser() {
6032   if (_cp != NULL) {
6033     MetadataFactory::free_metadata(_loader_data, _cp);
6034   }
6035   if (_fields != NULL) {
6036     MetadataFactory::free_array<u2>(_loader_data, _fields);
6037   }
6038 
6039   if (_methods != NULL) {
6040     // Free methods
6041     InstanceKlass::deallocate_methods(_loader_data, _methods);
6042   }
6043 
6044   // beware of the Universe::empty_blah_array!!
6045   if (_inner_classes != NULL && _inner_classes != Universe::the_empty_short_array()) {
6046     MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
6047   }
6048 
6049   // Free interfaces
6050   InstanceKlass::deallocate_interfaces(_loader_data, _super_klass,
6051                                        _local_interfaces, _transitive_interfaces);
6052 
6053   if (_combined_annotations != NULL) {
6054     // After all annotations arrays have been created, they are installed into the
6055     // Annotations object that will be assigned to the InstanceKlass being created.
6056 
6057     // Deallocate the Annotations object and the installed annotations arrays.
6058     _combined_annotations->deallocate_contents(_loader_data);
6059 
6060     // If the _combined_annotations pointer is non-NULL,
6061     // then the other annotations fields should have been cleared.
6062     assert(_annotations             == NULL, "Should have been cleared");
6063     assert(_type_annotations        == NULL, "Should have been cleared");
6064     assert(_fields_annotations      == NULL, "Should have been cleared");
6065     assert(_fields_type_annotations == NULL, "Should have been cleared");
6066   } else {
6067     // If the annotations arrays were not installed into the Annotations object,
6068     // then they have to be deallocated explicitly.
6069     MetadataFactory::free_array<u1>(_loader_data, _annotations);
6070     MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
6071     Annotations::free_contents(_loader_data, _fields_annotations);
6072     Annotations::free_contents(_loader_data, _fields_type_annotations);
6073   }
6074 
6075   clear_class_metadata();
6076 
6077   // deallocate the klass if already created.  Don't directly deallocate, but add
6078   // to the deallocate list so that the klass is removed from the CLD::_klasses list
6079   // at a safepoint.
6080   if (_klass_to_deallocate != NULL) {
6081     _loader_data->add_to_deallocate_list(_klass_to_deallocate);
6082   }
6083 }
6084 
6085 void ClassFileParser::parse_stream(const ClassFileStream* const stream,
6086                                    TRAPS) {
6087 
6088   assert(stream != NULL, "invariant");
6089   assert(_class_name != NULL, "invariant");
6090 
6091   // BEGIN STREAM PARSING
6092   stream->guarantee_more(8, CHECK);  // magic, major, minor
6093   // Magic value
6094   const u4 magic = stream->get_u4_fast();
6095   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
6096                      "Incompatible magic value %u in class file %s",
6097                      magic, CHECK);
6098 
6099   // Version numbers
6100   _minor_version = stream->get_u2_fast();
6101   _major_version = stream->get_u2_fast();
6102 
6103   if (DumpSharedSpaces && _major_version < JAVA_1_5_VERSION) {
6104     ResourceMark rm;
6105     warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
6106             _major_version,  _minor_version, _class_name->as_C_string());
6107     Exceptions::fthrow(
6108       THREAD_AND_LOCATION,
6109       vmSymbols::java_lang_UnsupportedClassVersionError(),
6110       "Unsupported major.minor version for dump time %u.%u",
6111       _major_version,
6112       _minor_version);
6113   }
6114 
6115   // Check version numbers - we check this even with verifier off
6116   if (!is_supported_version(_major_version, _minor_version)) {
6117     ResourceMark rm(THREAD);
6118     Exceptions::fthrow(
6119       THREAD_AND_LOCATION,
6120       vmSymbols::java_lang_UnsupportedClassVersionError(),
6121       "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
6122       "this version of the Java Runtime only recognizes class file versions up to %u.%u",
6123       _class_name->as_C_string(),
6124       _major_version,
6125       _minor_version,
6126       JVM_CLASSFILE_MAJOR_VERSION,
6127       JVM_CLASSFILE_MINOR_VERSION);
6128     return;
6129   }
6130 
6131   stream->guarantee_more(3, CHECK); // length, first cp tag
6132   u2 cp_size = stream->get_u2_fast();
6133 
6134   guarantee_property(
6135     cp_size >= 1, "Illegal constant pool size %u in class file %s",
6136     cp_size, CHECK);
6137 
6138   _orig_cp_size = cp_size;
6139   if (int(cp_size) + _max_num_patched_klasses > 0xffff) {
6140     THROW_MSG(vmSymbols::java_lang_InternalError(), "not enough space for patched classes");
6141   }
6142   cp_size += _max_num_patched_klasses;
6143 
6144   _cp = ConstantPool::allocate(_loader_data,
6145                                cp_size,
6146                                CHECK);
6147 
6148   ConstantPool* const cp = _cp;
6149 
6150   parse_constant_pool(stream, cp, _orig_cp_size, CHECK);
6151 
6152   assert(cp_size == (const u2)cp->length(), "invariant");
6153 
6154   // ACCESS FLAGS
6155   stream->guarantee_more(8, CHECK);  // flags, this_class, super_class, infs_len
6156 
6157   jint recognized_modifiers = JVM_RECOGNIZED_CLASS_MODIFIERS;
6158   // JVM_ACC_MODULE is defined in JDK-9 and later.
6159   if (_major_version >= JAVA_9_VERSION) {
6160     recognized_modifiers |= JVM_ACC_MODULE;
6161   }
6162   // JVM_ACC_VALUE is defined for class file version 53.1 and later
6163   if (supports_value_types()) {
6164     recognized_modifiers |= JVM_ACC_VALUE;
6165   }
6166 
6167   // Access flags
6168   jint flags = stream->get_u2_fast() & recognized_modifiers;
6169 
6170   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
6171     // Set abstract bit for old class files for backward compatibility
6172     flags |= JVM_ACC_ABSTRACT;
6173   }
6174 
6175   verify_legal_class_modifiers(flags, CHECK);
6176 
6177   short bad_constant = class_bad_constant_seen();
6178   if (bad_constant != 0) {
6179     // Do not throw CFE until after the access_flags are checked because if
6180     // ACC_MODULE is set in the access flags, then NCDFE must be thrown, not CFE.
6181     classfile_parse_error("Unknown constant tag %u in class file %s", bad_constant, CHECK);
6182   }
6183 
6184   _access_flags.set_flags(flags);
6185 
6186   // This class and superclass
6187   _this_class_index = stream->get_u2_fast();
6188   check_property(
6189     (valid_cp_range(_this_class_index, cp_size) &&
6190      (cp->tag_at(_this_class_index).is_unresolved_klass() ||
6191       cp->tag_at(_this_class_index).is_unresolved_value_type())),
6192     "Invalid this class index %u in constant pool in class file %s",
6193     _this_class_index, CHECK);
6194 
6195   Symbol* const class_name_in_cp = cp->klass_name_at(_this_class_index);
6196   assert(class_name_in_cp != NULL, "class_name can't be null");
6197 
6198   // Update _class_name which could be null previously
6199   // to reflect the name in the constant pool
6200   _class_name = class_name_in_cp;
6201 
6202   // Don't need to check whether this class name is legal or not.
6203   // It has been checked when constant pool is parsed.
6204   // However, make sure it is not an array type.
6205   if (_need_verify) {
6206     guarantee_property(_class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
6207                        "Bad class name in class file %s",
6208                        CHECK);
6209   }
6210 
6211   // Checks if name in class file matches requested name
6212   if (_requested_name != NULL && _requested_name != _class_name) {
6213     ResourceMark rm(THREAD);
6214     Exceptions::fthrow(
6215       THREAD_AND_LOCATION,
6216       vmSymbols::java_lang_NoClassDefFoundError(),
6217       "%s (wrong name: %s)",
6218       _class_name->as_C_string(),
6219       _requested_name != NULL ? _requested_name->as_C_string() : "NoName"
6220     );
6221     return;
6222   }
6223 
6224   // if this is an anonymous class fix up its name if it's in the unnamed
6225   // package.  Otherwise, throw IAE if it is in a different package than
6226   // its host class.
6227   if (_host_klass != NULL) {
6228     fix_anonymous_class_name(CHECK);
6229   }
6230 
6231   // Verification prevents us from creating names with dots in them, this
6232   // asserts that that's the case.
6233   assert(is_internal_format(_class_name), "external class name format used internally");
6234 
6235   if (!is_internal()) {
6236     LogTarget(Debug, class, preorder) lt;
6237     if (lt.is_enabled()){
6238       ResourceMark rm(THREAD);
6239       LogStream ls(lt);
6240       ls.print("%s", _class_name->as_klass_external_name());
6241       if (stream->source() != NULL) {
6242         ls.print(" source: %s", stream->source());
6243       }
6244       ls.cr();
6245     }
6246 
6247 #if INCLUDE_CDS
6248     if (DumpLoadedClassList != NULL && stream->source() != NULL && classlist_file->is_open()) {
6249       if (!ClassLoader::has_jrt_entry()) {
6250         warning("DumpLoadedClassList and CDS are not supported in exploded build");
6251         DumpLoadedClassList = NULL;
6252       } else if (SystemDictionaryShared::is_sharing_possible(_loader_data) &&
6253           _host_klass == NULL) {
6254         // Only dump the classes that can be stored into CDS archive.
6255         // Anonymous classes such as generated LambdaForm classes are also not included.
6256         oop class_loader = _loader_data->class_loader();
6257         ResourceMark rm(THREAD);
6258         bool skip = false;
6259         if (class_loader == NULL || SystemDictionary::is_platform_class_loader(class_loader)) {
6260           // For the boot and platform class loaders, skip classes that are not found in the
6261           // java runtime image, such as those found in the --patch-module entries.
6262           // These classes can't be loaded from the archive during runtime.
6263           if (!ClassLoader::is_modules_image(stream->source()) && strncmp(stream->source(), "jrt:", 4) != 0) {
6264             skip = true;
6265           }
6266 
6267           if (class_loader == NULL && ClassLoader::contains_append_entry(stream->source())) {
6268             // .. but don't skip the boot classes that are loaded from -Xbootclasspath/a
6269             // as they can be loaded from the archive during runtime.
6270             skip = false;
6271           }
6272         }
6273         if (skip) {
6274           tty->print_cr("skip writing class %s from source %s to classlist file",
6275             _class_name->as_C_string(), stream->source());
6276         } else {
6277           classlist_file->print_cr("%s", _class_name->as_C_string());
6278           classlist_file->flush();
6279         }
6280       }
6281     }
6282 #endif
6283   }
6284 
6285   // SUPERKLASS
6286   _super_class_index = stream->get_u2_fast();
6287   _super_klass = parse_super_class(cp,
6288                                    _super_class_index,
6289                                    _need_verify,
6290                                    CHECK);
6291 
6292   // Interfaces
6293   _itfs_len = stream->get_u2_fast();
6294   parse_interfaces(stream,
6295                    _itfs_len,
6296                    cp,
6297                    &_has_nonstatic_concrete_methods,
6298                    CHECK);
6299 
6300   assert(_local_interfaces != NULL, "invariant");
6301 
6302   // Fields (offsets are filled in later)
6303   _fac = new FieldAllocationCount();
6304   parse_fields(stream,
6305                _access_flags.is_interface(),
6306                _access_flags.is_value_type(),
6307                _fac,
6308                cp,
6309                cp_size,
6310                &_java_fields_count,
6311                CHECK);
6312 
6313   assert(_fields != NULL, "invariant");
6314 
6315   // Methods
6316   AccessFlags promoted_flags;
6317   parse_methods(stream,
6318                 _access_flags.is_interface(),
6319                 &promoted_flags,
6320                 &_has_final_method,
6321                 &_declares_nonstatic_concrete_methods,
6322                 CHECK);
6323 
6324   assert(_methods != NULL, "invariant");
6325 
6326   // promote flags from parse_methods() to the klass' flags
6327   _access_flags.add_promoted_flags(promoted_flags.as_int());
6328 
6329   if (_declares_nonstatic_concrete_methods) {
6330     _has_nonstatic_concrete_methods = true;
6331   }
6332 
6333   // Additional attributes/annotations
6334   _parsed_annotations = new ClassAnnotationCollector();
6335   parse_classfile_attributes(stream, cp, _parsed_annotations, CHECK);
6336 
6337   assert(_inner_classes != NULL, "invariant");
6338 
6339   // Finalize the Annotations metadata object,
6340   // now that all annotation arrays have been created.
6341   create_combined_annotations(CHECK);
6342 
6343   // Make sure this is the end of class file stream
6344   guarantee_property(stream->at_eos(),
6345                      "Extra bytes at the end of class file %s",
6346                      CHECK);
6347 
6348   // all bytes in stream read and parsed
6349 }
6350 
6351 void ClassFileParser::post_process_parsed_stream(const ClassFileStream* const stream,
6352                                                  ConstantPool* cp,
6353                                                  TRAPS) {
6354   assert(stream != NULL, "invariant");
6355   assert(stream->at_eos(), "invariant");
6356   assert(cp != NULL, "invariant");
6357   assert(_loader_data != NULL, "invariant");
6358 
6359   if (_class_name == vmSymbols::java_lang_Object()) {
6360     check_property(_local_interfaces == Universe::the_empty_klass_array(),
6361                    "java.lang.Object cannot implement an interface in class file %s",
6362                    CHECK);
6363   }
6364   // We check super class after class file is parsed and format is checked
6365   if (_super_class_index > 0 && NULL ==_super_klass) {
6366     Symbol* const super_class_name = cp->klass_name_at(_super_class_index);
6367     if (_access_flags.is_interface()) {
6368       // Before attempting to resolve the superclass, check for class format
6369       // errors not checked yet.
6370       guarantee_property(super_class_name == vmSymbols::java_lang_Object(),
6371         "Interfaces must have java.lang.Object as superclass in class file %s",
6372         CHECK);
6373     }
6374     Handle loader(THREAD, _loader_data->class_loader());
6375     _super_klass = (const InstanceKlass*)
6376                        SystemDictionary::resolve_super_or_fail(_class_name,
6377                                                                super_class_name,
6378                                                                loader,
6379                                                                _protection_domain,
6380                                                                true,
6381                                                                CHECK);
6382   }
6383 
6384   if (_super_klass != NULL) {
6385     if (_super_klass->has_nonstatic_concrete_methods()) {
6386       _has_nonstatic_concrete_methods = true;
6387     }
6388 
6389     if (_super_klass->is_interface()) {
6390       ResourceMark rm(THREAD);
6391       Exceptions::fthrow(
6392         THREAD_AND_LOCATION,
6393         vmSymbols::java_lang_IncompatibleClassChangeError(),
6394         "class %s has interface %s as super class",
6395         _class_name->as_klass_external_name(),
6396         _super_klass->external_name()
6397       );
6398       return;
6399     }
6400 
6401     // For a value class, only java/lang/Object is an acceptable super class
6402     if ((EnableValhalla || EnableMVT) &&
6403         _access_flags.get_flags() & JVM_ACC_VALUE) {
6404       guarantee_property(_super_klass->name() == vmSymbols::java_lang_Object(),
6405                          "Value class can only inherit java/lang/Object",
6406                          CHECK);
6407     }
6408 
6409     // Make sure super class is not final
6410     if (_super_klass->is_final()) {
6411       THROW_MSG(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class");
6412     }
6413   }
6414 
6415   // Compute the transitive list of all unique interfaces implemented by this class
6416   _transitive_interfaces =
6417     compute_transitive_interfaces(_super_klass,
6418                                   _local_interfaces,
6419                                   _loader_data,
6420                                   CHECK);
6421 
6422   assert(_transitive_interfaces != NULL, "invariant");
6423 
6424   // sort methods
6425   _method_ordering = sort_methods(_methods);
6426 
6427   _all_mirandas = new GrowableArray<Method*>(20);
6428 
6429   Handle loader(THREAD, _loader_data->class_loader());
6430   klassVtable::compute_vtable_size_and_num_mirandas(&_vtable_size,
6431                                                     &_num_miranda_methods,
6432                                                     _all_mirandas,
6433                                                     _super_klass,
6434                                                     _methods,
6435                                                     _access_flags,
6436                                                     _major_version,
6437                                                     loader,
6438                                                     _class_name,
6439                                                     _local_interfaces,
6440                                                     CHECK);
6441 
6442   // Size of Java itable (in words)
6443   _itable_size = _access_flags.is_interface() ? 0 :
6444     klassItable::compute_itable_size(_transitive_interfaces);
6445 
6446   assert(_fac != NULL, "invariant");
6447   assert(_parsed_annotations != NULL, "invariant");
6448 
6449   _field_info = new FieldLayoutInfo();
6450   layout_fields(cp, _fac, _parsed_annotations, _field_info, CHECK);
6451 
6452   // Compute reference typ
6453   _rt = (NULL ==_super_klass) ? REF_NONE : _super_klass->reference_type();
6454 
6455 }
6456 
6457 void ClassFileParser::set_klass(InstanceKlass* klass) {
6458 
6459 #ifdef ASSERT
6460   if (klass != NULL) {
6461     assert(NULL == _klass, "leaking?");
6462   }
6463 #endif
6464 
6465   _klass = klass;
6466 }
6467 
6468 void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {
6469 
6470 #ifdef ASSERT
6471   if (klass != NULL) {
6472     assert(NULL == _klass_to_deallocate, "leaking?");
6473   }
6474 #endif
6475 
6476   _klass_to_deallocate = klass;
6477 }
6478 
6479 // Caller responsible for ResourceMark
6480 // clone stream with rewound position
6481 const ClassFileStream* ClassFileParser::clone_stream() const {
6482   assert(_stream != NULL, "invariant");
6483 
6484   return _stream->clone();
6485 }
6486 
6487 // ----------------------------------------------------------------------------
6488 // debugging
6489 
6490 #ifdef ASSERT
6491 
6492 // return true if class_name contains no '.' (internal format is '/')
6493 bool ClassFileParser::is_internal_format(Symbol* class_name) {
6494   if (class_name != NULL) {
6495     ResourceMark rm;
6496     char* name = class_name->as_C_string();
6497     return strchr(name, '.') == NULL;
6498   } else {
6499     return true;
6500   }
6501 }
6502 
6503 #endif