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