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