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