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