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