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