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