1 /*
   2  * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/classFileParser.hpp"
  27 #include "classfile/classLoader.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/verificationType.hpp"
  32 #include "classfile/verifier.hpp"
  33 #include "classfile/vmSymbols.hpp"
  34 #include "memory/allocation.hpp"
  35 #include "memory/gcLocker.hpp"
  36 #include "memory/oopFactory.hpp"
  37 #include "memory/universe.inline.hpp"
  38 #include "oops/constantPoolOop.hpp"
  39 #include "oops/instanceKlass.hpp"
  40 #include "oops/klass.inline.hpp"
  41 #include "oops/klassOop.hpp"
  42 #include "oops/klassVtable.hpp"
  43 #include "oops/methodOop.hpp"
  44 #include "oops/symbolOop.hpp"
  45 #include "prims/jvmtiExport.hpp"
  46 #include "runtime/javaCalls.hpp"
  47 #include "runtime/perfData.hpp"
  48 #include "runtime/reflection.hpp"
  49 #include "runtime/signature.hpp"
  50 #include "runtime/timer.hpp"
  51 #include "services/classLoadingService.hpp"
  52 #include "services/threadService.hpp"
  53 
  54 // We generally try to create the oops directly when parsing, rather than
  55 // allocating temporary data structures and copying the bytes twice. A
  56 // temporary area is only needed when parsing utf8 entries in the constant
  57 // pool and when parsing line number tables.
  58 
  59 // We add assert in debug mode when class format is not checked.
  60 
  61 #define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
  62 #define JAVA_MIN_SUPPORTED_VERSION        45
  63 #define JAVA_MAX_SUPPORTED_VERSION        51
  64 #define JAVA_MAX_SUPPORTED_MINOR_VERSION  0
  65 
  66 // Used for two backward compatibility reasons:
  67 // - to check for new additions to the class file format in JDK1.5
  68 // - to check for bug fixes in the format checker in JDK1.5
  69 #define JAVA_1_5_VERSION                  49
  70 
  71 // Used for backward compatibility reasons:
  72 // - to check for javac bug fixes that happened after 1.5
  73 // - also used as the max version when running in jdk6
  74 #define JAVA_6_VERSION                    50
  75 
  76 // Used for backward compatibility reasons:
  77 // - to check NameAndType_info signatures more aggressively
  78 #define JAVA_7_VERSION                    51
  79 
  80 
  81 void ClassFileParser::parse_constant_pool_entries(constantPoolHandle cp, int length, TRAPS) {
  82   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
  83   // this function (_current can be allocated in a register, with scalar
  84   // replacement of aggregates). The _current pointer is copied back to
  85   // stream() when this function returns. DON'T call another method within
  86   // this method that uses stream().
  87   ClassFileStream* cfs0 = stream();
  88   ClassFileStream cfs1 = *cfs0;
  89   ClassFileStream* cfs = &cfs1;
  90 #ifdef ASSERT
  91   assert(cfs->allocated_on_stack(),"should be local");
  92   u1* old_current = cfs0->current();
  93 #endif
  94 
  95   // Used for batching symbol allocations.
  96   const char* names[SymbolTable::symbol_alloc_batch_size];
  97   int lengths[SymbolTable::symbol_alloc_batch_size];
  98   int indices[SymbolTable::symbol_alloc_batch_size];
  99   unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
 100   int names_count = 0;
 101 
 102   // parsing  Index 0 is unused
 103   for (int index = 1; index < length; index++) {
 104     // Each of the following case guarantees one more byte in the stream
 105     // for the following tag or the access_flags following constant pool,
 106     // so we don't need bounds-check for reading tag.
 107     u1 tag = cfs->get_u1_fast();
 108     switch (tag) {
 109       case JVM_CONSTANT_Class :
 110         {
 111           cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
 112           u2 name_index = cfs->get_u2_fast();
 113           cp->klass_index_at_put(index, name_index);
 114         }
 115         break;
 116       case JVM_CONSTANT_Fieldref :
 117         {
 118           cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 119           u2 class_index = cfs->get_u2_fast();
 120           u2 name_and_type_index = cfs->get_u2_fast();
 121           cp->field_at_put(index, class_index, name_and_type_index);
 122         }
 123         break;
 124       case JVM_CONSTANT_Methodref :
 125         {
 126           cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 127           u2 class_index = cfs->get_u2_fast();
 128           u2 name_and_type_index = cfs->get_u2_fast();
 129           cp->method_at_put(index, class_index, name_and_type_index);
 130         }
 131         break;
 132       case JVM_CONSTANT_InterfaceMethodref :
 133         {
 134           cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
 135           u2 class_index = cfs->get_u2_fast();
 136           u2 name_and_type_index = cfs->get_u2_fast();
 137           cp->interface_method_at_put(index, class_index, name_and_type_index);
 138         }
 139         break;
 140       case JVM_CONSTANT_String :
 141         {
 142           cfs->guarantee_more(3, CHECK);  // string_index, tag/access_flags
 143           u2 string_index = cfs->get_u2_fast();
 144           cp->string_index_at_put(index, string_index);
 145         }
 146         break;
 147       case JVM_CONSTANT_MethodHandle :
 148       case JVM_CONSTANT_MethodType :
 149         if (!EnableMethodHandles ||
 150             _major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
 151           classfile_parse_error(
 152             (!EnableMethodHandles ?
 153              "This JVM does not support constant tag %u in class file %s" :
 154              "Class file version does not support constant tag %u in class file %s"),
 155             tag, CHECK);
 156         }
 157         if (tag == JVM_CONSTANT_MethodHandle) {
 158           cfs->guarantee_more(4, CHECK);  // ref_kind, method_index, tag/access_flags
 159           u1 ref_kind = cfs->get_u1_fast();
 160           u2 method_index = cfs->get_u2_fast();
 161           cp->method_handle_index_at_put(index, ref_kind, method_index);
 162         } else if (tag == JVM_CONSTANT_MethodType) {
 163           cfs->guarantee_more(3, CHECK);  // signature_index, tag/access_flags
 164           u2 signature_index = cfs->get_u2_fast();
 165           cp->method_type_index_at_put(index, signature_index);
 166         } else {
 167           ShouldNotReachHere();
 168         }
 169         break;
 170       case JVM_CONSTANT_InvokeDynamic :
 171         {
 172           if (!EnableInvokeDynamic ||
 173               _major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
 174             classfile_parse_error(
 175               (!EnableInvokeDynamic ?
 176                "This JVM does not support constant tag %u in class file %s" :
 177                "Class file version does not support constant tag %u in class file %s"),
 178               tag, CHECK);
 179           }
 180           cfs->guarantee_more(5, CHECK);  // bsm_index, name_and_type_index, tag/access_flags
 181           u2 bootstrap_method_index = cfs->get_u2_fast();
 182           u2 name_and_type_index = cfs->get_u2_fast();
 183           cp->invoke_dynamic_at_put(index, bootstrap_method_index, name_and_type_index);
 184         }
 185         break;
 186       case JVM_CONSTANT_Integer :
 187         {
 188           cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
 189           u4 bytes = cfs->get_u4_fast();
 190           cp->int_at_put(index, (jint) bytes);
 191         }
 192         break;
 193       case JVM_CONSTANT_Float :
 194         {
 195           cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
 196           u4 bytes = cfs->get_u4_fast();
 197           cp->float_at_put(index, *(jfloat*)&bytes);
 198         }
 199         break;
 200       case JVM_CONSTANT_Long :
 201         // A mangled type might cause you to overrun allocated memory
 202         guarantee_property(index+1 < length,
 203                            "Invalid constant pool entry %u in class file %s",
 204                            index, CHECK);
 205         {
 206           cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
 207           u8 bytes = cfs->get_u8_fast();
 208           cp->long_at_put(index, bytes);
 209         }
 210         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
 211         break;
 212       case JVM_CONSTANT_Double :
 213         // A mangled type might cause you to overrun allocated memory
 214         guarantee_property(index+1 < length,
 215                            "Invalid constant pool entry %u in class file %s",
 216                            index, CHECK);
 217         {
 218           cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
 219           u8 bytes = cfs->get_u8_fast();
 220           cp->double_at_put(index, *(jdouble*)&bytes);
 221         }
 222         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
 223         break;
 224       case JVM_CONSTANT_NameAndType :
 225         {
 226           cfs->guarantee_more(5, CHECK);  // name_index, signature_index, tag/access_flags
 227           u2 name_index = cfs->get_u2_fast();
 228           u2 signature_index = cfs->get_u2_fast();
 229           cp->name_and_type_at_put(index, name_index, signature_index);
 230         }
 231         break;
 232       case JVM_CONSTANT_Utf8 :
 233         {
 234           cfs->guarantee_more(2, CHECK);  // utf8_length
 235           u2  utf8_length = cfs->get_u2_fast();
 236           u1* utf8_buffer = cfs->get_u1_buffer();
 237           assert(utf8_buffer != NULL, "null utf8 buffer");
 238           // Got utf8 string, guarantee utf8_length+1 bytes, set stream position forward.
 239           cfs->guarantee_more(utf8_length+1, CHECK);  // utf8 string, tag/access_flags
 240           cfs->skip_u1_fast(utf8_length);
 241 
 242           // Before storing the symbol, make sure it's legal
 243           if (_need_verify) {
 244             verify_legal_utf8((unsigned char*)utf8_buffer, utf8_length, CHECK);
 245           }
 246 
 247           if (AnonymousClasses && has_cp_patch_at(index)) {
 248             Handle patch = clear_cp_patch_at(index);
 249             guarantee_property(java_lang_String::is_instance(patch()),
 250                                "Illegal utf8 patch at %d in class file %s",
 251                                index, CHECK);
 252             char* str = java_lang_String::as_utf8_string(patch());
 253             // (could use java_lang_String::as_symbol instead, but might as well batch them)
 254             utf8_buffer = (u1*) str;
 255             utf8_length = (int) strlen(str);
 256           }
 257 
 258           unsigned int hash;
 259           symbolOop result = SymbolTable::lookup_only((char*)utf8_buffer, utf8_length, hash);
 260           if (result == NULL) {
 261             names[names_count] = (char*)utf8_buffer;
 262             lengths[names_count] = utf8_length;
 263             indices[names_count] = index;
 264             hashValues[names_count++] = hash;
 265             if (names_count == SymbolTable::symbol_alloc_batch_size) {
 266               oopFactory::new_symbols(cp, names_count, names, lengths, indices, hashValues, CHECK);
 267               names_count = 0;
 268             }
 269           } else {
 270             cp->symbol_at_put(index, result);
 271           }
 272         }
 273         break;
 274       default:
 275         classfile_parse_error(
 276           "Unknown constant tag %u in class file %s", tag, CHECK);
 277         break;
 278     }
 279   }
 280 
 281   // Allocate the remaining symbols
 282   if (names_count > 0) {
 283     oopFactory::new_symbols(cp, names_count, names, lengths, indices, hashValues, CHECK);
 284   }
 285 
 286   // Copy _current pointer of local copy back to stream().
 287 #ifdef ASSERT
 288   assert(cfs0->current() == old_current, "non-exclusive use of stream()");
 289 #endif
 290   cfs0->set_current(cfs1.current());
 291 }
 292 
 293 bool inline valid_cp_range(int index, int length) { return (index > 0 && index < length); }
 294 
 295 constantPoolHandle ClassFileParser::parse_constant_pool(TRAPS) {
 296   ClassFileStream* cfs = stream();
 297   constantPoolHandle nullHandle;
 298 
 299   cfs->guarantee_more(3, CHECK_(nullHandle)); // length, first cp tag
 300   u2 length = cfs->get_u2_fast();
 301   guarantee_property(
 302     length >= 1, "Illegal constant pool size %u in class file %s",
 303     length, CHECK_(nullHandle));
 304   constantPoolOop constant_pool =
 305                       oopFactory::new_constantPool(length,
 306                                                    methodOopDesc::IsSafeConc,
 307                                                    CHECK_(nullHandle));
 308   constantPoolHandle cp (THREAD, constant_pool);
 309 
 310   cp->set_partially_loaded();    // Enables heap verify to work on partial constantPoolOops
 311 
 312   // parsing constant pool entries
 313   parse_constant_pool_entries(cp, length, CHECK_(nullHandle));
 314 
 315   int index = 1;  // declared outside of loops for portability
 316 
 317   // first verification pass - validate cross references and fixup class and string constants
 318   for (index = 1; index < length; index++) {          // Index 0 is unused
 319     switch (cp->tag_at(index).value()) {
 320       case JVM_CONSTANT_Class :
 321         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 322         break;
 323       case JVM_CONSTANT_Fieldref :
 324         // fall through
 325       case JVM_CONSTANT_Methodref :
 326         // fall through
 327       case JVM_CONSTANT_InterfaceMethodref : {
 328         if (!_need_verify) break;
 329         int klass_ref_index = cp->klass_ref_index_at(index);
 330         int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
 331         check_property(valid_cp_range(klass_ref_index, length) &&
 332                        is_klass_reference(cp, klass_ref_index),
 333                        "Invalid constant pool index %u in class file %s",
 334                        klass_ref_index,
 335                        CHECK_(nullHandle));
 336         check_property(valid_cp_range(name_and_type_ref_index, length) &&
 337                        cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 338                        "Invalid constant pool index %u in class file %s",
 339                        name_and_type_ref_index,
 340                        CHECK_(nullHandle));
 341         break;
 342       }
 343       case JVM_CONSTANT_String :
 344         ShouldNotReachHere();     // Only JVM_CONSTANT_StringIndex should be present
 345         break;
 346       case JVM_CONSTANT_Integer :
 347         break;
 348       case JVM_CONSTANT_Float :
 349         break;
 350       case JVM_CONSTANT_Long :
 351       case JVM_CONSTANT_Double :
 352         index++;
 353         check_property(
 354           (index < length && cp->tag_at(index).is_invalid()),
 355           "Improper constant pool long/double index %u in class file %s",
 356           index, CHECK_(nullHandle));
 357         break;
 358       case JVM_CONSTANT_NameAndType : {
 359         if (!_need_verify) break;
 360         int name_ref_index = cp->name_ref_index_at(index);
 361         int signature_ref_index = cp->signature_ref_index_at(index);
 362         check_property(
 363           valid_cp_range(name_ref_index, length) &&
 364             cp->tag_at(name_ref_index).is_utf8(),
 365           "Invalid constant pool index %u in class file %s",
 366           name_ref_index, CHECK_(nullHandle));
 367         check_property(
 368           valid_cp_range(signature_ref_index, length) &&
 369             cp->tag_at(signature_ref_index).is_utf8(),
 370           "Invalid constant pool index %u in class file %s",
 371           signature_ref_index, CHECK_(nullHandle));
 372         break;
 373       }
 374       case JVM_CONSTANT_Utf8 :
 375         break;
 376       case JVM_CONSTANT_UnresolvedClass :         // fall-through
 377       case JVM_CONSTANT_UnresolvedClassInError:
 378         ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
 379         break;
 380       case JVM_CONSTANT_ClassIndex :
 381         {
 382           int class_index = cp->klass_index_at(index);
 383           check_property(
 384             valid_cp_range(class_index, length) &&
 385               cp->tag_at(class_index).is_utf8(),
 386             "Invalid constant pool index %u in class file %s",
 387             class_index, CHECK_(nullHandle));
 388           cp->unresolved_klass_at_put(index, cp->symbol_at(class_index));
 389         }
 390         break;
 391       case JVM_CONSTANT_UnresolvedString :
 392         ShouldNotReachHere();     // Only JVM_CONSTANT_StringIndex should be present
 393         break;
 394       case JVM_CONSTANT_StringIndex :
 395         {
 396           int string_index = cp->string_index_at(index);
 397           check_property(
 398             valid_cp_range(string_index, length) &&
 399               cp->tag_at(string_index).is_utf8(),
 400             "Invalid constant pool index %u in class file %s",
 401             string_index, CHECK_(nullHandle));
 402           symbolOop sym = cp->symbol_at(string_index);
 403           cp->unresolved_string_at_put(index, sym);
 404         }
 405         break;
 406       case JVM_CONSTANT_MethodHandle :
 407         {
 408           int ref_index = cp->method_handle_index_at(index);
 409           check_property(
 410             valid_cp_range(ref_index, length) &&
 411                 EnableMethodHandles,
 412               "Invalid constant pool index %u in class file %s",
 413               ref_index, CHECK_(nullHandle));
 414           constantTag tag = cp->tag_at(ref_index);
 415           int ref_kind  = cp->method_handle_ref_kind_at(index);
 416           switch (ref_kind) {
 417           case JVM_REF_getField:
 418           case JVM_REF_getStatic:
 419           case JVM_REF_putField:
 420           case JVM_REF_putStatic:
 421             check_property(
 422               tag.is_field(),
 423               "Invalid constant pool index %u in class file %s (not a field)",
 424               ref_index, CHECK_(nullHandle));
 425             break;
 426           case JVM_REF_invokeVirtual:
 427           case JVM_REF_invokeStatic:
 428           case JVM_REF_invokeSpecial:
 429           case JVM_REF_newInvokeSpecial:
 430             check_property(
 431               tag.is_method(),
 432               "Invalid constant pool index %u in class file %s (not a method)",
 433               ref_index, CHECK_(nullHandle));
 434             break;
 435           case JVM_REF_invokeInterface:
 436             check_property(
 437               tag.is_interface_method(),
 438               "Invalid constant pool index %u in class file %s (not an interface method)",
 439               ref_index, CHECK_(nullHandle));
 440             break;
 441           default:
 442             classfile_parse_error(
 443               "Bad method handle kind at constant pool index %u in class file %s",
 444               index, CHECK_(nullHandle));
 445           }
 446           // Keep the ref_index unchanged.  It will be indirected at link-time.
 447         }
 448         break;
 449       case JVM_CONSTANT_MethodType :
 450         {
 451           int ref_index = cp->method_type_index_at(index);
 452           check_property(
 453             valid_cp_range(ref_index, length) &&
 454                 cp->tag_at(ref_index).is_utf8() &&
 455                 EnableMethodHandles,
 456               "Invalid constant pool index %u in class file %s",
 457               ref_index, CHECK_(nullHandle));
 458         }
 459         break;
 460       case JVM_CONSTANT_InvokeDynamic :
 461         {
 462           int bootstrap_method_ref_index = cp->invoke_dynamic_bootstrap_method_ref_index_at(index);
 463           int name_and_type_ref_index = cp->invoke_dynamic_name_and_type_ref_index_at(index);
 464           check_property((bootstrap_method_ref_index == 0 && AllowTransitionalJSR292)
 465                          ||
 466                          (valid_cp_range(bootstrap_method_ref_index, length) &&
 467                           cp->tag_at(bootstrap_method_ref_index).is_method_handle()),
 468                          "Invalid constant pool index %u in class file %s",
 469                          bootstrap_method_ref_index,
 470                          CHECK_(nullHandle));
 471           check_property(valid_cp_range(name_and_type_ref_index, length) &&
 472                          cp->tag_at(name_and_type_ref_index).is_name_and_type(),
 473                          "Invalid constant pool index %u in class file %s",
 474                          name_and_type_ref_index,
 475                          CHECK_(nullHandle));
 476           break;
 477         }
 478       default:
 479         fatal(err_msg("bad constant pool tag value %u",
 480                       cp->tag_at(index).value()));
 481         ShouldNotReachHere();
 482         break;
 483     } // end of switch
 484   } // end of for
 485 
 486   if (_cp_patches != NULL) {
 487     // need to treat this_class specially...
 488     assert(AnonymousClasses, "");
 489     int this_class_index;
 490     {
 491       cfs->guarantee_more(8, CHECK_(nullHandle));  // flags, this_class, super_class, infs_len
 492       u1* mark = cfs->current();
 493       u2 flags         = cfs->get_u2_fast();
 494       this_class_index = cfs->get_u2_fast();
 495       cfs->set_current(mark);  // revert to mark
 496     }
 497 
 498     for (index = 1; index < length; index++) {          // Index 0 is unused
 499       if (has_cp_patch_at(index)) {
 500         guarantee_property(index != this_class_index,
 501                            "Illegal constant pool patch to self at %d in class file %s",
 502                            index, CHECK_(nullHandle));
 503         patch_constant_pool(cp, index, cp_patch_at(index), CHECK_(nullHandle));
 504       }
 505     }
 506     // Ensure that all the patches have been used.
 507     for (index = 0; index < _cp_patches->length(); index++) {
 508       guarantee_property(!has_cp_patch_at(index),
 509                          "Unused constant pool patch at %d in class file %s",
 510                          index, CHECK_(nullHandle));
 511     }
 512   }
 513 
 514   if (!_need_verify) {
 515     return cp;
 516   }
 517 
 518   // second verification pass - checks the strings are of the right format.
 519   // but not yet to the other entries
 520   for (index = 1; index < length; index++) {
 521     jbyte tag = cp->tag_at(index).value();
 522     switch (tag) {
 523       case JVM_CONSTANT_UnresolvedClass: {
 524         symbolHandle class_name(THREAD, cp->unresolved_klass_at(index));
 525         // check the name, even if _cp_patches will overwrite it
 526         verify_legal_class_name(class_name, CHECK_(nullHandle));
 527         break;
 528       }
 529       case JVM_CONSTANT_NameAndType: {
 530         if (_need_verify && _major_version >= JAVA_7_VERSION) {
 531           int sig_index = cp->signature_ref_index_at(index);
 532           int name_index = cp->name_ref_index_at(index);
 533           symbolHandle name(THREAD, cp->symbol_at(name_index));
 534           symbolHandle sig(THREAD, cp->symbol_at(sig_index));
 535           if (sig->byte_at(0) == JVM_SIGNATURE_FUNC) {
 536             verify_legal_method_signature(name, sig, CHECK_(nullHandle));
 537           } else {
 538             verify_legal_field_signature(name, sig, CHECK_(nullHandle));
 539           }
 540         }
 541         break;
 542       }
 543       case JVM_CONSTANT_Fieldref:
 544       case JVM_CONSTANT_Methodref:
 545       case JVM_CONSTANT_InterfaceMethodref: {
 546         int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
 547         // already verified to be utf8
 548         int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);
 549         // already verified to be utf8
 550         int signature_ref_index = cp->signature_ref_index_at(name_and_type_ref_index);
 551         symbolHandle name(THREAD, cp->symbol_at(name_ref_index));
 552         symbolHandle signature(THREAD, cp->symbol_at(signature_ref_index));
 553         if (tag == JVM_CONSTANT_Fieldref) {
 554           verify_legal_field_name(name, CHECK_(nullHandle));
 555           if (_need_verify && _major_version >= JAVA_7_VERSION) {
 556             // Signature is verified above, when iterating NameAndType_info.
 557             // Need only to be sure it's the right type.
 558             if (signature->byte_at(0) == JVM_SIGNATURE_FUNC) {
 559               throwIllegalSignature(
 560                   "Field", name, signature, CHECK_(nullHandle));
 561             }
 562           } else {
 563             verify_legal_field_signature(name, signature, CHECK_(nullHandle));
 564           }
 565         } else {
 566           verify_legal_method_name(name, CHECK_(nullHandle));
 567           if (_need_verify && _major_version >= JAVA_7_VERSION) {
 568             // Signature is verified above, when iterating NameAndType_info.
 569             // Need only to be sure it's the right type.
 570             if (signature->byte_at(0) != JVM_SIGNATURE_FUNC) {
 571               throwIllegalSignature(
 572                   "Method", name, signature, CHECK_(nullHandle));
 573             }
 574           } else {
 575             verify_legal_method_signature(name, signature, CHECK_(nullHandle));
 576           }
 577           if (tag == JVM_CONSTANT_Methodref) {
 578             // 4509014: If a class method name begins with '<', it must be "<init>".
 579             assert(!name.is_null(), "method name in constant pool is null");
 580             unsigned int name_len = name->utf8_length();
 581             assert(name_len > 0, "bad method name");  // already verified as legal name
 582             if (name->byte_at(0) == '<') {
 583               if (name() != vmSymbols::object_initializer_name()) {
 584                 classfile_parse_error(
 585                   "Bad method name at constant pool index %u in class file %s",
 586                   name_ref_index, CHECK_(nullHandle));
 587               }
 588             }
 589           }
 590         }
 591         break;
 592       }
 593       case JVM_CONSTANT_MethodHandle: {
 594         int ref_index = cp->method_handle_index_at(index);
 595         int ref_kind  = cp->method_handle_ref_kind_at(index);
 596         switch (ref_kind) {
 597         case JVM_REF_invokeVirtual:
 598         case JVM_REF_invokeStatic:
 599         case JVM_REF_invokeSpecial:
 600         case JVM_REF_newInvokeSpecial:
 601           {
 602             int name_and_type_ref_index = cp->name_and_type_ref_index_at(ref_index);
 603             int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);
 604             symbolHandle name(THREAD, cp->symbol_at(name_ref_index));
 605             if (ref_kind == JVM_REF_newInvokeSpecial) {
 606               if (name() != vmSymbols::object_initializer_name()) {
 607                 classfile_parse_error(
 608                   "Bad constructor name at constant pool index %u in class file %s",
 609                   name_ref_index, CHECK_(nullHandle));
 610               }
 611             } else {
 612               if (name() == vmSymbols::object_initializer_name()) {
 613                 classfile_parse_error(
 614                   "Bad method name at constant pool index %u in class file %s",
 615                   name_ref_index, CHECK_(nullHandle));
 616               }
 617             }
 618           }
 619           break;
 620           // Other ref_kinds are already fully checked in previous pass.
 621         }
 622         break;
 623       }
 624       case JVM_CONSTANT_MethodType: {
 625         symbolHandle no_name = vmSymbolHandles::type_name(); // place holder
 626         symbolHandle signature(THREAD, cp->method_type_signature_at(index));
 627         verify_legal_method_signature(no_name, signature, CHECK_(nullHandle));
 628         break;
 629       }
 630     }  // end of switch
 631   }  // end of for
 632 
 633   return cp;
 634 }
 635 
 636 
 637 void ClassFileParser::patch_constant_pool(constantPoolHandle cp, int index, Handle patch, TRAPS) {
 638   assert(AnonymousClasses, "");
 639   BasicType patch_type = T_VOID;
 640   switch (cp->tag_at(index).value()) {
 641 
 642   case JVM_CONSTANT_UnresolvedClass :
 643     // Patching a class means pre-resolving it.
 644     // The name in the constant pool is ignored.
 645     if (java_lang_Class::is_instance(patch())) {
 646       guarantee_property(!java_lang_Class::is_primitive(patch()),
 647                          "Illegal class patch at %d in class file %s",
 648                          index, CHECK);
 649       cp->klass_at_put(index, java_lang_Class::as_klassOop(patch()));
 650     } else {
 651       guarantee_property(java_lang_String::is_instance(patch()),
 652                          "Illegal class patch at %d in class file %s",
 653                          index, CHECK);
 654       symbolHandle name = java_lang_String::as_symbol(patch(), CHECK);
 655       cp->unresolved_klass_at_put(index, name());
 656     }
 657     break;
 658 
 659   case JVM_CONSTANT_UnresolvedString :
 660     // Patching a string means pre-resolving it.
 661     // The spelling in the constant pool is ignored.
 662     // The constant reference may be any object whatever.
 663     // If it is not a real interned string, the constant is referred
 664     // to as a "pseudo-string", and must be presented to the CP
 665     // explicitly, because it may require scavenging.
 666     cp->pseudo_string_at_put(index, patch());
 667     break;
 668 
 669   case JVM_CONSTANT_Integer : patch_type = T_INT;    goto patch_prim;
 670   case JVM_CONSTANT_Float :   patch_type = T_FLOAT;  goto patch_prim;
 671   case JVM_CONSTANT_Long :    patch_type = T_LONG;   goto patch_prim;
 672   case JVM_CONSTANT_Double :  patch_type = T_DOUBLE; goto patch_prim;
 673   patch_prim:
 674     {
 675       jvalue value;
 676       BasicType value_type = java_lang_boxing_object::get_value(patch(), &value);
 677       guarantee_property(value_type == patch_type,
 678                          "Illegal primitive patch at %d in class file %s",
 679                          index, CHECK);
 680       switch (value_type) {
 681       case T_INT:    cp->int_at_put(index,   value.i); break;
 682       case T_FLOAT:  cp->float_at_put(index, value.f); break;
 683       case T_LONG:   cp->long_at_put(index,  value.j); break;
 684       case T_DOUBLE: cp->double_at_put(index, value.d); break;
 685       default:       assert(false, "");
 686       }
 687     }
 688     break;
 689 
 690   default:
 691     // %%% TODO: put method handles into CONSTANT_InterfaceMethodref, etc.
 692     guarantee_property(!has_cp_patch_at(index),
 693                        "Illegal unexpected patch at %d in class file %s",
 694                        index, CHECK);
 695     return;
 696   }
 697 
 698   // On fall-through, mark the patch as used.
 699   clear_cp_patch_at(index);
 700 }
 701 
 702 
 703 
 704 class NameSigHash: public ResourceObj {
 705  public:
 706   symbolOop     _name;       // name
 707   symbolOop     _sig;        // signature
 708   NameSigHash*  _next;       // Next entry in hash table
 709 };
 710 
 711 
 712 #define HASH_ROW_SIZE 256
 713 
 714 unsigned int hash(symbolOop name, symbolOop sig) {
 715   unsigned int raw_hash = 0;
 716   raw_hash += ((unsigned int)(uintptr_t)name) >> (LogHeapWordSize + 2);
 717   raw_hash += ((unsigned int)(uintptr_t)sig) >> LogHeapWordSize;
 718 
 719   return (raw_hash + (unsigned int)(uintptr_t)name) % HASH_ROW_SIZE;
 720 }
 721 
 722 
 723 void initialize_hashtable(NameSigHash** table) {
 724   memset((void*)table, 0, sizeof(NameSigHash*) * HASH_ROW_SIZE);
 725 }
 726 
 727 // Return false if the name/sig combination is found in table.
 728 // Return true if no duplicate is found. And name/sig is added as a new entry in table.
 729 // The old format checker uses heap sort to find duplicates.
 730 // NOTE: caller should guarantee that GC doesn't happen during the life cycle
 731 // of table since we don't expect symbolOop's to move.
 732 bool put_after_lookup(symbolOop name, symbolOop sig, NameSigHash** table) {
 733   assert(name != NULL, "name in constant pool is NULL");
 734 
 735   // First lookup for duplicates
 736   int index = hash(name, sig);
 737   NameSigHash* entry = table[index];
 738   while (entry != NULL) {
 739     if (entry->_name == name && entry->_sig == sig) {
 740       return false;
 741     }
 742     entry = entry->_next;
 743   }
 744 
 745   // No duplicate is found, allocate a new entry and fill it.
 746   entry = new NameSigHash();
 747   entry->_name = name;
 748   entry->_sig = sig;
 749 
 750   // Insert into hash table
 751   entry->_next = table[index];
 752   table[index] = entry;
 753 
 754   return true;
 755 }
 756 
 757 
 758 objArrayHandle ClassFileParser::parse_interfaces(constantPoolHandle cp,
 759                                                  int length,
 760                                                  Handle class_loader,
 761                                                  Handle protection_domain,
 762                                                  symbolHandle class_name,
 763                                                  TRAPS) {
 764   ClassFileStream* cfs = stream();
 765   assert(length > 0, "only called for length>0");
 766   objArrayHandle nullHandle;
 767   objArrayOop interface_oop = oopFactory::new_system_objArray(length, CHECK_(nullHandle));
 768   objArrayHandle interfaces (THREAD, interface_oop);
 769 
 770   int index;
 771   for (index = 0; index < length; index++) {
 772     u2 interface_index = cfs->get_u2(CHECK_(nullHandle));
 773     KlassHandle interf;
 774     check_property(
 775       valid_cp_range(interface_index, cp->length()) &&
 776       is_klass_reference(cp, interface_index),
 777       "Interface name has bad constant pool index %u in class file %s",
 778       interface_index, CHECK_(nullHandle));
 779     if (cp->tag_at(interface_index).is_klass()) {
 780       interf = KlassHandle(THREAD, cp->resolved_klass_at(interface_index));
 781     } else {
 782       symbolHandle unresolved_klass (THREAD, cp->klass_name_at(interface_index));
 783 
 784       // Don't need to check legal name because it's checked when parsing constant pool.
 785       // But need to make sure it's not an array type.
 786       guarantee_property(unresolved_klass->byte_at(0) != JVM_SIGNATURE_ARRAY,
 787                          "Bad interface name in class file %s", CHECK_(nullHandle));
 788 
 789       // Call resolve_super so classcircularity is checked
 790       klassOop k = SystemDictionary::resolve_super_or_fail(class_name,
 791                     unresolved_klass, class_loader, protection_domain,
 792                     false, CHECK_(nullHandle));
 793       interf = KlassHandle(THREAD, k);
 794 
 795       if (LinkWellKnownClasses)  // my super type is well known to me
 796         cp->klass_at_put(interface_index, interf()); // eagerly resolve
 797     }
 798 
 799     if (!Klass::cast(interf())->is_interface()) {
 800       THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(), "Implementing class", nullHandle);
 801     }
 802     interfaces->obj_at_put(index, interf());
 803   }
 804 
 805   if (!_need_verify || length <= 1) {
 806     return interfaces;
 807   }
 808 
 809   // Check if there's any duplicates in interfaces
 810   ResourceMark rm(THREAD);
 811   NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(
 812     THREAD, NameSigHash*, HASH_ROW_SIZE);
 813   initialize_hashtable(interface_names);
 814   bool dup = false;
 815   {
 816     debug_only(No_Safepoint_Verifier nsv;)
 817     for (index = 0; index < length; index++) {
 818       klassOop k = (klassOop)interfaces->obj_at(index);
 819       symbolOop name = instanceKlass::cast(k)->name();
 820       // If no duplicates, add (name, NULL) in hashtable interface_names.
 821       if (!put_after_lookup(name, NULL, interface_names)) {
 822         dup = true;
 823         break;
 824       }
 825     }
 826   }
 827   if (dup) {
 828     classfile_parse_error("Duplicate interface name in class file %s",
 829                           CHECK_(nullHandle));
 830   }
 831 
 832   return interfaces;
 833 }
 834 
 835 
 836 void ClassFileParser::verify_constantvalue(int constantvalue_index, int signature_index, constantPoolHandle cp, TRAPS) {
 837   // Make sure the constant pool entry is of a type appropriate to this field
 838   guarantee_property(
 839     (constantvalue_index > 0 &&
 840       constantvalue_index < cp->length()),
 841     "Bad initial value index %u in ConstantValue attribute in class file %s",
 842     constantvalue_index, CHECK);
 843   constantTag value_type = cp->tag_at(constantvalue_index);
 844   switch ( cp->basic_type_for_signature_at(signature_index) ) {
 845     case T_LONG:
 846       guarantee_property(value_type.is_long(), "Inconsistent constant value type in class file %s", CHECK);
 847       break;
 848     case T_FLOAT:
 849       guarantee_property(value_type.is_float(), "Inconsistent constant value type in class file %s", CHECK);
 850       break;
 851     case T_DOUBLE:
 852       guarantee_property(value_type.is_double(), "Inconsistent constant value type in class file %s", CHECK);
 853       break;
 854     case T_BYTE: case T_CHAR: case T_SHORT: case T_BOOLEAN: case T_INT:
 855       guarantee_property(value_type.is_int(), "Inconsistent constant value type in class file %s", CHECK);
 856       break;
 857     case T_OBJECT:
 858       guarantee_property((cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
 859                          && (value_type.is_string() || value_type.is_unresolved_string())),
 860                          "Bad string initial value in class file %s", CHECK);
 861       break;
 862     default:
 863       classfile_parse_error(
 864         "Unable to set initial value %u in class file %s",
 865         constantvalue_index, CHECK);
 866   }
 867 }
 868 
 869 
 870 // Parse attributes for a field.
 871 void ClassFileParser::parse_field_attributes(constantPoolHandle cp,
 872                                              u2 attributes_count,
 873                                              bool is_static, u2 signature_index,
 874                                              u2* constantvalue_index_addr,
 875                                              bool* is_synthetic_addr,
 876                                              u2* generic_signature_index_addr,
 877                                              typeArrayHandle* field_annotations,
 878                                              TRAPS) {
 879   ClassFileStream* cfs = stream();
 880   assert(attributes_count > 0, "length should be greater than 0");
 881   u2 constantvalue_index = 0;
 882   u2 generic_signature_index = 0;
 883   bool is_synthetic = false;
 884   u1* runtime_visible_annotations = NULL;
 885   int runtime_visible_annotations_length = 0;
 886   u1* runtime_invisible_annotations = NULL;
 887   int runtime_invisible_annotations_length = 0;
 888   while (attributes_count--) {
 889     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
 890     u2 attribute_name_index = cfs->get_u2_fast();
 891     u4 attribute_length = cfs->get_u4_fast();
 892     check_property(valid_cp_range(attribute_name_index, cp->length()) &&
 893                    cp->tag_at(attribute_name_index).is_utf8(),
 894                    "Invalid field attribute index %u in class file %s",
 895                    attribute_name_index,
 896                    CHECK);
 897     symbolOop attribute_name = cp->symbol_at(attribute_name_index);
 898     if (is_static && attribute_name == vmSymbols::tag_constant_value()) {
 899       // ignore if non-static
 900       if (constantvalue_index != 0) {
 901         classfile_parse_error("Duplicate ConstantValue attribute in class file %s", CHECK);
 902       }
 903       check_property(
 904         attribute_length == 2,
 905         "Invalid ConstantValue field attribute length %u in class file %s",
 906         attribute_length, CHECK);
 907       constantvalue_index = cfs->get_u2(CHECK);
 908       if (_need_verify) {
 909         verify_constantvalue(constantvalue_index, signature_index, cp, CHECK);
 910       }
 911     } else if (attribute_name == vmSymbols::tag_synthetic()) {
 912       if (attribute_length != 0) {
 913         classfile_parse_error(
 914           "Invalid Synthetic field attribute length %u in class file %s",
 915           attribute_length, CHECK);
 916       }
 917       is_synthetic = true;
 918     } else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120
 919       if (attribute_length != 0) {
 920         classfile_parse_error(
 921           "Invalid Deprecated field attribute length %u in class file %s",
 922           attribute_length, CHECK);
 923       }
 924     } else if (_major_version >= JAVA_1_5_VERSION) {
 925       if (attribute_name == vmSymbols::tag_signature()) {
 926         if (attribute_length != 2) {
 927           classfile_parse_error(
 928             "Wrong size %u for field's Signature attribute in class file %s",
 929             attribute_length, CHECK);
 930         }
 931         generic_signature_index = cfs->get_u2(CHECK);
 932       } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
 933         runtime_visible_annotations_length = attribute_length;
 934         runtime_visible_annotations = cfs->get_u1_buffer();
 935         assert(runtime_visible_annotations != NULL, "null visible annotations");
 936         cfs->skip_u1(runtime_visible_annotations_length, CHECK);
 937       } else if (PreserveAllAnnotations && attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
 938         runtime_invisible_annotations_length = attribute_length;
 939         runtime_invisible_annotations = cfs->get_u1_buffer();
 940         assert(runtime_invisible_annotations != NULL, "null invisible annotations");
 941         cfs->skip_u1(runtime_invisible_annotations_length, CHECK);
 942       } else {
 943         cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
 944       }
 945     } else {
 946       cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
 947     }
 948   }
 949 
 950   *constantvalue_index_addr = constantvalue_index;
 951   *is_synthetic_addr = is_synthetic;
 952   *generic_signature_index_addr = generic_signature_index;
 953   *field_annotations = assemble_annotations(runtime_visible_annotations,
 954                                             runtime_visible_annotations_length,
 955                                             runtime_invisible_annotations,
 956                                             runtime_invisible_annotations_length,
 957                                             CHECK);
 958   return;
 959 }
 960 
 961 
 962 // Field allocation types. Used for computing field offsets.
 963 
 964 enum FieldAllocationType {
 965   STATIC_OOP,           // Oops
 966   STATIC_BYTE,          // Boolean, Byte, char
 967   STATIC_SHORT,         // shorts
 968   STATIC_WORD,          // ints
 969   STATIC_DOUBLE,        // long or double
 970   STATIC_ALIGNED_DOUBLE,// aligned long or double
 971   NONSTATIC_OOP,
 972   NONSTATIC_BYTE,
 973   NONSTATIC_SHORT,
 974   NONSTATIC_WORD,
 975   NONSTATIC_DOUBLE,
 976   NONSTATIC_ALIGNED_DOUBLE
 977 };
 978 
 979 
 980 struct FieldAllocationCount {
 981   unsigned int static_oop_count;
 982   unsigned int static_byte_count;
 983   unsigned int static_short_count;
 984   unsigned int static_word_count;
 985   unsigned int static_double_count;
 986   unsigned int nonstatic_oop_count;
 987   unsigned int nonstatic_byte_count;
 988   unsigned int nonstatic_short_count;
 989   unsigned int nonstatic_word_count;
 990   unsigned int nonstatic_double_count;
 991 };
 992 
 993 typeArrayHandle ClassFileParser::parse_fields(constantPoolHandle cp, bool is_interface,
 994                                               struct FieldAllocationCount *fac,
 995                                               objArrayHandle* fields_annotations, TRAPS) {
 996   ClassFileStream* cfs = stream();
 997   typeArrayHandle nullHandle;
 998   cfs->guarantee_more(2, CHECK_(nullHandle));  // length
 999   u2 length = cfs->get_u2_fast();
1000   // Tuples of shorts [access, name index, sig index, initial value index, byte offset, generic signature index]
1001   typeArrayOop new_fields = oopFactory::new_permanent_shortArray(length*instanceKlass::next_offset, CHECK_(nullHandle));
1002   typeArrayHandle fields(THREAD, new_fields);
1003 
1004   int index = 0;
1005   typeArrayHandle field_annotations;
1006   for (int n = 0; n < length; n++) {
1007     cfs->guarantee_more(8, CHECK_(nullHandle));  // access_flags, name_index, descriptor_index, attributes_count
1008 
1009     AccessFlags access_flags;
1010     jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1011     verify_legal_field_modifiers(flags, is_interface, CHECK_(nullHandle));
1012     access_flags.set_flags(flags);
1013 
1014     u2 name_index = cfs->get_u2_fast();
1015     int cp_size = cp->length();
1016     check_property(
1017       valid_cp_range(name_index, cp_size) && cp->tag_at(name_index).is_utf8(),
1018       "Invalid constant pool index %u for field name in class file %s",
1019       name_index, CHECK_(nullHandle));
1020     symbolHandle name(THREAD, cp->symbol_at(name_index));
1021     verify_legal_field_name(name, CHECK_(nullHandle));
1022 
1023     u2 signature_index = cfs->get_u2_fast();
1024     check_property(
1025       valid_cp_range(signature_index, cp_size) &&
1026         cp->tag_at(signature_index).is_utf8(),
1027       "Invalid constant pool index %u for field signature in class file %s",
1028       signature_index, CHECK_(nullHandle));
1029     symbolHandle sig(THREAD, cp->symbol_at(signature_index));
1030     verify_legal_field_signature(name, sig, CHECK_(nullHandle));
1031 
1032     u2 constantvalue_index = 0;
1033     bool is_synthetic = false;
1034     u2 generic_signature_index = 0;
1035     bool is_static = access_flags.is_static();
1036 
1037     u2 attributes_count = cfs->get_u2_fast();
1038     if (attributes_count > 0) {
1039       parse_field_attributes(cp, attributes_count, is_static, signature_index,
1040                              &constantvalue_index, &is_synthetic,
1041                              &generic_signature_index, &field_annotations,
1042                              CHECK_(nullHandle));
1043       if (field_annotations.not_null()) {
1044         if (fields_annotations->is_null()) {
1045           objArrayOop md = oopFactory::new_system_objArray(length, CHECK_(nullHandle));
1046           *fields_annotations = objArrayHandle(THREAD, md);
1047         }
1048         (*fields_annotations)->obj_at_put(n, field_annotations());
1049       }
1050       if (is_synthetic) {
1051         access_flags.set_is_synthetic();
1052       }
1053     }
1054 
1055     fields->short_at_put(index++, access_flags.as_short());
1056     fields->short_at_put(index++, name_index);
1057     fields->short_at_put(index++, signature_index);
1058     fields->short_at_put(index++, constantvalue_index);
1059 
1060     // Remember how many oops we encountered and compute allocation type
1061     BasicType type = cp->basic_type_for_signature_at(signature_index);
1062     FieldAllocationType atype;
1063     if ( is_static ) {
1064       switch ( type ) {
1065         case  T_BOOLEAN:
1066         case  T_BYTE:
1067           fac->static_byte_count++;
1068           atype = STATIC_BYTE;
1069           break;
1070         case  T_LONG:
1071         case  T_DOUBLE:
1072           if (Universe::field_type_should_be_aligned(type)) {
1073             atype = STATIC_ALIGNED_DOUBLE;
1074           } else {
1075             atype = STATIC_DOUBLE;
1076           }
1077           fac->static_double_count++;
1078           break;
1079         case  T_CHAR:
1080         case  T_SHORT:
1081           fac->static_short_count++;
1082           atype = STATIC_SHORT;
1083           break;
1084         case  T_FLOAT:
1085         case  T_INT:
1086           fac->static_word_count++;
1087           atype = STATIC_WORD;
1088           break;
1089         case  T_ARRAY:
1090         case  T_OBJECT:
1091           fac->static_oop_count++;
1092           atype = STATIC_OOP;
1093           break;
1094         case  T_ADDRESS:
1095         case  T_VOID:
1096         default:
1097           assert(0, "bad field type");
1098       }
1099     } else {
1100       switch ( type ) {
1101         case  T_BOOLEAN:
1102         case  T_BYTE:
1103           fac->nonstatic_byte_count++;
1104           atype = NONSTATIC_BYTE;
1105           break;
1106         case  T_LONG:
1107         case  T_DOUBLE:
1108           if (Universe::field_type_should_be_aligned(type)) {
1109             atype = NONSTATIC_ALIGNED_DOUBLE;
1110           } else {
1111             atype = NONSTATIC_DOUBLE;
1112           }
1113           fac->nonstatic_double_count++;
1114           break;
1115         case  T_CHAR:
1116         case  T_SHORT:
1117           fac->nonstatic_short_count++;
1118           atype = NONSTATIC_SHORT;
1119           break;
1120         case  T_FLOAT:
1121         case  T_INT:
1122           fac->nonstatic_word_count++;
1123           atype = NONSTATIC_WORD;
1124           break;
1125         case  T_ARRAY:
1126         case  T_OBJECT:
1127           fac->nonstatic_oop_count++;
1128           atype = NONSTATIC_OOP;
1129           break;
1130         case  T_ADDRESS:
1131         case  T_VOID:
1132         default:
1133           assert(0, "bad field type");
1134       }
1135     }
1136 
1137     // The correct offset is computed later (all oop fields will be located together)
1138     // We temporarily store the allocation type in the offset field
1139     fields->short_at_put(index++, atype);
1140     fields->short_at_put(index++, 0);  // Clear out high word of byte offset
1141     fields->short_at_put(index++, generic_signature_index);
1142   }
1143 
1144   if (_need_verify && length > 1) {
1145     // Check duplicated fields
1146     ResourceMark rm(THREAD);
1147     NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
1148       THREAD, NameSigHash*, HASH_ROW_SIZE);
1149     initialize_hashtable(names_and_sigs);
1150     bool dup = false;
1151     {
1152       debug_only(No_Safepoint_Verifier nsv;)
1153       for (int i = 0; i < length*instanceKlass::next_offset; i += instanceKlass::next_offset) {
1154         int name_index = fields->ushort_at(i + instanceKlass::name_index_offset);
1155         symbolOop name = cp->symbol_at(name_index);
1156         int sig_index = fields->ushort_at(i + instanceKlass::signature_index_offset);
1157         symbolOop sig = cp->symbol_at(sig_index);
1158         // If no duplicates, add name/signature in hashtable names_and_sigs.
1159         if (!put_after_lookup(name, sig, names_and_sigs)) {
1160           dup = true;
1161           break;
1162         }
1163       }
1164     }
1165     if (dup) {
1166       classfile_parse_error("Duplicate field name&signature in class file %s",
1167                             CHECK_(nullHandle));
1168     }
1169   }
1170 
1171   return fields;
1172 }
1173 
1174 
1175 static void copy_u2_with_conversion(u2* dest, u2* src, int length) {
1176   while (length-- > 0) {
1177     *dest++ = Bytes::get_Java_u2((u1*) (src++));
1178   }
1179 }
1180 
1181 
1182 typeArrayHandle ClassFileParser::parse_exception_table(u4 code_length,
1183                                                        u4 exception_table_length,
1184                                                        constantPoolHandle cp,
1185                                                        TRAPS) {
1186   ClassFileStream* cfs = stream();
1187   typeArrayHandle nullHandle;
1188 
1189   // 4-tuples of ints [start_pc, end_pc, handler_pc, catch_type index]
1190   typeArrayOop eh = oopFactory::new_permanent_intArray(exception_table_length*4, CHECK_(nullHandle));
1191   typeArrayHandle exception_handlers = typeArrayHandle(THREAD, eh);
1192 
1193   int index = 0;
1194   cfs->guarantee_more(8 * exception_table_length, CHECK_(nullHandle)); // start_pc, end_pc, handler_pc, catch_type_index
1195   for (unsigned int i = 0; i < exception_table_length; i++) {
1196     u2 start_pc = cfs->get_u2_fast();
1197     u2 end_pc = cfs->get_u2_fast();
1198     u2 handler_pc = cfs->get_u2_fast();
1199     u2 catch_type_index = cfs->get_u2_fast();
1200     // Will check legal target after parsing code array in verifier.
1201     if (_need_verify) {
1202       guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1203                          "Illegal exception table range in class file %s", CHECK_(nullHandle));
1204       guarantee_property(handler_pc < code_length,
1205                          "Illegal exception table handler in class file %s", CHECK_(nullHandle));
1206       if (catch_type_index != 0) {
1207         guarantee_property(valid_cp_range(catch_type_index, cp->length()) &&
1208                            is_klass_reference(cp, catch_type_index),
1209                            "Catch type in exception table has bad constant type in class file %s", CHECK_(nullHandle));
1210       }
1211     }
1212     exception_handlers->int_at_put(index++, start_pc);
1213     exception_handlers->int_at_put(index++, end_pc);
1214     exception_handlers->int_at_put(index++, handler_pc);
1215     exception_handlers->int_at_put(index++, catch_type_index);
1216   }
1217   return exception_handlers;
1218 }
1219 
1220 void ClassFileParser::parse_linenumber_table(
1221     u4 code_attribute_length, u4 code_length,
1222     CompressedLineNumberWriteStream** write_stream, TRAPS) {
1223   ClassFileStream* cfs = stream();
1224   unsigned int num_entries = cfs->get_u2(CHECK);
1225 
1226   // Each entry is a u2 start_pc, and a u2 line_number
1227   unsigned int length_in_bytes = num_entries * (sizeof(u2) + sizeof(u2));
1228 
1229   // Verify line number attribute and table length
1230   check_property(
1231     code_attribute_length == sizeof(u2) + length_in_bytes,
1232     "LineNumberTable attribute has wrong length in class file %s", CHECK);
1233 
1234   cfs->guarantee_more(length_in_bytes, CHECK);
1235 
1236   if ((*write_stream) == NULL) {
1237     if (length_in_bytes > fixed_buffer_size) {
1238       (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
1239     } else {
1240       (*write_stream) = new CompressedLineNumberWriteStream(
1241         linenumbertable_buffer, fixed_buffer_size);
1242     }
1243   }
1244 
1245   while (num_entries-- > 0) {
1246     u2 bci  = cfs->get_u2_fast(); // start_pc
1247     u2 line = cfs->get_u2_fast(); // line_number
1248     guarantee_property(bci < code_length,
1249         "Invalid pc in LineNumberTable in class file %s", CHECK);
1250     (*write_stream)->write_pair(bci, line);
1251   }
1252 }
1253 
1254 
1255 // Class file LocalVariableTable elements.
1256 class Classfile_LVT_Element VALUE_OBJ_CLASS_SPEC {
1257  public:
1258   u2 start_bci;
1259   u2 length;
1260   u2 name_cp_index;
1261   u2 descriptor_cp_index;
1262   u2 slot;
1263 };
1264 
1265 
1266 class LVT_Hash: public CHeapObj {
1267  public:
1268   LocalVariableTableElement  *_elem;  // element
1269   LVT_Hash*                   _next;  // Next entry in hash table
1270 };
1271 
1272 unsigned int hash(LocalVariableTableElement *elem) {
1273   unsigned int raw_hash = elem->start_bci;
1274 
1275   raw_hash = elem->length        + raw_hash * 37;
1276   raw_hash = elem->name_cp_index + raw_hash * 37;
1277   raw_hash = elem->slot          + raw_hash * 37;
1278 
1279   return raw_hash % HASH_ROW_SIZE;
1280 }
1281 
1282 void initialize_hashtable(LVT_Hash** table) {
1283   for (int i = 0; i < HASH_ROW_SIZE; i++) {
1284     table[i] = NULL;
1285   }
1286 }
1287 
1288 void clear_hashtable(LVT_Hash** table) {
1289   for (int i = 0; i < HASH_ROW_SIZE; i++) {
1290     LVT_Hash* current = table[i];
1291     LVT_Hash* next;
1292     while (current != NULL) {
1293       next = current->_next;
1294       current->_next = NULL;
1295       delete(current);
1296       current = next;
1297     }
1298     table[i] = NULL;
1299   }
1300 }
1301 
1302 LVT_Hash* LVT_lookup(LocalVariableTableElement *elem, int index, LVT_Hash** table) {
1303   LVT_Hash* entry = table[index];
1304 
1305   /*
1306    * 3-tuple start_bci/length/slot has to be unique key,
1307    * so the following comparison seems to be redundant:
1308    *       && elem->name_cp_index == entry->_elem->name_cp_index
1309    */
1310   while (entry != NULL) {
1311     if (elem->start_bci           == entry->_elem->start_bci
1312      && elem->length              == entry->_elem->length
1313      && elem->name_cp_index       == entry->_elem->name_cp_index
1314      && elem->slot                == entry->_elem->slot
1315     ) {
1316       return entry;
1317     }
1318     entry = entry->_next;
1319   }
1320   return NULL;
1321 }
1322 
1323 // Return false if the local variable is found in table.
1324 // Return true if no duplicate is found.
1325 // And local variable is added as a new entry in table.
1326 bool LVT_put_after_lookup(LocalVariableTableElement *elem, LVT_Hash** table) {
1327   // First lookup for duplicates
1328   int index = hash(elem);
1329   LVT_Hash* entry = LVT_lookup(elem, index, table);
1330 
1331   if (entry != NULL) {
1332       return false;
1333   }
1334   // No duplicate is found, allocate a new entry and fill it.
1335   if ((entry = new LVT_Hash()) == NULL) {
1336     return false;
1337   }
1338   entry->_elem = elem;
1339 
1340   // Insert into hash table
1341   entry->_next = table[index];
1342   table[index] = entry;
1343 
1344   return true;
1345 }
1346 
1347 void copy_lvt_element(Classfile_LVT_Element *src, LocalVariableTableElement *lvt) {
1348   lvt->start_bci           = Bytes::get_Java_u2((u1*) &src->start_bci);
1349   lvt->length              = Bytes::get_Java_u2((u1*) &src->length);
1350   lvt->name_cp_index       = Bytes::get_Java_u2((u1*) &src->name_cp_index);
1351   lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
1352   lvt->signature_cp_index  = 0;
1353   lvt->slot                = Bytes::get_Java_u2((u1*) &src->slot);
1354 }
1355 
1356 // Function is used to parse both attributes:
1357 //       LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
1358 u2* ClassFileParser::parse_localvariable_table(u4 code_length,
1359                                                u2 max_locals,
1360                                                u4 code_attribute_length,
1361                                                constantPoolHandle cp,
1362                                                u2* localvariable_table_length,
1363                                                bool isLVTT,
1364                                                TRAPS) {
1365   ClassFileStream* cfs = stream();
1366   const char * tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
1367   *localvariable_table_length = cfs->get_u2(CHECK_NULL);
1368   unsigned int size = (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);
1369   // Verify local variable table attribute has right length
1370   if (_need_verify) {
1371     guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
1372                        "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
1373   }
1374   u2* localvariable_table_start = cfs->get_u2_buffer();
1375   assert(localvariable_table_start != NULL, "null local variable table");
1376   if (!_need_verify) {
1377     cfs->skip_u2_fast(size);
1378   } else {
1379     cfs->guarantee_more(size * 2, CHECK_NULL);
1380     for(int i = 0; i < (*localvariable_table_length); i++) {
1381       u2 start_pc = cfs->get_u2_fast();
1382       u2 length = cfs->get_u2_fast();
1383       u2 name_index = cfs->get_u2_fast();
1384       u2 descriptor_index = cfs->get_u2_fast();
1385       u2 index = cfs->get_u2_fast();
1386       // Assign to a u4 to avoid overflow
1387       u4 end_pc = (u4)start_pc + (u4)length;
1388 
1389       if (start_pc >= code_length) {
1390         classfile_parse_error(
1391           "Invalid start_pc %u in %s in class file %s",
1392           start_pc, tbl_name, CHECK_NULL);
1393       }
1394       if (end_pc > code_length) {
1395         classfile_parse_error(
1396           "Invalid length %u in %s in class file %s",
1397           length, tbl_name, CHECK_NULL);
1398       }
1399       int cp_size = cp->length();
1400       guarantee_property(
1401         valid_cp_range(name_index, cp_size) &&
1402           cp->tag_at(name_index).is_utf8(),
1403         "Name index %u in %s has bad constant type in class file %s",
1404         name_index, tbl_name, CHECK_NULL);
1405       guarantee_property(
1406         valid_cp_range(descriptor_index, cp_size) &&
1407           cp->tag_at(descriptor_index).is_utf8(),
1408         "Signature index %u in %s has bad constant type in class file %s",
1409         descriptor_index, tbl_name, CHECK_NULL);
1410 
1411       symbolHandle name(THREAD, cp->symbol_at(name_index));
1412       symbolHandle sig(THREAD, cp->symbol_at(descriptor_index));
1413       verify_legal_field_name(name, CHECK_NULL);
1414       u2 extra_slot = 0;
1415       if (!isLVTT) {
1416         verify_legal_field_signature(name, sig, CHECK_NULL);
1417 
1418         // 4894874: check special cases for double and long local variables
1419         if (sig() == vmSymbols::type_signature(T_DOUBLE) ||
1420             sig() == vmSymbols::type_signature(T_LONG)) {
1421           extra_slot = 1;
1422         }
1423       }
1424       guarantee_property((index + extra_slot) < max_locals,
1425                           "Invalid index %u in %s in class file %s",
1426                           index, tbl_name, CHECK_NULL);
1427     }
1428   }
1429   return localvariable_table_start;
1430 }
1431 
1432 
1433 void ClassFileParser::parse_type_array(u2 array_length, u4 code_length, u4* u1_index, u4* u2_index,
1434                                       u1* u1_array, u2* u2_array, constantPoolHandle cp, TRAPS) {
1435   ClassFileStream* cfs = stream();
1436   u2 index = 0; // index in the array with long/double occupying two slots
1437   u4 i1 = *u1_index;
1438   u4 i2 = *u2_index + 1;
1439   for(int i = 0; i < array_length; i++) {
1440     u1 tag = u1_array[i1++] = cfs->get_u1(CHECK);
1441     index++;
1442     if (tag == ITEM_Long || tag == ITEM_Double) {
1443       index++;
1444     } else if (tag == ITEM_Object) {
1445       u2 class_index = u2_array[i2++] = cfs->get_u2(CHECK);
1446       guarantee_property(valid_cp_range(class_index, cp->length()) &&
1447                          is_klass_reference(cp, class_index),
1448                          "Bad class index %u in StackMap in class file %s",
1449                          class_index, CHECK);
1450     } else if (tag == ITEM_Uninitialized) {
1451       u2 offset = u2_array[i2++] = cfs->get_u2(CHECK);
1452       guarantee_property(
1453         offset < code_length,
1454         "Bad uninitialized type offset %u in StackMap in class file %s",
1455         offset, CHECK);
1456     } else {
1457       guarantee_property(
1458         tag <= (u1)ITEM_Uninitialized,
1459         "Unknown variable type %u in StackMap in class file %s",
1460         tag, CHECK);
1461     }
1462   }
1463   u2_array[*u2_index] = index;
1464   *u1_index = i1;
1465   *u2_index = i2;
1466 }
1467 
1468 typeArrayOop ClassFileParser::parse_stackmap_table(
1469     u4 code_attribute_length, TRAPS) {
1470   if (code_attribute_length == 0)
1471     return NULL;
1472 
1473   ClassFileStream* cfs = stream();
1474   u1* stackmap_table_start = cfs->get_u1_buffer();
1475   assert(stackmap_table_start != NULL, "null stackmap table");
1476 
1477   // check code_attribute_length first
1478   stream()->skip_u1(code_attribute_length, CHECK_NULL);
1479 
1480   if (!_need_verify && !DumpSharedSpaces) {
1481     return NULL;
1482   }
1483 
1484   typeArrayOop stackmap_data =
1485     oopFactory::new_permanent_byteArray(code_attribute_length, CHECK_NULL);
1486 
1487   stackmap_data->set_length(code_attribute_length);
1488   memcpy((void*)stackmap_data->byte_at_addr(0),
1489          (void*)stackmap_table_start, code_attribute_length);
1490   return stackmap_data;
1491 }
1492 
1493 u2* ClassFileParser::parse_checked_exceptions(u2* checked_exceptions_length,
1494                                               u4 method_attribute_length,
1495                                               constantPoolHandle cp, TRAPS) {
1496   ClassFileStream* cfs = stream();
1497   cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
1498   *checked_exceptions_length = cfs->get_u2_fast();
1499   unsigned int size = (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
1500   u2* checked_exceptions_start = cfs->get_u2_buffer();
1501   assert(checked_exceptions_start != NULL, "null checked exceptions");
1502   if (!_need_verify) {
1503     cfs->skip_u2_fast(size);
1504   } else {
1505     // Verify each value in the checked exception table
1506     u2 checked_exception;
1507     u2 len = *checked_exceptions_length;
1508     cfs->guarantee_more(2 * len, CHECK_NULL);
1509     for (int i = 0; i < len; i++) {
1510       checked_exception = cfs->get_u2_fast();
1511       check_property(
1512         valid_cp_range(checked_exception, cp->length()) &&
1513         is_klass_reference(cp, checked_exception),
1514         "Exception name has bad type at constant pool %u in class file %s",
1515         checked_exception, CHECK_NULL);
1516     }
1517   }
1518   // check exceptions attribute length
1519   if (_need_verify) {
1520     guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
1521                                                    sizeof(u2) * size),
1522                       "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
1523   }
1524   return checked_exceptions_start;
1525 }
1526 
1527 void ClassFileParser::throwIllegalSignature(
1528     const char* type, symbolHandle name, symbolHandle sig, TRAPS) {
1529   ResourceMark rm(THREAD);
1530   Exceptions::fthrow(THREAD_AND_LOCATION,
1531       vmSymbols::java_lang_ClassFormatError(),
1532       "%s \"%s\" in class %s has illegal signature \"%s\"", type,
1533       name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
1534 }
1535 
1536 #define MAX_ARGS_SIZE 255
1537 #define MAX_CODE_SIZE 65535
1538 #define INITIAL_MAX_LVT_NUMBER 256
1539 
1540 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
1541 // attribute is inlined. This is curbersome to avoid since we inline most of the parts in the
1542 // methodOop to save footprint, so we only know the size of the resulting methodOop when the
1543 // entire method attribute is parsed.
1544 //
1545 // The promoted_flags parameter is used to pass relevant access_flags
1546 // from the method back up to the containing klass. These flag values
1547 // are added to klass's access_flags.
1548 
1549 methodHandle ClassFileParser::parse_method(constantPoolHandle cp, bool is_interface,
1550                                            AccessFlags *promoted_flags,
1551                                            typeArrayHandle* method_annotations,
1552                                            typeArrayHandle* method_parameter_annotations,
1553                                            typeArrayHandle* method_default_annotations,
1554                                            TRAPS) {
1555   ClassFileStream* cfs = stream();
1556   methodHandle nullHandle;
1557   ResourceMark rm(THREAD);
1558   // Parse fixed parts
1559   cfs->guarantee_more(8, CHECK_(nullHandle)); // access_flags, name_index, descriptor_index, attributes_count
1560 
1561   int flags = cfs->get_u2_fast();
1562   u2 name_index = cfs->get_u2_fast();
1563   int cp_size = cp->length();
1564   check_property(
1565     valid_cp_range(name_index, cp_size) &&
1566       cp->tag_at(name_index).is_utf8(),
1567     "Illegal constant pool index %u for method name in class file %s",
1568     name_index, CHECK_(nullHandle));
1569   symbolHandle name(THREAD, cp->symbol_at(name_index));
1570   verify_legal_method_name(name, CHECK_(nullHandle));
1571 
1572   u2 signature_index = cfs->get_u2_fast();
1573   guarantee_property(
1574     valid_cp_range(signature_index, cp_size) &&
1575       cp->tag_at(signature_index).is_utf8(),
1576     "Illegal constant pool index %u for method signature in class file %s",
1577     signature_index, CHECK_(nullHandle));
1578   symbolHandle signature(THREAD, cp->symbol_at(signature_index));
1579 
1580   AccessFlags access_flags;
1581   if (name == vmSymbols::class_initializer_name()) {
1582     // We ignore the access flags for a class initializer. (JVM Spec. p. 116)
1583     flags = JVM_ACC_STATIC;
1584   } else {
1585     verify_legal_method_modifiers(flags, is_interface, name, CHECK_(nullHandle));
1586   }
1587 
1588   int args_size = -1;  // only used when _need_verify is true
1589   if (_need_verify) {
1590     args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
1591                  verify_legal_method_signature(name, signature, CHECK_(nullHandle));
1592     if (args_size > MAX_ARGS_SIZE) {
1593       classfile_parse_error("Too many arguments in method signature in class file %s", CHECK_(nullHandle));
1594     }
1595   }
1596 
1597   access_flags.set_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);
1598 
1599   // Default values for code and exceptions attribute elements
1600   u2 max_stack = 0;
1601   u2 max_locals = 0;
1602   u4 code_length = 0;
1603   u1* code_start = 0;
1604   u2 exception_table_length = 0;
1605   typeArrayHandle exception_handlers(THREAD, Universe::the_empty_int_array());
1606   u2 checked_exceptions_length = 0;
1607   u2* checked_exceptions_start = NULL;
1608   CompressedLineNumberWriteStream* linenumber_table = NULL;
1609   int linenumber_table_length = 0;
1610   int total_lvt_length = 0;
1611   u2 lvt_cnt = 0;
1612   u2 lvtt_cnt = 0;
1613   bool lvt_allocated = false;
1614   u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
1615   u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
1616   u2* localvariable_table_length;
1617   u2** localvariable_table_start;
1618   u2* localvariable_type_table_length;
1619   u2** localvariable_type_table_start;
1620   bool parsed_code_attribute = false;
1621   bool parsed_checked_exceptions_attribute = false;
1622   bool parsed_stackmap_attribute = false;
1623   // stackmap attribute - JDK1.5
1624   typeArrayHandle stackmap_data;
1625   u2 generic_signature_index = 0;
1626   u1* runtime_visible_annotations = NULL;
1627   int runtime_visible_annotations_length = 0;
1628   u1* runtime_invisible_annotations = NULL;
1629   int runtime_invisible_annotations_length = 0;
1630   u1* runtime_visible_parameter_annotations = NULL;
1631   int runtime_visible_parameter_annotations_length = 0;
1632   u1* runtime_invisible_parameter_annotations = NULL;
1633   int runtime_invisible_parameter_annotations_length = 0;
1634   u1* annotation_default = NULL;
1635   int annotation_default_length = 0;
1636 
1637   // Parse code and exceptions attribute
1638   u2 method_attributes_count = cfs->get_u2_fast();
1639   while (method_attributes_count--) {
1640     cfs->guarantee_more(6, CHECK_(nullHandle));  // method_attribute_name_index, method_attribute_length
1641     u2 method_attribute_name_index = cfs->get_u2_fast();
1642     u4 method_attribute_length = cfs->get_u4_fast();
1643     check_property(
1644       valid_cp_range(method_attribute_name_index, cp_size) &&
1645         cp->tag_at(method_attribute_name_index).is_utf8(),
1646       "Invalid method attribute name index %u in class file %s",
1647       method_attribute_name_index, CHECK_(nullHandle));
1648 
1649     symbolOop method_attribute_name = cp->symbol_at(method_attribute_name_index);
1650     if (method_attribute_name == vmSymbols::tag_code()) {
1651       // Parse Code attribute
1652       if (_need_verify) {
1653         guarantee_property(!access_flags.is_native() && !access_flags.is_abstract(),
1654                         "Code attribute in native or abstract methods in class file %s",
1655                          CHECK_(nullHandle));
1656       }
1657       if (parsed_code_attribute) {
1658         classfile_parse_error("Multiple Code attributes in class file %s", CHECK_(nullHandle));
1659       }
1660       parsed_code_attribute = true;
1661 
1662       // Stack size, locals size, and code size
1663       if (_major_version == 45 && _minor_version <= 2) {
1664         cfs->guarantee_more(4, CHECK_(nullHandle));
1665         max_stack = cfs->get_u1_fast();
1666         max_locals = cfs->get_u1_fast();
1667         code_length = cfs->get_u2_fast();
1668       } else {
1669         cfs->guarantee_more(8, CHECK_(nullHandle));
1670         max_stack = cfs->get_u2_fast();
1671         max_locals = cfs->get_u2_fast();
1672         code_length = cfs->get_u4_fast();
1673       }
1674       if (_need_verify) {
1675         guarantee_property(args_size <= max_locals,
1676                            "Arguments can't fit into locals in class file %s", CHECK_(nullHandle));
1677         guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
1678                            "Invalid method Code length %u in class file %s",
1679                            code_length, CHECK_(nullHandle));
1680       }
1681       // Code pointer
1682       code_start = cfs->get_u1_buffer();
1683       assert(code_start != NULL, "null code start");
1684       cfs->guarantee_more(code_length, CHECK_(nullHandle));
1685       cfs->skip_u1_fast(code_length);
1686 
1687       // Exception handler table
1688       cfs->guarantee_more(2, CHECK_(nullHandle));  // exception_table_length
1689       exception_table_length = cfs->get_u2_fast();
1690       if (exception_table_length > 0) {
1691         exception_handlers =
1692               parse_exception_table(code_length, exception_table_length, cp, CHECK_(nullHandle));
1693       }
1694 
1695       // Parse additional attributes in code attribute
1696       cfs->guarantee_more(2, CHECK_(nullHandle));  // code_attributes_count
1697       u2 code_attributes_count = cfs->get_u2_fast();
1698 
1699       unsigned int calculated_attribute_length = 0;
1700 
1701       if (_major_version > 45 || (_major_version == 45 && _minor_version > 2)) {
1702         calculated_attribute_length =
1703             sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
1704       } else {
1705         // max_stack, locals and length are smaller in pre-version 45.2 classes
1706         calculated_attribute_length = sizeof(u1) + sizeof(u1) + sizeof(u2);
1707       }
1708       calculated_attribute_length +=
1709         code_length +
1710         sizeof(exception_table_length) +
1711         sizeof(code_attributes_count) +
1712         exception_table_length *
1713             ( sizeof(u2) +   // start_pc
1714               sizeof(u2) +   // end_pc
1715               sizeof(u2) +   // handler_pc
1716               sizeof(u2) );  // catch_type_index
1717 
1718       while (code_attributes_count--) {
1719         cfs->guarantee_more(6, CHECK_(nullHandle));  // code_attribute_name_index, code_attribute_length
1720         u2 code_attribute_name_index = cfs->get_u2_fast();
1721         u4 code_attribute_length = cfs->get_u4_fast();
1722         calculated_attribute_length += code_attribute_length +
1723                                        sizeof(code_attribute_name_index) +
1724                                        sizeof(code_attribute_length);
1725         check_property(valid_cp_range(code_attribute_name_index, cp_size) &&
1726                        cp->tag_at(code_attribute_name_index).is_utf8(),
1727                        "Invalid code attribute name index %u in class file %s",
1728                        code_attribute_name_index,
1729                        CHECK_(nullHandle));
1730         if (LoadLineNumberTables &&
1731             cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
1732           // Parse and compress line number table
1733           parse_linenumber_table(code_attribute_length, code_length,
1734             &linenumber_table, CHECK_(nullHandle));
1735 
1736         } else if (LoadLocalVariableTables &&
1737                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
1738           // Parse local variable table
1739           if (!lvt_allocated) {
1740             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
1741               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
1742             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
1743               THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
1744             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
1745               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
1746             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
1747               THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
1748             lvt_allocated = true;
1749           }
1750           if (lvt_cnt == max_lvt_cnt) {
1751             max_lvt_cnt <<= 1;
1752             REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
1753             REALLOC_RESOURCE_ARRAY(u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
1754           }
1755           localvariable_table_start[lvt_cnt] =
1756             parse_localvariable_table(code_length,
1757                                       max_locals,
1758                                       code_attribute_length,
1759                                       cp,
1760                                       &localvariable_table_length[lvt_cnt],
1761                                       false,    // is not LVTT
1762                                       CHECK_(nullHandle));
1763           total_lvt_length += localvariable_table_length[lvt_cnt];
1764           lvt_cnt++;
1765         } else if (LoadLocalVariableTypeTables &&
1766                    _major_version >= JAVA_1_5_VERSION &&
1767                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
1768           if (!lvt_allocated) {
1769             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
1770               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
1771             localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
1772               THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
1773             localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
1774               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
1775             localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
1776               THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
1777             lvt_allocated = true;
1778           }
1779           // Parse local variable type table
1780           if (lvtt_cnt == max_lvtt_cnt) {
1781             max_lvtt_cnt <<= 1;
1782             REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
1783             REALLOC_RESOURCE_ARRAY(u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
1784           }
1785           localvariable_type_table_start[lvtt_cnt] =
1786             parse_localvariable_table(code_length,
1787                                       max_locals,
1788                                       code_attribute_length,
1789                                       cp,
1790                                       &localvariable_type_table_length[lvtt_cnt],
1791                                       true,     // is LVTT
1792                                       CHECK_(nullHandle));
1793           lvtt_cnt++;
1794         } else if (UseSplitVerifier &&
1795                    _major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
1796                    cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
1797           // Stack map is only needed by the new verifier in JDK1.5.
1798           if (parsed_stackmap_attribute) {
1799             classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_(nullHandle));
1800           }
1801           typeArrayOop sm =
1802             parse_stackmap_table(code_attribute_length, CHECK_(nullHandle));
1803           stackmap_data = typeArrayHandle(THREAD, sm);
1804           parsed_stackmap_attribute = true;
1805         } else {
1806           // Skip unknown attributes
1807           cfs->skip_u1(code_attribute_length, CHECK_(nullHandle));
1808         }
1809       }
1810       // check method attribute length
1811       if (_need_verify) {
1812         guarantee_property(method_attribute_length == calculated_attribute_length,
1813                            "Code segment has wrong length in class file %s", CHECK_(nullHandle));
1814       }
1815     } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
1816       // Parse Exceptions attribute
1817       if (parsed_checked_exceptions_attribute) {
1818         classfile_parse_error("Multiple Exceptions attributes in class file %s", CHECK_(nullHandle));
1819       }
1820       parsed_checked_exceptions_attribute = true;
1821       checked_exceptions_start =
1822             parse_checked_exceptions(&checked_exceptions_length,
1823                                      method_attribute_length,
1824                                      cp, CHECK_(nullHandle));
1825     } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
1826       if (method_attribute_length != 0) {
1827         classfile_parse_error(
1828           "Invalid Synthetic method attribute length %u in class file %s",
1829           method_attribute_length, CHECK_(nullHandle));
1830       }
1831       // Should we check that there hasn't already been a synthetic attribute?
1832       access_flags.set_is_synthetic();
1833     } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
1834       if (method_attribute_length != 0) {
1835         classfile_parse_error(
1836           "Invalid Deprecated method attribute length %u in class file %s",
1837           method_attribute_length, CHECK_(nullHandle));
1838       }
1839     } else if (_major_version >= JAVA_1_5_VERSION) {
1840       if (method_attribute_name == vmSymbols::tag_signature()) {
1841         if (method_attribute_length != 2) {
1842           classfile_parse_error(
1843             "Invalid Signature attribute length %u in class file %s",
1844             method_attribute_length, CHECK_(nullHandle));
1845         }
1846         cfs->guarantee_more(2, CHECK_(nullHandle));  // generic_signature_index
1847         generic_signature_index = cfs->get_u2_fast();
1848       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
1849         runtime_visible_annotations_length = method_attribute_length;
1850         runtime_visible_annotations = cfs->get_u1_buffer();
1851         assert(runtime_visible_annotations != NULL, "null visible annotations");
1852         cfs->skip_u1(runtime_visible_annotations_length, CHECK_(nullHandle));
1853       } else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
1854         runtime_invisible_annotations_length = method_attribute_length;
1855         runtime_invisible_annotations = cfs->get_u1_buffer();
1856         assert(runtime_invisible_annotations != NULL, "null invisible annotations");
1857         cfs->skip_u1(runtime_invisible_annotations_length, CHECK_(nullHandle));
1858       } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
1859         runtime_visible_parameter_annotations_length = method_attribute_length;
1860         runtime_visible_parameter_annotations = cfs->get_u1_buffer();
1861         assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");
1862         cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_(nullHandle));
1863       } else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
1864         runtime_invisible_parameter_annotations_length = method_attribute_length;
1865         runtime_invisible_parameter_annotations = cfs->get_u1_buffer();
1866         assert(runtime_invisible_parameter_annotations != NULL, "null invisible parameter annotations");
1867         cfs->skip_u1(runtime_invisible_parameter_annotations_length, CHECK_(nullHandle));
1868       } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
1869         annotation_default_length = method_attribute_length;
1870         annotation_default = cfs->get_u1_buffer();
1871         assert(annotation_default != NULL, "null annotation default");
1872         cfs->skip_u1(annotation_default_length, CHECK_(nullHandle));
1873       } else {
1874         // Skip unknown attributes
1875         cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));
1876       }
1877     } else {
1878       // Skip unknown attributes
1879       cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));
1880     }
1881   }
1882 
1883   if (linenumber_table != NULL) {
1884     linenumber_table->write_terminator();
1885     linenumber_table_length = linenumber_table->position();
1886   }
1887 
1888   // Make sure there's at least one Code attribute in non-native/non-abstract method
1889   if (_need_verify) {
1890     guarantee_property(access_flags.is_native() || access_flags.is_abstract() || parsed_code_attribute,
1891                       "Absent Code attribute in method that is not native or abstract in class file %s", CHECK_(nullHandle));
1892   }
1893 
1894   // All sizing information for a methodOop is finally available, now create it
1895   methodOop m_oop  = oopFactory::new_method(
1896     code_length, access_flags, linenumber_table_length,
1897     total_lvt_length, checked_exceptions_length,
1898     methodOopDesc::IsSafeConc, CHECK_(nullHandle));
1899   methodHandle m (THREAD, m_oop);
1900 
1901   ClassLoadingService::add_class_method_size(m_oop->size()*HeapWordSize);
1902 
1903   // Fill in information from fixed part (access_flags already set)
1904   m->set_constants(cp());
1905   m->set_name_index(name_index);
1906   m->set_signature_index(signature_index);
1907   m->set_generic_signature_index(generic_signature_index);
1908 #ifdef CC_INTERP
1909   // hmm is there a gc issue here??
1910   ResultTypeFinder rtf(cp->symbol_at(signature_index));
1911   m->set_result_index(rtf.type());
1912 #endif
1913 
1914   if (args_size >= 0) {
1915     m->set_size_of_parameters(args_size);
1916   } else {
1917     m->compute_size_of_parameters(THREAD);
1918   }
1919 #ifdef ASSERT
1920   if (args_size >= 0) {
1921     m->compute_size_of_parameters(THREAD);
1922     assert(args_size == m->size_of_parameters(), "");
1923   }
1924 #endif
1925 
1926   // Fill in code attribute information
1927   m->set_max_stack(max_stack);
1928   m->set_max_locals(max_locals);
1929   m->constMethod()->set_stackmap_data(stackmap_data());
1930 
1931   /**
1932    * The exception_table field is the flag used to indicate
1933    * that the methodOop and it's associated constMethodOop are partially
1934    * initialized and thus are exempt from pre/post GC verification.  Once
1935    * the field is set, the oops are considered fully initialized so make
1936    * sure that the oops can pass verification when this field is set.
1937    */
1938   m->set_exception_table(exception_handlers());
1939 
1940   // Copy byte codes
1941   m->set_code(code_start);
1942 
1943   // Copy line number table
1944   if (linenumber_table != NULL) {
1945     memcpy(m->compressed_linenumber_table(),
1946            linenumber_table->buffer(), linenumber_table_length);
1947   }
1948 
1949   // Copy checked exceptions
1950   if (checked_exceptions_length > 0) {
1951     int size = checked_exceptions_length * sizeof(CheckedExceptionElement) / sizeof(u2);
1952     copy_u2_with_conversion((u2*) m->checked_exceptions_start(), checked_exceptions_start, size);
1953   }
1954 
1955   /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
1956    *
1957    * Rules for LVT's and LVTT's are:
1958    *   - There can be any number of LVT's and LVTT's.
1959    *   - If there are n LVT's, it is the same as if there was just
1960    *     one LVT containing all the entries from the n LVT's.
1961    *   - There may be no more than one LVT entry per local variable.
1962    *     Two LVT entries are 'equal' if these fields are the same:
1963    *        start_pc, length, name, slot
1964    *   - There may be no more than one LVTT entry per each LVT entry.
1965    *     Each LVTT entry has to match some LVT entry.
1966    *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
1967    */
1968   if (total_lvt_length > 0) {
1969     int tbl_no, idx;
1970 
1971     promoted_flags->set_has_localvariable_table();
1972 
1973     LVT_Hash** lvt_Hash = NEW_RESOURCE_ARRAY(LVT_Hash*, HASH_ROW_SIZE);
1974     initialize_hashtable(lvt_Hash);
1975 
1976     // To fill LocalVariableTable in
1977     Classfile_LVT_Element*  cf_lvt;
1978     LocalVariableTableElement* lvt = m->localvariable_table_start();
1979 
1980     for (tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
1981       cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
1982       for (idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
1983         copy_lvt_element(&cf_lvt[idx], lvt);
1984         // If no duplicates, add LVT elem in hashtable lvt_Hash.
1985         if (LVT_put_after_lookup(lvt, lvt_Hash) == false
1986           && _need_verify
1987           && _major_version >= JAVA_1_5_VERSION ) {
1988           clear_hashtable(lvt_Hash);
1989           classfile_parse_error("Duplicated LocalVariableTable attribute "
1990                                 "entry for '%s' in class file %s",
1991                                  cp->symbol_at(lvt->name_cp_index)->as_utf8(),
1992                                  CHECK_(nullHandle));
1993         }
1994       }
1995     }
1996 
1997     // To merge LocalVariableTable and LocalVariableTypeTable
1998     Classfile_LVT_Element* cf_lvtt;
1999     LocalVariableTableElement lvtt_elem;
2000 
2001     for (tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
2002       cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
2003       for (idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
2004         copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
2005         int index = hash(&lvtt_elem);
2006         LVT_Hash* entry = LVT_lookup(&lvtt_elem, index, lvt_Hash);
2007         if (entry == NULL) {
2008           if (_need_verify) {
2009             clear_hashtable(lvt_Hash);
2010             classfile_parse_error("LVTT entry for '%s' in class file %s "
2011                                   "does not match any LVT entry",
2012                                    cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2013                                    CHECK_(nullHandle));
2014           }
2015         } else if (entry->_elem->signature_cp_index != 0 && _need_verify) {
2016           clear_hashtable(lvt_Hash);
2017           classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
2018                                 "entry for '%s' in class file %s",
2019                                  cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
2020                                  CHECK_(nullHandle));
2021         } else {
2022           // to add generic signatures into LocalVariableTable
2023           entry->_elem->signature_cp_index = lvtt_elem.descriptor_cp_index;
2024         }
2025       }
2026     }
2027     clear_hashtable(lvt_Hash);
2028   }
2029 
2030   *method_annotations = assemble_annotations(runtime_visible_annotations,
2031                                              runtime_visible_annotations_length,
2032                                              runtime_invisible_annotations,
2033                                              runtime_invisible_annotations_length,
2034                                              CHECK_(nullHandle));
2035   *method_parameter_annotations = assemble_annotations(runtime_visible_parameter_annotations,
2036                                                        runtime_visible_parameter_annotations_length,
2037                                                        runtime_invisible_parameter_annotations,
2038                                                        runtime_invisible_parameter_annotations_length,
2039                                                        CHECK_(nullHandle));
2040   *method_default_annotations = assemble_annotations(annotation_default,
2041                                                      annotation_default_length,
2042                                                      NULL,
2043                                                      0,
2044                                                      CHECK_(nullHandle));
2045 
2046   if (name() == vmSymbols::finalize_method_name() &&
2047       signature() == vmSymbols::void_method_signature()) {
2048     if (m->is_empty_method()) {
2049       _has_empty_finalizer = true;
2050     } else {
2051       _has_finalizer = true;
2052     }
2053   }
2054   if (name() == vmSymbols::object_initializer_name() &&
2055       signature() == vmSymbols::void_method_signature() &&
2056       m->is_vanilla_constructor()) {
2057     _has_vanilla_constructor = true;
2058   }
2059 
2060   if (EnableMethodHandles && (m->is_method_handle_invoke() ||
2061                               m->is_method_handle_adapter())) {
2062     THROW_MSG_(vmSymbols::java_lang_VirtualMachineError(),
2063                "Method handle invokers must be defined internally to the VM", nullHandle);
2064   }
2065 
2066   return m;
2067 }
2068 
2069 
2070 // The promoted_flags parameter is used to pass relevant access_flags
2071 // from the methods back up to the containing klass. These flag values
2072 // are added to klass's access_flags.
2073 
2074 objArrayHandle ClassFileParser::parse_methods(constantPoolHandle cp, bool is_interface,
2075                                               AccessFlags* promoted_flags,
2076                                               bool* has_final_method,
2077                                               objArrayOop* methods_annotations_oop,
2078                                               objArrayOop* methods_parameter_annotations_oop,
2079                                               objArrayOop* methods_default_annotations_oop,
2080                                               TRAPS) {
2081   ClassFileStream* cfs = stream();
2082   objArrayHandle nullHandle;
2083   typeArrayHandle method_annotations;
2084   typeArrayHandle method_parameter_annotations;
2085   typeArrayHandle method_default_annotations;
2086   cfs->guarantee_more(2, CHECK_(nullHandle));  // length
2087   u2 length = cfs->get_u2_fast();
2088   if (length == 0) {
2089     return objArrayHandle(THREAD, Universe::the_empty_system_obj_array());
2090   } else {
2091     objArrayOop m = oopFactory::new_system_objArray(length, CHECK_(nullHandle));
2092     objArrayHandle methods(THREAD, m);
2093     HandleMark hm(THREAD);
2094     objArrayHandle methods_annotations;
2095     objArrayHandle methods_parameter_annotations;
2096     objArrayHandle methods_default_annotations;
2097     for (int index = 0; index < length; index++) {
2098       methodHandle method = parse_method(cp, is_interface,
2099                                          promoted_flags,
2100                                          &method_annotations,
2101                                          &method_parameter_annotations,
2102                                          &method_default_annotations,
2103                                          CHECK_(nullHandle));
2104       if (method->is_final()) {
2105         *has_final_method = true;
2106       }
2107       methods->obj_at_put(index, method());
2108       if (method_annotations.not_null()) {
2109         if (methods_annotations.is_null()) {
2110           objArrayOop md = oopFactory::new_system_objArray(length, CHECK_(nullHandle));
2111           methods_annotations = objArrayHandle(THREAD, md);
2112         }
2113         methods_annotations->obj_at_put(index, method_annotations());
2114       }
2115       if (method_parameter_annotations.not_null()) {
2116         if (methods_parameter_annotations.is_null()) {
2117           objArrayOop md = oopFactory::new_system_objArray(length, CHECK_(nullHandle));
2118           methods_parameter_annotations = objArrayHandle(THREAD, md);
2119         }
2120         methods_parameter_annotations->obj_at_put(index, method_parameter_annotations());
2121       }
2122       if (method_default_annotations.not_null()) {
2123         if (methods_default_annotations.is_null()) {
2124           objArrayOop md = oopFactory::new_system_objArray(length, CHECK_(nullHandle));
2125           methods_default_annotations = objArrayHandle(THREAD, md);
2126         }
2127         methods_default_annotations->obj_at_put(index, method_default_annotations());
2128       }
2129     }
2130     if (_need_verify && length > 1) {
2131       // Check duplicated methods
2132       ResourceMark rm(THREAD);
2133       NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
2134         THREAD, NameSigHash*, HASH_ROW_SIZE);
2135       initialize_hashtable(names_and_sigs);
2136       bool dup = false;
2137       {
2138         debug_only(No_Safepoint_Verifier nsv;)
2139         for (int i = 0; i < length; i++) {
2140           methodOop m = (methodOop)methods->obj_at(i);
2141           // If no duplicates, add name/signature in hashtable names_and_sigs.
2142           if (!put_after_lookup(m->name(), m->signature(), names_and_sigs)) {
2143             dup = true;
2144             break;
2145           }
2146         }
2147       }
2148       if (dup) {
2149         classfile_parse_error("Duplicate method name&signature in class file %s",
2150                               CHECK_(nullHandle));
2151       }
2152     }
2153 
2154     *methods_annotations_oop = methods_annotations();
2155     *methods_parameter_annotations_oop = methods_parameter_annotations();
2156     *methods_default_annotations_oop = methods_default_annotations();
2157 
2158     return methods;
2159   }
2160 }
2161 
2162 
2163 typeArrayHandle ClassFileParser::sort_methods(objArrayHandle methods,
2164                                               objArrayHandle methods_annotations,
2165                                               objArrayHandle methods_parameter_annotations,
2166                                               objArrayHandle methods_default_annotations,
2167                                               TRAPS) {
2168   typeArrayHandle nullHandle;
2169   int length = methods()->length();
2170   // If JVMTI original method ordering is enabled we have to
2171   // remember the original class file ordering.
2172   // We temporarily use the vtable_index field in the methodOop to store the
2173   // class file index, so we can read in after calling qsort.
2174   if (JvmtiExport::can_maintain_original_method_order()) {
2175     for (int index = 0; index < length; index++) {
2176       methodOop m = methodOop(methods->obj_at(index));
2177       assert(!m->valid_vtable_index(), "vtable index should not be set");
2178       m->set_vtable_index(index);
2179     }
2180   }
2181   // Sort method array by ascending method name (for faster lookups & vtable construction)
2182   // Note that the ordering is not alphabetical, see symbolOopDesc::fast_compare
2183   methodOopDesc::sort_methods(methods(),
2184                               methods_annotations(),
2185                               methods_parameter_annotations(),
2186                               methods_default_annotations());
2187 
2188   // If JVMTI original method ordering is enabled construct int array remembering the original ordering
2189   if (JvmtiExport::can_maintain_original_method_order()) {
2190     typeArrayOop new_ordering = oopFactory::new_permanent_intArray(length, CHECK_(nullHandle));
2191     typeArrayHandle method_ordering(THREAD, new_ordering);
2192     for (int index = 0; index < length; index++) {
2193       methodOop m = methodOop(methods->obj_at(index));
2194       int old_index = m->vtable_index();
2195       assert(old_index >= 0 && old_index < length, "invalid method index");
2196       method_ordering->int_at_put(index, old_index);
2197       m->set_vtable_index(methodOopDesc::invalid_vtable_index);
2198     }
2199     return method_ordering;
2200   } else {
2201     return typeArrayHandle(THREAD, Universe::the_empty_int_array());
2202   }
2203 }
2204 
2205 
2206 void ClassFileParser::parse_classfile_sourcefile_attribute(constantPoolHandle cp, instanceKlassHandle k, TRAPS) {
2207   ClassFileStream* cfs = stream();
2208   cfs->guarantee_more(2, CHECK);  // sourcefile_index
2209   u2 sourcefile_index = cfs->get_u2_fast();
2210   check_property(
2211     valid_cp_range(sourcefile_index, cp->length()) &&
2212       cp->tag_at(sourcefile_index).is_utf8(),
2213     "Invalid SourceFile attribute at constant pool index %u in class file %s",
2214     sourcefile_index, CHECK);
2215   k->set_source_file_name(cp->symbol_at(sourcefile_index));
2216 }
2217 
2218 
2219 
2220 void ClassFileParser::parse_classfile_source_debug_extension_attribute(constantPoolHandle cp,
2221                                                                        instanceKlassHandle k,
2222                                                                        int length, TRAPS) {
2223   ClassFileStream* cfs = stream();
2224   u1* sde_buffer = cfs->get_u1_buffer();
2225   assert(sde_buffer != NULL, "null sde buffer");
2226 
2227   // Don't bother storing it if there is no way to retrieve it
2228   if (JvmtiExport::can_get_source_debug_extension()) {
2229     // Optimistically assume that only 1 byte UTF format is used
2230     // (common case)
2231     symbolOop sde_symbol = oopFactory::new_symbol((char*)sde_buffer,
2232                                                   length, CHECK);
2233     k->set_source_debug_extension(sde_symbol);
2234   }
2235   // Got utf8 string, set stream position forward
2236   cfs->skip_u1(length, CHECK);
2237 }
2238 
2239 
2240 // Inner classes can be static, private or protected (classic VM does this)
2241 #define RECOGNIZED_INNER_CLASS_MODIFIERS (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED | JVM_ACC_STATIC)
2242 
2243 // Return number of classes in the inner classes attribute table
2244 u2 ClassFileParser::parse_classfile_inner_classes_attribute(constantPoolHandle cp, instanceKlassHandle k, TRAPS) {
2245   ClassFileStream* cfs = stream();
2246   cfs->guarantee_more(2, CHECK_0);  // length
2247   u2 length = cfs->get_u2_fast();
2248 
2249   // 4-tuples of shorts [inner_class_info_index, outer_class_info_index, inner_name_index, inner_class_access_flags]
2250   typeArrayOop ic = oopFactory::new_permanent_shortArray(length*4, CHECK_0);
2251   typeArrayHandle inner_classes(THREAD, ic);
2252   int index = 0;
2253   int cp_size = cp->length();
2254   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
2255   for (int n = 0; n < length; n++) {
2256     // Inner class index
2257     u2 inner_class_info_index = cfs->get_u2_fast();
2258     check_property(
2259       inner_class_info_index == 0 ||
2260         (valid_cp_range(inner_class_info_index, cp_size) &&
2261         is_klass_reference(cp, inner_class_info_index)),
2262       "inner_class_info_index %u has bad constant type in class file %s",
2263       inner_class_info_index, CHECK_0);
2264     // Outer class index
2265     u2 outer_class_info_index = cfs->get_u2_fast();
2266     check_property(
2267       outer_class_info_index == 0 ||
2268         (valid_cp_range(outer_class_info_index, cp_size) &&
2269         is_klass_reference(cp, outer_class_info_index)),
2270       "outer_class_info_index %u has bad constant type in class file %s",
2271       outer_class_info_index, CHECK_0);
2272     // Inner class name
2273     u2 inner_name_index = cfs->get_u2_fast();
2274     check_property(
2275       inner_name_index == 0 || (valid_cp_range(inner_name_index, cp_size) &&
2276         cp->tag_at(inner_name_index).is_utf8()),
2277       "inner_name_index %u has bad constant type in class file %s",
2278       inner_name_index, CHECK_0);
2279     if (_need_verify) {
2280       guarantee_property(inner_class_info_index != outer_class_info_index,
2281                          "Class is both outer and inner class in class file %s", CHECK_0);
2282     }
2283     // Access flags
2284     AccessFlags inner_access_flags;
2285     jint flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
2286     if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
2287       // Set abstract bit for old class files for backward compatibility
2288       flags |= JVM_ACC_ABSTRACT;
2289     }
2290     verify_legal_class_modifiers(flags, CHECK_0);
2291     inner_access_flags.set_flags(flags);
2292 
2293     inner_classes->short_at_put(index++, inner_class_info_index);
2294     inner_classes->short_at_put(index++, outer_class_info_index);
2295     inner_classes->short_at_put(index++, inner_name_index);
2296     inner_classes->short_at_put(index++, inner_access_flags.as_short());
2297   }
2298 
2299   // 4347400: make sure there's no duplicate entry in the classes array
2300   if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
2301     for(int i = 0; i < inner_classes->length(); i += 4) {
2302       for(int j = i + 4; j < inner_classes->length(); j += 4) {
2303         guarantee_property((inner_classes->ushort_at(i)   != inner_classes->ushort_at(j) ||
2304                             inner_classes->ushort_at(i+1) != inner_classes->ushort_at(j+1) ||
2305                             inner_classes->ushort_at(i+2) != inner_classes->ushort_at(j+2) ||
2306                             inner_classes->ushort_at(i+3) != inner_classes->ushort_at(j+3)),
2307                             "Duplicate entry in InnerClasses in class file %s",
2308                             CHECK_0);
2309       }
2310     }
2311   }
2312 
2313   // Update instanceKlass with inner class info.
2314   k->set_inner_classes(inner_classes());
2315   return length;
2316 }
2317 
2318 void ClassFileParser::parse_classfile_synthetic_attribute(constantPoolHandle cp, instanceKlassHandle k, TRAPS) {
2319   k->set_is_synthetic();
2320 }
2321 
2322 void ClassFileParser::parse_classfile_signature_attribute(constantPoolHandle cp, instanceKlassHandle k, TRAPS) {
2323   ClassFileStream* cfs = stream();
2324   u2 signature_index = cfs->get_u2(CHECK);
2325   check_property(
2326     valid_cp_range(signature_index, cp->length()) &&
2327       cp->tag_at(signature_index).is_utf8(),
2328     "Invalid constant pool index %u in Signature attribute in class file %s",
2329     signature_index, CHECK);
2330   k->set_generic_signature(cp->symbol_at(signature_index));
2331 }
2332 
2333 void ClassFileParser::parse_classfile_attributes(constantPoolHandle cp, instanceKlassHandle k, TRAPS) {
2334   ClassFileStream* cfs = stream();
2335   // Set inner classes attribute to default sentinel
2336   k->set_inner_classes(Universe::the_empty_short_array());
2337   cfs->guarantee_more(2, CHECK);  // attributes_count
2338   u2 attributes_count = cfs->get_u2_fast();
2339   bool parsed_sourcefile_attribute = false;
2340   bool parsed_innerclasses_attribute = false;
2341   bool parsed_enclosingmethod_attribute = false;
2342   u1* runtime_visible_annotations = NULL;
2343   int runtime_visible_annotations_length = 0;
2344   u1* runtime_invisible_annotations = NULL;
2345   int runtime_invisible_annotations_length = 0;
2346   // Iterate over attributes
2347   while (attributes_count--) {
2348     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
2349     u2 attribute_name_index = cfs->get_u2_fast();
2350     u4 attribute_length = cfs->get_u4_fast();
2351     check_property(
2352       valid_cp_range(attribute_name_index, cp->length()) &&
2353         cp->tag_at(attribute_name_index).is_utf8(),
2354       "Attribute name has bad constant pool index %u in class file %s",
2355       attribute_name_index, CHECK);
2356     symbolOop tag = cp->symbol_at(attribute_name_index);
2357     if (tag == vmSymbols::tag_source_file()) {
2358       // Check for SourceFile tag
2359       if (_need_verify) {
2360         guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
2361       }
2362       if (parsed_sourcefile_attribute) {
2363         classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
2364       } else {
2365         parsed_sourcefile_attribute = true;
2366       }
2367       parse_classfile_sourcefile_attribute(cp, k, CHECK);
2368     } else if (tag == vmSymbols::tag_source_debug_extension()) {
2369       // Check for SourceDebugExtension tag
2370       parse_classfile_source_debug_extension_attribute(cp, k, (int)attribute_length, CHECK);
2371     } else if (tag == vmSymbols::tag_inner_classes()) {
2372       // Check for InnerClasses tag
2373       if (parsed_innerclasses_attribute) {
2374         classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
2375       } else {
2376         parsed_innerclasses_attribute = true;
2377       }
2378       u2 num_of_classes = parse_classfile_inner_classes_attribute(cp, k, CHECK);
2379       if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
2380         guarantee_property(attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
2381                           "Wrong InnerClasses attribute length in class file %s", CHECK);
2382       }
2383     } else if (tag == vmSymbols::tag_synthetic()) {
2384       // Check for Synthetic tag
2385       // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
2386       if (attribute_length != 0) {
2387         classfile_parse_error(
2388           "Invalid Synthetic classfile attribute length %u in class file %s",
2389           attribute_length, CHECK);
2390       }
2391       parse_classfile_synthetic_attribute(cp, k, CHECK);
2392     } else if (tag == vmSymbols::tag_deprecated()) {
2393       // Check for Deprecatd tag - 4276120
2394       if (attribute_length != 0) {
2395         classfile_parse_error(
2396           "Invalid Deprecated classfile attribute length %u in class file %s",
2397           attribute_length, CHECK);
2398       }
2399     } else if (_major_version >= JAVA_1_5_VERSION) {
2400       if (tag == vmSymbols::tag_signature()) {
2401         if (attribute_length != 2) {
2402           classfile_parse_error(
2403             "Wrong Signature attribute length %u in class file %s",
2404             attribute_length, CHECK);
2405         }
2406         parse_classfile_signature_attribute(cp, k, CHECK);
2407       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
2408         runtime_visible_annotations_length = attribute_length;
2409         runtime_visible_annotations = cfs->get_u1_buffer();
2410         assert(runtime_visible_annotations != NULL, "null visible annotations");
2411         cfs->skip_u1(runtime_visible_annotations_length, CHECK);
2412       } else if (PreserveAllAnnotations && tag == vmSymbols::tag_runtime_invisible_annotations()) {
2413         runtime_invisible_annotations_length = attribute_length;
2414         runtime_invisible_annotations = cfs->get_u1_buffer();
2415         assert(runtime_invisible_annotations != NULL, "null invisible annotations");
2416         cfs->skip_u1(runtime_invisible_annotations_length, CHECK);
2417       } else if (tag == vmSymbols::tag_enclosing_method()) {
2418         if (parsed_enclosingmethod_attribute) {
2419           classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
2420         }   else {
2421           parsed_enclosingmethod_attribute = true;
2422         }
2423         cfs->guarantee_more(4, CHECK);  // class_index, method_index
2424         u2 class_index  = cfs->get_u2_fast();
2425         u2 method_index = cfs->get_u2_fast();
2426         if (class_index == 0) {
2427           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
2428         }
2429         // Validate the constant pool indices and types
2430         if (!cp->is_within_bounds(class_index) ||
2431             !is_klass_reference(cp, class_index)) {
2432           classfile_parse_error("Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
2433         }
2434         if (method_index != 0 &&
2435             (!cp->is_within_bounds(method_index) ||
2436              !cp->tag_at(method_index).is_name_and_type())) {
2437           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
2438         }
2439         k->set_enclosing_method_indices(class_index, method_index);
2440       } else {
2441         // Unknown attribute
2442         cfs->skip_u1(attribute_length, CHECK);
2443       }
2444     } else {
2445       // Unknown attribute
2446       cfs->skip_u1(attribute_length, CHECK);
2447     }
2448   }
2449   typeArrayHandle annotations = assemble_annotations(runtime_visible_annotations,
2450                                                      runtime_visible_annotations_length,
2451                                                      runtime_invisible_annotations,
2452                                                      runtime_invisible_annotations_length,
2453                                                      CHECK);
2454   k->set_class_annotations(annotations());
2455 }
2456 
2457 
2458 typeArrayHandle ClassFileParser::assemble_annotations(u1* runtime_visible_annotations,
2459                                                       int runtime_visible_annotations_length,
2460                                                       u1* runtime_invisible_annotations,
2461                                                       int runtime_invisible_annotations_length, TRAPS) {
2462   typeArrayHandle annotations;
2463   if (runtime_visible_annotations != NULL ||
2464       runtime_invisible_annotations != NULL) {
2465     typeArrayOop anno = oopFactory::new_permanent_byteArray(runtime_visible_annotations_length +
2466                                                             runtime_invisible_annotations_length, CHECK_(annotations));
2467     annotations = typeArrayHandle(THREAD, anno);
2468     if (runtime_visible_annotations != NULL) {
2469       memcpy(annotations->byte_at_addr(0), runtime_visible_annotations, runtime_visible_annotations_length);
2470     }
2471     if (runtime_invisible_annotations != NULL) {
2472       memcpy(annotations->byte_at_addr(runtime_visible_annotations_length), runtime_invisible_annotations, runtime_invisible_annotations_length);
2473     }
2474   }
2475   return annotations;
2476 }
2477 
2478 
2479 static void initialize_static_field(fieldDescriptor* fd, TRAPS) {
2480   KlassHandle h_k (THREAD, fd->field_holder());
2481   assert(h_k.not_null() && fd->is_static(), "just checking");
2482   if (fd->has_initial_value()) {
2483     BasicType t = fd->field_type();
2484     switch (t) {
2485       case T_BYTE:
2486         h_k()->byte_field_put(fd->offset(), fd->int_initial_value());
2487               break;
2488       case T_BOOLEAN:
2489         h_k()->bool_field_put(fd->offset(), fd->int_initial_value());
2490               break;
2491       case T_CHAR:
2492         h_k()->char_field_put(fd->offset(), fd->int_initial_value());
2493               break;
2494       case T_SHORT:
2495         h_k()->short_field_put(fd->offset(), fd->int_initial_value());
2496               break;
2497       case T_INT:
2498         h_k()->int_field_put(fd->offset(), fd->int_initial_value());
2499         break;
2500       case T_FLOAT:
2501         h_k()->float_field_put(fd->offset(), fd->float_initial_value());
2502         break;
2503       case T_DOUBLE:
2504         h_k()->double_field_put(fd->offset(), fd->double_initial_value());
2505         break;
2506       case T_LONG:
2507         h_k()->long_field_put(fd->offset(), fd->long_initial_value());
2508         break;
2509       case T_OBJECT:
2510         {
2511           #ifdef ASSERT
2512           symbolOop sym = oopFactory::new_symbol("Ljava/lang/String;", CHECK);
2513           assert(fd->signature() == sym, "just checking");
2514           #endif
2515           oop string = fd->string_initial_value(CHECK);
2516           h_k()->obj_field_put(fd->offset(), string);
2517         }
2518         break;
2519       default:
2520         THROW_MSG(vmSymbols::java_lang_ClassFormatError(),
2521                   "Illegal ConstantValue attribute in class file");
2522     }
2523   }
2524 }
2525 
2526 
2527 void ClassFileParser::java_lang_ref_Reference_fix_pre(typeArrayHandle* fields_ptr,
2528   constantPoolHandle cp, FieldAllocationCount *fac_ptr, TRAPS) {
2529   // This code is for compatibility with earlier jdk's that do not
2530   // have the "discovered" field in java.lang.ref.Reference.  For 1.5
2531   // the check for the "discovered" field should issue a warning if
2532   // the field is not found.  For 1.6 this code should be issue a
2533   // fatal error if the "discovered" field is not found.
2534   //
2535   // Increment fac.nonstatic_oop_count so that the start of the
2536   // next type of non-static oops leaves room for the fake oop.
2537   // Do not increment next_nonstatic_oop_offset so that the
2538   // fake oop is place after the java.lang.ref.Reference oop
2539   // fields.
2540   //
2541   // Check the fields in java.lang.ref.Reference for the "discovered"
2542   // field.  If it is not present, artifically create a field for it.
2543   // This allows this VM to run on early JDK where the field is not
2544   // present.
2545 
2546   //
2547   // Increment fac.nonstatic_oop_count so that the start of the
2548   // next type of non-static oops leaves room for the fake oop.
2549   // Do not increment next_nonstatic_oop_offset so that the
2550   // fake oop is place after the java.lang.ref.Reference oop
2551   // fields.
2552   //
2553   // Check the fields in java.lang.ref.Reference for the "discovered"
2554   // field.  If it is not present, artifically create a field for it.
2555   // This allows this VM to run on early JDK where the field is not
2556   // present.
2557   int reference_sig_index = 0;
2558   int reference_name_index = 0;
2559   int reference_index = 0;
2560   int extra = java_lang_ref_Reference::number_of_fake_oop_fields;
2561   const int n = (*fields_ptr)()->length();
2562   for (int i = 0; i < n; i += instanceKlass::next_offset ) {
2563     int name_index =
2564     (*fields_ptr)()->ushort_at(i + instanceKlass::name_index_offset);
2565     int sig_index  =
2566       (*fields_ptr)()->ushort_at(i + instanceKlass::signature_index_offset);
2567     symbolOop f_name = cp->symbol_at(name_index);
2568     symbolOop f_sig  = cp->symbol_at(sig_index);
2569     if (f_sig == vmSymbols::reference_signature() && reference_index == 0) {
2570       // Save the index for reference signature for later use.
2571       // The fake discovered field does not entries in the
2572       // constant pool so the index for its signature cannot
2573       // be extracted from the constant pool.  It will need
2574       // later, however.  It's signature is vmSymbols::reference_signature()
2575       // so same an index for that signature.
2576       reference_sig_index = sig_index;
2577       reference_name_index = name_index;
2578       reference_index = i;
2579     }
2580     if (f_name == vmSymbols::reference_discovered_name() &&
2581       f_sig == vmSymbols::reference_signature()) {
2582       // The values below are fake but will force extra
2583       // non-static oop fields and a corresponding non-static
2584       // oop map block to be allocated.
2585       extra = 0;
2586       break;
2587     }
2588   }
2589   if (extra != 0) {
2590     fac_ptr->nonstatic_oop_count += extra;
2591     // Add the additional entry to "fields" so that the klass
2592     // contains the "discoverd" field and the field will be initialized
2593     // in instances of the object.
2594     int fields_with_fix_length = (*fields_ptr)()->length() +
2595       instanceKlass::next_offset;
2596     typeArrayOop ff = oopFactory::new_permanent_shortArray(
2597                                                 fields_with_fix_length, CHECK);
2598     typeArrayHandle fields_with_fix(THREAD, ff);
2599 
2600     // Take everything from the original but the length.
2601     for (int idx = 0; idx < (*fields_ptr)->length(); idx++) {
2602       fields_with_fix->ushort_at_put(idx, (*fields_ptr)->ushort_at(idx));
2603     }
2604 
2605     // Add the fake field at the end.
2606     int i = (*fields_ptr)->length();
2607     // There is no name index for the fake "discovered" field nor
2608     // signature but a signature is needed so that the field will
2609     // be properly initialized.  Use one found for
2610     // one of the other reference fields. Be sure the index for the
2611     // name is 0.  In fieldDescriptor::initialize() the index of the
2612     // name is checked.  That check is by passed for the last nonstatic
2613     // oop field in a java.lang.ref.Reference which is assumed to be
2614     // this artificial "discovered" field.  An assertion checks that
2615     // the name index is 0.
2616     assert(reference_index != 0, "Missing signature for reference");
2617 
2618     int j;
2619     for (j = 0; j < instanceKlass::next_offset; j++) {
2620       fields_with_fix->ushort_at_put(i + j,
2621         (*fields_ptr)->ushort_at(reference_index +j));
2622     }
2623     // Clear the public access flag and set the private access flag.
2624     short flags;
2625     flags =
2626       fields_with_fix->ushort_at(i + instanceKlass::access_flags_offset);
2627     assert(!(flags & JVM_RECOGNIZED_FIELD_MODIFIERS), "Unexpected access flags set");
2628     flags = flags & (~JVM_ACC_PUBLIC);
2629     flags = flags | JVM_ACC_PRIVATE;
2630     AccessFlags access_flags;
2631     access_flags.set_flags(flags);
2632     assert(!access_flags.is_public(), "Failed to clear public flag");
2633     assert(access_flags.is_private(), "Failed to set private flag");
2634     fields_with_fix->ushort_at_put(i + instanceKlass::access_flags_offset,
2635       flags);
2636 
2637     assert(fields_with_fix->ushort_at(i + instanceKlass::name_index_offset)
2638       == reference_name_index, "The fake reference name is incorrect");
2639     assert(fields_with_fix->ushort_at(i + instanceKlass::signature_index_offset)
2640       == reference_sig_index, "The fake reference signature is incorrect");
2641     // The type of the field is stored in the low_offset entry during
2642     // parsing.
2643     assert(fields_with_fix->ushort_at(i + instanceKlass::low_offset) ==
2644       NONSTATIC_OOP, "The fake reference type is incorrect");
2645 
2646     // "fields" is allocated in the permanent generation.  Disgard
2647     // it and let it be collected.
2648     (*fields_ptr) = fields_with_fix;
2649   }
2650   return;
2651 }
2652 
2653 
2654 void ClassFileParser::java_lang_Class_fix_pre(objArrayHandle* methods_ptr,
2655   FieldAllocationCount *fac_ptr, TRAPS) {
2656   // Add fake fields for java.lang.Class instances
2657   //
2658   // This is not particularly nice. We should consider adding a
2659   // private transient object field at the Java level to
2660   // java.lang.Class. Alternatively we could add a subclass of
2661   // instanceKlass which provides an accessor and size computer for
2662   // this field, but that appears to be more code than this hack.
2663   //
2664   // NOTE that we wedge these in at the beginning rather than the
2665   // end of the object because the Class layout changed between JDK
2666   // 1.3 and JDK 1.4 with the new reflection implementation; some
2667   // nonstatic oop fields were added at the Java level. The offsets
2668   // of these fake fields can't change between these two JDK
2669   // versions because when the offsets are computed at bootstrap
2670   // time we don't know yet which version of the JDK we're running in.
2671 
2672   // The values below are fake but will force two non-static oop fields and
2673   // a corresponding non-static oop map block to be allocated.
2674   const int extra = java_lang_Class::number_of_fake_oop_fields;
2675   fac_ptr->nonstatic_oop_count += extra;
2676 }
2677 
2678 
2679 void ClassFileParser::java_lang_Class_fix_post(int* next_nonstatic_oop_offset_ptr) {
2680   // Cause the extra fake fields in java.lang.Class to show up before
2681   // the Java fields for layout compatibility between 1.3 and 1.4
2682   // Incrementing next_nonstatic_oop_offset here advances the
2683   // location where the real java fields are placed.
2684   const int extra = java_lang_Class::number_of_fake_oop_fields;
2685   (*next_nonstatic_oop_offset_ptr) += (extra * heapOopSize);
2686 }
2687 
2688 
2689 // Force MethodHandle.vmentry to be an unmanaged pointer.
2690 // There is no way for a classfile to express this, so we must help it.
2691 void ClassFileParser::java_dyn_MethodHandle_fix_pre(constantPoolHandle cp,
2692                                                     typeArrayHandle* fields_ptr,
2693                                                     FieldAllocationCount *fac_ptr,
2694                                                     TRAPS) {
2695   // Add fake fields for java.dyn.MethodHandle instances
2696   //
2697   // This is not particularly nice, but since there is no way to express
2698   // a native wordSize field in Java, we must do it at this level.
2699 
2700   if (!EnableMethodHandles)  return;
2701 
2702   int word_sig_index = 0;
2703   const int cp_size = cp->length();
2704   for (int index = 1; index < cp_size; index++) {
2705     if (cp->tag_at(index).is_utf8() &&
2706         cp->symbol_at(index) == vmSymbols::machine_word_signature()) {
2707       word_sig_index = index;
2708       break;
2709     }
2710   }
2711 
2712   if (word_sig_index == 0)
2713     THROW_MSG(vmSymbols::java_lang_VirtualMachineError(),
2714               "missing I or J signature (for vmentry) in java.dyn.MethodHandle");
2715 
2716   bool found_vmentry = false;
2717 
2718   const int n = (*fields_ptr)()->length();
2719   for (int i = 0; i < n; i += instanceKlass::next_offset) {
2720     int name_index = (*fields_ptr)->ushort_at(i + instanceKlass::name_index_offset);
2721     int sig_index  = (*fields_ptr)->ushort_at(i + instanceKlass::signature_index_offset);
2722     int acc_flags  = (*fields_ptr)->ushort_at(i + instanceKlass::access_flags_offset);
2723     symbolOop f_name = cp->symbol_at(name_index);
2724     symbolOop f_sig  = cp->symbol_at(sig_index);
2725     if (f_sig == vmSymbols::byte_signature() &&
2726         f_name == vmSymbols::vmentry_name() &&
2727         (acc_flags & JVM_ACC_STATIC) == 0) {
2728       // Adjust the field type from byte to an unmanaged pointer.
2729       assert(fac_ptr->nonstatic_byte_count > 0, "");
2730       fac_ptr->nonstatic_byte_count -= 1;
2731 
2732       (*fields_ptr)->ushort_at_put(i + instanceKlass::signature_index_offset, word_sig_index);
2733       assert(wordSize == longSize || wordSize == jintSize, "ILP32 or LP64");
2734       if (wordSize == longSize)  fac_ptr->nonstatic_double_count += 1;
2735       else                       fac_ptr->nonstatic_word_count   += 1;
2736 
2737       FieldAllocationType atype = (FieldAllocationType) (*fields_ptr)->ushort_at(i + instanceKlass::low_offset);
2738       assert(atype == NONSTATIC_BYTE, "");
2739       FieldAllocationType new_atype = (wordSize == longSize) ? NONSTATIC_DOUBLE : NONSTATIC_WORD;
2740       (*fields_ptr)->ushort_at_put(i + instanceKlass::low_offset, new_atype);
2741 
2742       found_vmentry = true;
2743       break;
2744     }
2745   }
2746 
2747   if (!found_vmentry)
2748     THROW_MSG(vmSymbols::java_lang_VirtualMachineError(),
2749               "missing vmentry byte field in java.dyn.MethodHandle");
2750 
2751 }
2752 
2753 
2754 instanceKlassHandle ClassFileParser::parseClassFile(symbolHandle name,
2755                                                     Handle class_loader,
2756                                                     Handle protection_domain,
2757                                                     KlassHandle host_klass,
2758                                                     GrowableArray<Handle>* cp_patches,
2759                                                     symbolHandle& parsed_name,
2760                                                     bool verify,
2761                                                     TRAPS) {
2762   // So that JVMTI can cache class file in the state before retransformable agents
2763   // have modified it
2764   unsigned char *cached_class_file_bytes = NULL;
2765   jint cached_class_file_length;
2766 
2767   ClassFileStream* cfs = stream();
2768   // Timing
2769   assert(THREAD->is_Java_thread(), "must be a JavaThread");
2770   JavaThread* jt = (JavaThread*) THREAD;
2771 
2772   PerfClassTraceTime ctimer(ClassLoader::perf_class_parse_time(),
2773                             ClassLoader::perf_class_parse_selftime(),
2774                             NULL,
2775                             jt->get_thread_stat()->perf_recursion_counts_addr(),
2776                             jt->get_thread_stat()->perf_timers_addr(),
2777                             PerfClassTraceTime::PARSE_CLASS);
2778 
2779   _has_finalizer = _has_empty_finalizer = _has_vanilla_constructor = false;
2780 
2781   if (JvmtiExport::should_post_class_file_load_hook()) {
2782     unsigned char* ptr = cfs->buffer();
2783     unsigned char* end_ptr = cfs->buffer() + cfs->length();
2784 
2785     JvmtiExport::post_class_file_load_hook(name, class_loader, protection_domain,
2786                                            &ptr, &end_ptr,
2787                                            &cached_class_file_bytes,
2788                                            &cached_class_file_length);
2789 
2790     if (ptr != cfs->buffer()) {
2791       // JVMTI agent has modified class file data.
2792       // Set new class file stream using JVMTI agent modified
2793       // class file data.
2794       cfs = new ClassFileStream(ptr, end_ptr - ptr, cfs->source());
2795       set_stream(cfs);
2796     }
2797   }
2798 
2799   _host_klass = host_klass;
2800   _cp_patches = cp_patches;
2801 
2802   instanceKlassHandle nullHandle;
2803 
2804   // Figure out whether we can skip format checking (matching classic VM behavior)
2805   _need_verify = Verifier::should_verify_for(class_loader(), verify);
2806 
2807   // Set the verify flag in stream
2808   cfs->set_verify(_need_verify);
2809 
2810   // Save the class file name for easier error message printing.
2811   _class_name = name.not_null()? name : vmSymbolHandles::unknown_class_name();
2812 
2813   cfs->guarantee_more(8, CHECK_(nullHandle));  // magic, major, minor
2814   // Magic value
2815   u4 magic = cfs->get_u4_fast();
2816   guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
2817                      "Incompatible magic value %u in class file %s",
2818                      magic, CHECK_(nullHandle));
2819 
2820   // Version numbers
2821   u2 minor_version = cfs->get_u2_fast();
2822   u2 major_version = cfs->get_u2_fast();
2823 
2824   // Check version numbers - we check this even with verifier off
2825   if (!is_supported_version(major_version, minor_version)) {
2826     if (name.is_null()) {
2827       Exceptions::fthrow(
2828         THREAD_AND_LOCATION,
2829         vmSymbolHandles::java_lang_UnsupportedClassVersionError(),
2830         "Unsupported major.minor version %u.%u",
2831         major_version,
2832         minor_version);
2833     } else {
2834       ResourceMark rm(THREAD);
2835       Exceptions::fthrow(
2836         THREAD_AND_LOCATION,
2837         vmSymbolHandles::java_lang_UnsupportedClassVersionError(),
2838         "%s : Unsupported major.minor version %u.%u",
2839         name->as_C_string(),
2840         major_version,
2841         minor_version);
2842     }
2843     return nullHandle;
2844   }
2845 
2846   _major_version = major_version;
2847   _minor_version = minor_version;
2848 
2849 
2850   // Check if verification needs to be relaxed for this class file
2851   // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
2852   _relax_verify = Verifier::relax_verify_for(class_loader());
2853 
2854   // Constant pool
2855   constantPoolHandle cp = parse_constant_pool(CHECK_(nullHandle));
2856   int cp_size = cp->length();
2857 
2858   cfs->guarantee_more(8, CHECK_(nullHandle));  // flags, this_class, super_class, infs_len
2859 
2860   // Access flags
2861   AccessFlags access_flags;
2862   jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;
2863 
2864   if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
2865     // Set abstract bit for old class files for backward compatibility
2866     flags |= JVM_ACC_ABSTRACT;
2867   }
2868   verify_legal_class_modifiers(flags, CHECK_(nullHandle));
2869   access_flags.set_flags(flags);
2870 
2871   // This class and superclass
2872   instanceKlassHandle super_klass;
2873   u2 this_class_index = cfs->get_u2_fast();
2874   check_property(
2875     valid_cp_range(this_class_index, cp_size) &&
2876       cp->tag_at(this_class_index).is_unresolved_klass(),
2877     "Invalid this class index %u in constant pool in class file %s",
2878     this_class_index, CHECK_(nullHandle));
2879 
2880   symbolHandle class_name (THREAD, cp->unresolved_klass_at(this_class_index));
2881   assert(class_name.not_null(), "class_name can't be null");
2882 
2883   // It's important to set parsed_name *before* resolving the super class.
2884   // (it's used for cleanup by the caller if parsing fails)
2885   parsed_name = class_name;
2886 
2887   // Update _class_name which could be null previously to be class_name
2888   _class_name = class_name;
2889 
2890   // Don't need to check whether this class name is legal or not.
2891   // It has been checked when constant pool is parsed.
2892   // However, make sure it is not an array type.
2893   if (_need_verify) {
2894     guarantee_property(class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
2895                        "Bad class name in class file %s",
2896                        CHECK_(nullHandle));
2897   }
2898 
2899   klassOop preserve_this_klass;   // for storing result across HandleMark
2900 
2901   // release all handles when parsing is done
2902   { HandleMark hm(THREAD);
2903 
2904     // Checks if name in class file matches requested name
2905     if (name.not_null() && class_name() != name()) {
2906       ResourceMark rm(THREAD);
2907       Exceptions::fthrow(
2908         THREAD_AND_LOCATION,
2909         vmSymbolHandles::java_lang_NoClassDefFoundError(),
2910         "%s (wrong name: %s)",
2911         name->as_C_string(),
2912         class_name->as_C_string()
2913       );
2914       return nullHandle;
2915     }
2916 
2917     if (TraceClassLoadingPreorder) {
2918       tty->print("[Loading %s", name()->as_klass_external_name());
2919       if (cfs->source() != NULL) tty->print(" from %s", cfs->source());
2920       tty->print_cr("]");
2921     }
2922 
2923     u2 super_class_index = cfs->get_u2_fast();
2924     if (super_class_index == 0) {
2925       check_property(class_name() == vmSymbols::java_lang_Object(),
2926                      "Invalid superclass index %u in class file %s",
2927                      super_class_index,
2928                      CHECK_(nullHandle));
2929     } else {
2930       check_property(valid_cp_range(super_class_index, cp_size) &&
2931                      is_klass_reference(cp, super_class_index),
2932                      "Invalid superclass index %u in class file %s",
2933                      super_class_index,
2934                      CHECK_(nullHandle));
2935       // The class name should be legal because it is checked when parsing constant pool.
2936       // However, make sure it is not an array type.
2937       bool is_array = false;
2938       if (cp->tag_at(super_class_index).is_klass()) {
2939         super_klass = instanceKlassHandle(THREAD, cp->resolved_klass_at(super_class_index));
2940         if (_need_verify)
2941           is_array = super_klass->oop_is_array();
2942       } else if (_need_verify) {
2943         is_array = (cp->unresolved_klass_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
2944       }
2945       if (_need_verify) {
2946         guarantee_property(!is_array,
2947                           "Bad superclass name in class file %s", CHECK_(nullHandle));
2948       }
2949     }
2950 
2951     // Interfaces
2952     u2 itfs_len = cfs->get_u2_fast();
2953     objArrayHandle local_interfaces;
2954     if (itfs_len == 0) {
2955       local_interfaces = objArrayHandle(THREAD, Universe::the_empty_system_obj_array());
2956     } else {
2957       local_interfaces = parse_interfaces(cp, itfs_len, class_loader, protection_domain, _class_name, CHECK_(nullHandle));
2958     }
2959 
2960     // Fields (offsets are filled in later)
2961     struct FieldAllocationCount fac = {0,0,0,0,0,0,0,0,0,0};
2962     objArrayHandle fields_annotations;
2963     typeArrayHandle fields = parse_fields(cp, access_flags.is_interface(), &fac, &fields_annotations, CHECK_(nullHandle));
2964     // Methods
2965     bool has_final_method = false;
2966     AccessFlags promoted_flags;
2967     promoted_flags.set_flags(0);
2968     // These need to be oop pointers because they are allocated lazily
2969     // inside parse_methods inside a nested HandleMark
2970     objArrayOop methods_annotations_oop = NULL;
2971     objArrayOop methods_parameter_annotations_oop = NULL;
2972     objArrayOop methods_default_annotations_oop = NULL;
2973     objArrayHandle methods = parse_methods(cp, access_flags.is_interface(),
2974                                            &promoted_flags,
2975                                            &has_final_method,
2976                                            &methods_annotations_oop,
2977                                            &methods_parameter_annotations_oop,
2978                                            &methods_default_annotations_oop,
2979                                            CHECK_(nullHandle));
2980 
2981     objArrayHandle methods_annotations(THREAD, methods_annotations_oop);
2982     objArrayHandle methods_parameter_annotations(THREAD, methods_parameter_annotations_oop);
2983     objArrayHandle methods_default_annotations(THREAD, methods_default_annotations_oop);
2984 
2985     // We check super class after class file is parsed and format is checked
2986     if (super_class_index > 0 && super_klass.is_null()) {
2987       symbolHandle sk (THREAD, cp->klass_name_at(super_class_index));
2988       if (access_flags.is_interface()) {
2989         // Before attempting to resolve the superclass, check for class format
2990         // errors not checked yet.
2991         guarantee_property(sk() == vmSymbols::java_lang_Object(),
2992                            "Interfaces must have java.lang.Object as superclass in class file %s",
2993                            CHECK_(nullHandle));
2994       }
2995       klassOop k = SystemDictionary::resolve_super_or_fail(class_name,
2996                                                            sk,
2997                                                            class_loader,
2998                                                            protection_domain,
2999                                                            true,
3000                                                            CHECK_(nullHandle));
3001 
3002       KlassHandle kh (THREAD, k);
3003       super_klass = instanceKlassHandle(THREAD, kh());
3004       if (LinkWellKnownClasses)  // my super class is well known to me
3005         cp->klass_at_put(super_class_index, super_klass()); // eagerly resolve
3006     }
3007     if (super_klass.not_null()) {
3008       if (super_klass->is_interface()) {
3009         ResourceMark rm(THREAD);
3010         Exceptions::fthrow(
3011           THREAD_AND_LOCATION,
3012           vmSymbolHandles::java_lang_IncompatibleClassChangeError(),
3013           "class %s has interface %s as super class",
3014           class_name->as_klass_external_name(),
3015           super_klass->external_name()
3016         );
3017         return nullHandle;
3018       }
3019       // Make sure super class is not final
3020       if (super_klass->is_final()) {
3021         THROW_MSG_(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class", nullHandle);
3022       }
3023     }
3024 
3025     // Compute the transitive list of all unique interfaces implemented by this class
3026     objArrayHandle transitive_interfaces = compute_transitive_interfaces(super_klass, local_interfaces, CHECK_(nullHandle));
3027 
3028     // sort methods
3029     typeArrayHandle method_ordering = sort_methods(methods,
3030                                                    methods_annotations,
3031                                                    methods_parameter_annotations,
3032                                                    methods_default_annotations,
3033                                                    CHECK_(nullHandle));
3034 
3035     // promote flags from parse_methods() to the klass' flags
3036     access_flags.add_promoted_flags(promoted_flags.as_int());
3037 
3038     // Size of Java vtable (in words)
3039     int vtable_size = 0;
3040     int itable_size = 0;
3041     int num_miranda_methods = 0;
3042 
3043     klassVtable::compute_vtable_size_and_num_mirandas(vtable_size,
3044                                                       num_miranda_methods,
3045                                                       super_klass(),
3046                                                       methods(),
3047                                                       access_flags,
3048                                                       class_loader,
3049                                                       class_name,
3050                                                       local_interfaces(),
3051                                                       CHECK_(nullHandle));
3052 
3053     // Size of Java itable (in words)
3054     itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(transitive_interfaces);
3055 
3056     // Field size and offset computation
3057     int nonstatic_field_size = super_klass() == NULL ? 0 : super_klass->nonstatic_field_size();
3058 #ifndef PRODUCT
3059     int orig_nonstatic_field_size = 0;
3060 #endif
3061     int static_field_size = 0;
3062     int next_static_oop_offset;
3063     int next_static_double_offset;
3064     int next_static_word_offset;
3065     int next_static_short_offset;
3066     int next_static_byte_offset;
3067     int next_static_type_offset;
3068     int next_nonstatic_oop_offset;
3069     int next_nonstatic_double_offset;
3070     int next_nonstatic_word_offset;
3071     int next_nonstatic_short_offset;
3072     int next_nonstatic_byte_offset;
3073     int next_nonstatic_type_offset;
3074     int first_nonstatic_oop_offset;
3075     int first_nonstatic_field_offset;
3076     int next_nonstatic_field_offset;
3077 
3078     // Calculate the starting byte offsets
3079     next_static_oop_offset      = (instanceKlass::header_size() +
3080                                   align_object_offset(vtable_size) +
3081                                   align_object_offset(itable_size)) * wordSize;
3082     next_static_double_offset   = next_static_oop_offset +
3083                                   (fac.static_oop_count * heapOopSize);
3084     if ( fac.static_double_count &&
3085          (Universe::field_type_should_be_aligned(T_DOUBLE) ||
3086           Universe::field_type_should_be_aligned(T_LONG)) ) {
3087       next_static_double_offset = align_size_up(next_static_double_offset, BytesPerLong);
3088     }
3089 
3090     next_static_word_offset     = next_static_double_offset +
3091                                   (fac.static_double_count * BytesPerLong);
3092     next_static_short_offset    = next_static_word_offset +
3093                                   (fac.static_word_count * BytesPerInt);
3094     next_static_byte_offset     = next_static_short_offset +
3095                                   (fac.static_short_count * BytesPerShort);
3096     next_static_type_offset     = align_size_up((next_static_byte_offset +
3097                                   fac.static_byte_count ), wordSize );
3098     static_field_size           = (next_static_type_offset -
3099                                   next_static_oop_offset) / wordSize;
3100     first_nonstatic_field_offset = instanceOopDesc::base_offset_in_bytes() +
3101                                    nonstatic_field_size * heapOopSize;
3102     next_nonstatic_field_offset = first_nonstatic_field_offset;
3103 
3104     // Add fake fields for java.lang.Class instances (also see below)
3105     if (class_name() == vmSymbols::java_lang_Class() && class_loader.is_null()) {
3106       java_lang_Class_fix_pre(&methods, &fac, CHECK_(nullHandle));
3107     }
3108 
3109     // adjust the vmentry field declaration in java.dyn.MethodHandle
3110     if (EnableMethodHandles && class_name() == vmSymbols::sun_dyn_MethodHandleImpl() && class_loader.is_null()) {
3111       java_dyn_MethodHandle_fix_pre(cp, &fields, &fac, CHECK_(nullHandle));
3112     }
3113 
3114     // Add a fake "discovered" field if it is not present
3115     // for compatibility with earlier jdk's.
3116     if (class_name() == vmSymbols::java_lang_ref_Reference()
3117       && class_loader.is_null()) {
3118       java_lang_ref_Reference_fix_pre(&fields, cp, &fac, CHECK_(nullHandle));
3119     }
3120     // end of "discovered" field compactibility fix
3121 
3122     unsigned int nonstatic_double_count = fac.nonstatic_double_count;
3123     unsigned int nonstatic_word_count   = fac.nonstatic_word_count;
3124     unsigned int nonstatic_short_count  = fac.nonstatic_short_count;
3125     unsigned int nonstatic_byte_count   = fac.nonstatic_byte_count;
3126     unsigned int nonstatic_oop_count    = fac.nonstatic_oop_count;
3127 
3128     bool super_has_nonstatic_fields =
3129             (super_klass() != NULL && super_klass->has_nonstatic_fields());
3130     bool has_nonstatic_fields  =  super_has_nonstatic_fields ||
3131             ((nonstatic_double_count + nonstatic_word_count +
3132               nonstatic_short_count + nonstatic_byte_count +
3133               nonstatic_oop_count) != 0);
3134 
3135 
3136     // Prepare list of oops for oop map generation.
3137     int* nonstatic_oop_offsets;
3138     unsigned int* nonstatic_oop_counts;
3139     unsigned int nonstatic_oop_map_count = 0;
3140 
3141     nonstatic_oop_offsets = NEW_RESOURCE_ARRAY_IN_THREAD(
3142               THREAD, int, nonstatic_oop_count + 1);
3143     nonstatic_oop_counts  = NEW_RESOURCE_ARRAY_IN_THREAD(
3144               THREAD, unsigned int, nonstatic_oop_count + 1);
3145 
3146     // Add fake fields for java.lang.Class instances (also see above).
3147     // FieldsAllocationStyle and CompactFields values will be reset to default.
3148     if(class_name() == vmSymbols::java_lang_Class() && class_loader.is_null()) {
3149       java_lang_Class_fix_post(&next_nonstatic_field_offset);
3150       nonstatic_oop_offsets[0] = first_nonstatic_field_offset;
3151       const uint fake_oop_count = (next_nonstatic_field_offset -
3152                                    first_nonstatic_field_offset) / heapOopSize;
3153       nonstatic_oop_counts[0] = fake_oop_count;
3154       nonstatic_oop_map_count = 1;
3155       nonstatic_oop_count -= fake_oop_count;
3156       first_nonstatic_oop_offset = first_nonstatic_field_offset;
3157     } else {
3158       first_nonstatic_oop_offset = 0; // will be set for first oop field
3159     }
3160 
3161 #ifndef PRODUCT
3162     if( PrintCompactFieldsSavings ) {
3163       next_nonstatic_double_offset = next_nonstatic_field_offset +
3164                                      (nonstatic_oop_count * heapOopSize);
3165       if ( nonstatic_double_count > 0 ) {
3166         next_nonstatic_double_offset = align_size_up(next_nonstatic_double_offset, BytesPerLong);
3167       }
3168       next_nonstatic_word_offset  = next_nonstatic_double_offset +
3169                                     (nonstatic_double_count * BytesPerLong);
3170       next_nonstatic_short_offset = next_nonstatic_word_offset +
3171                                     (nonstatic_word_count * BytesPerInt);
3172       next_nonstatic_byte_offset  = next_nonstatic_short_offset +
3173                                     (nonstatic_short_count * BytesPerShort);
3174       next_nonstatic_type_offset  = align_size_up((next_nonstatic_byte_offset +
3175                                     nonstatic_byte_count ), heapOopSize );
3176       orig_nonstatic_field_size   = nonstatic_field_size +
3177       ((next_nonstatic_type_offset - first_nonstatic_field_offset)/heapOopSize);
3178     }
3179 #endif
3180     bool compact_fields   = CompactFields;
3181     int  allocation_style = FieldsAllocationStyle;
3182     if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
3183       assert(false, "0 <= FieldsAllocationStyle <= 2");
3184       allocation_style = 1; // Optimistic
3185     }
3186 
3187     // The next classes have predefined hard-coded fields offsets
3188     // (see in JavaClasses::compute_hard_coded_offsets()).
3189     // Use default fields allocation order for them.
3190     if( (allocation_style != 0 || compact_fields ) && class_loader.is_null() &&
3191         (class_name() == vmSymbols::java_lang_AssertionStatusDirectives() ||
3192          class_name() == vmSymbols::java_lang_Class() ||
3193          class_name() == vmSymbols::java_lang_ClassLoader() ||
3194          class_name() == vmSymbols::java_lang_ref_Reference() ||
3195          class_name() == vmSymbols::java_lang_ref_SoftReference() ||
3196          class_name() == vmSymbols::java_lang_StackTraceElement() ||
3197          class_name() == vmSymbols::java_lang_String() ||
3198          class_name() == vmSymbols::java_lang_Throwable() ||
3199          class_name() == vmSymbols::java_lang_Boolean() ||
3200          class_name() == vmSymbols::java_lang_Character() ||
3201          class_name() == vmSymbols::java_lang_Float() ||
3202          class_name() == vmSymbols::java_lang_Double() ||
3203          class_name() == vmSymbols::java_lang_Byte() ||
3204          class_name() == vmSymbols::java_lang_Short() ||
3205          class_name() == vmSymbols::java_lang_Integer() ||
3206          class_name() == vmSymbols::java_lang_Long())) {
3207       allocation_style = 0;     // Allocate oops first
3208       compact_fields   = false; // Don't compact fields
3209     }
3210 
3211     if( allocation_style == 0 ) {
3212       // Fields order: oops, longs/doubles, ints, shorts/chars, bytes
3213       next_nonstatic_oop_offset    = next_nonstatic_field_offset;
3214       next_nonstatic_double_offset = next_nonstatic_oop_offset +
3215                                       (nonstatic_oop_count * heapOopSize);
3216     } else if( allocation_style == 1 ) {
3217       // Fields order: longs/doubles, ints, shorts/chars, bytes, oops
3218       next_nonstatic_double_offset = next_nonstatic_field_offset;
3219     } else if( allocation_style == 2 ) {
3220       // Fields allocation: oops fields in super and sub classes are together.
3221       if( nonstatic_field_size > 0 && super_klass() != NULL &&
3222           super_klass->nonstatic_oop_map_size() > 0 ) {
3223         int map_size = super_klass->nonstatic_oop_map_size();
3224         OopMapBlock* first_map = super_klass->start_of_nonstatic_oop_maps();
3225         OopMapBlock* last_map = first_map + map_size - 1;
3226         int next_offset = last_map->offset() + (last_map->count() * heapOopSize);
3227         if (next_offset == next_nonstatic_field_offset) {
3228           allocation_style = 0;   // allocate oops first
3229           next_nonstatic_oop_offset    = next_nonstatic_field_offset;
3230           next_nonstatic_double_offset = next_nonstatic_oop_offset +
3231                                          (nonstatic_oop_count * heapOopSize);
3232         }
3233       }
3234       if( allocation_style == 2 ) {
3235         allocation_style = 1;     // allocate oops last
3236         next_nonstatic_double_offset = next_nonstatic_field_offset;
3237       }
3238     } else {
3239       ShouldNotReachHere();
3240     }
3241 
3242     int nonstatic_oop_space_count   = 0;
3243     int nonstatic_word_space_count  = 0;
3244     int nonstatic_short_space_count = 0;
3245     int nonstatic_byte_space_count  = 0;
3246     int nonstatic_oop_space_offset;
3247     int nonstatic_word_space_offset;
3248     int nonstatic_short_space_offset;
3249     int nonstatic_byte_space_offset;
3250 
3251     if( nonstatic_double_count > 0 ) {
3252       int offset = next_nonstatic_double_offset;
3253       next_nonstatic_double_offset = align_size_up(offset, BytesPerLong);
3254       if( compact_fields && offset != next_nonstatic_double_offset ) {
3255         // Allocate available fields into the gap before double field.
3256         int length = next_nonstatic_double_offset - offset;
3257         assert(length == BytesPerInt, "");
3258         nonstatic_word_space_offset = offset;
3259         if( nonstatic_word_count > 0 ) {
3260           nonstatic_word_count      -= 1;
3261           nonstatic_word_space_count = 1; // Only one will fit
3262           length -= BytesPerInt;
3263           offset += BytesPerInt;
3264         }
3265         nonstatic_short_space_offset = offset;
3266         while( length >= BytesPerShort && nonstatic_short_count > 0 ) {
3267           nonstatic_short_count       -= 1;
3268           nonstatic_short_space_count += 1;
3269           length -= BytesPerShort;
3270           offset += BytesPerShort;
3271         }
3272         nonstatic_byte_space_offset = offset;
3273         while( length > 0 && nonstatic_byte_count > 0 ) {
3274           nonstatic_byte_count       -= 1;
3275           nonstatic_byte_space_count += 1;
3276           length -= 1;
3277         }
3278         // Allocate oop field in the gap if there are no other fields for that.
3279         nonstatic_oop_space_offset = offset;
3280         if( length >= heapOopSize && nonstatic_oop_count > 0 &&
3281             allocation_style != 0 ) { // when oop fields not first
3282           nonstatic_oop_count      -= 1;
3283           nonstatic_oop_space_count = 1; // Only one will fit
3284           length -= heapOopSize;
3285           offset += heapOopSize;
3286         }
3287       }
3288     }
3289 
3290     next_nonstatic_word_offset  = next_nonstatic_double_offset +
3291                                   (nonstatic_double_count * BytesPerLong);
3292     next_nonstatic_short_offset = next_nonstatic_word_offset +
3293                                   (nonstatic_word_count * BytesPerInt);
3294     next_nonstatic_byte_offset  = next_nonstatic_short_offset +
3295                                   (nonstatic_short_count * BytesPerShort);
3296 
3297     int notaligned_offset;
3298     if( allocation_style == 0 ) {
3299       notaligned_offset = next_nonstatic_byte_offset + nonstatic_byte_count;
3300     } else { // allocation_style == 1
3301       next_nonstatic_oop_offset = next_nonstatic_byte_offset + nonstatic_byte_count;
3302       if( nonstatic_oop_count > 0 ) {
3303         next_nonstatic_oop_offset = align_size_up(next_nonstatic_oop_offset, heapOopSize);
3304       }
3305       notaligned_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
3306     }
3307     next_nonstatic_type_offset = align_size_up(notaligned_offset, heapOopSize );
3308     nonstatic_field_size = nonstatic_field_size + ((next_nonstatic_type_offset
3309                                    - first_nonstatic_field_offset)/heapOopSize);
3310 
3311     // Iterate over fields again and compute correct offsets.
3312     // The field allocation type was temporarily stored in the offset slot.
3313     // oop fields are located before non-oop fields (static and non-static).
3314     int len = fields->length();
3315     for (int i = 0; i < len; i += instanceKlass::next_offset) {
3316       int real_offset;
3317       FieldAllocationType atype = (FieldAllocationType) fields->ushort_at(i + instanceKlass::low_offset);
3318       switch (atype) {
3319         case STATIC_OOP:
3320           real_offset = next_static_oop_offset;
3321           next_static_oop_offset += heapOopSize;
3322           break;
3323         case STATIC_BYTE:
3324           real_offset = next_static_byte_offset;
3325           next_static_byte_offset += 1;
3326           break;
3327         case STATIC_SHORT:
3328           real_offset = next_static_short_offset;
3329           next_static_short_offset += BytesPerShort;
3330           break;
3331         case STATIC_WORD:
3332           real_offset = next_static_word_offset;
3333           next_static_word_offset += BytesPerInt;
3334           break;
3335         case STATIC_ALIGNED_DOUBLE:
3336         case STATIC_DOUBLE:
3337           real_offset = next_static_double_offset;
3338           next_static_double_offset += BytesPerLong;
3339           break;
3340         case NONSTATIC_OOP:
3341           if( nonstatic_oop_space_count > 0 ) {
3342             real_offset = nonstatic_oop_space_offset;
3343             nonstatic_oop_space_offset += heapOopSize;
3344             nonstatic_oop_space_count  -= 1;
3345           } else {
3346             real_offset = next_nonstatic_oop_offset;
3347             next_nonstatic_oop_offset += heapOopSize;
3348           }
3349           // Update oop maps
3350           if( nonstatic_oop_map_count > 0 &&
3351               nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
3352               real_offset -
3353               int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
3354               heapOopSize ) {
3355             // Extend current oop map
3356             nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
3357           } else {
3358             // Create new oop map
3359             nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
3360             nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
3361             nonstatic_oop_map_count += 1;
3362             if( first_nonstatic_oop_offset == 0 ) { // Undefined
3363               first_nonstatic_oop_offset = real_offset;
3364             }
3365           }
3366           break;
3367         case NONSTATIC_BYTE:
3368           if( nonstatic_byte_space_count > 0 ) {
3369             real_offset = nonstatic_byte_space_offset;
3370             nonstatic_byte_space_offset += 1;
3371             nonstatic_byte_space_count  -= 1;
3372           } else {
3373             real_offset = next_nonstatic_byte_offset;
3374             next_nonstatic_byte_offset += 1;
3375           }
3376           break;
3377         case NONSTATIC_SHORT:
3378           if( nonstatic_short_space_count > 0 ) {
3379             real_offset = nonstatic_short_space_offset;
3380             nonstatic_short_space_offset += BytesPerShort;
3381             nonstatic_short_space_count  -= 1;
3382           } else {
3383             real_offset = next_nonstatic_short_offset;
3384             next_nonstatic_short_offset += BytesPerShort;
3385           }
3386           break;
3387         case NONSTATIC_WORD:
3388           if( nonstatic_word_space_count > 0 ) {
3389             real_offset = nonstatic_word_space_offset;
3390             nonstatic_word_space_offset += BytesPerInt;
3391             nonstatic_word_space_count  -= 1;
3392           } else {
3393             real_offset = next_nonstatic_word_offset;
3394             next_nonstatic_word_offset += BytesPerInt;
3395           }
3396           break;
3397         case NONSTATIC_ALIGNED_DOUBLE:
3398         case NONSTATIC_DOUBLE:
3399           real_offset = next_nonstatic_double_offset;
3400           next_nonstatic_double_offset += BytesPerLong;
3401           break;
3402         default:
3403           ShouldNotReachHere();
3404       }
3405       fields->short_at_put(i + instanceKlass::low_offset,  extract_low_short_from_int(real_offset));
3406       fields->short_at_put(i + instanceKlass::high_offset, extract_high_short_from_int(real_offset));
3407     }
3408 
3409     // Size of instances
3410     int instance_size;
3411 
3412     next_nonstatic_type_offset = align_size_up(notaligned_offset, wordSize );
3413     instance_size = align_object_size(next_nonstatic_type_offset / wordSize);
3414 
3415     assert(instance_size == align_object_size(align_size_up((instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize), wordSize) / wordSize), "consistent layout helper value");
3416 
3417     // Number of non-static oop map blocks allocated at end of klass.
3418     const unsigned int total_oop_map_count =
3419       compute_oop_map_count(super_klass, nonstatic_oop_map_count,
3420                             first_nonstatic_oop_offset);
3421 
3422     // Compute reference type
3423     ReferenceType rt;
3424     if (super_klass() == NULL) {
3425       rt = REF_NONE;
3426     } else {
3427       rt = super_klass->reference_type();
3428     }
3429 
3430     // We can now create the basic klassOop for this klass
3431     klassOop ik = oopFactory::new_instanceKlass(vtable_size, itable_size,
3432                                                 static_field_size,
3433                                                 total_oop_map_count,
3434                                                 rt, CHECK_(nullHandle));
3435     instanceKlassHandle this_klass (THREAD, ik);
3436 
3437     assert(this_klass->static_field_size() == static_field_size, "sanity");
3438     assert(this_klass->nonstatic_oop_map_count() == total_oop_map_count,
3439            "sanity");
3440 
3441     // Fill in information already parsed
3442     this_klass->set_access_flags(access_flags);
3443     this_klass->set_should_verify_class(verify);
3444     jint lh = Klass::instance_layout_helper(instance_size, false);
3445     this_klass->set_layout_helper(lh);
3446     assert(this_klass->oop_is_instance(), "layout is correct");
3447     assert(this_klass->size_helper() == instance_size, "correct size_helper");
3448     // Not yet: supers are done below to support the new subtype-checking fields
3449     //this_klass->set_super(super_klass());
3450     this_klass->set_class_loader(class_loader());
3451     this_klass->set_nonstatic_field_size(nonstatic_field_size);
3452     this_klass->set_has_nonstatic_fields(has_nonstatic_fields);
3453     this_klass->set_static_oop_field_size(fac.static_oop_count);
3454     cp->set_pool_holder(this_klass());
3455     this_klass->set_constants(cp());
3456     this_klass->set_local_interfaces(local_interfaces());
3457     this_klass->set_fields(fields());
3458     this_klass->set_methods(methods());
3459     if (has_final_method) {
3460       this_klass->set_has_final_method();
3461     }
3462     this_klass->set_method_ordering(method_ordering());
3463     // The instanceKlass::_methods_jmethod_ids cache and the
3464     // instanceKlass::_methods_cached_itable_indices cache are
3465     // both managed on the assumption that the initial cache
3466     // size is equal to the number of methods in the class. If
3467     // that changes, then instanceKlass::idnum_can_increment()
3468     // has to be changed accordingly.
3469     this_klass->set_initial_method_idnum(methods->length());
3470     this_klass->set_name(cp->klass_name_at(this_class_index));
3471     if (LinkWellKnownClasses || is_anonymous())  // I am well known to myself
3472       cp->klass_at_put(this_class_index, this_klass()); // eagerly resolve
3473     this_klass->set_protection_domain(protection_domain());
3474     this_klass->set_fields_annotations(fields_annotations());
3475     this_klass->set_methods_annotations(methods_annotations());
3476     this_klass->set_methods_parameter_annotations(methods_parameter_annotations());
3477     this_klass->set_methods_default_annotations(methods_default_annotations());
3478 
3479     this_klass->set_minor_version(minor_version);
3480     this_klass->set_major_version(major_version);
3481 
3482     // Set up methodOop::intrinsic_id as soon as we know the names of methods.
3483     // (We used to do this lazily, but now we query it in Rewriter,
3484     // which is eagerly done for every method, so we might as well do it now,
3485     // when everything is fresh in memory.)
3486     if (methodOopDesc::klass_id_for_intrinsics(this_klass->as_klassOop()) != vmSymbols::NO_SID) {
3487       for (int j = 0; j < methods->length(); j++) {
3488         ((methodOop)methods->obj_at(j))->init_intrinsic_id();
3489       }
3490     }
3491 
3492     if (cached_class_file_bytes != NULL) {
3493       // JVMTI: we have an instanceKlass now, tell it about the cached bytes
3494       this_klass->set_cached_class_file(cached_class_file_bytes,
3495                                         cached_class_file_length);
3496     }
3497 
3498     // Miranda methods
3499     if ((num_miranda_methods > 0) ||
3500         // if this class introduced new miranda methods or
3501         (super_klass.not_null() && (super_klass->has_miranda_methods()))
3502         // super class exists and this class inherited miranda methods
3503         ) {
3504       this_klass->set_has_miranda_methods(); // then set a flag
3505     }
3506 
3507     // Additional attributes
3508     parse_classfile_attributes(cp, this_klass, CHECK_(nullHandle));
3509 
3510     // Make sure this is the end of class file stream
3511     guarantee_property(cfs->at_eos(), "Extra bytes at the end of class file %s", CHECK_(nullHandle));
3512 
3513     // Initialize static fields
3514     this_klass->do_local_static_fields(&initialize_static_field, CHECK_(nullHandle));
3515 
3516     // VerifyOops believes that once this has been set, the object is completely loaded.
3517     // Compute transitive closure of interfaces this class implements
3518     this_klass->set_transitive_interfaces(transitive_interfaces());
3519 
3520     // Fill in information needed to compute superclasses.
3521     this_klass->initialize_supers(super_klass(), CHECK_(nullHandle));
3522 
3523     // Initialize itable offset tables
3524     klassItable::setup_itable_offset_table(this_klass);
3525 
3526     // Do final class setup
3527     fill_oop_maps(this_klass, nonstatic_oop_map_count, nonstatic_oop_offsets, nonstatic_oop_counts);
3528 
3529     set_precomputed_flags(this_klass);
3530 
3531     // reinitialize modifiers, using the InnerClasses attribute
3532     int computed_modifiers = this_klass->compute_modifier_flags(CHECK_(nullHandle));
3533     this_klass->set_modifier_flags(computed_modifiers);
3534 
3535     // check if this class can access its super class
3536     check_super_class_access(this_klass, CHECK_(nullHandle));
3537 
3538     // check if this class can access its superinterfaces
3539     check_super_interface_access(this_klass, CHECK_(nullHandle));
3540 
3541     // check if this class overrides any final method
3542     check_final_method_override(this_klass, CHECK_(nullHandle));
3543 
3544     // check that if this class is an interface then it doesn't have static methods
3545     if (this_klass->is_interface()) {
3546       check_illegal_static_method(this_klass, CHECK_(nullHandle));
3547     }
3548 
3549     ClassLoadingService::notify_class_loaded(instanceKlass::cast(this_klass()),
3550                                              false /* not shared class */);
3551 
3552     if (TraceClassLoading) {
3553       // print in a single call to reduce interleaving of output
3554       if (cfs->source() != NULL) {
3555         tty->print("[Loaded %s from %s]\n", this_klass->external_name(),
3556                    cfs->source());
3557       } else if (class_loader.is_null()) {
3558         if (THREAD->is_Java_thread()) {
3559           klassOop caller = ((JavaThread*)THREAD)->security_get_caller_class(1);
3560           tty->print("[Loaded %s by instance of %s]\n",
3561                      this_klass->external_name(),
3562                      instanceKlass::cast(caller)->external_name());
3563         } else {
3564           tty->print("[Loaded %s]\n", this_klass->external_name());
3565         }
3566       } else {
3567         ResourceMark rm;
3568         tty->print("[Loaded %s from %s]\n", this_klass->external_name(),
3569                    instanceKlass::cast(class_loader->klass())->external_name());
3570       }
3571     }
3572 
3573     if (TraceClassResolution) {
3574       // print out the superclass.
3575       const char * from = Klass::cast(this_klass())->external_name();
3576       if (this_klass->java_super() != NULL) {
3577         tty->print("RESOLVE %s %s (super)\n", from, instanceKlass::cast(this_klass->java_super())->external_name());
3578       }
3579       // print out each of the interface classes referred to by this class.
3580       objArrayHandle local_interfaces(THREAD, this_klass->local_interfaces());
3581       if (!local_interfaces.is_null()) {
3582         int length = local_interfaces->length();
3583         for (int i = 0; i < length; i++) {
3584           klassOop k = klassOop(local_interfaces->obj_at(i));
3585           instanceKlass* to_class = instanceKlass::cast(k);
3586           const char * to = to_class->external_name();
3587           tty->print("RESOLVE %s %s (interface)\n", from, to);
3588         }
3589       }
3590     }
3591 
3592 #ifndef PRODUCT
3593     if( PrintCompactFieldsSavings ) {
3594       if( nonstatic_field_size < orig_nonstatic_field_size ) {
3595         tty->print("[Saved %d of %d bytes in %s]\n",
3596                  (orig_nonstatic_field_size - nonstatic_field_size)*heapOopSize,
3597                  orig_nonstatic_field_size*heapOopSize,
3598                  this_klass->external_name());
3599       } else if( nonstatic_field_size > orig_nonstatic_field_size ) {
3600         tty->print("[Wasted %d over %d bytes in %s]\n",
3601                  (nonstatic_field_size - orig_nonstatic_field_size)*heapOopSize,
3602                  orig_nonstatic_field_size*heapOopSize,
3603                  this_klass->external_name());
3604       }
3605     }
3606 #endif
3607 
3608     // preserve result across HandleMark
3609     preserve_this_klass = this_klass();
3610   }
3611 
3612   // Create new handle outside HandleMark
3613   instanceKlassHandle this_klass (THREAD, preserve_this_klass);
3614   debug_only(this_klass->as_klassOop()->verify();)
3615 
3616   return this_klass;
3617 }
3618 
3619 
3620 unsigned int
3621 ClassFileParser::compute_oop_map_count(instanceKlassHandle super,
3622                                        unsigned int nonstatic_oop_map_count,
3623                                        int first_nonstatic_oop_offset) {
3624   unsigned int map_count =
3625     super.is_null() ? 0 : super->nonstatic_oop_map_count();
3626   if (nonstatic_oop_map_count > 0) {
3627     // We have oops to add to map
3628     if (map_count == 0) {
3629       map_count = nonstatic_oop_map_count;
3630     } else {
3631       // Check whether we should add a new map block or whether the last one can
3632       // be extended
3633       OopMapBlock* const first_map = super->start_of_nonstatic_oop_maps();
3634       OopMapBlock* const last_map = first_map + map_count - 1;
3635 
3636       int next_offset = last_map->offset() + last_map->count() * heapOopSize;
3637       if (next_offset == first_nonstatic_oop_offset) {
3638         // There is no gap bettwen superklass's last oop field and first
3639         // local oop field, merge maps.
3640         nonstatic_oop_map_count -= 1;
3641       } else {
3642         // Superklass didn't end with a oop field, add extra maps
3643         assert(next_offset < first_nonstatic_oop_offset, "just checking");
3644       }
3645       map_count += nonstatic_oop_map_count;
3646     }
3647   }
3648   return map_count;
3649 }
3650 
3651 
3652 void ClassFileParser::fill_oop_maps(instanceKlassHandle k,
3653                                     unsigned int nonstatic_oop_map_count,
3654                                     int* nonstatic_oop_offsets,
3655                                     unsigned int* nonstatic_oop_counts) {
3656   OopMapBlock* this_oop_map = k->start_of_nonstatic_oop_maps();
3657   const instanceKlass* const super = k->superklass();
3658   const unsigned int super_count = super ? super->nonstatic_oop_map_count() : 0;
3659   if (super_count > 0) {
3660     // Copy maps from superklass
3661     OopMapBlock* super_oop_map = super->start_of_nonstatic_oop_maps();
3662     for (unsigned int i = 0; i < super_count; ++i) {
3663       *this_oop_map++ = *super_oop_map++;
3664     }
3665   }
3666 
3667   if (nonstatic_oop_map_count > 0) {
3668     if (super_count + nonstatic_oop_map_count > k->nonstatic_oop_map_count()) {
3669       // The counts differ because there is no gap between superklass's last oop
3670       // field and the first local oop field.  Extend the last oop map copied
3671       // from the superklass instead of creating new one.
3672       nonstatic_oop_map_count--;
3673       nonstatic_oop_offsets++;
3674       this_oop_map--;
3675       this_oop_map->set_count(this_oop_map->count() + *nonstatic_oop_counts++);
3676       this_oop_map++;
3677     }
3678 
3679     // Add new map blocks, fill them
3680     while (nonstatic_oop_map_count-- > 0) {
3681       this_oop_map->set_offset(*nonstatic_oop_offsets++);
3682       this_oop_map->set_count(*nonstatic_oop_counts++);
3683       this_oop_map++;
3684     }
3685     assert(k->start_of_nonstatic_oop_maps() + k->nonstatic_oop_map_count() ==
3686            this_oop_map, "sanity");
3687   }
3688 }
3689 
3690 
3691 void ClassFileParser::set_precomputed_flags(instanceKlassHandle k) {
3692   klassOop super = k->super();
3693 
3694   // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
3695   // in which case we don't have to register objects as finalizable
3696   if (!_has_empty_finalizer) {
3697     if (_has_finalizer ||
3698         (super != NULL && super->klass_part()->has_finalizer())) {
3699       k->set_has_finalizer();
3700     }
3701   }
3702 
3703 #ifdef ASSERT
3704   bool f = false;
3705   methodOop m = k->lookup_method(vmSymbols::finalize_method_name(),
3706                                  vmSymbols::void_method_signature());
3707   if (m != NULL && !m->is_empty_method()) {
3708     f = true;
3709   }
3710   assert(f == k->has_finalizer(), "inconsistent has_finalizer");
3711 #endif
3712 
3713   // Check if this klass supports the java.lang.Cloneable interface
3714   if (SystemDictionary::Cloneable_klass_loaded()) {
3715     if (k->is_subtype_of(SystemDictionary::Cloneable_klass())) {
3716       k->set_is_cloneable();
3717     }
3718   }
3719 
3720   // Check if this klass has a vanilla default constructor
3721   if (super == NULL) {
3722     // java.lang.Object has empty default constructor
3723     k->set_has_vanilla_constructor();
3724   } else {
3725     if (Klass::cast(super)->has_vanilla_constructor() &&
3726         _has_vanilla_constructor) {
3727       k->set_has_vanilla_constructor();
3728     }
3729 #ifdef ASSERT
3730     bool v = false;
3731     if (Klass::cast(super)->has_vanilla_constructor()) {
3732       methodOop constructor = k->find_method(vmSymbols::object_initializer_name(
3733 ), vmSymbols::void_method_signature());
3734       if (constructor != NULL && constructor->is_vanilla_constructor()) {
3735         v = true;
3736       }
3737     }
3738     assert(v == k->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
3739 #endif
3740   }
3741 
3742   // If it cannot be fast-path allocated, set a bit in the layout helper.
3743   // See documentation of instanceKlass::can_be_fastpath_allocated().
3744   assert(k->size_helper() > 0, "layout_helper is initialized");
3745   if ((!RegisterFinalizersAtInit && k->has_finalizer())
3746       || k->is_abstract() || k->is_interface()
3747       || (k->name() == vmSymbols::java_lang_Class()
3748           && k->class_loader() == NULL)
3749       || k->size_helper() >= FastAllocateSizeLimit) {
3750     // Forbid fast-path allocation.
3751     jint lh = Klass::instance_layout_helper(k->size_helper(), true);
3752     k->set_layout_helper(lh);
3753   }
3754 }
3755 
3756 
3757 // utility method for appending and array with check for duplicates
3758 
3759 void append_interfaces(objArrayHandle result, int& index, objArrayOop ifs) {
3760   // iterate over new interfaces
3761   for (int i = 0; i < ifs->length(); i++) {
3762     oop e = ifs->obj_at(i);
3763     assert(e->is_klass() && instanceKlass::cast(klassOop(e))->is_interface(), "just checking");
3764     // check for duplicates
3765     bool duplicate = false;
3766     for (int j = 0; j < index; j++) {
3767       if (result->obj_at(j) == e) {
3768         duplicate = true;
3769         break;
3770       }
3771     }
3772     // add new interface
3773     if (!duplicate) {
3774       result->obj_at_put(index++, e);
3775     }
3776   }
3777 }
3778 
3779 objArrayHandle ClassFileParser::compute_transitive_interfaces(instanceKlassHandle super, objArrayHandle local_ifs, TRAPS) {
3780   // Compute maximum size for transitive interfaces
3781   int max_transitive_size = 0;
3782   int super_size = 0;
3783   // Add superclass transitive interfaces size
3784   if (super.not_null()) {
3785     super_size = super->transitive_interfaces()->length();
3786     max_transitive_size += super_size;
3787   }
3788   // Add local interfaces' super interfaces
3789   int local_size = local_ifs->length();
3790   for (int i = 0; i < local_size; i++) {
3791     klassOop l = klassOop(local_ifs->obj_at(i));
3792     max_transitive_size += instanceKlass::cast(l)->transitive_interfaces()->length();
3793   }
3794   // Finally add local interfaces
3795   max_transitive_size += local_size;
3796   // Construct array
3797   objArrayHandle result;
3798   if (max_transitive_size == 0) {
3799     // no interfaces, use canonicalized array
3800     result = objArrayHandle(THREAD, Universe::the_empty_system_obj_array());
3801   } else if (max_transitive_size == super_size) {
3802     // no new local interfaces added, share superklass' transitive interface array
3803     result = objArrayHandle(THREAD, super->transitive_interfaces());
3804   } else if (max_transitive_size == local_size) {
3805     // only local interfaces added, share local interface array
3806     result = local_ifs;
3807   } else {
3808     objArrayHandle nullHandle;
3809     objArrayOop new_objarray = oopFactory::new_system_objArray(max_transitive_size, CHECK_(nullHandle));
3810     result = objArrayHandle(THREAD, new_objarray);
3811     int index = 0;
3812     // Copy down from superclass
3813     if (super.not_null()) {
3814       append_interfaces(result, index, super->transitive_interfaces());
3815     }
3816     // Copy down from local interfaces' superinterfaces
3817     for (int i = 0; i < local_ifs->length(); i++) {
3818       klassOop l = klassOop(local_ifs->obj_at(i));
3819       append_interfaces(result, index, instanceKlass::cast(l)->transitive_interfaces());
3820     }
3821     // Finally add local interfaces
3822     append_interfaces(result, index, local_ifs());
3823 
3824     // Check if duplicates were removed
3825     if (index != max_transitive_size) {
3826       assert(index < max_transitive_size, "just checking");
3827       objArrayOop new_result = oopFactory::new_system_objArray(index, CHECK_(nullHandle));
3828       for (int i = 0; i < index; i++) {
3829         oop e = result->obj_at(i);
3830         assert(e != NULL, "just checking");
3831         new_result->obj_at_put(i, e);
3832       }
3833       result = objArrayHandle(THREAD, new_result);
3834     }
3835   }
3836   return result;
3837 }
3838 
3839 
3840 void ClassFileParser::check_super_class_access(instanceKlassHandle this_klass, TRAPS) {
3841   klassOop super = this_klass->super();
3842   if ((super != NULL) &&
3843       (!Reflection::verify_class_access(this_klass->as_klassOop(), super, false))) {
3844     ResourceMark rm(THREAD);
3845     Exceptions::fthrow(
3846       THREAD_AND_LOCATION,
3847       vmSymbolHandles::java_lang_IllegalAccessError(),
3848       "class %s cannot access its superclass %s",
3849       this_klass->external_name(),
3850       instanceKlass::cast(super)->external_name()
3851     );
3852     return;
3853   }
3854 }
3855 
3856 
3857 void ClassFileParser::check_super_interface_access(instanceKlassHandle this_klass, TRAPS) {
3858   objArrayHandle local_interfaces (THREAD, this_klass->local_interfaces());
3859   int lng = local_interfaces->length();
3860   for (int i = lng - 1; i >= 0; i--) {
3861     klassOop k = klassOop(local_interfaces->obj_at(i));
3862     assert (k != NULL && Klass::cast(k)->is_interface(), "invalid interface");
3863     if (!Reflection::verify_class_access(this_klass->as_klassOop(), k, false)) {
3864       ResourceMark rm(THREAD);
3865       Exceptions::fthrow(
3866         THREAD_AND_LOCATION,
3867         vmSymbolHandles::java_lang_IllegalAccessError(),
3868         "class %s cannot access its superinterface %s",
3869         this_klass->external_name(),
3870         instanceKlass::cast(k)->external_name()
3871       );
3872       return;
3873     }
3874   }
3875 }
3876 
3877 
3878 void ClassFileParser::check_final_method_override(instanceKlassHandle this_klass, TRAPS) {
3879   objArrayHandle methods (THREAD, this_klass->methods());
3880   int num_methods = methods->length();
3881 
3882   // go thru each method and check if it overrides a final method
3883   for (int index = 0; index < num_methods; index++) {
3884     methodOop m = (methodOop)methods->obj_at(index);
3885 
3886     // skip private, static and <init> methods
3887     if ((!m->is_private()) &&
3888         (!m->is_static()) &&
3889         (m->name() != vmSymbols::object_initializer_name())) {
3890 
3891       symbolOop name = m->name();
3892       symbolOop signature = m->signature();
3893       klassOop k = this_klass->super();
3894       methodOop super_m = NULL;
3895       while (k != NULL) {
3896         // skip supers that don't have final methods.
3897         if (k->klass_part()->has_final_method()) {
3898           // lookup a matching method in the super class hierarchy
3899           super_m = instanceKlass::cast(k)->lookup_method(name, signature);
3900           if (super_m == NULL) {
3901             break; // didn't find any match; get out
3902           }
3903 
3904           if (super_m->is_final() &&
3905               // matching method in super is final
3906               (Reflection::verify_field_access(this_klass->as_klassOop(),
3907                                                super_m->method_holder(),
3908                                                super_m->method_holder(),
3909                                                super_m->access_flags(), false))
3910             // this class can access super final method and therefore override
3911             ) {
3912             ResourceMark rm(THREAD);
3913             Exceptions::fthrow(
3914               THREAD_AND_LOCATION,
3915               vmSymbolHandles::java_lang_VerifyError(),
3916               "class %s overrides final method %s.%s",
3917               this_klass->external_name(),
3918               name->as_C_string(),
3919               signature->as_C_string()
3920             );
3921             return;
3922           }
3923 
3924           // continue to look from super_m's holder's super.
3925           k = instanceKlass::cast(super_m->method_holder())->super();
3926           continue;
3927         }
3928 
3929         k = k->klass_part()->super();
3930       }
3931     }
3932   }
3933 }
3934 
3935 
3936 // assumes that this_klass is an interface
3937 void ClassFileParser::check_illegal_static_method(instanceKlassHandle this_klass, TRAPS) {
3938   assert(this_klass->is_interface(), "not an interface");
3939   objArrayHandle methods (THREAD, this_klass->methods());
3940   int num_methods = methods->length();
3941 
3942   for (int index = 0; index < num_methods; index++) {
3943     methodOop m = (methodOop)methods->obj_at(index);
3944     // if m is static and not the init method, throw a verify error
3945     if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
3946       ResourceMark rm(THREAD);
3947       Exceptions::fthrow(
3948         THREAD_AND_LOCATION,
3949         vmSymbolHandles::java_lang_VerifyError(),
3950         "Illegal static method %s in interface %s",
3951         m->name()->as_C_string(),
3952         this_klass->external_name()
3953       );
3954       return;
3955     }
3956   }
3957 }
3958 
3959 // utility methods for format checking
3960 
3961 void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) {
3962   if (!_need_verify) { return; }
3963 
3964   const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
3965   const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
3966   const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
3967   const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
3968   const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
3969   const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
3970   const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;
3971 
3972   if ((is_abstract && is_final) ||
3973       (is_interface && !is_abstract) ||
3974       (is_interface && major_gte_15 && (is_super || is_enum)) ||
3975       (!is_interface && major_gte_15 && is_annotation)) {
3976     ResourceMark rm(THREAD);
3977     Exceptions::fthrow(
3978       THREAD_AND_LOCATION,
3979       vmSymbolHandles::java_lang_ClassFormatError(),
3980       "Illegal class modifiers in class %s: 0x%X",
3981       _class_name->as_C_string(), flags
3982     );
3983     return;
3984   }
3985 }
3986 
3987 bool ClassFileParser::has_illegal_visibility(jint flags) {
3988   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
3989   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
3990   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
3991 
3992   return ((is_public && is_protected) ||
3993           (is_public && is_private) ||
3994           (is_protected && is_private));
3995 }
3996 
3997 bool ClassFileParser::is_supported_version(u2 major, u2 minor) {
3998   u2 max_version =
3999     JDK_Version::is_gte_jdk17x_version() ? JAVA_MAX_SUPPORTED_VERSION :
4000     (JDK_Version::is_gte_jdk16x_version() ? JAVA_6_VERSION : JAVA_1_5_VERSION);
4001   return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
4002          (major <= max_version) &&
4003          ((major != max_version) ||
4004           (minor <= JAVA_MAX_SUPPORTED_MINOR_VERSION));
4005 }
4006 
4007 void ClassFileParser::verify_legal_field_modifiers(
4008     jint flags, bool is_interface, TRAPS) {
4009   if (!_need_verify) { return; }
4010 
4011   const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
4012   const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
4013   const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
4014   const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
4015   const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
4016   const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
4017   const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
4018   const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
4019   const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;
4020 
4021   bool is_illegal = false;
4022 
4023   if (is_interface) {
4024     if (!is_public || !is_static || !is_final || is_private ||
4025         is_protected || is_volatile || is_transient ||
4026         (major_gte_15 && is_enum)) {
4027       is_illegal = true;
4028     }
4029   } else { // not interface
4030     if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
4031       is_illegal = true;
4032     }
4033   }
4034 
4035   if (is_illegal) {
4036     ResourceMark rm(THREAD);
4037     Exceptions::fthrow(
4038       THREAD_AND_LOCATION,
4039       vmSymbolHandles::java_lang_ClassFormatError(),
4040       "Illegal field modifiers in class %s: 0x%X",
4041       _class_name->as_C_string(), flags);
4042     return;
4043   }
4044 }
4045 
4046 void ClassFileParser::verify_legal_method_modifiers(
4047     jint flags, bool is_interface, symbolHandle name, TRAPS) {
4048   if (!_need_verify) { return; }
4049 
4050   const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
4051   const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
4052   const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
4053   const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
4054   const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
4055   const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
4056   const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
4057   const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
4058   const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4059   const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
4060   const bool is_initializer  = (name == vmSymbols::object_initializer_name());
4061 
4062   bool is_illegal = false;
4063 
4064   if (is_interface) {
4065     if (!is_abstract || !is_public || is_static || is_final ||
4066         is_native || (major_gte_15 && (is_synchronized || is_strict))) {
4067       is_illegal = true;
4068     }
4069   } else { // not interface
4070     if (is_initializer) {
4071       if (is_static || is_final || is_synchronized || is_native ||
4072           is_abstract || (major_gte_15 && is_bridge)) {
4073         is_illegal = true;
4074       }
4075     } else { // not initializer
4076       if (is_abstract) {
4077         if ((is_final || is_native || is_private || is_static ||
4078             (major_gte_15 && (is_synchronized || is_strict)))) {
4079           is_illegal = true;
4080         }
4081       }
4082       if (has_illegal_visibility(flags)) {
4083         is_illegal = true;
4084       }
4085     }
4086   }
4087 
4088   if (is_illegal) {
4089     ResourceMark rm(THREAD);
4090     Exceptions::fthrow(
4091       THREAD_AND_LOCATION,
4092       vmSymbolHandles::java_lang_ClassFormatError(),
4093       "Method %s in class %s has illegal modifiers: 0x%X",
4094       name->as_C_string(), _class_name->as_C_string(), flags);
4095     return;
4096   }
4097 }
4098 
4099 void ClassFileParser::verify_legal_utf8(const unsigned char* buffer, int length, TRAPS) {
4100   assert(_need_verify, "only called when _need_verify is true");
4101   int i = 0;
4102   int count = length >> 2;
4103   for (int k=0; k<count; k++) {
4104     unsigned char b0 = buffer[i];
4105     unsigned char b1 = buffer[i+1];
4106     unsigned char b2 = buffer[i+2];
4107     unsigned char b3 = buffer[i+3];
4108     // For an unsigned char v,
4109     // (v | v - 1) is < 128 (highest bit 0) for 0 < v < 128;
4110     // (v | v - 1) is >= 128 (highest bit 1) for v == 0 or v >= 128.
4111     unsigned char res = b0 | b0 - 1 |
4112                         b1 | b1 - 1 |
4113                         b2 | b2 - 1 |
4114                         b3 | b3 - 1;
4115     if (res >= 128) break;
4116     i += 4;
4117   }
4118   for(; i < length; i++) {
4119     unsigned short c;
4120     // no embedded zeros
4121     guarantee_property((buffer[i] != 0), "Illegal UTF8 string in constant pool in class file %s", CHECK);
4122     if(buffer[i] < 128) {
4123       continue;
4124     }
4125     if ((i + 5) < length) { // see if it's legal supplementary character
4126       if (UTF8::is_supplementary_character(&buffer[i])) {
4127         c = UTF8::get_supplementary_character(&buffer[i]);
4128         i += 5;
4129         continue;
4130       }
4131     }
4132     switch (buffer[i] >> 4) {
4133       default: break;
4134       case 0x8: case 0x9: case 0xA: case 0xB: case 0xF:
4135         classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
4136       case 0xC: case 0xD:  // 110xxxxx  10xxxxxx
4137         c = (buffer[i] & 0x1F) << 6;
4138         i++;
4139         if ((i < length) && ((buffer[i] & 0xC0) == 0x80)) {
4140           c += buffer[i] & 0x3F;
4141           if (_major_version <= 47 || c == 0 || c >= 0x80) {
4142             // for classes with major > 47, c must a null or a character in its shortest form
4143             break;
4144           }
4145         }
4146         classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
4147       case 0xE:  // 1110xxxx 10xxxxxx 10xxxxxx
4148         c = (buffer[i] & 0xF) << 12;
4149         i += 2;
4150         if ((i < length) && ((buffer[i-1] & 0xC0) == 0x80) && ((buffer[i] & 0xC0) == 0x80)) {
4151           c += ((buffer[i-1] & 0x3F) << 6) + (buffer[i] & 0x3F);
4152           if (_major_version <= 47 || c >= 0x800) {
4153             // for classes with major > 47, c must be in its shortest form
4154             break;
4155           }
4156         }
4157         classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
4158     }  // end of switch
4159   } // end of for
4160 }
4161 
4162 // Checks if name is a legal class name.
4163 void ClassFileParser::verify_legal_class_name(symbolHandle name, TRAPS) {
4164   if (!_need_verify || _relax_verify) { return; }
4165 
4166   char buf[fixed_buffer_size];
4167   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
4168   unsigned int length = name->utf8_length();
4169   bool legal = false;
4170 
4171   if (length > 0) {
4172     char* p;
4173     if (bytes[0] == JVM_SIGNATURE_ARRAY) {
4174       p = skip_over_field_signature(bytes, false, length, CHECK);
4175       legal = (p != NULL) && ((p - bytes) == (int)length);
4176     } else if (_major_version < JAVA_1_5_VERSION) {
4177       if (bytes[0] != '<') {
4178         p = skip_over_field_name(bytes, true, length);
4179         legal = (p != NULL) && ((p - bytes) == (int)length);
4180       }
4181     } else {
4182       // 4900761: relax the constraints based on JSR202 spec
4183       // Class names may be drawn from the entire Unicode character set.
4184       // Identifiers between '/' must be unqualified names.
4185       // The utf8 string has been verified when parsing cpool entries.
4186       legal = verify_unqualified_name(bytes, length, LegalClass);
4187     }
4188   }
4189   if (!legal) {
4190     ResourceMark rm(THREAD);
4191     Exceptions::fthrow(
4192       THREAD_AND_LOCATION,
4193       vmSymbolHandles::java_lang_ClassFormatError(),
4194       "Illegal class name \"%s\" in class file %s", bytes,
4195       _class_name->as_C_string()
4196     );
4197     return;
4198   }
4199 }
4200 
4201 // Checks if name is a legal field name.
4202 void ClassFileParser::verify_legal_field_name(symbolHandle name, TRAPS) {
4203   if (!_need_verify || _relax_verify) { return; }
4204 
4205   char buf[fixed_buffer_size];
4206   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
4207   unsigned int length = name->utf8_length();
4208   bool legal = false;
4209 
4210   if (length > 0) {
4211     if (_major_version < JAVA_1_5_VERSION) {
4212       if (bytes[0] != '<') {
4213         char* p = skip_over_field_name(bytes, false, length);
4214         legal = (p != NULL) && ((p - bytes) == (int)length);
4215       }
4216     } else {
4217       // 4881221: relax the constraints based on JSR202 spec
4218       legal = verify_unqualified_name(bytes, length, LegalField);
4219     }
4220   }
4221 
4222   if (!legal) {
4223     ResourceMark rm(THREAD);
4224     Exceptions::fthrow(
4225       THREAD_AND_LOCATION,
4226       vmSymbolHandles::java_lang_ClassFormatError(),
4227       "Illegal field name \"%s\" in class %s", bytes,
4228       _class_name->as_C_string()
4229     );
4230     return;
4231   }
4232 }
4233 
4234 // Checks if name is a legal method name.
4235 void ClassFileParser::verify_legal_method_name(symbolHandle name, TRAPS) {
4236   if (!_need_verify || _relax_verify) { return; }
4237 
4238   assert(!name.is_null(), "method name is null");
4239   char buf[fixed_buffer_size];
4240   char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
4241   unsigned int length = name->utf8_length();
4242   bool legal = false;
4243 
4244   if (length > 0) {
4245     if (bytes[0] == '<') {
4246       if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
4247         legal = true;
4248       }
4249     } else if (_major_version < JAVA_1_5_VERSION) {
4250       char* p;
4251       p = skip_over_field_name(bytes, false, length);
4252       legal = (p != NULL) && ((p - bytes) == (int)length);
4253     } else {
4254       // 4881221: relax the constraints based on JSR202 spec
4255       legal = verify_unqualified_name(bytes, length, LegalMethod);
4256     }
4257   }
4258 
4259   if (!legal) {
4260     ResourceMark rm(THREAD);
4261     Exceptions::fthrow(
4262       THREAD_AND_LOCATION,
4263       vmSymbolHandles::java_lang_ClassFormatError(),
4264       "Illegal method name \"%s\" in class %s", bytes,
4265       _class_name->as_C_string()
4266     );
4267     return;
4268   }
4269 }
4270 
4271 
4272 // Checks if signature is a legal field signature.
4273 void ClassFileParser::verify_legal_field_signature(symbolHandle name, symbolHandle signature, TRAPS) {
4274   if (!_need_verify) { return; }
4275 
4276   char buf[fixed_buffer_size];
4277   char* bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
4278   unsigned int length = signature->utf8_length();
4279   char* p = skip_over_field_signature(bytes, false, length, CHECK);
4280 
4281   if (p == NULL || (p - bytes) != (int)length) {
4282     throwIllegalSignature("Field", name, signature, CHECK);
4283   }
4284 }
4285 
4286 // Checks if signature is a legal method signature.
4287 // Returns number of parameters
4288 int ClassFileParser::verify_legal_method_signature(symbolHandle name, symbolHandle signature, TRAPS) {
4289   if (!_need_verify) {
4290     // make sure caller's args_size will be less than 0 even for non-static
4291     // method so it will be recomputed in compute_size_of_parameters().
4292     return -2;
4293   }
4294 
4295   unsigned int args_size = 0;
4296   char buf[fixed_buffer_size];
4297   char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
4298   unsigned int length = signature->utf8_length();
4299   char* nextp;
4300 
4301   // The first character must be a '('
4302   if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
4303     length--;
4304     // Skip over legal field signatures
4305     nextp = skip_over_field_signature(p, false, length, CHECK_0);
4306     while ((length > 0) && (nextp != NULL)) {
4307       args_size++;
4308       if (p[0] == 'J' || p[0] == 'D') {
4309         args_size++;
4310       }
4311       length -= nextp - p;
4312       p = nextp;
4313       nextp = skip_over_field_signature(p, false, length, CHECK_0);
4314     }
4315     // The first non-signature thing better be a ')'
4316     if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
4317       length--;
4318       if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
4319         // All internal methods must return void
4320         if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
4321           return args_size;
4322         }
4323       } else {
4324         // Now we better just have a return value
4325         nextp = skip_over_field_signature(p, true, length, CHECK_0);
4326         if (nextp && ((int)length == (nextp - p))) {
4327           return args_size;
4328         }
4329       }
4330     }
4331   }
4332   // Report error
4333   throwIllegalSignature("Method", name, signature, CHECK_0);
4334   return 0;
4335 }
4336 
4337 
4338 // Unqualified names may not contain the characters '.', ';', '[', or '/'.
4339 // Method names also may not contain the characters '<' or '>', unless <init>
4340 // or <clinit>.  Note that method names may not be <init> or <clinit> in this
4341 // method.  Because these names have been checked as special cases before
4342 // calling this method in verify_legal_method_name.
4343 bool ClassFileParser::verify_unqualified_name(
4344     char* name, unsigned int length, int type) {
4345   jchar ch;
4346 
4347   for (char* p = name; p != name + length; ) {
4348     ch = *p;
4349     if (ch < 128) {
4350       p++;
4351       if (ch == '.' || ch == ';' || ch == '[' ) {
4352         return false;   // do not permit '.', ';', or '['
4353       }
4354       if (type != LegalClass && ch == '/') {
4355         return false;   // do not permit '/' unless it's class name
4356       }
4357       if (type == LegalMethod && (ch == '<' || ch == '>')) {
4358         return false;   // do not permit '<' or '>' in method names
4359       }
4360     } else {
4361       char* tmp_p = UTF8::next(p, &ch);
4362       p = tmp_p;
4363     }
4364   }
4365   return true;
4366 }
4367 
4368 
4369 // Take pointer to a string. Skip over the longest part of the string that could
4370 // be taken as a fieldname. Allow '/' if slash_ok is true.
4371 // Return a pointer to just past the fieldname.
4372 // Return NULL if no fieldname at all was found, or in the case of slash_ok
4373 // being true, we saw consecutive slashes (meaning we were looking for a
4374 // qualified path but found something that was badly-formed).
4375 char* ClassFileParser::skip_over_field_name(char* name, bool slash_ok, unsigned int length) {
4376   char* p;
4377   jchar ch;
4378   jboolean last_is_slash = false;
4379   jboolean not_first_ch = false;
4380 
4381   for (p = name; p != name + length; not_first_ch = true) {
4382     char* old_p = p;
4383     ch = *p;
4384     if (ch < 128) {
4385       p++;
4386       // quick check for ascii
4387       if ((ch >= 'a' && ch <= 'z') ||
4388           (ch >= 'A' && ch <= 'Z') ||
4389           (ch == '_' || ch == '$') ||
4390           (not_first_ch && ch >= '0' && ch <= '9')) {
4391         last_is_slash = false;
4392         continue;
4393       }
4394       if (slash_ok && ch == '/') {
4395         if (last_is_slash) {
4396           return NULL;  // Don't permit consecutive slashes
4397         }
4398         last_is_slash = true;
4399         continue;
4400       }
4401     } else {
4402       jint unicode_ch;
4403       char* tmp_p = UTF8::next_character(p, &unicode_ch);
4404       p = tmp_p;
4405       last_is_slash = false;
4406       // Check if ch is Java identifier start or is Java identifier part
4407       // 4672820: call java.lang.Character methods directly without generating separate tables.
4408       EXCEPTION_MARK;
4409       instanceKlassHandle klass (THREAD, SystemDictionary::Character_klass());
4410 
4411       // return value
4412       JavaValue result(T_BOOLEAN);
4413       // Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart
4414       JavaCallArguments args;
4415       args.push_int(unicode_ch);
4416 
4417       // public static boolean isJavaIdentifierStart(char ch);
4418       JavaCalls::call_static(&result,
4419                              klass,
4420                              vmSymbolHandles::isJavaIdentifierStart_name(),
4421                              vmSymbolHandles::int_bool_signature(),
4422                              &args,
4423                              THREAD);
4424 
4425       if (HAS_PENDING_EXCEPTION) {
4426         CLEAR_PENDING_EXCEPTION;
4427         return 0;
4428       }
4429       if (result.get_jboolean()) {
4430         continue;
4431       }
4432 
4433       if (not_first_ch) {
4434         // public static boolean isJavaIdentifierPart(char ch);
4435         JavaCalls::call_static(&result,
4436                                klass,
4437                                vmSymbolHandles::isJavaIdentifierPart_name(),
4438                                vmSymbolHandles::int_bool_signature(),
4439                                &args,
4440                                THREAD);
4441 
4442         if (HAS_PENDING_EXCEPTION) {
4443           CLEAR_PENDING_EXCEPTION;
4444           return 0;
4445         }
4446 
4447         if (result.get_jboolean()) {
4448           continue;
4449         }
4450       }
4451     }
4452     return (not_first_ch) ? old_p : NULL;
4453   }
4454   return (not_first_ch) ? p : NULL;
4455 }
4456 
4457 
4458 // Take pointer to a string. Skip over the longest part of the string that could
4459 // be taken as a field signature. Allow "void" if void_ok.
4460 // Return a pointer to just past the signature.
4461 // Return NULL if no legal signature is found.
4462 char* ClassFileParser::skip_over_field_signature(char* signature,
4463                                                  bool void_ok,
4464                                                  unsigned int length,
4465                                                  TRAPS) {
4466   unsigned int array_dim = 0;
4467   while (length > 0) {
4468     switch (signature[0]) {
4469       case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
4470       case JVM_SIGNATURE_BOOLEAN:
4471       case JVM_SIGNATURE_BYTE:
4472       case JVM_SIGNATURE_CHAR:
4473       case JVM_SIGNATURE_SHORT:
4474       case JVM_SIGNATURE_INT:
4475       case JVM_SIGNATURE_FLOAT:
4476       case JVM_SIGNATURE_LONG:
4477       case JVM_SIGNATURE_DOUBLE:
4478         return signature + 1;
4479       case JVM_SIGNATURE_CLASS: {
4480         if (_major_version < JAVA_1_5_VERSION) {
4481           // Skip over the class name if one is there
4482           char* p = skip_over_field_name(signature + 1, true, --length);
4483 
4484           // The next character better be a semicolon
4485           if (p && (p - signature) > 1 && p[0] == ';') {
4486             return p + 1;
4487           }
4488         } else {
4489           // 4900761: For class version > 48, any unicode is allowed in class name.
4490           length--;
4491           signature++;
4492           while (length > 0 && signature[0] != ';') {
4493             if (signature[0] == '.') {
4494               classfile_parse_error("Class name contains illegal character '.' in descriptor in class file %s", CHECK_0);
4495             }
4496             length--;
4497             signature++;
4498           }
4499           if (signature[0] == ';') { return signature + 1; }
4500         }
4501 
4502         return NULL;
4503       }
4504       case JVM_SIGNATURE_ARRAY:
4505         array_dim++;
4506         if (array_dim > 255) {
4507           // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
4508           classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
4509         }
4510         // The rest of what's there better be a legal signature
4511         signature++;
4512         length--;
4513         void_ok = false;
4514         break;
4515 
4516       default:
4517         return NULL;
4518     }
4519   }
4520   return NULL;
4521 }