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