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