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