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