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