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