classFileParser.cpp 212.7 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27
#include "precompiled.hpp"
#include "classfile/classFileParser.hpp"
#include "classfile/classLoader.hpp"
28 29
#include "classfile/classLoaderData.hpp"
#include "classfile/classLoaderData.inline.hpp"
30
#include "classfile/defaultMethods.hpp"
31 32 33
#include "classfile/javaClasses.hpp"
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
34 35 36
#if INCLUDE_CDS
#include "classfile/systemDictionaryShared.hpp"
#endif
37 38 39 40 41
#include "classfile/verificationType.hpp"
#include "classfile/verifier.hpp"
#include "classfile/vmSymbols.hpp"
#include "memory/allocation.hpp"
#include "memory/gcLocker.hpp"
42
#include "memory/metadataFactory.hpp"
43
#include "memory/oopFactory.hpp"
S
sla 已提交
44
#include "memory/referenceType.hpp"
45
#include "memory/universe.inline.hpp"
46
#include "oops/constantPool.hpp"
47
#include "oops/fieldStreams.hpp"
48
#include "oops/instanceKlass.hpp"
49
#include "oops/instanceMirrorKlass.hpp"
50 51
#include "oops/klass.inline.hpp"
#include "oops/klassVtable.hpp"
52
#include "oops/method.hpp"
53
#include "oops/symbol.hpp"
54
#include "prims/jvm.h"
55
#include "prims/jvmtiExport.hpp"
56
#include "prims/jvmtiThreadState.hpp"
57 58 59 60 61 62 63
#include "runtime/javaCalls.hpp"
#include "runtime/perfData.hpp"
#include "runtime/reflection.hpp"
#include "runtime/signature.hpp"
#include "runtime/timer.hpp"
#include "services/classLoadingService.hpp"
#include "services/threadService.hpp"
64
#include "utilities/array.hpp"
65
#include "utilities/globalDefinitions.hpp"
66
#include "utilities/ostream.hpp"
D
duke 已提交
67

68 69 70 71
// We generally try to create the oops directly when parsing, rather than
// allocating temporary data structures and copying the bytes twice. A
// temporary area is only needed when parsing utf8 entries in the constant
// pool and when parsing line number tables.
D
duke 已提交
72 73 74 75 76

// We add assert in debug mode when class format is not checked.

#define JAVA_CLASSFILE_MAGIC              0xCAFEBABE
#define JAVA_MIN_SUPPORTED_VERSION        45
77
#define JAVA_MAX_SUPPORTED_VERSION        52
D
duke 已提交
78 79 80 81 82 83 84 85 86
#define JAVA_MAX_SUPPORTED_MINOR_VERSION  0

// Used for two backward compatibility reasons:
// - to check for new additions to the class file format in JDK1.5
// - to check for bug fixes in the format checker in JDK1.5
#define JAVA_1_5_VERSION                  49

// Used for backward compatibility reasons:
// - to check for javac bug fixes that happened after 1.5
87
// - also used as the max version when running in jdk6
D
duke 已提交
88 89
#define JAVA_6_VERSION                    50

90 91 92 93
// Used for backward compatibility reasons:
// - to check NameAndType_info signatures more aggressively
#define JAVA_7_VERSION                    51

94 95 96
// Extension method support.
#define JAVA_8_VERSION                    52

97
void ClassFileParser::parse_constant_pool_entries(int length, TRAPS) {
D
duke 已提交
98 99 100 101 102 103 104 105 106
  // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
  // this function (_current can be allocated in a register, with scalar
  // replacement of aggregates). The _current pointer is copied back to
  // stream() when this function returns. DON'T call another method within
  // this method that uses stream().
  ClassFileStream* cfs0 = stream();
  ClassFileStream cfs1 = *cfs0;
  ClassFileStream* cfs = &cfs1;
#ifdef ASSERT
107
  assert(cfs->allocated_on_stack(),"should be local");
D
duke 已提交
108 109
  u1* old_current = cfs0->current();
#endif
110
  Handle class_loader(THREAD, _loader_data->class_loader());
D
duke 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

  // Used for batching symbol allocations.
  const char* names[SymbolTable::symbol_alloc_batch_size];
  int lengths[SymbolTable::symbol_alloc_batch_size];
  int indices[SymbolTable::symbol_alloc_batch_size];
  unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];
  int names_count = 0;

  // parsing  Index 0 is unused
  for (int index = 1; index < length; index++) {
    // Each of the following case guarantees one more byte in the stream
    // for the following tag or the access_flags following constant pool,
    // so we don't need bounds-check for reading tag.
    u1 tag = cfs->get_u1_fast();
    switch (tag) {
      case JVM_CONSTANT_Class :
        {
          cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
          u2 name_index = cfs->get_u2_fast();
130
          _cp->klass_index_at_put(index, name_index);
D
duke 已提交
131 132 133 134 135 136 137
        }
        break;
      case JVM_CONSTANT_Fieldref :
        {
          cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
          u2 class_index = cfs->get_u2_fast();
          u2 name_and_type_index = cfs->get_u2_fast();
138
          _cp->field_at_put(index, class_index, name_and_type_index);
D
duke 已提交
139 140 141 142 143 144 145
        }
        break;
      case JVM_CONSTANT_Methodref :
        {
          cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
          u2 class_index = cfs->get_u2_fast();
          u2 name_and_type_index = cfs->get_u2_fast();
146
          _cp->method_at_put(index, class_index, name_and_type_index);
D
duke 已提交
147 148 149 150 151 152 153
        }
        break;
      case JVM_CONSTANT_InterfaceMethodref :
        {
          cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
          u2 class_index = cfs->get_u2_fast();
          u2 name_and_type_index = cfs->get_u2_fast();
154
          _cp->interface_method_at_put(index, class_index, name_and_type_index);
D
duke 已提交
155 156 157 158 159 160
        }
        break;
      case JVM_CONSTANT_String :
        {
          cfs->guarantee_more(3, CHECK);  // string_index, tag/access_flags
          u2 string_index = cfs->get_u2_fast();
161
          _cp->string_index_at_put(index, string_index);
D
duke 已提交
162 163
        }
        break;
164 165
      case JVM_CONSTANT_MethodHandle :
      case JVM_CONSTANT_MethodType :
166
        if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
167
          classfile_parse_error(
168 169 170
            "Class file version does not support constant tag %u in class file %s",
            tag, CHECK);
        }
171
        if (!EnableInvokeDynamic) {
172 173
          classfile_parse_error(
            "This JVM does not support constant tag %u in class file %s",
174 175 176 177 178 179
            tag, CHECK);
        }
        if (tag == JVM_CONSTANT_MethodHandle) {
          cfs->guarantee_more(4, CHECK);  // ref_kind, method_index, tag/access_flags
          u1 ref_kind = cfs->get_u1_fast();
          u2 method_index = cfs->get_u2_fast();
180
          _cp->method_handle_index_at_put(index, ref_kind, method_index);
181 182 183
        } else if (tag == JVM_CONSTANT_MethodType) {
          cfs->guarantee_more(3, CHECK);  // signature_index, tag/access_flags
          u2 signature_index = cfs->get_u2_fast();
184
          _cp->method_type_index_at_put(index, signature_index);
185 186 187 188
        } else {
          ShouldNotReachHere();
        }
        break;
189 190
      case JVM_CONSTANT_InvokeDynamic :
        {
191 192 193 194 195 196
          if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
            classfile_parse_error(
              "Class file version does not support constant tag %u in class file %s",
              tag, CHECK);
          }
          if (!EnableInvokeDynamic) {
197
            classfile_parse_error(
198
              "This JVM does not support constant tag %u in class file %s",
199 200
              tag, CHECK);
          }
201 202 203 204 205
          cfs->guarantee_more(5, CHECK);  // bsm_index, nt, tag/access_flags
          u2 bootstrap_specifier_index = cfs->get_u2_fast();
          u2 name_and_type_index = cfs->get_u2_fast();
          if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index)
            _max_bootstrap_specifier_index = (int) bootstrap_specifier_index;  // collect for later
206
          _cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);
207 208
        }
        break;
D
duke 已提交
209 210 211 212
      case JVM_CONSTANT_Integer :
        {
          cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
          u4 bytes = cfs->get_u4_fast();
213
          _cp->int_at_put(index, (jint) bytes);
D
duke 已提交
214 215 216 217 218 219
        }
        break;
      case JVM_CONSTANT_Float :
        {
          cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
          u4 bytes = cfs->get_u4_fast();
220
          _cp->float_at_put(index, *(jfloat*)&bytes);
D
duke 已提交
221 222 223 224 225 226 227 228 229 230
        }
        break;
      case JVM_CONSTANT_Long :
        // A mangled type might cause you to overrun allocated memory
        guarantee_property(index+1 < length,
                           "Invalid constant pool entry %u in class file %s",
                           index, CHECK);
        {
          cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
          u8 bytes = cfs->get_u8_fast();
231
          _cp->long_at_put(index, bytes);
D
duke 已提交
232 233 234 235 236 237 238 239 240 241 242
        }
        index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
        break;
      case JVM_CONSTANT_Double :
        // A mangled type might cause you to overrun allocated memory
        guarantee_property(index+1 < length,
                           "Invalid constant pool entry %u in class file %s",
                           index, CHECK);
        {
          cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
          u8 bytes = cfs->get_u8_fast();
243
          _cp->double_at_put(index, *(jdouble*)&bytes);
D
duke 已提交
244 245 246 247 248 249 250 251
        }
        index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
        break;
      case JVM_CONSTANT_NameAndType :
        {
          cfs->guarantee_more(5, CHECK);  // name_index, signature_index, tag/access_flags
          u2 name_index = cfs->get_u2_fast();
          u2 signature_index = cfs->get_u2_fast();
252
          _cp->name_and_type_at_put(index, name_index, signature_index);
D
duke 已提交
253 254 255 256 257 258 259 260 261 262 263
        }
        break;
      case JVM_CONSTANT_Utf8 :
        {
          cfs->guarantee_more(2, CHECK);  // utf8_length
          u2  utf8_length = cfs->get_u2_fast();
          u1* utf8_buffer = cfs->get_u1_buffer();
          assert(utf8_buffer != NULL, "null utf8 buffer");
          // Got utf8 string, guarantee utf8_length+1 bytes, set stream position forward.
          cfs->guarantee_more(utf8_length+1, CHECK);  // utf8 string, tag/access_flags
          cfs->skip_u1_fast(utf8_length);
264

D
duke 已提交
265 266 267 268 269
          // Before storing the symbol, make sure it's legal
          if (_need_verify) {
            verify_legal_utf8((unsigned char*)utf8_buffer, utf8_length, CHECK);
          }

270
          if (EnableInvokeDynamic && has_cp_patch_at(index)) {
271 272 273 274 275 276 277
            Handle patch = clear_cp_patch_at(index);
            guarantee_property(java_lang_String::is_instance(patch()),
                               "Illegal utf8 patch at %d in class file %s",
                               index, CHECK);
            char* str = java_lang_String::as_utf8_string(patch());
            // (could use java_lang_String::as_symbol instead, but might as well batch them)
            utf8_buffer = (u1*) str;
278
            utf8_length = (u2) strlen(str);
279 280
          }

D
duke 已提交
281
          unsigned int hash;
282
          Symbol* result = SymbolTable::lookup_only((char*)utf8_buffer, utf8_length, hash);
D
duke 已提交
283 284 285 286 287 288
          if (result == NULL) {
            names[names_count] = (char*)utf8_buffer;
            lengths[names_count] = utf8_length;
            indices[names_count] = index;
            hashValues[names_count++] = hash;
            if (names_count == SymbolTable::symbol_alloc_batch_size) {
289
              SymbolTable::new_symbols(_loader_data, _cp, names_count, names, lengths, indices, hashValues, CHECK);
D
duke 已提交
290 291 292
              names_count = 0;
            }
          } else {
293
            _cp->symbol_at_put(index, result);
D
duke 已提交
294 295 296 297 298 299 300 301 302 303 304 305
          }
        }
        break;
      default:
        classfile_parse_error(
          "Unknown constant tag %u in class file %s", tag, CHECK);
        break;
    }
  }

  // Allocate the remaining symbols
  if (names_count > 0) {
306
    SymbolTable::new_symbols(_loader_data, _cp, names_count, names, lengths, indices, hashValues, CHECK);
D
duke 已提交
307 308 309 310 311 312 313 314 315 316 317
  }

  // Copy _current pointer of local copy back to stream().
#ifdef ASSERT
  assert(cfs0->current() == old_current, "non-exclusive use of stream()");
#endif
  cfs0->set_current(cfs1.current());
}

bool inline valid_cp_range(int index, int length) { return (index > 0 && index < length); }

318 319 320 321 322 323 324
inline Symbol* check_symbol_at(constantPoolHandle cp, int index) {
  if (valid_cp_range(index, cp->length()) && cp->tag_at(index).is_utf8())
    return cp->symbol_at(index);
  else
    return NULL;
}

325
constantPoolHandle ClassFileParser::parse_constant_pool(TRAPS) {
D
duke 已提交
326 327 328 329 330 331 332 333
  ClassFileStream* cfs = stream();
  constantPoolHandle nullHandle;

  cfs->guarantee_more(3, CHECK_(nullHandle)); // length, first cp tag
  u2 length = cfs->get_u2_fast();
  guarantee_property(
    length >= 1, "Illegal constant pool size %u in class file %s",
    length, CHECK_(nullHandle));
334 335 336
  ConstantPool* constant_pool = ConstantPool::allocate(_loader_data, length,
                                                        CHECK_(nullHandle));
  _cp = constant_pool; // save in case of errors
D
duke 已提交
337 338 339
  constantPoolHandle cp (THREAD, constant_pool);

  // parsing constant pool entries
340
  parse_constant_pool_entries(length, CHECK_(nullHandle));
D
duke 已提交
341 342 343 344 345

  int index = 1;  // declared outside of loops for portability

  // first verification pass - validate cross references and fixup class and string constants
  for (index = 1; index < length; index++) {          // Index 0 is unused
346 347
    jbyte tag = cp->tag_at(index).value();
    switch (tag) {
D
duke 已提交
348 349 350 351 352 353 354 355 356 357 358
      case JVM_CONSTANT_Class :
        ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
        break;
      case JVM_CONSTANT_Fieldref :
        // fall through
      case JVM_CONSTANT_Methodref :
        // fall through
      case JVM_CONSTANT_InterfaceMethodref : {
        if (!_need_verify) break;
        int klass_ref_index = cp->klass_ref_index_at(index);
        int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
359
        check_property(valid_klass_reference_at(klass_ref_index),
D
duke 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
                       "Invalid constant pool index %u in class file %s",
                       klass_ref_index,
                       CHECK_(nullHandle));
        check_property(valid_cp_range(name_and_type_ref_index, length) &&
                       cp->tag_at(name_and_type_ref_index).is_name_and_type(),
                       "Invalid constant pool index %u in class file %s",
                       name_and_type_ref_index,
                       CHECK_(nullHandle));
        break;
      }
      case JVM_CONSTANT_String :
        ShouldNotReachHere();     // Only JVM_CONSTANT_StringIndex should be present
        break;
      case JVM_CONSTANT_Integer :
        break;
      case JVM_CONSTANT_Float :
        break;
      case JVM_CONSTANT_Long :
      case JVM_CONSTANT_Double :
        index++;
        check_property(
          (index < length && cp->tag_at(index).is_invalid()),
          "Improper constant pool long/double index %u in class file %s",
          index, CHECK_(nullHandle));
        break;
      case JVM_CONSTANT_NameAndType : {
        if (!_need_verify) break;
        int name_ref_index = cp->name_ref_index_at(index);
        int signature_ref_index = cp->signature_ref_index_at(index);
389 390 391 392 393 394
        check_property(valid_symbol_at(name_ref_index),
                 "Invalid constant pool index %u in class file %s",
                 name_ref_index, CHECK_(nullHandle));
        check_property(valid_symbol_at(signature_ref_index),
                 "Invalid constant pool index %u in class file %s",
                 signature_ref_index, CHECK_(nullHandle));
D
duke 已提交
395 396 397 398 399 400 401 402 403 404 405
        break;
      }
      case JVM_CONSTANT_Utf8 :
        break;
      case JVM_CONSTANT_UnresolvedClass :         // fall-through
      case JVM_CONSTANT_UnresolvedClassInError:
        ShouldNotReachHere();     // Only JVM_CONSTANT_ClassIndex should be present
        break;
      case JVM_CONSTANT_ClassIndex :
        {
          int class_index = cp->klass_index_at(index);
406 407 408
          check_property(valid_symbol_at(class_index),
                 "Invalid constant pool index %u in class file %s",
                 class_index, CHECK_(nullHandle));
D
duke 已提交
409 410 411 412 413 414
          cp->unresolved_klass_at_put(index, cp->symbol_at(class_index));
        }
        break;
      case JVM_CONSTANT_StringIndex :
        {
          int string_index = cp->string_index_at(index);
415 416 417
          check_property(valid_symbol_at(string_index),
                 "Invalid constant pool index %u in class file %s",
                 string_index, CHECK_(nullHandle));
418
          Symbol* sym = cp->symbol_at(string_index);
D
duke 已提交
419 420 421
          cp->unresolved_string_at_put(index, sym);
        }
        break;
422 423 424 425 426
      case JVM_CONSTANT_MethodHandle :
        {
          int ref_index = cp->method_handle_index_at(index);
          check_property(
            valid_cp_range(ref_index, length) &&
427
                EnableInvokeDynamic,
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
              "Invalid constant pool index %u in class file %s",
              ref_index, CHECK_(nullHandle));
          constantTag tag = cp->tag_at(ref_index);
          int ref_kind  = cp->method_handle_ref_kind_at(index);
          switch (ref_kind) {
          case JVM_REF_getField:
          case JVM_REF_getStatic:
          case JVM_REF_putField:
          case JVM_REF_putStatic:
            check_property(
              tag.is_field(),
              "Invalid constant pool index %u in class file %s (not a field)",
              ref_index, CHECK_(nullHandle));
            break;
          case JVM_REF_invokeVirtual:
          case JVM_REF_newInvokeSpecial:
            check_property(
              tag.is_method(),
              "Invalid constant pool index %u in class file %s (not a method)",
              ref_index, CHECK_(nullHandle));
            break;
449 450
          case JVM_REF_invokeStatic:
          case JVM_REF_invokeSpecial:
451 452
            check_property(tag.is_method() ||
                           ((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()),
453 454 455
               "Invalid constant pool index %u in class file %s (not a method)",
               ref_index, CHECK_(nullHandle));
             break;
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
          case JVM_REF_invokeInterface:
            check_property(
              tag.is_interface_method(),
              "Invalid constant pool index %u in class file %s (not an interface method)",
              ref_index, CHECK_(nullHandle));
            break;
          default:
            classfile_parse_error(
              "Bad method handle kind at constant pool index %u in class file %s",
              index, CHECK_(nullHandle));
          }
          // Keep the ref_index unchanged.  It will be indirected at link-time.
        }
        break;
      case JVM_CONSTANT_MethodType :
        {
          int ref_index = cp->method_type_index_at(index);
473 474 475
          check_property(valid_symbol_at(ref_index) && EnableInvokeDynamic,
                 "Invalid constant pool index %u in class file %s",
                 ref_index, CHECK_(nullHandle));
476 477
        }
        break;
478 479 480 481 482 483 484 485
      case JVM_CONSTANT_InvokeDynamic :
        {
          int name_and_type_ref_index = cp->invoke_dynamic_name_and_type_ref_index_at(index);
          check_property(valid_cp_range(name_and_type_ref_index, length) &&
                         cp->tag_at(name_and_type_ref_index).is_name_and_type(),
                         "Invalid constant pool index %u in class file %s",
                         name_and_type_ref_index,
                         CHECK_(nullHandle));
486
          // bootstrap specifier index must be checked later, when BootstrapMethods attr is available
487 488
          break;
        }
D
duke 已提交
489
      default:
490 491
        fatal(err_msg("bad constant pool tag value %u",
                      cp->tag_at(index).value()));
D
duke 已提交
492 493 494 495 496
        ShouldNotReachHere();
        break;
    } // end of switch
  } // end of for

497 498
  if (_cp_patches != NULL) {
    // need to treat this_class specially...
499
    assert(EnableInvokeDynamic, "");
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    int this_class_index;
    {
      cfs->guarantee_more(8, CHECK_(nullHandle));  // flags, this_class, super_class, infs_len
      u1* mark = cfs->current();
      u2 flags         = cfs->get_u2_fast();
      this_class_index = cfs->get_u2_fast();
      cfs->set_current(mark);  // revert to mark
    }

    for (index = 1; index < length; index++) {          // Index 0 is unused
      if (has_cp_patch_at(index)) {
        guarantee_property(index != this_class_index,
                           "Illegal constant pool patch to self at %d in class file %s",
                           index, CHECK_(nullHandle));
        patch_constant_pool(cp, index, cp_patch_at(index), CHECK_(nullHandle));
      }
    }
  }

D
duke 已提交
519 520 521 522 523
  if (!_need_verify) {
    return cp;
  }

  // second verification pass - checks the strings are of the right format.
524
  // but not yet to the other entries
D
duke 已提交
525 526 527 528
  for (index = 1; index < length; index++) {
    jbyte tag = cp->tag_at(index).value();
    switch (tag) {
      case JVM_CONSTANT_UnresolvedClass: {
529
        Symbol*  class_name = cp->unresolved_klass_at(index);
530
        // check the name, even if _cp_patches will overwrite it
D
duke 已提交
531 532 533
        verify_legal_class_name(class_name, CHECK_(nullHandle));
        break;
      }
534 535 536 537
      case JVM_CONSTANT_NameAndType: {
        if (_need_verify && _major_version >= JAVA_7_VERSION) {
          int sig_index = cp->signature_ref_index_at(index);
          int name_index = cp->name_ref_index_at(index);
538 539
          Symbol*  name = cp->symbol_at(name_index);
          Symbol*  sig = cp->symbol_at(sig_index);
540 541 542
          guarantee_property(sig->utf8_length() != 0,
            "Illegal zero length constant pool entry at %d in class %s",
            sig_index, CHECK_(nullHandle));
543 544 545 546 547 548 549 550
          if (sig->byte_at(0) == JVM_SIGNATURE_FUNC) {
            verify_legal_method_signature(name, sig, CHECK_(nullHandle));
          } else {
            verify_legal_field_signature(name, sig, CHECK_(nullHandle));
          }
        }
        break;
      }
551
      case JVM_CONSTANT_InvokeDynamic:
D
duke 已提交
552 553 554 555 556 557 558 559
      case JVM_CONSTANT_Fieldref:
      case JVM_CONSTANT_Methodref:
      case JVM_CONSTANT_InterfaceMethodref: {
        int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
        // already verified to be utf8
        int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);
        // already verified to be utf8
        int signature_ref_index = cp->signature_ref_index_at(name_and_type_ref_index);
560 561
        Symbol*  name = cp->symbol_at(name_ref_index);
        Symbol*  signature = cp->symbol_at(signature_ref_index);
D
duke 已提交
562 563
        if (tag == JVM_CONSTANT_Fieldref) {
          verify_legal_field_name(name, CHECK_(nullHandle));
564 565
          if (_need_verify && _major_version >= JAVA_7_VERSION) {
            // Signature is verified above, when iterating NameAndType_info.
566 567 568
            // Need only to be sure it's non-zero length and the right type.
            if (signature->utf8_length() == 0 ||
                signature->byte_at(0) == JVM_SIGNATURE_FUNC) {
569 570 571 572 573 574
              throwIllegalSignature(
                  "Field", name, signature, CHECK_(nullHandle));
            }
          } else {
            verify_legal_field_signature(name, signature, CHECK_(nullHandle));
          }
D
duke 已提交
575 576
        } else {
          verify_legal_method_name(name, CHECK_(nullHandle));
577 578
          if (_need_verify && _major_version >= JAVA_7_VERSION) {
            // Signature is verified above, when iterating NameAndType_info.
579 580 581
            // Need only to be sure it's non-zero length and the right type.
            if (signature->utf8_length() == 0 ||
                signature->byte_at(0) != JVM_SIGNATURE_FUNC) {
582 583 584 585 586 587
              throwIllegalSignature(
                  "Method", name, signature, CHECK_(nullHandle));
            }
          } else {
            verify_legal_method_signature(name, signature, CHECK_(nullHandle));
          }
D
duke 已提交
588 589
          if (tag == JVM_CONSTANT_Methodref) {
            // 4509014: If a class method name begins with '<', it must be "<init>".
590
            assert(name != NULL, "method name in constant pool is null");
D
duke 已提交
591
            unsigned int name_len = name->utf8_length();
592
            if (name_len != 0 && name->byte_at(0) == '<') {
593
              if (name != vmSymbols::object_initializer_name()) {
D
duke 已提交
594 595 596 597 598 599 600 601 602
                classfile_parse_error(
                  "Bad method name at constant pool index %u in class file %s",
                  name_ref_index, CHECK_(nullHandle));
              }
            }
          }
        }
        break;
      }
603 604 605 606 607 608 609 610 611 612 613
      case JVM_CONSTANT_MethodHandle: {
        int ref_index = cp->method_handle_index_at(index);
        int ref_kind  = cp->method_handle_ref_kind_at(index);
        switch (ref_kind) {
        case JVM_REF_invokeVirtual:
        case JVM_REF_invokeStatic:
        case JVM_REF_invokeSpecial:
        case JVM_REF_newInvokeSpecial:
          {
            int name_and_type_ref_index = cp->name_and_type_ref_index_at(ref_index);
            int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);
614
            Symbol*  name = cp->symbol_at(name_ref_index);
615
            if (ref_kind == JVM_REF_newInvokeSpecial) {
616
              if (name != vmSymbols::object_initializer_name()) {
617 618 619 620 621
                classfile_parse_error(
                  "Bad constructor name at constant pool index %u in class file %s",
                  name_ref_index, CHECK_(nullHandle));
              }
            } else {
622
              if (name == vmSymbols::object_initializer_name()) {
623 624 625 626 627 628 629 630 631 632 633 634
                classfile_parse_error(
                  "Bad method name at constant pool index %u in class file %s",
                  name_ref_index, CHECK_(nullHandle));
              }
            }
          }
          break;
          // Other ref_kinds are already fully checked in previous pass.
        }
        break;
      }
      case JVM_CONSTANT_MethodType: {
635 636
        Symbol* no_name = vmSymbols::type_name(); // place holder
        Symbol*  signature = cp->method_type_signature_at(index);
637 638 639
        verify_legal_method_signature(no_name, signature, CHECK_(nullHandle));
        break;
      }
640 641 642
      case JVM_CONSTANT_Utf8: {
        assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");
      }
D
duke 已提交
643 644 645 646 647 648 649
    }  // end of switch
  }  // end of for

  return cp;
}


650
void ClassFileParser::patch_constant_pool(constantPoolHandle cp, int index, Handle patch, TRAPS) {
651
  assert(EnableInvokeDynamic, "");
652
  BasicType patch_type = T_VOID;
653

654 655 656 657 658
  switch (cp->tag_at(index).value()) {

  case JVM_CONSTANT_UnresolvedClass :
    // Patching a class means pre-resolving it.
    // The name in the constant pool is ignored.
659
    if (java_lang_Class::is_instance(patch())) {
660 661 662
      guarantee_property(!java_lang_Class::is_primitive(patch()),
                         "Illegal class patch at %d in class file %s",
                         index, CHECK);
663
      cp->klass_at_put(index, java_lang_Class::as_Klass(patch()));
664 665 666 667
    } else {
      guarantee_property(java_lang_String::is_instance(patch()),
                         "Illegal class patch at %d in class file %s",
                         index, CHECK);
668 669
      Symbol* name = java_lang_String::as_symbol(patch(), CHECK);
      cp->unresolved_klass_at_put(index, name);
670 671 672
    }
    break;

673 674 675 676
  case JVM_CONSTANT_String :
    // skip this patch and don't clear it.  Needs the oop array for resolved
    // references to be created first.
    return;
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

  case JVM_CONSTANT_Integer : patch_type = T_INT;    goto patch_prim;
  case JVM_CONSTANT_Float :   patch_type = T_FLOAT;  goto patch_prim;
  case JVM_CONSTANT_Long :    patch_type = T_LONG;   goto patch_prim;
  case JVM_CONSTANT_Double :  patch_type = T_DOUBLE; goto patch_prim;
  patch_prim:
    {
      jvalue value;
      BasicType value_type = java_lang_boxing_object::get_value(patch(), &value);
      guarantee_property(value_type == patch_type,
                         "Illegal primitive patch at %d in class file %s",
                         index, CHECK);
      switch (value_type) {
      case T_INT:    cp->int_at_put(index,   value.i); break;
      case T_FLOAT:  cp->float_at_put(index, value.f); break;
      case T_LONG:   cp->long_at_put(index,  value.j); break;
      case T_DOUBLE: cp->double_at_put(index, value.d); break;
      default:       assert(false, "");
      }
    }
    break;

  default:
    // %%% TODO: put method handles into CONSTANT_InterfaceMethodref, etc.
    guarantee_property(!has_cp_patch_at(index),
                       "Illegal unexpected patch at %d in class file %s",
                       index, CHECK);
    return;
  }

  // On fall-through, mark the patch as used.
  clear_cp_patch_at(index);
}



D
duke 已提交
713 714
class NameSigHash: public ResourceObj {
 public:
715 716
  Symbol*       _name;       // name
  Symbol*       _sig;        // signature
D
duke 已提交
717 718 719 720 721 722
  NameSigHash*  _next;       // Next entry in hash table
};


#define HASH_ROW_SIZE 256

723
unsigned int hash(Symbol* name, Symbol* sig) {
D
duke 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
  unsigned int raw_hash = 0;
  raw_hash += ((unsigned int)(uintptr_t)name) >> (LogHeapWordSize + 2);
  raw_hash += ((unsigned int)(uintptr_t)sig) >> LogHeapWordSize;

  return (raw_hash + (unsigned int)(uintptr_t)name) % HASH_ROW_SIZE;
}


void initialize_hashtable(NameSigHash** table) {
  memset((void*)table, 0, sizeof(NameSigHash*) * HASH_ROW_SIZE);
}

// Return false if the name/sig combination is found in table.
// Return true if no duplicate is found. And name/sig is added as a new entry in table.
// The old format checker uses heap sort to find duplicates.
// NOTE: caller should guarantee that GC doesn't happen during the life cycle
740 741
// of table since we don't expect Symbol*'s to move.
bool put_after_lookup(Symbol* name, Symbol* sig, NameSigHash** table) {
D
duke 已提交
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
  assert(name != NULL, "name in constant pool is NULL");

  // First lookup for duplicates
  int index = hash(name, sig);
  NameSigHash* entry = table[index];
  while (entry != NULL) {
    if (entry->_name == name && entry->_sig == sig) {
      return false;
    }
    entry = entry->_next;
  }

  // No duplicate is found, allocate a new entry and fill it.
  entry = new NameSigHash();
  entry->_name = name;
  entry->_sig = sig;

  // Insert into hash table
  entry->_next = table[index];
  table[index] = entry;

  return true;
}


767
Array<Klass*>* ClassFileParser::parse_interfaces(int length,
D
duke 已提交
768
                                                 Handle protection_domain,
769
                                                 Symbol* class_name,
770
                                                 bool* has_default_methods,
D
duke 已提交
771
                                                 TRAPS) {
772 773 774 775 776 777
  if (length == 0) {
    _local_interfaces = Universe::the_empty_klass_array();
  } else {
    ClassFileStream* cfs = stream();
    assert(length > 0, "only called for length>0");
    _local_interfaces = MetadataFactory::new_array<Klass*>(_loader_data, length, NULL, CHECK_NULL);
D
duke 已提交
778

779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    int index;
    for (index = 0; index < length; index++) {
      u2 interface_index = cfs->get_u2(CHECK_NULL);
      KlassHandle interf;
      check_property(
        valid_klass_reference_at(interface_index),
        "Interface name has bad constant pool index %u in class file %s",
        interface_index, CHECK_NULL);
      if (_cp->tag_at(interface_index).is_klass()) {
        interf = KlassHandle(THREAD, _cp->resolved_klass_at(interface_index));
      } else {
        Symbol*  unresolved_klass  = _cp->klass_name_at(interface_index);

        // Don't need to check legal name because it's checked when parsing constant pool.
        // But need to make sure it's not an array type.
        guarantee_property(unresolved_klass->byte_at(0) != JVM_SIGNATURE_ARRAY,
                           "Bad interface name in class file %s", CHECK_NULL);
        Handle class_loader(THREAD, _loader_data->class_loader());

        // Call resolve_super so classcircularity is checked
        Klass* k = SystemDictionary::resolve_super_or_fail(class_name,
                      unresolved_klass, class_loader, protection_domain,
                      false, CHECK_NULL);
        interf = KlassHandle(THREAD, k);
      }

      if (!interf()->is_interface()) {
        THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(), "Implementing class", NULL);
      }
      if (InstanceKlass::cast(interf())->has_default_methods()) {
        *has_default_methods = true;
      }
      _local_interfaces->at_put(index, interf());
812
    }
D
duke 已提交
813

814 815 816
    if (!_need_verify || length <= 1) {
      return _local_interfaces;
    }
D
duke 已提交
817

818 819 820 821 822 823
    // Check if there's any duplicates in interfaces
    ResourceMark rm(THREAD);
    NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(
      THREAD, NameSigHash*, HASH_ROW_SIZE);
    initialize_hashtable(interface_names);
    bool dup = false;
824
    Symbol* name = NULL;
825 826 827 828
    {
      debug_only(No_Safepoint_Verifier nsv;)
      for (index = 0; index < length; index++) {
        Klass* k = _local_interfaces->at(index);
829
        name = InstanceKlass::cast(k)->name();
830 831 832 833 834
        // If no duplicates, add (name, NULL) in hashtable interface_names.
        if (!put_after_lookup(name, NULL, interface_names)) {
          dup = true;
          break;
        }
D
duke 已提交
835 836
      }
    }
837
    if (dup) {
838 839
      classfile_parse_error("Duplicate interface name \"%s\" in class file %s",
               name->as_C_string(), CHECK_NULL);
840
    }
D
duke 已提交
841
  }
842
  return _local_interfaces;
D
duke 已提交
843 844 845
}


846
void ClassFileParser::verify_constantvalue(int constantvalue_index, int signature_index, TRAPS) {
D
duke 已提交
847 848 849
  // Make sure the constant pool entry is of a type appropriate to this field
  guarantee_property(
    (constantvalue_index > 0 &&
850
      constantvalue_index < _cp->length()),
D
duke 已提交
851 852
    "Bad initial value index %u in ConstantValue attribute in class file %s",
    constantvalue_index, CHECK);
853 854
  constantTag value_type = _cp->tag_at(constantvalue_index);
  switch ( _cp->basic_type_for_signature_at(signature_index) ) {
D
duke 已提交
855 856 857 858 859 860 861 862 863 864 865 866 867
    case T_LONG:
      guarantee_property(value_type.is_long(), "Inconsistent constant value type in class file %s", CHECK);
      break;
    case T_FLOAT:
      guarantee_property(value_type.is_float(), "Inconsistent constant value type in class file %s", CHECK);
      break;
    case T_DOUBLE:
      guarantee_property(value_type.is_double(), "Inconsistent constant value type in class file %s", CHECK);
      break;
    case T_BYTE: case T_CHAR: case T_SHORT: case T_BOOLEAN: case T_INT:
      guarantee_property(value_type.is_int(), "Inconsistent constant value type in class file %s", CHECK);
      break;
    case T_OBJECT:
868
      guarantee_property((_cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
869
                         && value_type.is_string()),
D
duke 已提交
870 871 872 873 874 875 876 877 878 879 880
                         "Bad string initial value in class file %s", CHECK);
      break;
    default:
      classfile_parse_error(
        "Unable to set initial value %u in class file %s",
        constantvalue_index, CHECK);
  }
}


// Parse attributes for a field.
881
void ClassFileParser::parse_field_attributes(u2 attributes_count,
D
duke 已提交
882 883 884 885
                                             bool is_static, u2 signature_index,
                                             u2* constantvalue_index_addr,
                                             bool* is_synthetic_addr,
                                             u2* generic_signature_index_addr,
886
                                             ClassFileParser::FieldAnnotationCollector* parsed_annotations,
D
duke 已提交
887 888 889 890 891 892 893 894 895 896
                                             TRAPS) {
  ClassFileStream* cfs = stream();
  assert(attributes_count > 0, "length should be greater than 0");
  u2 constantvalue_index = 0;
  u2 generic_signature_index = 0;
  bool is_synthetic = false;
  u1* runtime_visible_annotations = NULL;
  int runtime_visible_annotations_length = 0;
  u1* runtime_invisible_annotations = NULL;
  int runtime_invisible_annotations_length = 0;
897 898 899 900
  u1* runtime_visible_type_annotations = NULL;
  int runtime_visible_type_annotations_length = 0;
  u1* runtime_invisible_type_annotations = NULL;
  int runtime_invisible_type_annotations_length = 0;
901
  bool runtime_invisible_type_annotations_exists = false;
D
duke 已提交
902 903 904 905
  while (attributes_count--) {
    cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
    u2 attribute_name_index = cfs->get_u2_fast();
    u4 attribute_length = cfs->get_u4_fast();
906
    check_property(valid_symbol_at(attribute_name_index),
D
duke 已提交
907 908 909
                   "Invalid field attribute index %u in class file %s",
                   attribute_name_index,
                   CHECK);
910
    Symbol* attribute_name = _cp->symbol_at(attribute_name_index);
D
duke 已提交
911 912 913 914 915 916 917 918 919 920 921
    if (is_static && attribute_name == vmSymbols::tag_constant_value()) {
      // ignore if non-static
      if (constantvalue_index != 0) {
        classfile_parse_error("Duplicate ConstantValue attribute in class file %s", CHECK);
      }
      check_property(
        attribute_length == 2,
        "Invalid ConstantValue field attribute length %u in class file %s",
        attribute_length, CHECK);
      constantvalue_index = cfs->get_u2(CHECK);
      if (_need_verify) {
922
        verify_constantvalue(constantvalue_index, signature_index, CHECK);
D
duke 已提交
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
      }
    } else if (attribute_name == vmSymbols::tag_synthetic()) {
      if (attribute_length != 0) {
        classfile_parse_error(
          "Invalid Synthetic field attribute length %u in class file %s",
          attribute_length, CHECK);
      }
      is_synthetic = true;
    } else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120
      if (attribute_length != 0) {
        classfile_parse_error(
          "Invalid Deprecated field attribute length %u in class file %s",
          attribute_length, CHECK);
      }
    } else if (_major_version >= JAVA_1_5_VERSION) {
      if (attribute_name == vmSymbols::tag_signature()) {
        if (attribute_length != 2) {
          classfile_parse_error(
            "Wrong size %u for field's Signature attribute in class file %s",
            attribute_length, CHECK);
        }
944
        generic_signature_index = parse_generic_signature_attribute(CHECK);
D
duke 已提交
945 946 947 948
      } else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
        runtime_visible_annotations_length = attribute_length;
        runtime_visible_annotations = cfs->get_u1_buffer();
        assert(runtime_visible_annotations != NULL, "null visible annotations");
949
        cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
950
        parse_annotations(runtime_visible_annotations,
951 952 953
                          runtime_visible_annotations_length,
                          parsed_annotations,
                          CHECK);
954
        cfs->skip_u1_fast(runtime_visible_annotations_length);
D
duke 已提交
955 956 957 958 959
      } else if (PreserveAllAnnotations && attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
        runtime_invisible_annotations_length = attribute_length;
        runtime_invisible_annotations = cfs->get_u1_buffer();
        assert(runtime_invisible_annotations != NULL, "null invisible annotations");
        cfs->skip_u1(runtime_invisible_annotations_length, CHECK);
960
      } else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
961 962 963 964
        if (runtime_visible_type_annotations != NULL) {
          classfile_parse_error(
            "Multiple RuntimeVisibleTypeAnnotations attributes for field in class file %s", CHECK);
        }
965 966 967 968
        runtime_visible_type_annotations_length = attribute_length;
        runtime_visible_type_annotations = cfs->get_u1_buffer();
        assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
        cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
969 970 971 972 973 974 975 976 977 978 979 980 981
      } else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
        if (runtime_invisible_type_annotations_exists) {
          classfile_parse_error(
            "Multiple RuntimeInvisibleTypeAnnotations attributes for field in class file %s", CHECK);
        } else {
          runtime_invisible_type_annotations_exists = true;
        }
        if (PreserveAllAnnotations) {
          runtime_invisible_type_annotations_length = attribute_length;
          runtime_invisible_type_annotations = cfs->get_u1_buffer();
          assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
        }
        cfs->skip_u1(attribute_length, CHECK);
D
duke 已提交
982 983 984 985 986 987 988 989 990 991 992
      } else {
        cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
      }
    } else {
      cfs->skip_u1(attribute_length, CHECK);  // Skip unknown attributes
    }
  }

  *constantvalue_index_addr = constantvalue_index;
  *is_synthetic_addr = is_synthetic;
  *generic_signature_index_addr = generic_signature_index;
993
  AnnotationArray* a = assemble_annotations(runtime_visible_annotations,
D
duke 已提交
994 995 996 997
                                            runtime_visible_annotations_length,
                                            runtime_invisible_annotations,
                                            runtime_invisible_annotations_length,
                                            CHECK);
998 999 1000 1001 1002 1003 1004
  parsed_annotations->set_field_annotations(a);
  a = assemble_annotations(runtime_visible_type_annotations,
                           runtime_visible_type_annotations_length,
                           runtime_invisible_type_annotations,
                           runtime_invisible_type_annotations_length,
                           CHECK);
  parsed_annotations->set_field_type_annotations(a);
D
duke 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  return;
}


// Field allocation types. Used for computing field offsets.

enum FieldAllocationType {
  STATIC_OOP,           // Oops
  STATIC_BYTE,          // Boolean, Byte, char
  STATIC_SHORT,         // shorts
  STATIC_WORD,          // ints
1016
  STATIC_DOUBLE,        // aligned long or double
D
duke 已提交
1017 1018 1019 1020 1021
  NONSTATIC_OOP,
  NONSTATIC_BYTE,
  NONSTATIC_SHORT,
  NONSTATIC_WORD,
  NONSTATIC_DOUBLE,
1022 1023
  MAX_FIELD_ALLOCATION_TYPE,
  BAD_ALLOCATION_TYPE = -1
D
duke 已提交
1024 1025
};

1026 1027 1028 1029 1030
static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {
  BAD_ALLOCATION_TYPE, // 0
  BAD_ALLOCATION_TYPE, // 1
  BAD_ALLOCATION_TYPE, // 2
  BAD_ALLOCATION_TYPE, // 3
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
  NONSTATIC_BYTE ,     // T_BOOLEAN     =  4,
  NONSTATIC_SHORT,     // T_CHAR        =  5,
  NONSTATIC_WORD,      // T_FLOAT       =  6,
  NONSTATIC_DOUBLE,    // T_DOUBLE      =  7,
  NONSTATIC_BYTE,      // T_BYTE        =  8,
  NONSTATIC_SHORT,     // T_SHORT       =  9,
  NONSTATIC_WORD,      // T_INT         = 10,
  NONSTATIC_DOUBLE,    // T_LONG        = 11,
  NONSTATIC_OOP,       // T_OBJECT      = 12,
  NONSTATIC_OOP,       // T_ARRAY       = 13,
  BAD_ALLOCATION_TYPE, // T_VOID        = 14,
  BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
  BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
  BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
  BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
  BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,
1047 1048 1049 1050
  BAD_ALLOCATION_TYPE, // 0
  BAD_ALLOCATION_TYPE, // 1
  BAD_ALLOCATION_TYPE, // 2
  BAD_ALLOCATION_TYPE, // 3
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
  STATIC_BYTE ,        // T_BOOLEAN     =  4,
  STATIC_SHORT,        // T_CHAR        =  5,
  STATIC_WORD,         // T_FLOAT       =  6,
  STATIC_DOUBLE,       // T_DOUBLE      =  7,
  STATIC_BYTE,         // T_BYTE        =  8,
  STATIC_SHORT,        // T_SHORT       =  9,
  STATIC_WORD,         // T_INT         = 10,
  STATIC_DOUBLE,       // T_LONG        = 11,
  STATIC_OOP,          // T_OBJECT      = 12,
  STATIC_OOP,          // T_ARRAY       = 13,
  BAD_ALLOCATION_TYPE, // T_VOID        = 14,
  BAD_ALLOCATION_TYPE, // T_ADDRESS     = 15,
  BAD_ALLOCATION_TYPE, // T_NARROWOOP   = 16,
  BAD_ALLOCATION_TYPE, // T_METADATA    = 17,
  BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,
  BAD_ALLOCATION_TYPE, // T_CONFLICT    = 19,
1067 1068 1069 1070 1071 1072 1073 1074
};

static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type) {
  assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");
  FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];
  assert(result != BAD_ALLOCATION_TYPE, "bad type");
  return result;
}
D
duke 已提交
1075

1076 1077
class FieldAllocationCount: public ResourceObj {
 public:
1078
  u2 count[MAX_FIELD_ALLOCATION_TYPE];
1079 1080 1081 1082 1083 1084 1085 1086 1087

  FieldAllocationCount() {
    for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {
      count[i] = 0;
    }
  }

  FieldAllocationType update(bool is_static, BasicType type) {
    FieldAllocationType atype = basic_type_to_atype(is_static, type);
1088 1089
    // Make sure there is no overflow with injected fields.
    assert(count[atype] < 0xFFFF, "More than 65535 fields");
1090 1091 1092
    count[atype]++;
    return atype;
  }
D
duke 已提交
1093 1094
};

1095
Array<u2>* ClassFileParser::parse_fields(Symbol* class_name,
1096 1097 1098
                                         bool is_interface,
                                         FieldAllocationCount *fac,
                                         u2* java_fields_count_ptr, TRAPS) {
D
duke 已提交
1099
  ClassFileStream* cfs = stream();
1100
  cfs->guarantee_more(2, CHECK_NULL);  // length
D
duke 已提交
1101
  u2 length = cfs->get_u2_fast();
1102 1103 1104 1105
  *java_fields_count_ptr = length;

  int num_injected = 0;
  InjectedField* injected = JavaClasses::get_injected(class_name, &num_injected);
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
  int total_fields = length + num_injected;

  // The field array starts with tuples of shorts
  // [access, name index, sig index, initial value index, byte offset].
  // A generic signature slot only exists for field with generic
  // signature attribute. And the access flag is set with
  // JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE for that field. The generic
  // signature slots are at the end of the field array and after all
  // other fields data.
  //
  //   f1: [access, name index, sig index, initial value index, low_offset, high_offset]
  //   f2: [access, name index, sig index, initial value index, low_offset, high_offset]
  //       ...
  //   fn: [access, name index, sig index, initial value index, low_offset, high_offset]
  //       [generic signature index]
  //       [generic signature index]
  //       ...
  //
  // Allocate a temporary resource array for field data. For each field,
  // a slot is reserved in the temporary array for the generic signature
  // index. After parsing all fields, the data are copied to a permanent
  // array and any unused slots will be discarded.
  ResourceMark rm(THREAD);
  u2* fa = NEW_RESOURCE_ARRAY_IN_THREAD(
             THREAD, u2, total_fields * (FieldInfo::field_slots + 1));
D
duke 已提交
1131

1132 1133 1134
  // The generic signature slots start after all other fields' data.
  int generic_signature_slot = total_fields * FieldInfo::field_slots;
  int num_generic_signature = 0;
D
duke 已提交
1135
  for (int n = 0; n < length; n++) {
1136
    cfs->guarantee_more(8, CHECK_NULL);  // access_flags, name_index, descriptor_index, attributes_count
D
duke 已提交
1137 1138 1139

    AccessFlags access_flags;
    jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;
1140
    verify_legal_field_modifiers(flags, is_interface, CHECK_NULL);
D
duke 已提交
1141 1142 1143
    access_flags.set_flags(flags);

    u2 name_index = cfs->get_u2_fast();
1144 1145
    int cp_size = _cp->length();
    check_property(valid_symbol_at(name_index),
D
duke 已提交
1146
      "Invalid constant pool index %u for field name in class file %s",
1147 1148 1149
      name_index,
      CHECK_NULL);
    Symbol*  name = _cp->symbol_at(name_index);
1150
    verify_legal_field_name(name, CHECK_NULL);
D
duke 已提交
1151 1152

    u2 signature_index = cfs->get_u2_fast();
1153
    check_property(valid_symbol_at(signature_index),
D
duke 已提交
1154
      "Invalid constant pool index %u for field signature in class file %s",
1155
      signature_index, CHECK_NULL);
1156
    Symbol*  sig = _cp->symbol_at(signature_index);
1157
    verify_legal_field_signature(name, sig, CHECK_NULL);
D
duke 已提交
1158 1159 1160 1161 1162

    u2 constantvalue_index = 0;
    bool is_synthetic = false;
    u2 generic_signature_index = 0;
    bool is_static = access_flags.is_static();
1163
    FieldAnnotationCollector parsed_annotations(_loader_data);
D
duke 已提交
1164 1165 1166

    u2 attributes_count = cfs->get_u2_fast();
    if (attributes_count > 0) {
1167
      parse_field_attributes(attributes_count, is_static, signature_index,
D
duke 已提交
1168
                             &constantvalue_index, &is_synthetic,
1169
                             &generic_signature_index, &parsed_annotations,
1170
                             CHECK_NULL);
1171 1172 1173 1174
      if (parsed_annotations.field_annotations() != NULL) {
        if (_fields_annotations == NULL) {
          _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
                                             _loader_data, length, NULL,
1175
                                             CHECK_NULL);
D
duke 已提交
1176
        }
1177 1178
        _fields_annotations->at_put(n, parsed_annotations.field_annotations());
        parsed_annotations.set_field_annotations(NULL);
D
duke 已提交
1179
      }
1180 1181 1182 1183
      if (parsed_annotations.field_type_annotations() != NULL) {
        if (_fields_type_annotations == NULL) {
          _fields_type_annotations = MetadataFactory::new_array<AnnotationArray*>(
                                                  _loader_data, length, NULL,
1184 1185
                                                  CHECK_NULL);
        }
1186 1187
        _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
        parsed_annotations.set_field_type_annotations(NULL);
1188
      }
1189

D
duke 已提交
1190 1191 1192
      if (is_synthetic) {
        access_flags.set_is_synthetic();
      }
1193 1194 1195 1196 1197 1198
      if (generic_signature_index != 0) {
        access_flags.set_field_has_generic_signature();
        fa[generic_signature_slot] = generic_signature_index;
        generic_signature_slot ++;
        num_generic_signature ++;
      }
D
duke 已提交
1199 1200
    }

1201
    FieldInfo* field = FieldInfo::from_field_array(fa, n);
1202 1203 1204
    field->initialize(access_flags.as_short(),
                      name_index,
                      signature_index,
1205
                      constantvalue_index);
1206
    BasicType type = _cp->basic_type_for_signature_at(signature_index);
1207 1208 1209

    // Remember how many oops we encountered and compute allocation type
    FieldAllocationType atype = fac->update(is_static, type);
1210
    field->set_allocation_type(atype);
1211

1212 1213 1214
    // After field is initialized with type, we can augment it with aux info
    if (parsed_annotations.has_any_annotations())
      parsed_annotations.apply_to(field);
1215 1216
  }

1217
  int index = length;
1218 1219 1220 1221 1222 1223 1224 1225
  if (num_injected != 0) {
    for (int n = 0; n < num_injected; n++) {
      // Check for duplicates
      if (injected[n].may_be_java) {
        Symbol* name      = injected[n].name();
        Symbol* signature = injected[n].signature();
        bool duplicate = false;
        for (int i = 0; i < length; i++) {
1226
          FieldInfo* f = FieldInfo::from_field_array(fa, i);
1227 1228
          if (name      == _cp->symbol_at(f->name_index()) &&
              signature == _cp->symbol_at(f->signature_index())) {
1229 1230 1231
            // Symbol is desclared in Java so skip this one
            duplicate = true;
            break;
D
duke 已提交
1232
          }
1233 1234 1235 1236 1237
        }
        if (duplicate) {
          // These will be removed from the field array at the end
          continue;
        }
D
duke 已提交
1238
      }
1239 1240

      // Injected field
1241
      FieldInfo* field = FieldInfo::from_field_array(fa, index);
1242 1243 1244 1245 1246 1247 1248 1249 1250
      field->initialize(JVM_ACC_FIELD_INTERNAL,
                        injected[n].name_index,
                        injected[n].signature_index,
                        0);

      BasicType type = FieldType::basic_type(injected[n].signature());

      // Remember how many oops we encountered and compute allocation type
      FieldAllocationType atype = fac->update(false, type);
1251
      field->set_allocation_type(atype);
1252
      index++;
D
duke 已提交
1253
    }
1254
  }
D
duke 已提交
1255

1256 1257 1258 1259 1260
  // Now copy the fields' data from the temporary resource array.
  // Sometimes injected fields already exist in the Java source so
  // the fields array could be too long.  In that case the
  // fields array is trimed. Also unused slots that were reserved
  // for generic signature indexes are discarded.
1261
  Array<u2>* fields = MetadataFactory::new_array<u2>(
1262
          _loader_data, index * FieldInfo::field_slots + num_generic_signature,
1263
          CHECK_NULL);
1264
  _fields = fields; // save in case of error
1265 1266 1267
  {
    int i = 0;
    for (; i < index * FieldInfo::field_slots; i++) {
1268
      fields->at_put(i, fa[i]);
1269 1270 1271
    }
    for (int j = total_fields * FieldInfo::field_slots;
         j < generic_signature_slot; j++) {
1272
      fields->at_put(i++, fa[j]);
1273
    }
1274
    assert(i == fields->length(), "");
D
duke 已提交
1275 1276 1277 1278 1279 1280 1281 1282 1283
  }

  if (_need_verify && length > 1) {
    // Check duplicated fields
    ResourceMark rm(THREAD);
    NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
      THREAD, NameSigHash*, HASH_ROW_SIZE);
    initialize_hashtable(names_and_sigs);
    bool dup = false;
1284 1285
    Symbol* name = NULL;
    Symbol* sig = NULL;
D
duke 已提交
1286 1287
    {
      debug_only(No_Safepoint_Verifier nsv;)
1288
      for (AllFieldStream fs(fields, _cp); !fs.done(); fs.next()) {
1289 1290
        name = fs.name();
        sig = fs.signature();
D
duke 已提交
1291 1292 1293 1294 1295 1296 1297 1298
        // If no duplicates, add name/signature in hashtable names_and_sigs.
        if (!put_after_lookup(name, sig, names_and_sigs)) {
          dup = true;
          break;
        }
      }
    }
    if (dup) {
1299 1300
      classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",
                             name->as_C_string(), sig->as_klass_external_name(), CHECK_NULL);
D
duke 已提交
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
    }
  }

  return fields;
}


static void copy_u2_with_conversion(u2* dest, u2* src, int length) {
  while (length-- > 0) {
    *dest++ = Bytes::get_Java_u2((u1*) (src++));
  }
}


1315
u2* ClassFileParser::parse_exception_table(u4 code_length,
1316 1317
                                           u4 exception_table_length,
                                           TRAPS) {
D
duke 已提交
1318 1319
  ClassFileStream* cfs = stream();

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
  u2* exception_table_start = cfs->get_u2_buffer();
  assert(exception_table_start != NULL, "null exception table");
  cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc, end_pc, handler_pc, catch_type_index
  // Will check legal target after parsing code array in verifier.
  if (_need_verify) {
    for (unsigned int i = 0; i < exception_table_length; i++) {
      u2 start_pc = cfs->get_u2_fast();
      u2 end_pc = cfs->get_u2_fast();
      u2 handler_pc = cfs->get_u2_fast();
      u2 catch_type_index = cfs->get_u2_fast();
D
duke 已提交
1330
      guarantee_property((start_pc < end_pc) && (end_pc <= code_length),
1331 1332
                         "Illegal exception table range in class file %s",
                         CHECK_NULL);
D
duke 已提交
1333
      guarantee_property(handler_pc < code_length,
1334 1335
                         "Illegal exception table handler in class file %s",
                         CHECK_NULL);
D
duke 已提交
1336
      if (catch_type_index != 0) {
1337
        guarantee_property(valid_klass_reference_at(catch_type_index),
1338
                           "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
D
duke 已提交
1339 1340
      }
    }
1341 1342
  } else {
    cfs->skip_u2_fast(exception_table_length * 4);
D
duke 已提交
1343
  }
1344
  return exception_table_start;
D
duke 已提交
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
}

void ClassFileParser::parse_linenumber_table(
    u4 code_attribute_length, u4 code_length,
    CompressedLineNumberWriteStream** write_stream, TRAPS) {
  ClassFileStream* cfs = stream();
  unsigned int num_entries = cfs->get_u2(CHECK);

  // Each entry is a u2 start_pc, and a u2 line_number
  unsigned int length_in_bytes = num_entries * (sizeof(u2) + sizeof(u2));

  // Verify line number attribute and table length
  check_property(
    code_attribute_length == sizeof(u2) + length_in_bytes,
    "LineNumberTable attribute has wrong length in class file %s", CHECK);

  cfs->guarantee_more(length_in_bytes, CHECK);

  if ((*write_stream) == NULL) {
    if (length_in_bytes > fixed_buffer_size) {
      (*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);
    } else {
      (*write_stream) = new CompressedLineNumberWriteStream(
        linenumbertable_buffer, fixed_buffer_size);
    }
  }

  while (num_entries-- > 0) {
    u2 bci  = cfs->get_u2_fast(); // start_pc
    u2 line = cfs->get_u2_fast(); // line_number
    guarantee_property(bci < code_length,
        "Invalid pc in LineNumberTable in class file %s", CHECK);
    (*write_stream)->write_pair(bci, line);
  }
}


// Class file LocalVariableTable elements.
class Classfile_LVT_Element VALUE_OBJ_CLASS_SPEC {
 public:
  u2 start_bci;
  u2 length;
  u2 name_cp_index;
  u2 descriptor_cp_index;
  u2 slot;
};


Z
zgu 已提交
1393
class LVT_Hash: public CHeapObj<mtClass> {
D
duke 已提交
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
 public:
  LocalVariableTableElement  *_elem;  // element
  LVT_Hash*                   _next;  // Next entry in hash table
};

unsigned int hash(LocalVariableTableElement *elem) {
  unsigned int raw_hash = elem->start_bci;

  raw_hash = elem->length        + raw_hash * 37;
  raw_hash = elem->name_cp_index + raw_hash * 37;
  raw_hash = elem->slot          + raw_hash * 37;

  return raw_hash % HASH_ROW_SIZE;
}

void initialize_hashtable(LVT_Hash** table) {
  for (int i = 0; i < HASH_ROW_SIZE; i++) {
    table[i] = NULL;
  }
}

void clear_hashtable(LVT_Hash** table) {
  for (int i = 0; i < HASH_ROW_SIZE; i++) {
    LVT_Hash* current = table[i];
    LVT_Hash* next;
    while (current != NULL) {
      next = current->_next;
      current->_next = NULL;
      delete(current);
      current = next;
    }
    table[i] = NULL;
  }
}

LVT_Hash* LVT_lookup(LocalVariableTableElement *elem, int index, LVT_Hash** table) {
  LVT_Hash* entry = table[index];

  /*
   * 3-tuple start_bci/length/slot has to be unique key,
   * so the following comparison seems to be redundant:
   *       && elem->name_cp_index == entry->_elem->name_cp_index
   */
  while (entry != NULL) {
    if (elem->start_bci           == entry->_elem->start_bci
     && elem->length              == entry->_elem->length
     && elem->name_cp_index       == entry->_elem->name_cp_index
     && elem->slot                == entry->_elem->slot
    ) {
      return entry;
    }
    entry = entry->_next;
  }
  return NULL;
}

// Return false if the local variable is found in table.
// Return true if no duplicate is found.
// And local variable is added as a new entry in table.
bool LVT_put_after_lookup(LocalVariableTableElement *elem, LVT_Hash** table) {
  // First lookup for duplicates
  int index = hash(elem);
  LVT_Hash* entry = LVT_lookup(elem, index, table);

  if (entry != NULL) {
      return false;
  }
  // No duplicate is found, allocate a new entry and fill it.
  if ((entry = new LVT_Hash()) == NULL) {
    return false;
  }
  entry->_elem = elem;

  // Insert into hash table
  entry->_next = table[index];
  table[index] = entry;

  return true;
}

void copy_lvt_element(Classfile_LVT_Element *src, LocalVariableTableElement *lvt) {
  lvt->start_bci           = Bytes::get_Java_u2((u1*) &src->start_bci);
  lvt->length              = Bytes::get_Java_u2((u1*) &src->length);
  lvt->name_cp_index       = Bytes::get_Java_u2((u1*) &src->name_cp_index);
  lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);
  lvt->signature_cp_index  = 0;
  lvt->slot                = Bytes::get_Java_u2((u1*) &src->slot);
}

// Function is used to parse both attributes:
//       LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)
u2* ClassFileParser::parse_localvariable_table(u4 code_length,
                                               u2 max_locals,
                                               u4 code_attribute_length,
                                               u2* localvariable_table_length,
                                               bool isLVTT,
                                               TRAPS) {
  ClassFileStream* cfs = stream();
  const char * tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";
  *localvariable_table_length = cfs->get_u2(CHECK_NULL);
  unsigned int size = (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);
  // Verify local variable table attribute has right length
  if (_need_verify) {
    guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),
                       "%s has wrong length in class file %s", tbl_name, CHECK_NULL);
  }
  u2* localvariable_table_start = cfs->get_u2_buffer();
  assert(localvariable_table_start != NULL, "null local variable table");
  if (!_need_verify) {
    cfs->skip_u2_fast(size);
  } else {
    cfs->guarantee_more(size * 2, CHECK_NULL);
    for(int i = 0; i < (*localvariable_table_length); i++) {
      u2 start_pc = cfs->get_u2_fast();
      u2 length = cfs->get_u2_fast();
      u2 name_index = cfs->get_u2_fast();
      u2 descriptor_index = cfs->get_u2_fast();
      u2 index = cfs->get_u2_fast();
      // Assign to a u4 to avoid overflow
      u4 end_pc = (u4)start_pc + (u4)length;

      if (start_pc >= code_length) {
        classfile_parse_error(
          "Invalid start_pc %u in %s in class file %s",
          start_pc, tbl_name, CHECK_NULL);
      }
      if (end_pc > code_length) {
        classfile_parse_error(
          "Invalid length %u in %s in class file %s",
          length, tbl_name, CHECK_NULL);
      }
1525 1526
      int cp_size = _cp->length();
      guarantee_property(valid_symbol_at(name_index),
D
duke 已提交
1527 1528
        "Name index %u in %s has bad constant type in class file %s",
        name_index, tbl_name, CHECK_NULL);
1529
      guarantee_property(valid_symbol_at(descriptor_index),
D
duke 已提交
1530 1531 1532
        "Signature index %u in %s has bad constant type in class file %s",
        descriptor_index, tbl_name, CHECK_NULL);

1533 1534
      Symbol*  name = _cp->symbol_at(name_index);
      Symbol*  sig = _cp->symbol_at(descriptor_index);
D
duke 已提交
1535 1536 1537 1538 1539 1540
      verify_legal_field_name(name, CHECK_NULL);
      u2 extra_slot = 0;
      if (!isLVTT) {
        verify_legal_field_signature(name, sig, CHECK_NULL);

        // 4894874: check special cases for double and long local variables
1541 1542
        if (sig == vmSymbols::type_signature(T_DOUBLE) ||
            sig == vmSymbols::type_signature(T_LONG)) {
D
duke 已提交
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
          extra_slot = 1;
        }
      }
      guarantee_property((index + extra_slot) < max_locals,
                          "Invalid index %u in %s in class file %s",
                          index, tbl_name, CHECK_NULL);
    }
  }
  return localvariable_table_start;
}


void ClassFileParser::parse_type_array(u2 array_length, u4 code_length, u4* u1_index, u4* u2_index,
1556
                                      u1* u1_array, u2* u2_array, TRAPS) {
D
duke 已提交
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
  ClassFileStream* cfs = stream();
  u2 index = 0; // index in the array with long/double occupying two slots
  u4 i1 = *u1_index;
  u4 i2 = *u2_index + 1;
  for(int i = 0; i < array_length; i++) {
    u1 tag = u1_array[i1++] = cfs->get_u1(CHECK);
    index++;
    if (tag == ITEM_Long || tag == ITEM_Double) {
      index++;
    } else if (tag == ITEM_Object) {
      u2 class_index = u2_array[i2++] = cfs->get_u2(CHECK);
1568
      guarantee_property(valid_klass_reference_at(class_index),
D
duke 已提交
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
                         "Bad class index %u in StackMap in class file %s",
                         class_index, CHECK);
    } else if (tag == ITEM_Uninitialized) {
      u2 offset = u2_array[i2++] = cfs->get_u2(CHECK);
      guarantee_property(
        offset < code_length,
        "Bad uninitialized type offset %u in StackMap in class file %s",
        offset, CHECK);
    } else {
      guarantee_property(
        tag <= (u1)ITEM_Uninitialized,
        "Unknown variable type %u in StackMap in class file %s",
        tag, CHECK);
    }
  }
  u2_array[*u2_index] = index;
  *u1_index = i1;
  *u2_index = i2;
}

1589
u1* ClassFileParser::parse_stackmap_table(
D
duke 已提交
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
    u4 code_attribute_length, TRAPS) {
  if (code_attribute_length == 0)
    return NULL;

  ClassFileStream* cfs = stream();
  u1* stackmap_table_start = cfs->get_u1_buffer();
  assert(stackmap_table_start != NULL, "null stackmap table");

  // check code_attribute_length first
  stream()->skip_u1(code_attribute_length, CHECK_NULL);

  if (!_need_verify && !DumpSharedSpaces) {
    return NULL;
  }
1604
  return stackmap_table_start;
D
duke 已提交
1605 1606 1607 1608
}

u2* ClassFileParser::parse_checked_exceptions(u2* checked_exceptions_length,
                                              u4 method_attribute_length,
1609
                                              TRAPS) {
D
duke 已提交
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
  ClassFileStream* cfs = stream();
  cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
  *checked_exceptions_length = cfs->get_u2_fast();
  unsigned int size = (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);
  u2* checked_exceptions_start = cfs->get_u2_buffer();
  assert(checked_exceptions_start != NULL, "null checked exceptions");
  if (!_need_verify) {
    cfs->skip_u2_fast(size);
  } else {
    // Verify each value in the checked exception table
    u2 checked_exception;
    u2 len = *checked_exceptions_length;
    cfs->guarantee_more(2 * len, CHECK_NULL);
    for (int i = 0; i < len; i++) {
      checked_exception = cfs->get_u2_fast();
      check_property(
1626
        valid_klass_reference_at(checked_exception),
D
duke 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
        "Exception name has bad type at constant pool %u in class file %s",
        checked_exception, CHECK_NULL);
    }
  }
  // check exceptions attribute length
  if (_need_verify) {
    guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +
                                                   sizeof(u2) * size),
                      "Exceptions attribute has wrong length in class file %s", CHECK_NULL);
  }
  return checked_exceptions_start;
}

1640
void ClassFileParser::throwIllegalSignature(
1641
    const char* type, Symbol* name, Symbol* sig, TRAPS) {
1642 1643 1644 1645 1646 1647
  ResourceMark rm(THREAD);
  Exceptions::fthrow(THREAD_AND_LOCATION,
      vmSymbols::java_lang_ClassFormatError(),
      "%s \"%s\" in class %s has illegal signature \"%s\"", type,
      name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());
}
D
duke 已提交
1648

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
// Skip an annotation.  Return >=limit if there is any problem.
int ClassFileParser::skip_annotation(u1* buffer, int limit, int index) {
  // annotation := atype:u2 do(nmem:u2) {member:u2 value}
  // value := switch (tag:u1) { ... }
  index += 2;  // skip atype
  if ((index += 2) >= limit)  return limit;  // read nmem
  int nmem = Bytes::get_Java_u2(buffer+index-2);
  while (--nmem >= 0 && index < limit) {
    index += 2; // skip member
    index = skip_annotation_value(buffer, limit, index);
  }
  return index;
}

1663 1664 1665 1666 1667
// Safely increment index by val if does not pass limit
#define SAFE_ADD(index, limit, val) \
if (index >= limit - val) return limit; \
index += val;

1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
// Skip an annotation value.  Return >=limit if there is any problem.
int ClassFileParser::skip_annotation_value(u1* buffer, int limit, int index) {
  // value := switch (tag:u1) {
  //   case B, C, I, S, Z, D, F, J, c: con:u2;
  //   case e: e_class:u2 e_name:u2;
  //   case s: s_con:u2;
  //   case [: do(nval:u2) {value};
  //   case @: annotation;
  //   case s: s_con:u2;
  // }
1678
  SAFE_ADD(index, limit, 1); // read tag
1679 1680 1681 1682
  u1 tag = buffer[index-1];
  switch (tag) {
  case 'B': case 'C': case 'I': case 'S': case 'Z':
  case 'D': case 'F': case 'J': case 'c': case 's':
1683
    SAFE_ADD(index, limit, 2);  // skip con or s_con
1684 1685
    break;
  case 'e':
1686
    SAFE_ADD(index, limit, 4);  // skip e_class, e_name
1687 1688 1689
    break;
  case '[':
    {
1690
      SAFE_ADD(index, limit, 2);  // read nval
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
      int nval = Bytes::get_Java_u2(buffer+index-2);
      while (--nval >= 0 && index < limit) {
        index = skip_annotation_value(buffer, limit, index);
      }
    }
    break;
  case '@':
    index = skip_annotation(buffer, limit, index);
    break;
  default:
    assert(false, "annotation tag");
    return limit;  //  bad tag byte
  }
  return index;
}

// Sift through annotations, looking for those significant to the VM:
1708
void ClassFileParser::parse_annotations(u1* buffer, int limit,
1709 1710 1711
                                        ClassFileParser::AnnotationCollector* coll,
                                        TRAPS) {
  // annotations := do(nann:u2) {annotation}
1712 1713
  int index = 2;
  if (index >= limit)  return;  // read nann
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
  int nann = Bytes::get_Java_u2(buffer+index-2);
  enum {  // initial annotation layout
    atype_off = 0,      // utf8 such as 'Ljava/lang/annotation/Retention;'
    count_off = 2,      // u2   such as 1 (one value)
    member_off = 4,     // utf8 such as 'value'
    tag_off = 6,        // u1   such as 'c' (type) or 'e' (enum)
    e_tag_val = 'e',
      e_type_off = 7,   // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'
      e_con_off = 9,    // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'
      e_size = 11,     // end of 'e' annotation
1724 1725
    c_tag_val = 'c',    // payload is type
      c_con_off = 7,    // utf8 payload, such as 'I'
1726
      c_size = 9,       // end of 'c' annotation
1727 1728 1729
    s_tag_val = 's',    // payload is String
      s_con_off = 7,    // utf8 payload, such as 'Ljava/lang/String;'
      s_size = 9,
1730 1731
    min_size = 6        // smallest possible size (zero members)
  };
1732 1733
  // Cannot add min_size to index in case of overflow MAX_INT
  while ((--nann) >= 0 && (index-2 <= limit - min_size)) {
1734 1735 1736 1737 1738
    int index0 = index;
    index = skip_annotation(buffer, limit, index);
    u1* abase = buffer + index0;
    int atype = Bytes::get_Java_u2(abase + atype_off);
    int count = Bytes::get_Java_u2(abase + count_off);
1739
    Symbol* aname = check_symbol_at(_cp, atype);
1740 1741 1742 1743
    if (aname == NULL)  break;  // invalid annotation name
    Symbol* member = NULL;
    if (count >= 1) {
      int member_index = Bytes::get_Java_u2(abase + member_off);
1744
      member = check_symbol_at(_cp, member_index);
1745 1746 1747 1748
      if (member == NULL)  break;  // invalid member name
    }

    // Here is where parsing particular annotations will take place.
1749
    AnnotationCollector::ID id = coll->annotation_index(_loader_data, aname);
1750 1751
    if (id == AnnotationCollector::_unknown)  continue;
    coll->set_annotation(id);
1752 1753

    if (id == AnnotationCollector::_sun_misc_Contended) {
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
      // @Contended can optionally specify the contention group.
      //
      // Contended group defines the equivalence class over the fields:
      // the fields within the same contended group are not treated distinct.
      // The only exception is default group, which does not incur the
      // equivalence. Naturally, contention group for classes is meaningless.
      //
      // While the contention group is specified as String, annotation
      // values are already interned, and we might as well use the constant
      // pool index as the group tag.
      //
      u2 group_index = 0; // default contended group
1766 1767 1768 1769
      if (count == 1
          && s_size == (index - index0)  // match size
          && s_tag_val == *(abase + tag_off)
          && member == vmSymbols::value_name()) {
1770 1771 1772 1773
        group_index = Bytes::get_Java_u2(abase + s_con_off);
        if (_cp->symbol_at(group_index)->utf8_length() == 0) {
          group_index = 0; // default contended group
        }
1774
      }
1775
      coll->set_contended_group(group_index);
1776
    }
1777 1778 1779
  }
}

1780 1781 1782
ClassFileParser::AnnotationCollector::ID
ClassFileParser::AnnotationCollector::annotation_index(ClassLoaderData* loader_data,
                                                                Symbol* name) {
1783
  vmSymbols::SID sid = vmSymbols::find_sid(name);
1784
  // Privileged code can use all annotations.  Other code silently drops some.
1785 1786 1787
  const bool privileged = loader_data->is_the_null_class_loader_data() ||
                          loader_data->is_ext_class_loader_data() ||
                          loader_data->is_anonymous();
1788
  switch (sid) {
1789 1790 1791 1792
  case vmSymbols::VM_SYMBOL_ENUM_NAME(sun_reflect_CallerSensitive_signature):
    if (_location != _in_method)  break;  // only allow for methods
    if (!privileged)              break;  // only allow in privileged code
    return _method_CallerSensitive;
1793 1794
  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_ForceInline_signature):
    if (_location != _in_method)  break;  // only allow for methods
1795
    if (!privileged)              break;  // only allow in privileged code
1796
    return _method_ForceInline;
1797 1798
  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_DontInline_signature):
    if (_location != _in_method)  break;  // only allow for methods
1799
    if (!privileged)              break;  // only allow in privileged code
1800
    return _method_DontInline;
1801 1802 1803 1804
  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature):
    if (_location != _in_method)  break;  // only allow for methods
    if (!privileged)              break;  // only allow in privileged code
    return _method_InjectedProfile;
1805 1806
  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature):
    if (_location != _in_method)  break;  // only allow for methods
1807
    if (!privileged)              break;  // only allow in privileged code
1808 1809 1810
    return _method_LambdaForm_Compiled;
  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Hidden_signature):
    if (_location != _in_method)  break;  // only allow for methods
1811
    if (!privileged)              break;  // only allow in privileged code
1812
    return _method_LambdaForm_Hidden;
1813
  case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_Stable_signature):
1814 1815 1816
    if (_location != _in_field)   break;  // only allow for fields
    if (!privileged)              break;  // only allow in privileged code
    return _field_Stable;
1817 1818 1819 1820
  case vmSymbols::VM_SYMBOL_ENUM_NAME(sun_misc_Contended_signature):
    if (_location != _in_field && _location != _in_class)          break;  // only allow for fields and classes
    if (!EnableContended || (RestrictContended && !privileged))    break;  // honor privileges
    return _sun_misc_Contended;
1821 1822 1823 1824 1825 1826
  default: break;
  }
  return AnnotationCollector::_unknown;
}

void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {
1827 1828
  if (is_contended())
    f->set_contended_group(contended_group());
1829 1830
  if (is_stable())
    f->set_stable(true);
1831 1832
}

1833 1834 1835 1836 1837 1838
ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
  // If there's an error deallocate metadata for field annotations
  MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
  MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
}

1839
void ClassFileParser::MethodAnnotationCollector::apply_to(methodHandle m) {
1840 1841
  if (has_annotation(_method_CallerSensitive))
    m->set_caller_sensitive(true);
1842 1843
  if (has_annotation(_method_ForceInline))
    m->set_force_inline(true);
1844 1845
  if (has_annotation(_method_DontInline))
    m->set_dont_inline(true);
1846 1847
  if (has_annotation(_method_InjectedProfile))
    m->set_has_injected_profile(true);
1848 1849 1850 1851
  if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)
    m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);
  if (has_annotation(_method_LambdaForm_Hidden))
    m->set_hidden(true);
1852 1853 1854
}

void ClassFileParser::ClassAnnotationCollector::apply_to(instanceKlassHandle k) {
1855
  k->set_is_contended(is_contended());
1856 1857 1858
}


D
duke 已提交
1859 1860 1861 1862
#define MAX_ARGS_SIZE 255
#define MAX_CODE_SIZE 65535
#define INITIAL_MAX_LVT_NUMBER 256

C
coleenp 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
/* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
 *
 * Rules for LVT's and LVTT's are:
 *   - There can be any number of LVT's and LVTT's.
 *   - If there are n LVT's, it is the same as if there was just
 *     one LVT containing all the entries from the n LVT's.
 *   - There may be no more than one LVT entry per local variable.
 *     Two LVT entries are 'equal' if these fields are the same:
 *        start_pc, length, name, slot
 *   - There may be no more than one LVTT entry per each LVT entry.
 *     Each LVTT entry has to match some LVT entry.
 *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
 */
void ClassFileParser::copy_localvariable_table(ConstMethod* cm,
                                               int lvt_cnt,
                                               u2* localvariable_table_length,
                                               u2** localvariable_table_start,
                                               int lvtt_cnt,
                                               u2* localvariable_type_table_length,
                                               u2** localvariable_type_table_start,
                                               TRAPS) {

  LVT_Hash** lvt_Hash = NEW_RESOURCE_ARRAY(LVT_Hash*, HASH_ROW_SIZE);
  initialize_hashtable(lvt_Hash);

  // To fill LocalVariableTable in
  Classfile_LVT_Element*  cf_lvt;
  LocalVariableTableElement* lvt = cm->localvariable_table_start();

  for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
    cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
    for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
      copy_lvt_element(&cf_lvt[idx], lvt);
      // If no duplicates, add LVT elem in hashtable lvt_Hash.
      if (LVT_put_after_lookup(lvt, lvt_Hash) == false
          && _need_verify
          && _major_version >= JAVA_1_5_VERSION) {
        clear_hashtable(lvt_Hash);
        classfile_parse_error("Duplicated LocalVariableTable attribute "
                              "entry for '%s' in class file %s",
1903
                               _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
C
coleenp 已提交
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
                               CHECK);
      }
    }
  }

  // To merge LocalVariableTable and LocalVariableTypeTable
  Classfile_LVT_Element* cf_lvtt;
  LocalVariableTableElement lvtt_elem;

  for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
    cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
    for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
      copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
      int index = hash(&lvtt_elem);
      LVT_Hash* entry = LVT_lookup(&lvtt_elem, index, lvt_Hash);
      if (entry == NULL) {
        if (_need_verify) {
          clear_hashtable(lvt_Hash);
          classfile_parse_error("LVTT entry for '%s' in class file %s "
                                "does not match any LVT entry",
1924
                                 _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
C
coleenp 已提交
1925 1926 1927 1928 1929 1930
                                 CHECK);
        }
      } else if (entry->_elem->signature_cp_index != 0 && _need_verify) {
        clear_hashtable(lvt_Hash);
        classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
                              "entry for '%s' in class file %s",
1931
                               _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
C
coleenp 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
                               CHECK);
      } else {
        // to add generic signatures into LocalVariableTable
        entry->_elem->signature_cp_index = lvtt_elem.descriptor_cp_index;
      }
    }
  }
  clear_hashtable(lvt_Hash);
}


1943
void ClassFileParser::copy_method_annotations(ConstMethod* cm,
C
coleenp 已提交
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
                                       u1* runtime_visible_annotations,
                                       int runtime_visible_annotations_length,
                                       u1* runtime_invisible_annotations,
                                       int runtime_invisible_annotations_length,
                                       u1* runtime_visible_parameter_annotations,
                                       int runtime_visible_parameter_annotations_length,
                                       u1* runtime_invisible_parameter_annotations,
                                       int runtime_invisible_parameter_annotations_length,
                                       u1* runtime_visible_type_annotations,
                                       int runtime_visible_type_annotations_length,
                                       u1* runtime_invisible_type_annotations,
                                       int runtime_invisible_type_annotations_length,
                                       u1* annotation_default,
                                       int annotation_default_length,
                                       TRAPS) {

  AnnotationArray* a;

  if (runtime_visible_annotations_length +
      runtime_invisible_annotations_length > 0) {
1964
     a = assemble_annotations(runtime_visible_annotations,
C
coleenp 已提交
1965 1966 1967 1968 1969 1970 1971 1972 1973
                              runtime_visible_annotations_length,
                              runtime_invisible_annotations,
                              runtime_invisible_annotations_length,
                              CHECK);
     cm->set_method_annotations(a);
  }

  if (runtime_visible_parameter_annotations_length +
      runtime_invisible_parameter_annotations_length > 0) {
1974
    a = assemble_annotations(runtime_visible_parameter_annotations,
C
coleenp 已提交
1975 1976 1977 1978 1979 1980 1981 1982
                             runtime_visible_parameter_annotations_length,
                             runtime_invisible_parameter_annotations,
                             runtime_invisible_parameter_annotations_length,
                             CHECK);
    cm->set_parameter_annotations(a);
  }

  if (annotation_default_length > 0) {
1983
    a = assemble_annotations(annotation_default,
C
coleenp 已提交
1984 1985 1986 1987 1988 1989 1990 1991 1992
                             annotation_default_length,
                             NULL,
                             0,
                             CHECK);
    cm->set_default_annotations(a);
  }

  if (runtime_visible_type_annotations_length +
      runtime_invisible_type_annotations_length > 0) {
1993
    a = assemble_annotations(runtime_visible_type_annotations,
C
coleenp 已提交
1994 1995 1996 1997 1998 1999 2000 2001 2002
                             runtime_visible_type_annotations_length,
                             runtime_invisible_type_annotations,
                             runtime_invisible_type_annotations_length,
                             CHECK);
    cm->set_type_annotations(a);
  }
}


D
duke 已提交
2003
// Note: the parse_method below is big and clunky because all parsing of the code and exceptions
2004
// attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
2005
// Method* to save footprint, so we only know the size of the resulting Method* when the
D
duke 已提交
2006 2007 2008 2009 2010 2011
// entire method attribute is parsed.
//
// The promoted_flags parameter is used to pass relevant access_flags
// from the method back up to the containing klass. These flag values
// are added to klass's access_flags.

2012
methodHandle ClassFileParser::parse_method(bool is_interface,
D
duke 已提交
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
                                           AccessFlags *promoted_flags,
                                           TRAPS) {
  ClassFileStream* cfs = stream();
  methodHandle nullHandle;
  ResourceMark rm(THREAD);
  // Parse fixed parts
  cfs->guarantee_more(8, CHECK_(nullHandle)); // access_flags, name_index, descriptor_index, attributes_count

  int flags = cfs->get_u2_fast();
  u2 name_index = cfs->get_u2_fast();
2023
  int cp_size = _cp->length();
D
duke 已提交
2024
  check_property(
2025
    valid_symbol_at(name_index),
D
duke 已提交
2026 2027
    "Illegal constant pool index %u for method name in class file %s",
    name_index, CHECK_(nullHandle));
2028
  Symbol*  name = _cp->symbol_at(name_index);
D
duke 已提交
2029 2030 2031 2032
  verify_legal_method_name(name, CHECK_(nullHandle));

  u2 signature_index = cfs->get_u2_fast();
  guarantee_property(
2033
    valid_symbol_at(signature_index),
D
duke 已提交
2034 2035
    "Illegal constant pool index %u for method signature in class file %s",
    signature_index, CHECK_(nullHandle));
2036
  Symbol*  signature = _cp->symbol_at(signature_index);
D
duke 已提交
2037 2038 2039

  AccessFlags access_flags;
  if (name == vmSymbols::class_initializer_name()) {
2040 2041 2042 2043 2044 2045 2046
    // We ignore the other access flags for a valid class initializer.
    // (JVM Spec 2nd ed., chapter 4.6)
    if (_major_version < 51) { // backward compatibility
      flags = JVM_ACC_STATIC;
    } else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {
      flags &= JVM_ACC_STATIC | JVM_ACC_STRICT;
    }
D
duke 已提交
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
  } else {
    verify_legal_method_modifiers(flags, is_interface, name, CHECK_(nullHandle));
  }

  int args_size = -1;  // only used when _need_verify is true
  if (_need_verify) {
    args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +
                 verify_legal_method_signature(name, signature, CHECK_(nullHandle));
    if (args_size > MAX_ARGS_SIZE) {
      classfile_parse_error("Too many arguments in method signature in class file %s", CHECK_(nullHandle));
    }
  }

  access_flags.set_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);

  // Default values for code and exceptions attribute elements
  u2 max_stack = 0;
  u2 max_locals = 0;
  u4 code_length = 0;
  u1* code_start = 0;
  u2 exception_table_length = 0;
2068
  u2* exception_table_start = NULL;
2069
  Array<int>* exception_handlers = Universe::the_empty_int_array();
D
duke 已提交
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
  u2 checked_exceptions_length = 0;
  u2* checked_exceptions_start = NULL;
  CompressedLineNumberWriteStream* linenumber_table = NULL;
  int linenumber_table_length = 0;
  int total_lvt_length = 0;
  u2 lvt_cnt = 0;
  u2 lvtt_cnt = 0;
  bool lvt_allocated = false;
  u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;
  u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;
  u2* localvariable_table_length;
  u2** localvariable_table_start;
  u2* localvariable_type_table_length;
  u2** localvariable_type_table_start;
2084 2085
  u2 method_parameters_length = 0;
  u1* method_parameters_data = NULL;
2086
  bool method_parameters_seen = false;
D
duke 已提交
2087 2088 2089 2090
  bool parsed_code_attribute = false;
  bool parsed_checked_exceptions_attribute = false;
  bool parsed_stackmap_attribute = false;
  // stackmap attribute - JDK1.5
2091 2092
  u1* stackmap_data = NULL;
  int stackmap_data_length = 0;
D
duke 已提交
2093
  u2 generic_signature_index = 0;
2094
  MethodAnnotationCollector parsed_annotations;
D
duke 已提交
2095 2096 2097 2098 2099 2100 2101 2102
  u1* runtime_visible_annotations = NULL;
  int runtime_visible_annotations_length = 0;
  u1* runtime_invisible_annotations = NULL;
  int runtime_invisible_annotations_length = 0;
  u1* runtime_visible_parameter_annotations = NULL;
  int runtime_visible_parameter_annotations_length = 0;
  u1* runtime_invisible_parameter_annotations = NULL;
  int runtime_invisible_parameter_annotations_length = 0;
2103 2104 2105 2106
  u1* runtime_visible_type_annotations = NULL;
  int runtime_visible_type_annotations_length = 0;
  u1* runtime_invisible_type_annotations = NULL;
  int runtime_invisible_type_annotations_length = 0;
2107
  bool runtime_invisible_type_annotations_exists = false;
D
duke 已提交
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
  u1* annotation_default = NULL;
  int annotation_default_length = 0;

  // Parse code and exceptions attribute
  u2 method_attributes_count = cfs->get_u2_fast();
  while (method_attributes_count--) {
    cfs->guarantee_more(6, CHECK_(nullHandle));  // method_attribute_name_index, method_attribute_length
    u2 method_attribute_name_index = cfs->get_u2_fast();
    u4 method_attribute_length = cfs->get_u4_fast();
    check_property(
2118
      valid_symbol_at(method_attribute_name_index),
D
duke 已提交
2119 2120 2121
      "Invalid method attribute name index %u in class file %s",
      method_attribute_name_index, CHECK_(nullHandle));

2122
    Symbol* method_attribute_name = _cp->symbol_at(method_attribute_name_index);
D
duke 已提交
2123 2124 2125
    if (method_attribute_name == vmSymbols::tag_code()) {
      // Parse Code attribute
      if (_need_verify) {
2126 2127
        guarantee_property(
            !access_flags.is_native() && !access_flags.is_abstract(),
D
duke 已提交
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
                        "Code attribute in native or abstract methods in class file %s",
                         CHECK_(nullHandle));
      }
      if (parsed_code_attribute) {
        classfile_parse_error("Multiple Code attributes in class file %s", CHECK_(nullHandle));
      }
      parsed_code_attribute = true;

      // Stack size, locals size, and code size
      if (_major_version == 45 && _minor_version <= 2) {
        cfs->guarantee_more(4, CHECK_(nullHandle));
        max_stack = cfs->get_u1_fast();
        max_locals = cfs->get_u1_fast();
        code_length = cfs->get_u2_fast();
      } else {
        cfs->guarantee_more(8, CHECK_(nullHandle));
        max_stack = cfs->get_u2_fast();
        max_locals = cfs->get_u2_fast();
        code_length = cfs->get_u4_fast();
      }
      if (_need_verify) {
        guarantee_property(args_size <= max_locals,
                           "Arguments can't fit into locals in class file %s", CHECK_(nullHandle));
        guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,
                           "Invalid method Code length %u in class file %s",
                           code_length, CHECK_(nullHandle));
      }
      // Code pointer
      code_start = cfs->get_u1_buffer();
      assert(code_start != NULL, "null code start");
      cfs->guarantee_more(code_length, CHECK_(nullHandle));
      cfs->skip_u1_fast(code_length);

      // Exception handler table
      cfs->guarantee_more(2, CHECK_(nullHandle));  // exception_table_length
      exception_table_length = cfs->get_u2_fast();
      if (exception_table_length > 0) {
2165
        exception_table_start =
2166
              parse_exception_table(code_length, exception_table_length, CHECK_(nullHandle));
D
duke 已提交
2167 2168 2169 2170 2171
      }

      // Parse additional attributes in code attribute
      cfs->guarantee_more(2, CHECK_(nullHandle));  // code_attributes_count
      u2 code_attributes_count = cfs->get_u2_fast();
2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190

      unsigned int calculated_attribute_length = 0;

      if (_major_version > 45 || (_major_version == 45 && _minor_version > 2)) {
        calculated_attribute_length =
            sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);
      } else {
        // max_stack, locals and length are smaller in pre-version 45.2 classes
        calculated_attribute_length = sizeof(u1) + sizeof(u1) + sizeof(u2);
      }
      calculated_attribute_length +=
        code_length +
        sizeof(exception_table_length) +
        sizeof(code_attributes_count) +
        exception_table_length *
            ( sizeof(u2) +   // start_pc
              sizeof(u2) +   // end_pc
              sizeof(u2) +   // handler_pc
              sizeof(u2) );  // catch_type_index
D
duke 已提交
2191 2192 2193 2194 2195 2196 2197 2198

      while (code_attributes_count--) {
        cfs->guarantee_more(6, CHECK_(nullHandle));  // code_attribute_name_index, code_attribute_length
        u2 code_attribute_name_index = cfs->get_u2_fast();
        u4 code_attribute_length = cfs->get_u4_fast();
        calculated_attribute_length += code_attribute_length +
                                       sizeof(code_attribute_name_index) +
                                       sizeof(code_attribute_length);
2199
        check_property(valid_symbol_at(code_attribute_name_index),
D
duke 已提交
2200 2201 2202 2203
                       "Invalid code attribute name index %u in class file %s",
                       code_attribute_name_index,
                       CHECK_(nullHandle));
        if (LoadLineNumberTables &&
2204
            _cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
D
duke 已提交
2205 2206 2207 2208 2209
          // Parse and compress line number table
          parse_linenumber_table(code_attribute_length, code_length,
            &linenumber_table, CHECK_(nullHandle));

        } else if (LoadLocalVariableTables &&
2210
                   _cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
D
duke 已提交
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
          // Parse local variable table
          if (!lvt_allocated) {
            localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
            localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
            localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
            localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
            lvt_allocated = true;
          }
          if (lvt_cnt == max_lvt_cnt) {
            max_lvt_cnt <<= 1;
I
iklam 已提交
2225 2226
            localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);
            localvariable_table_start  = REALLOC_RESOURCE_ARRAY(u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);
D
duke 已提交
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
          }
          localvariable_table_start[lvt_cnt] =
            parse_localvariable_table(code_length,
                                      max_locals,
                                      code_attribute_length,
                                      &localvariable_table_length[lvt_cnt],
                                      false,    // is not LVTT
                                      CHECK_(nullHandle));
          total_lvt_length += localvariable_table_length[lvt_cnt];
          lvt_cnt++;
        } else if (LoadLocalVariableTypeTables &&
                   _major_version >= JAVA_1_5_VERSION &&
2239
                   _cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
D
duke 已提交
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
          if (!lvt_allocated) {
            localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
            localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
            localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
            localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2*, INITIAL_MAX_LVT_NUMBER);
            lvt_allocated = true;
          }
          // Parse local variable type table
          if (lvtt_cnt == max_lvtt_cnt) {
            max_lvtt_cnt <<= 1;
I
iklam 已提交
2254 2255
            localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);
            localvariable_type_table_start  = REALLOC_RESOURCE_ARRAY(u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);
D
duke 已提交
2256 2257 2258 2259 2260 2261 2262 2263 2264
          }
          localvariable_type_table_start[lvtt_cnt] =
            parse_localvariable_table(code_length,
                                      max_locals,
                                      code_attribute_length,
                                      &localvariable_type_table_length[lvtt_cnt],
                                      true,     // is LVTT
                                      CHECK_(nullHandle));
          lvtt_cnt++;
2265
        } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
2266
                   _cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
D
duke 已提交
2267 2268 2269 2270
          // Stack map is only needed by the new verifier in JDK1.5.
          if (parsed_stackmap_attribute) {
            classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_(nullHandle));
          }
2271 2272
          stackmap_data = parse_stackmap_table(code_attribute_length, CHECK_(nullHandle));
          stackmap_data_length = code_attribute_length;
D
duke 已提交
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
          parsed_stackmap_attribute = true;
        } else {
          // Skip unknown attributes
          cfs->skip_u1(code_attribute_length, CHECK_(nullHandle));
        }
      }
      // check method attribute length
      if (_need_verify) {
        guarantee_property(method_attribute_length == calculated_attribute_length,
                           "Code segment has wrong length in class file %s", CHECK_(nullHandle));
      }
    } else if (method_attribute_name == vmSymbols::tag_exceptions()) {
      // Parse Exceptions attribute
      if (parsed_checked_exceptions_attribute) {
        classfile_parse_error("Multiple Exceptions attributes in class file %s", CHECK_(nullHandle));
      }
      parsed_checked_exceptions_attribute = true;
      checked_exceptions_start =
            parse_checked_exceptions(&checked_exceptions_length,
                                     method_attribute_length,
2293
                                     CHECK_(nullHandle));
2294
    } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
2295 2296 2297 2298 2299
      // reject multiple method parameters
      if (method_parameters_seen) {
        classfile_parse_error("Multiple MethodParameters attributes in class file %s", CHECK_(nullHandle));
      }
      method_parameters_seen = true;
2300
      method_parameters_length = cfs->get_u1_fast();
2301
      if (method_attribute_length != (method_parameters_length * 4u) + 1u) {
2302
        classfile_parse_error(
2303
          "Invalid MethodParameters method attribute length %u in class file",
2304 2305
          method_attribute_length, CHECK_(nullHandle));
      }
2306 2307
      method_parameters_data = cfs->get_u1_buffer();
      cfs->skip_u2_fast(method_parameters_length);
2308
      cfs->skip_u2_fast(method_parameters_length);
2309 2310 2311
      // ignore this attribute if it cannot be reflected
      if (!SystemDictionary::Parameter_klass_loaded())
        method_parameters_length = 0;
D
duke 已提交
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
    } else if (method_attribute_name == vmSymbols::tag_synthetic()) {
      if (method_attribute_length != 0) {
        classfile_parse_error(
          "Invalid Synthetic method attribute length %u in class file %s",
          method_attribute_length, CHECK_(nullHandle));
      }
      // Should we check that there hasn't already been a synthetic attribute?
      access_flags.set_is_synthetic();
    } else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 4276120
      if (method_attribute_length != 0) {
        classfile_parse_error(
          "Invalid Deprecated method attribute length %u in class file %s",
          method_attribute_length, CHECK_(nullHandle));
      }
    } else if (_major_version >= JAVA_1_5_VERSION) {
      if (method_attribute_name == vmSymbols::tag_signature()) {
        if (method_attribute_length != 2) {
          classfile_parse_error(
            "Invalid Signature attribute length %u in class file %s",
            method_attribute_length, CHECK_(nullHandle));
        }
2333
        generic_signature_index = parse_generic_signature_attribute(CHECK_(nullHandle));
D
duke 已提交
2334 2335 2336 2337
      } else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {
        runtime_visible_annotations_length = method_attribute_length;
        runtime_visible_annotations = cfs->get_u1_buffer();
        assert(runtime_visible_annotations != NULL, "null visible annotations");
2338
        cfs->guarantee_more(runtime_visible_annotations_length, CHECK_(nullHandle));
2339 2340
        parse_annotations(runtime_visible_annotations,
            runtime_visible_annotations_length, &parsed_annotations,
2341
            CHECK_(nullHandle));
2342
        cfs->skip_u1_fast(runtime_visible_annotations_length);
D
duke 已提交
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
      } else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
        runtime_invisible_annotations_length = method_attribute_length;
        runtime_invisible_annotations = cfs->get_u1_buffer();
        assert(runtime_invisible_annotations != NULL, "null invisible annotations");
        cfs->skip_u1(runtime_invisible_annotations_length, CHECK_(nullHandle));
      } else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {
        runtime_visible_parameter_annotations_length = method_attribute_length;
        runtime_visible_parameter_annotations = cfs->get_u1_buffer();
        assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");
        cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_(nullHandle));
      } else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {
        runtime_invisible_parameter_annotations_length = method_attribute_length;
        runtime_invisible_parameter_annotations = cfs->get_u1_buffer();
        assert(runtime_invisible_parameter_annotations != NULL, "null invisible parameter annotations");
        cfs->skip_u1(runtime_invisible_parameter_annotations_length, CHECK_(nullHandle));
      } else if (method_attribute_name == vmSymbols::tag_annotation_default()) {
        annotation_default_length = method_attribute_length;
        annotation_default = cfs->get_u1_buffer();
        assert(annotation_default != NULL, "null annotation default");
        cfs->skip_u1(annotation_default_length, CHECK_(nullHandle));
2363
      } else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {
2364 2365 2366 2367 2368
        if (runtime_visible_type_annotations != NULL) {
          classfile_parse_error(
            "Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",
            CHECK_(nullHandle));
        }
2369 2370 2371 2372 2373
        runtime_visible_type_annotations_length = method_attribute_length;
        runtime_visible_type_annotations = cfs->get_u1_buffer();
        assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
        // No need for the VM to parse Type annotations
        cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_(nullHandle));
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
      } else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {
        if (runtime_invisible_type_annotations_exists) {
          classfile_parse_error(
            "Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",
            CHECK_(nullHandle));
        } else {
          runtime_invisible_type_annotations_exists = true;
        }
        if (PreserveAllAnnotations) {
          runtime_invisible_type_annotations_length = method_attribute_length;
          runtime_invisible_type_annotations = cfs->get_u1_buffer();
          assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
        }
        cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));
D
duke 已提交
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
      } else {
        // Skip unknown attributes
        cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));
      }
    } else {
      // Skip unknown attributes
      cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));
    }
  }

  if (linenumber_table != NULL) {
    linenumber_table->write_terminator();
    linenumber_table_length = linenumber_table->position();
  }

  // Make sure there's at least one Code attribute in non-native/non-abstract method
  if (_need_verify) {
    guarantee_property(access_flags.is_native() || access_flags.is_abstract() || parsed_code_attribute,
                      "Absent Code attribute in method that is not native or abstract in class file %s", CHECK_(nullHandle));
  }

2409
  // All sizing information for a Method* is finally available, now create it
C
coleenp 已提交
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
  InlineTableSizes sizes(
      total_lvt_length,
      linenumber_table_length,
      exception_table_length,
      checked_exceptions_length,
      method_parameters_length,
      generic_signature_index,
      runtime_visible_annotations_length +
           runtime_invisible_annotations_length,
      runtime_visible_parameter_annotations_length +
           runtime_invisible_parameter_annotations_length,
      runtime_visible_type_annotations_length +
           runtime_invisible_type_annotations_length,
      annotation_default_length,
      0);

2426
  Method* m = Method::allocate(
2427
      _loader_data, code_length, access_flags, &sizes,
2428
      ConstMethod::NORMAL, CHECK_(nullHandle));
D
duke 已提交
2429

2430
  ClassLoadingService::add_class_method_size(m->size()*HeapWordSize);
D
duke 已提交
2431 2432

  // Fill in information from fixed part (access_flags already set)
2433
  m->set_constants(_cp);
D
duke 已提交
2434 2435
  m->set_name_index(name_index);
  m->set_signature_index(signature_index);
K
kevinw 已提交
2436

2437
  ResultTypeFinder rtf(_cp->symbol_at(signature_index));
K
kevinw 已提交
2438
  m->constMethod()->set_result_type(rtf.type());
D
duke 已提交
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454

  if (args_size >= 0) {
    m->set_size_of_parameters(args_size);
  } else {
    m->compute_size_of_parameters(THREAD);
  }
#ifdef ASSERT
  if (args_size >= 0) {
    m->compute_size_of_parameters(THREAD);
    assert(args_size == m->size_of_parameters(), "");
  }
#endif

  // Fill in code attribute information
  m->set_max_stack(max_stack);
  m->set_max_locals(max_locals);
2455 2456 2457 2458
  if (stackmap_data != NULL) {
    m->constMethod()->copy_stackmap_data(_loader_data, stackmap_data,
                                         stackmap_data_length, CHECK_NULL);
  }
D
duke 已提交
2459 2460

  // Copy byte codes
2461
  m->set_code(code_start);
D
duke 已提交
2462 2463 2464 2465 2466 2467 2468

  // Copy line number table
  if (linenumber_table != NULL) {
    memcpy(m->compressed_linenumber_table(),
           linenumber_table->buffer(), linenumber_table_length);
  }

2469 2470 2471 2472 2473 2474 2475 2476
  // Copy exception table
  if (exception_table_length > 0) {
    int size =
      exception_table_length * sizeof(ExceptionTableElement) / sizeof(u2);
    copy_u2_with_conversion((u2*) m->exception_table_start(),
                             exception_table_start, size);
  }

2477 2478 2479
  // Copy method parameters
  if (method_parameters_length > 0) {
    MethodParametersElement* elem = m->constMethod()->method_parameters_start();
2480 2481
    for (int i = 0; i < method_parameters_length; i++) {
      elem[i].name_cp_index = Bytes::get_Java_u2(method_parameters_data);
2482
      method_parameters_data += 2;
2483 2484
      elem[i].flags = Bytes::get_Java_u2(method_parameters_data);
      method_parameters_data += 2;
2485 2486 2487
    }
  }

D
duke 已提交
2488 2489 2490 2491 2492 2493
  // Copy checked exceptions
  if (checked_exceptions_length > 0) {
    int size = checked_exceptions_length * sizeof(CheckedExceptionElement) / sizeof(u2);
    copy_u2_with_conversion((u2*) m->checked_exceptions_start(), checked_exceptions_start, size);
  }

C
coleenp 已提交
2494
  // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
D
duke 已提交
2495 2496
  if (total_lvt_length > 0) {
    promoted_flags->set_has_localvariable_table();
C
coleenp 已提交
2497 2498 2499 2500 2501 2502
    copy_localvariable_table(m->constMethod(), lvt_cnt,
                             localvariable_table_length,
                             localvariable_table_start,
                             lvtt_cnt,
                             localvariable_type_table_length,
                             localvariable_type_table_start, CHECK_NULL);
D
duke 已提交
2503 2504
  }

2505 2506
  if (parsed_annotations.has_any_annotations())
    parsed_annotations.apply_to(m);
C
coleenp 已提交
2507 2508

  // Copy annotations
2509
  copy_method_annotations(m->constMethod(),
C
coleenp 已提交
2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
                          runtime_visible_annotations,
                          runtime_visible_annotations_length,
                          runtime_invisible_annotations,
                          runtime_invisible_annotations_length,
                          runtime_visible_parameter_annotations,
                          runtime_visible_parameter_annotations_length,
                          runtime_invisible_parameter_annotations,
                          runtime_invisible_parameter_annotations_length,
                          runtime_visible_type_annotations,
                          runtime_visible_type_annotations_length,
                          runtime_invisible_type_annotations,
                          runtime_invisible_type_annotations_length,
                          annotation_default,
                          annotation_default_length,
                          CHECK_NULL);
D
duke 已提交
2525

2526 2527
  if (name == vmSymbols::finalize_method_name() &&
      signature == vmSymbols::void_method_signature()) {
D
duke 已提交
2528 2529 2530 2531 2532 2533
    if (m->is_empty_method()) {
      _has_empty_finalizer = true;
    } else {
      _has_finalizer = true;
    }
  }
2534 2535
  if (name == vmSymbols::object_initializer_name() &&
      signature == vmSymbols::void_method_signature() &&
D
duke 已提交
2536 2537 2538 2539
      m->is_vanilla_constructor()) {
    _has_vanilla_constructor = true;
  }

C
coleenp 已提交
2540
  NOT_PRODUCT(m->verify());
D
duke 已提交
2541 2542 2543 2544 2545 2546 2547 2548
  return m;
}


// The promoted_flags parameter is used to pass relevant access_flags
// from the methods back up to the containing klass. These flag values
// are added to klass's access_flags.

2549
Array<Method*>* ClassFileParser::parse_methods(bool is_interface,
2550 2551
                                               AccessFlags* promoted_flags,
                                               bool* has_final_method,
2552
                                               bool* declares_default_methods,
2553
                                               TRAPS) {
D
duke 已提交
2554
  ClassFileStream* cfs = stream();
2555
  cfs->guarantee_more(2, CHECK_NULL);  // length
D
duke 已提交
2556 2557
  u2 length = cfs->get_u2_fast();
  if (length == 0) {
2558
    _methods = Universe::the_empty_method_array();
D
duke 已提交
2559
  } else {
2560
    _methods = MetadataFactory::new_array<Method*>(_loader_data, length, NULL, CHECK_NULL);
2561

D
duke 已提交
2562 2563
    HandleMark hm(THREAD);
    for (int index = 0; index < length; index++) {
2564
      methodHandle method = parse_method(is_interface,
D
duke 已提交
2565
                                         promoted_flags,
2566 2567
                                         CHECK_NULL);

D
duke 已提交
2568 2569 2570
      if (method->is_final()) {
        *has_final_method = true;
      }
2571 2572 2573 2574 2575
      // declares_default_methods: declares concrete instance methods, any access flags
      // used for interface initialization, and default method inheritance analysis
      if (is_interface && !(*declares_default_methods)
        && !method->is_abstract() && !method->is_static()) {
        *declares_default_methods = true;
2576
      }
2577
      _methods->at_put(index, method());
D
duke 已提交
2578
    }
2579

D
duke 已提交
2580 2581 2582 2583 2584 2585 2586
    if (_need_verify && length > 1) {
      // Check duplicated methods
      ResourceMark rm(THREAD);
      NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(
        THREAD, NameSigHash*, HASH_ROW_SIZE);
      initialize_hashtable(names_and_sigs);
      bool dup = false;
2587 2588
      Symbol* name = NULL;
      Symbol* sig = NULL;
D
duke 已提交
2589 2590 2591
      {
        debug_only(No_Safepoint_Verifier nsv;)
        for (int i = 0; i < length; i++) {
2592
          Method* m = _methods->at(i);
2593 2594
          name = m->name();
          sig = m->signature();
D
duke 已提交
2595
          // If no duplicates, add name/signature in hashtable names_and_sigs.
2596
          if (!put_after_lookup(name, sig, names_and_sigs)) {
D
duke 已提交
2597 2598 2599 2600 2601 2602
            dup = true;
            break;
          }
        }
      }
      if (dup) {
2603 2604
        classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",
                              name->as_C_string(), sig->as_klass_external_name(), CHECK_NULL);
D
duke 已提交
2605 2606 2607
      }
    }
  }
2608
  return _methods;
D
duke 已提交
2609 2610 2611
}


2612
intArray* ClassFileParser::sort_methods(Array<Method*>* methods) {
2613
  int length = methods->length();
2614
  // If JVMTI original method ordering or sharing is enabled we have to
D
duke 已提交
2615
  // remember the original class file ordering.
2616
  // We temporarily use the vtable_index field in the Method* to store the
D
duke 已提交
2617
  // class file index, so we can read in after calling qsort.
2618 2619
  // Put the method ordering in the shared archive.
  if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
D
duke 已提交
2620
    for (int index = 0; index < length; index++) {
2621
      Method* m = methods->at(index);
D
duke 已提交
2622 2623 2624 2625 2626
      assert(!m->valid_vtable_index(), "vtable index should not be set");
      m->set_vtable_index(index);
    }
  }
  // Sort method array by ascending method name (for faster lookups & vtable construction)
2627
  // Note that the ordering is not alphabetical, see Symbol::fast_compare
C
coleenp 已提交
2628
  Method::sort_methods(methods);
D
duke 已提交
2629

2630
  intArray* method_ordering = NULL;
2631 2632 2633
  // If JVMTI original method ordering or sharing is enabled construct int
  // array remembering the original ordering
  if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
2634
    method_ordering = new intArray(length);
D
duke 已提交
2635
    for (int index = 0; index < length; index++) {
2636
      Method* m = methods->at(index);
D
duke 已提交
2637 2638
      int old_index = m->vtable_index();
      assert(old_index >= 0 && old_index < length, "invalid method index");
2639 2640
      method_ordering->at_put(index, old_index);
      m->set_vtable_index(Method::invalid_vtable_index);
D
duke 已提交
2641 2642
    }
  }
2643
  return method_ordering;
D
duke 已提交
2644 2645
}

2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656
// Parse generic_signature attribute for methods and fields
u2 ClassFileParser::parse_generic_signature_attribute(TRAPS) {
  ClassFileStream* cfs = stream();
  cfs->guarantee_more(2, CHECK_0);  // generic_signature_index
  u2 generic_signature_index = cfs->get_u2_fast();
  check_property(
    valid_symbol_at(generic_signature_index),
    "Invalid Signature attribute at constant pool index %u in class file %s",
    generic_signature_index, CHECK_0);
  return generic_signature_index;
}
D
duke 已提交
2657

2658
void ClassFileParser::parse_classfile_sourcefile_attribute(TRAPS) {
D
duke 已提交
2659 2660 2661 2662
  ClassFileStream* cfs = stream();
  cfs->guarantee_more(2, CHECK);  // sourcefile_index
  u2 sourcefile_index = cfs->get_u2_fast();
  check_property(
2663
    valid_symbol_at(sourcefile_index),
D
duke 已提交
2664 2665
    "Invalid SourceFile attribute at constant pool index %u in class file %s",
    sourcefile_index, CHECK);
2666
  set_class_sourcefile_index(sourcefile_index);
D
duke 已提交
2667 2668 2669 2670
}



2671
void ClassFileParser::parse_classfile_source_debug_extension_attribute(int length, TRAPS) {
D
duke 已提交
2672 2673 2674 2675 2676 2677
  ClassFileStream* cfs = stream();
  u1* sde_buffer = cfs->get_u1_buffer();
  assert(sde_buffer != NULL, "null sde buffer");

  // Don't bother storing it if there is no way to retrieve it
  if (JvmtiExport::can_get_source_debug_extension()) {
K
Merge  
kvn 已提交
2678 2679 2680 2681 2682 2683 2684
    assert((length+1) > length, "Overflow checking");
    u1* sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);
    for (int i = 0; i < length; i++) {
      sde[i] = sde_buffer[i];
    }
    sde[length] = '\0';
    set_class_sde_buffer((char*)sde, length);
D
duke 已提交
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
  }
  // Got utf8 string, set stream position forward
  cfs->skip_u1(length, CHECK);
}


// Inner classes can be static, private or protected (classic VM does this)
#define RECOGNIZED_INNER_CLASS_MODIFIERS (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED | JVM_ACC_STATIC)

// Return number of classes in the inner classes attribute table
2695
u2 ClassFileParser::parse_classfile_inner_classes_attribute(u1* inner_classes_attribute_start,
2696 2697 2698
                                                            bool parsed_enclosingmethod_attribute,
                                                            u2 enclosing_method_class_index,
                                                            u2 enclosing_method_method_index,
2699
                                                            TRAPS) {
D
duke 已提交
2700
  ClassFileStream* cfs = stream();
2701 2702 2703 2704 2705 2706 2707
  u1* current_mark = cfs->current();
  u2 length = 0;
  if (inner_classes_attribute_start != NULL) {
    cfs->set_current(inner_classes_attribute_start);
    cfs->guarantee_more(2, CHECK_0);  // length
    length = cfs->get_u2_fast();
  }
D
duke 已提交
2708

2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
  // 4-tuples of shorts of inner classes data and 2 shorts of enclosing
  // method data:
  //   [inner_class_info_index,
  //    outer_class_info_index,
  //    inner_name_index,
  //    inner_class_access_flags,
  //    ...
  //    enclosing_method_class_index,
  //    enclosing_method_method_index]
  int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
2719 2720 2721
  Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
  _inner_classes = inner_classes;

D
duke 已提交
2722
  int index = 0;
2723
  int cp_size = _cp->length();
D
duke 已提交
2724 2725 2726 2727 2728 2729
  cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
  for (int n = 0; n < length; n++) {
    // Inner class index
    u2 inner_class_info_index = cfs->get_u2_fast();
    check_property(
      inner_class_info_index == 0 ||
2730
        valid_klass_reference_at(inner_class_info_index),
D
duke 已提交
2731 2732 2733 2734 2735 2736
      "inner_class_info_index %u has bad constant type in class file %s",
      inner_class_info_index, CHECK_0);
    // Outer class index
    u2 outer_class_info_index = cfs->get_u2_fast();
    check_property(
      outer_class_info_index == 0 ||
2737
        valid_klass_reference_at(outer_class_info_index),
D
duke 已提交
2738 2739 2740 2741 2742
      "outer_class_info_index %u has bad constant type in class file %s",
      outer_class_info_index, CHECK_0);
    // Inner class name
    u2 inner_name_index = cfs->get_u2_fast();
    check_property(
2743
      inner_name_index == 0 || valid_symbol_at(inner_name_index),
D
duke 已提交
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759
      "inner_name_index %u has bad constant type in class file %s",
      inner_name_index, CHECK_0);
    if (_need_verify) {
      guarantee_property(inner_class_info_index != outer_class_info_index,
                         "Class is both outer and inner class in class file %s", CHECK_0);
    }
    // Access flags
    AccessFlags inner_access_flags;
    jint flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;
    if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
      // Set abstract bit for old class files for backward compatibility
      flags |= JVM_ACC_ABSTRACT;
    }
    verify_legal_class_modifiers(flags, CHECK_0);
    inner_access_flags.set_flags(flags);

2760 2761 2762 2763
    inner_classes->at_put(index++, inner_class_info_index);
    inner_classes->at_put(index++, outer_class_info_index);
    inner_classes->at_put(index++, inner_name_index);
    inner_classes->at_put(index++, inner_access_flags.as_short());
D
duke 已提交
2764 2765 2766 2767
  }

  // 4347400: make sure there's no duplicate entry in the classes array
  if (_need_verify && _major_version >= JAVA_1_5_VERSION) {
2768 2769
    for(int i = 0; i < length * 4; i += 4) {
      for(int j = i + 4; j < length * 4; j += 4) {
2770 2771 2772 2773
        guarantee_property((inner_classes->at(i)   != inner_classes->at(j) ||
                            inner_classes->at(i+1) != inner_classes->at(j+1) ||
                            inner_classes->at(i+2) != inner_classes->at(j+2) ||
                            inner_classes->at(i+3) != inner_classes->at(j+3)),
D
duke 已提交
2774 2775 2776 2777 2778 2779
                            "Duplicate entry in InnerClasses in class file %s",
                            CHECK_0);
      }
    }
  }

2780 2781
  // Set EnclosingMethod class and method indexes.
  if (parsed_enclosingmethod_attribute) {
2782 2783
    inner_classes->at_put(index++, enclosing_method_class_index);
    inner_classes->at_put(index++, enclosing_method_method_index);
2784 2785 2786 2787 2788 2789
  }
  assert(index == size, "wrong size");

  // Restore buffer's current position.
  cfs->set_current(current_mark);

D
duke 已提交
2790 2791 2792
  return length;
}

2793
void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
2794
  set_class_synthetic_flag(true);
D
duke 已提交
2795 2796
}

2797
void ClassFileParser::parse_classfile_signature_attribute(TRAPS) {
D
duke 已提交
2798 2799 2800
  ClassFileStream* cfs = stream();
  u2 signature_index = cfs->get_u2(CHECK);
  check_property(
2801
    valid_symbol_at(signature_index),
D
duke 已提交
2802 2803
    "Invalid constant pool index %u in Signature attribute in class file %s",
    signature_index, CHECK);
2804
  set_class_generic_signature_index(signature_index);
D
duke 已提交
2805 2806
}

2807
void ClassFileParser::parse_classfile_bootstrap_methods_attribute(u4 attribute_byte_length, TRAPS) {
2808 2809 2810
  ClassFileStream* cfs = stream();
  u1* current_start = cfs->current();

2811
  guarantee_property(attribute_byte_length >= sizeof(u2),
2812 2813 2814 2815 2816 2817
                     "Invalid BootstrapMethods attribute length %u in class file %s",
                     attribute_byte_length,
                     CHECK);

  cfs->guarantee_more(attribute_byte_length, CHECK);

2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
  int attribute_array_length = cfs->get_u2_fast();

  guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,
                     "Short length on BootstrapMethods in class file %s",
                     CHECK);

  // The attribute contains a counted array of counted tuples of shorts,
  // represending bootstrap specifiers:
  //    length*{bootstrap_method_index, argument_count*{argument_index}}
  int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);
  // operand_count = number of shorts in attr, except for leading length

  // The attribute is copied into a short[] array.
  // The array begins with a series of short[2] pairs, one for each tuple.
  int index_size = (attribute_array_length * 2);

2834 2835 2836 2837 2838
  Array<u2>* operands = MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);

  // Eagerly assign operands so they will be deallocated with the constant
  // pool if there is an error.
  _cp->set_operands(operands);
2839 2840

  int operand_fill_index = index_size;
2841
  int cp_size = _cp->length();
2842 2843 2844

  for (int n = 0; n < attribute_array_length; n++) {
    // Store a 32-bit offset into the header of the operand array.
2845
    ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);
2846 2847 2848 2849 2850 2851 2852

    // Read a bootstrap specifier.
    cfs->guarantee_more(sizeof(u2) * 2, CHECK);  // bsm, argc
    u2 bootstrap_method_index = cfs->get_u2_fast();
    u2 argument_count = cfs->get_u2_fast();
    check_property(
      valid_cp_range(bootstrap_method_index, cp_size) &&
2853
      _cp->tag_at(bootstrap_method_index).is_method_handle(),
2854
      "bootstrap_method_index %u has bad constant type in class file %s",
2855
      bootstrap_method_index,
2856
      CHECK);
H
hseigel 已提交
2857 2858 2859 2860 2861

    guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),
      "Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",
      CHECK);

2862 2863
    operands->at_put(operand_fill_index++, bootstrap_method_index);
    operands->at_put(operand_fill_index++, argument_count);
2864 2865 2866

    cfs->guarantee_more(sizeof(u2) * argument_count, CHECK);  // argv[argc]
    for (int j = 0; j < argument_count; j++) {
2867
      u2 argument_index = cfs->get_u2_fast();
2868
      check_property(
2869
        valid_cp_range(argument_index, cp_size) &&
2870
        _cp->tag_at(argument_index).is_loadable_constant(),
2871
        "argument_index %u has bad constant type in class file %s",
2872
        argument_index,
2873
        CHECK);
2874
      operands->at_put(operand_fill_index++, argument_index);
2875 2876 2877
    }
  }

2878
  assert(operand_fill_index == operands->length(), "exact fill");
2879 2880 2881 2882 2883 2884 2885

  u1* current_end = cfs->current();
  guarantee_property(current_end == current_start + attribute_byte_length,
                     "Bad length on BootstrapMethods in class file %s",
                     CHECK);
}

2886
void ClassFileParser::parse_classfile_attributes(ClassFileParser::ClassAnnotationCollector* parsed_annotations,
2887
                                                 TRAPS) {
D
duke 已提交
2888 2889
  ClassFileStream* cfs = stream();
  // Set inner classes attribute to default sentinel
2890
  _inner_classes = Universe::the_empty_short_array();
D
duke 已提交
2891 2892 2893 2894 2895
  cfs->guarantee_more(2, CHECK);  // attributes_count
  u2 attributes_count = cfs->get_u2_fast();
  bool parsed_sourcefile_attribute = false;
  bool parsed_innerclasses_attribute = false;
  bool parsed_enclosingmethod_attribute = false;
2896
  bool parsed_bootstrap_methods_attribute = false;
D
duke 已提交
2897 2898 2899 2900
  u1* runtime_visible_annotations = NULL;
  int runtime_visible_annotations_length = 0;
  u1* runtime_invisible_annotations = NULL;
  int runtime_invisible_annotations_length = 0;
2901 2902 2903 2904
  u1* runtime_visible_type_annotations = NULL;
  int runtime_visible_type_annotations_length = 0;
  u1* runtime_invisible_type_annotations = NULL;
  int runtime_invisible_type_annotations_length = 0;
2905
  bool runtime_invisible_type_annotations_exists = false;
2906 2907 2908 2909
  u1* inner_classes_attribute_start = NULL;
  u4  inner_classes_attribute_length = 0;
  u2  enclosing_method_class_index = 0;
  u2  enclosing_method_method_index = 0;
D
duke 已提交
2910 2911 2912 2913 2914 2915
  // Iterate over attributes
  while (attributes_count--) {
    cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
    u2 attribute_name_index = cfs->get_u2_fast();
    u4 attribute_length = cfs->get_u4_fast();
    check_property(
2916
      valid_symbol_at(attribute_name_index),
D
duke 已提交
2917 2918
      "Attribute name has bad constant pool index %u in class file %s",
      attribute_name_index, CHECK);
2919
    Symbol* tag = _cp->symbol_at(attribute_name_index);
D
duke 已提交
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929
    if (tag == vmSymbols::tag_source_file()) {
      // Check for SourceFile tag
      if (_need_verify) {
        guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);
      }
      if (parsed_sourcefile_attribute) {
        classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);
      } else {
        parsed_sourcefile_attribute = true;
      }
2930
      parse_classfile_sourcefile_attribute(CHECK);
D
duke 已提交
2931 2932
    } else if (tag == vmSymbols::tag_source_debug_extension()) {
      // Check for SourceDebugExtension tag
2933
      parse_classfile_source_debug_extension_attribute((int)attribute_length, CHECK);
D
duke 已提交
2934 2935 2936 2937 2938 2939 2940
    } else if (tag == vmSymbols::tag_inner_classes()) {
      // Check for InnerClasses tag
      if (parsed_innerclasses_attribute) {
        classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);
      } else {
        parsed_innerclasses_attribute = true;
      }
2941 2942 2943
      inner_classes_attribute_start = cfs->get_u1_buffer();
      inner_classes_attribute_length = attribute_length;
      cfs->skip_u1(inner_classes_attribute_length, CHECK);
D
duke 已提交
2944 2945 2946 2947 2948 2949 2950 2951
    } else if (tag == vmSymbols::tag_synthetic()) {
      // Check for Synthetic tag
      // Shouldn't we check that the synthetic flags wasn't already set? - not required in spec
      if (attribute_length != 0) {
        classfile_parse_error(
          "Invalid Synthetic classfile attribute length %u in class file %s",
          attribute_length, CHECK);
      }
2952
      parse_classfile_synthetic_attribute(CHECK);
D
duke 已提交
2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
    } else if (tag == vmSymbols::tag_deprecated()) {
      // Check for Deprecatd tag - 4276120
      if (attribute_length != 0) {
        classfile_parse_error(
          "Invalid Deprecated classfile attribute length %u in class file %s",
          attribute_length, CHECK);
      }
    } else if (_major_version >= JAVA_1_5_VERSION) {
      if (tag == vmSymbols::tag_signature()) {
        if (attribute_length != 2) {
          classfile_parse_error(
            "Wrong Signature attribute length %u in class file %s",
            attribute_length, CHECK);
        }
2967
        parse_classfile_signature_attribute(CHECK);
D
duke 已提交
2968 2969 2970 2971
      } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
        runtime_visible_annotations_length = attribute_length;
        runtime_visible_annotations = cfs->get_u1_buffer();
        assert(runtime_visible_annotations != NULL, "null visible annotations");
2972
        cfs->guarantee_more(runtime_visible_annotations_length, CHECK);
2973
        parse_annotations(runtime_visible_annotations,
2974 2975 2976
                          runtime_visible_annotations_length,
                          parsed_annotations,
                          CHECK);
2977
        cfs->skip_u1_fast(runtime_visible_annotations_length);
D
duke 已提交
2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989
      } else if (PreserveAllAnnotations && tag == vmSymbols::tag_runtime_invisible_annotations()) {
        runtime_invisible_annotations_length = attribute_length;
        runtime_invisible_annotations = cfs->get_u1_buffer();
        assert(runtime_invisible_annotations != NULL, "null invisible annotations");
        cfs->skip_u1(runtime_invisible_annotations_length, CHECK);
      } else if (tag == vmSymbols::tag_enclosing_method()) {
        if (parsed_enclosingmethod_attribute) {
          classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);
        }   else {
          parsed_enclosingmethod_attribute = true;
        }
        cfs->guarantee_more(4, CHECK);  // class_index, method_index
2990 2991 2992
        enclosing_method_class_index  = cfs->get_u2_fast();
        enclosing_method_method_index = cfs->get_u2_fast();
        if (enclosing_method_class_index == 0) {
D
duke 已提交
2993 2994 2995
          classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
        }
        // Validate the constant pool indices and types
2996 2997
        check_property(valid_klass_reference_at(enclosing_method_class_index),
          "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
2998
        if (enclosing_method_method_index != 0 &&
2999 3000
            (!_cp->is_within_bounds(enclosing_method_method_index) ||
             !_cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
D
duke 已提交
3001 3002
          classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
        }
3003 3004 3005 3006 3007
      } else if (tag == vmSymbols::tag_bootstrap_methods() &&
                 _major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {
        if (parsed_bootstrap_methods_attribute)
          classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
        parsed_bootstrap_methods_attribute = true;
3008
        parse_classfile_bootstrap_methods_attribute(attribute_length, CHECK);
3009
      } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
3010 3011 3012 3013
        if (runtime_visible_type_annotations != NULL) {
          classfile_parse_error(
            "Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);
        }
3014 3015 3016 3017 3018
        runtime_visible_type_annotations_length = attribute_length;
        runtime_visible_type_annotations = cfs->get_u1_buffer();
        assert(runtime_visible_type_annotations != NULL, "null visible type annotations");
        // No need for the VM to parse Type annotations
        cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031
      } else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {
        if (runtime_invisible_type_annotations_exists) {
          classfile_parse_error(
            "Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);
        } else {
          runtime_invisible_type_annotations_exists = true;
        }
        if (PreserveAllAnnotations) {
          runtime_invisible_type_annotations_length = attribute_length;
          runtime_invisible_type_annotations = cfs->get_u1_buffer();
          assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");
        }
        cfs->skip_u1(attribute_length, CHECK);
D
duke 已提交
3032 3033 3034 3035 3036 3037 3038 3039 3040
      } else {
        // Unknown attribute
        cfs->skip_u1(attribute_length, CHECK);
      }
    } else {
      // Unknown attribute
      cfs->skip_u1(attribute_length, CHECK);
    }
  }
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050
  _annotations = assemble_annotations(runtime_visible_annotations,
                                      runtime_visible_annotations_length,
                                      runtime_invisible_annotations,
                                      runtime_invisible_annotations_length,
                                      CHECK);
  _type_annotations = assemble_annotations(runtime_visible_type_annotations,
                                           runtime_visible_type_annotations_length,
                                           runtime_invisible_type_annotations,
                                           runtime_invisible_type_annotations_length,
                                           CHECK);
3051

3052 3053 3054 3055 3056 3057
  if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
    u2 num_of_classes = parse_classfile_inner_classes_attribute(
                            inner_classes_attribute_start,
                            parsed_innerclasses_attribute,
                            enclosing_method_class_index,
                            enclosing_method_method_index,
3058
                            CHECK);
3059 3060 3061 3062 3063 3064 3065
    if (parsed_innerclasses_attribute &&_need_verify && _major_version >= JAVA_1_5_VERSION) {
      guarantee_property(
        inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
        "Wrong InnerClasses attribute length in class file %s", CHECK);
    }
  }

3066 3067 3068 3069
  if (_max_bootstrap_specifier_index >= 0) {
    guarantee_property(parsed_bootstrap_methods_attribute,
                       "Missing BootstrapMethods attribute in class file %s", CHECK);
  }
D
duke 已提交
3070 3071
}

3072 3073 3074
void ClassFileParser::apply_parsed_class_attributes(instanceKlassHandle k) {
  if (_synthetic_flag)
    k->set_is_synthetic();
3075 3076
  if (_sourcefile_index != 0) {
    k->set_source_file_name_index(_sourcefile_index);
3077
  }
3078 3079
  if (_generic_signature_index != 0) {
    k->set_generic_signature_index(_generic_signature_index);
3080
  }
K
Merge  
kvn 已提交
3081 3082 3083
  if (_sde_buffer != NULL) {
    k->set_source_debug_extension(_sde_buffer, _sde_length);
  }
3084
}
D
duke 已提交
3085

3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
// Create the Annotations object that will
// hold the annotations array for the Klass.
void ClassFileParser::create_combined_annotations(TRAPS) {
    if (_annotations == NULL &&
        _type_annotations == NULL &&
        _fields_annotations == NULL &&
        _fields_type_annotations == NULL) {
      // Don't create the Annotations object unnecessarily.
      return;
    }

3097 3098 3099 3100 3101 3102
    Annotations* annotations = Annotations::allocate(_loader_data, CHECK);
    annotations->set_class_annotations(_annotations);
    annotations->set_class_type_annotations(_type_annotations);
    annotations->set_fields_annotations(_fields_annotations);
    annotations->set_fields_type_annotations(_fields_type_annotations);

3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118
    // This is the Annotations object that will be
    // assigned to InstanceKlass being constructed.
    _combined_annotations = annotations;

    // The annotations arrays below has been transfered the
    // _combined_annotations so these fields can now be cleared.
    _annotations             = NULL;
    _type_annotations        = NULL;
    _fields_annotations      = NULL;
    _fields_type_annotations = NULL;
}

// Transfer ownership of metadata allocated to the InstanceKlass.
void ClassFileParser::apply_parsed_class_metadata(
                                            instanceKlassHandle this_klass,
                                            int java_fields_count, TRAPS) {
3119 3120 3121 3122 3123 3124 3125
  _cp->set_pool_holder(this_klass());
  this_klass->set_constants(_cp);
  this_klass->set_fields(_fields, java_fields_count);
  this_klass->set_methods(_methods);
  this_klass->set_inner_classes(_inner_classes);
  this_klass->set_local_interfaces(_local_interfaces);
  this_klass->set_transitive_interfaces(_transitive_interfaces);
3126
  this_klass->set_annotations(_combined_annotations);
3127 3128 3129 3130 3131 3132

  // Clear out these fields so they don't get deallocated by the destructor
  clear_class_metadata();
}

AnnotationArray* ClassFileParser::assemble_annotations(u1* runtime_visible_annotations,
3133 3134 3135
                                                       int runtime_visible_annotations_length,
                                                       u1* runtime_invisible_annotations,
                                                       int runtime_invisible_annotations_length, TRAPS) {
3136
  AnnotationArray* annotations = NULL;
D
duke 已提交
3137 3138
  if (runtime_visible_annotations != NULL ||
      runtime_invisible_annotations != NULL) {
3139
    annotations = MetadataFactory::new_array<u1>(_loader_data,
3140 3141 3142
                                          runtime_visible_annotations_length +
                                          runtime_invisible_annotations_length,
                                          CHECK_(annotations));
D
duke 已提交
3143
    if (runtime_visible_annotations != NULL) {
3144 3145 3146
      for (int i = 0; i < runtime_visible_annotations_length; i++) {
        annotations->at_put(i, runtime_visible_annotations[i]);
      }
D
duke 已提交
3147 3148
    }
    if (runtime_invisible_annotations != NULL) {
3149 3150 3151 3152
      for (int i = 0; i < runtime_invisible_annotations_length; i++) {
        int append = runtime_visible_annotations_length+i;
        annotations->at_put(append, runtime_invisible_annotations[i]);
      }
D
duke 已提交
3153 3154 3155 3156 3157
    }
  }
  return annotations;
}

3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211
instanceKlassHandle ClassFileParser::parse_super_class(int super_class_index,
                                                       TRAPS) {
  instanceKlassHandle super_klass;
  if (super_class_index == 0) {
    check_property(_class_name == vmSymbols::java_lang_Object(),
                   "Invalid superclass index %u in class file %s",
                   super_class_index,
                   CHECK_NULL);
  } else {
    check_property(valid_klass_reference_at(super_class_index),
                   "Invalid superclass index %u in class file %s",
                   super_class_index,
                   CHECK_NULL);
    // The class name should be legal because it is checked when parsing constant pool.
    // However, make sure it is not an array type.
    bool is_array = false;
    if (_cp->tag_at(super_class_index).is_klass()) {
      super_klass = instanceKlassHandle(THREAD, _cp->resolved_klass_at(super_class_index));
      if (_need_verify)
        is_array = super_klass->oop_is_array();
    } else if (_need_verify) {
      is_array = (_cp->unresolved_klass_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
    }
    if (_need_verify) {
      guarantee_property(!is_array,
                        "Bad superclass name in class file %s", CHECK_NULL);
    }
  }
  return super_klass;
}


// Values needed for oopmap and InstanceKlass creation
class FieldLayoutInfo : public StackObj {
 public:
  int*          nonstatic_oop_offsets;
  unsigned int* nonstatic_oop_counts;
  unsigned int  nonstatic_oop_map_count;
  unsigned int  total_oop_map_count;
  int           instance_size;
  int           nonstatic_field_size;
  int           static_field_size;
  bool          has_nonstatic_fields;
};

// Layout fields and fill in FieldLayoutInfo.  Could use more refactoring!
void ClassFileParser::layout_fields(Handle class_loader,
                                    FieldAllocationCount* fac,
                                    ClassAnnotationCollector* parsed_annotations,
                                    FieldLayoutInfo* info,
                                    TRAPS) {

  // Field size and offset computation
  int nonstatic_field_size = _super_klass() == NULL ? 0 : _super_klass()->nonstatic_field_size();
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
  int next_static_oop_offset = 0;
  int next_static_double_offset = 0;
  int next_static_word_offset = 0;
  int next_static_short_offset = 0;
  int next_static_byte_offset = 0;
  int next_nonstatic_oop_offset = 0;
  int next_nonstatic_double_offset = 0;
  int next_nonstatic_word_offset = 0;
  int next_nonstatic_short_offset = 0;
  int next_nonstatic_byte_offset = 0;
  int first_nonstatic_oop_offset = 0;
  int next_nonstatic_field_offset = 0;
  int next_nonstatic_padded_offset = 0;
3225 3226

  // Count the contended fields by type.
3227 3228 3229
  //
  // We ignore static fields, because @Contended is not supported for them.
  // The layout code below will also ignore the static fields.
3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259
  int nonstatic_contended_count = 0;
  FieldAllocationCount fac_contended;
  for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
    FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
    if (fs.is_contended()) {
      fac_contended.count[atype]++;
      if (!fs.access_flags().is_static()) {
        nonstatic_contended_count++;
      }
    }
  }


  // Calculate the starting byte offsets
  next_static_oop_offset      = InstanceMirrorKlass::offset_of_static_fields();
  next_static_double_offset   = next_static_oop_offset +
                                ((fac->count[STATIC_OOP]) * heapOopSize);
  if ( fac->count[STATIC_DOUBLE] &&
       (Universe::field_type_should_be_aligned(T_DOUBLE) ||
        Universe::field_type_should_be_aligned(T_LONG)) ) {
    next_static_double_offset = align_size_up(next_static_double_offset, BytesPerLong);
  }

  next_static_word_offset     = next_static_double_offset +
                                ((fac->count[STATIC_DOUBLE]) * BytesPerLong);
  next_static_short_offset    = next_static_word_offset +
                                ((fac->count[STATIC_WORD]) * BytesPerInt);
  next_static_byte_offset     = next_static_short_offset +
                                ((fac->count[STATIC_SHORT]) * BytesPerShort);

3260 3261
  int nonstatic_fields_start  = instanceOopDesc::base_offset_in_bytes() +
                                nonstatic_field_size * heapOopSize;
3262

3263
  next_nonstatic_field_offset = nonstatic_fields_start;
3264

3265 3266
  bool is_contended_class     = parsed_annotations->is_contended();

3267
  // Class is contended, pad before all the fields
3268
  if (is_contended_class) {
3269
    next_nonstatic_field_offset += ContendedPaddingWidth;
3270 3271
  }

3272 3273 3274 3275
  // Compute the non-contended fields count.
  // The packing code below relies on these counts to determine if some field
  // can be squeezed into the alignment gap. Contended fields are obviously
  // exempt from that.
3276 3277 3278 3279 3280 3281
  unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
  unsigned int nonstatic_word_count   = fac->count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
  unsigned int nonstatic_short_count  = fac->count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
  unsigned int nonstatic_byte_count   = fac->count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
  unsigned int nonstatic_oop_count    = fac->count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];

3282 3283 3284 3285 3286
  // Total non-static fields count, including every contended field
  unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +
                                        fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +
                                        fac->count[NONSTATIC_OOP];

3287 3288
  bool super_has_nonstatic_fields =
          (_super_klass() != NULL && _super_klass->has_nonstatic_fields());
3289
  bool has_nonstatic_fields = super_has_nonstatic_fields || (nonstatic_fields_count != 0);
3290 3291 3292


  // Prepare list of oops for oop map generation.
3293 3294 3295 3296 3297 3298 3299 3300 3301
  //
  // "offset" and "count" lists are describing the set of contiguous oop
  // regions. offset[i] is the start of the i-th region, which then has
  // count[i] oops following. Before we know how many regions are required,
  // we pessimistically allocate the maps to fit all the oops into the
  // distinct regions.
  //
  // TODO: We add +1 to always allocate non-zero resource arrays; we need
  // to figure out if we still need to do this.
3302 3303 3304
  int* nonstatic_oop_offsets;
  unsigned int* nonstatic_oop_counts;
  unsigned int nonstatic_oop_map_count = 0;
3305
  unsigned int max_nonstatic_oop_maps  = fac->count[NONSTATIC_OOP] + 1;
3306 3307

  nonstatic_oop_offsets = NEW_RESOURCE_ARRAY_IN_THREAD(
3308
            THREAD, int, max_nonstatic_oop_maps);
3309
  nonstatic_oop_counts  = NEW_RESOURCE_ARRAY_IN_THREAD(
3310
            THREAD, unsigned int, max_nonstatic_oop_maps);
3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344

  first_nonstatic_oop_offset = 0; // will be set for first oop field

  bool compact_fields   = CompactFields;
  int  allocation_style = FieldsAllocationStyle;
  if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
    assert(false, "0 <= FieldsAllocationStyle <= 2");
    allocation_style = 1; // Optimistic
  }

  // The next classes have predefined hard-coded fields offsets
  // (see in JavaClasses::compute_hard_coded_offsets()).
  // Use default fields allocation order for them.
  if( (allocation_style != 0 || compact_fields ) && class_loader.is_null() &&
      (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
       _class_name == vmSymbols::java_lang_Class() ||
       _class_name == vmSymbols::java_lang_ClassLoader() ||
       _class_name == vmSymbols::java_lang_ref_Reference() ||
       _class_name == vmSymbols::java_lang_ref_SoftReference() ||
       _class_name == vmSymbols::java_lang_StackTraceElement() ||
       _class_name == vmSymbols::java_lang_String() ||
       _class_name == vmSymbols::java_lang_Throwable() ||
       _class_name == vmSymbols::java_lang_Boolean() ||
       _class_name == vmSymbols::java_lang_Character() ||
       _class_name == vmSymbols::java_lang_Float() ||
       _class_name == vmSymbols::java_lang_Double() ||
       _class_name == vmSymbols::java_lang_Byte() ||
       _class_name == vmSymbols::java_lang_Short() ||
       _class_name == vmSymbols::java_lang_Integer() ||
       _class_name == vmSymbols::java_lang_Long())) {
    allocation_style = 0;     // Allocate oops first
    compact_fields   = false; // Don't compact fields
  }

3345
  // Rearrange fields for a given allocation style
3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
  if( allocation_style == 0 ) {
    // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
    next_nonstatic_oop_offset    = next_nonstatic_field_offset;
    next_nonstatic_double_offset = next_nonstatic_oop_offset +
                                    (nonstatic_oop_count * heapOopSize);
  } else if( allocation_style == 1 ) {
    // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
    next_nonstatic_double_offset = next_nonstatic_field_offset;
  } else if( allocation_style == 2 ) {
    // Fields allocation: oops fields in super and sub classes are together.
    if( nonstatic_field_size > 0 && _super_klass() != NULL &&
        _super_klass->nonstatic_oop_map_size() > 0 ) {
      unsigned int map_count = _super_klass->nonstatic_oop_map_count();
      OopMapBlock* first_map = _super_klass->start_of_nonstatic_oop_maps();
      OopMapBlock* last_map = first_map + map_count - 1;
      int next_offset = last_map->offset() + (last_map->count() * heapOopSize);
      if (next_offset == next_nonstatic_field_offset) {
        allocation_style = 0;   // allocate oops first
        next_nonstatic_oop_offset    = next_nonstatic_field_offset;
        next_nonstatic_double_offset = next_nonstatic_oop_offset +
                                       (nonstatic_oop_count * heapOopSize);
      }
    }
    if( allocation_style == 2 ) {
      allocation_style = 1;     // allocate oops last
      next_nonstatic_double_offset = next_nonstatic_field_offset;
    }
  } else {
    ShouldNotReachHere();
  }

3377 3378 3379 3380 3381 3382 3383 3384
  int nonstatic_oop_space_count    = 0;
  int nonstatic_word_space_count   = 0;
  int nonstatic_short_space_count  = 0;
  int nonstatic_byte_space_count   = 0;
  int nonstatic_oop_space_offset   = 0;
  int nonstatic_word_space_offset  = 0;
  int nonstatic_short_space_offset = 0;
  int nonstatic_byte_space_offset  = 0;
3385

3386 3387
  // Try to squeeze some of the fields into the gaps due to
  // long/double alignment.
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455
  if( nonstatic_double_count > 0 ) {
    int offset = next_nonstatic_double_offset;
    next_nonstatic_double_offset = align_size_up(offset, BytesPerLong);
    if( compact_fields && offset != next_nonstatic_double_offset ) {
      // Allocate available fields into the gap before double field.
      int length = next_nonstatic_double_offset - offset;
      assert(length == BytesPerInt, "");
      nonstatic_word_space_offset = offset;
      if( nonstatic_word_count > 0 ) {
        nonstatic_word_count      -= 1;
        nonstatic_word_space_count = 1; // Only one will fit
        length -= BytesPerInt;
        offset += BytesPerInt;
      }
      nonstatic_short_space_offset = offset;
      while( length >= BytesPerShort && nonstatic_short_count > 0 ) {
        nonstatic_short_count       -= 1;
        nonstatic_short_space_count += 1;
        length -= BytesPerShort;
        offset += BytesPerShort;
      }
      nonstatic_byte_space_offset = offset;
      while( length > 0 && nonstatic_byte_count > 0 ) {
        nonstatic_byte_count       -= 1;
        nonstatic_byte_space_count += 1;
        length -= 1;
      }
      // Allocate oop field in the gap if there are no other fields for that.
      nonstatic_oop_space_offset = offset;
      if( length >= heapOopSize && nonstatic_oop_count > 0 &&
          allocation_style != 0 ) { // when oop fields not first
        nonstatic_oop_count      -= 1;
        nonstatic_oop_space_count = 1; // Only one will fit
        length -= heapOopSize;
        offset += heapOopSize;
      }
    }
  }

  next_nonstatic_word_offset  = next_nonstatic_double_offset +
                                (nonstatic_double_count * BytesPerLong);
  next_nonstatic_short_offset = next_nonstatic_word_offset +
                                (nonstatic_word_count * BytesPerInt);
  next_nonstatic_byte_offset  = next_nonstatic_short_offset +
                                (nonstatic_short_count * BytesPerShort);
  next_nonstatic_padded_offset = next_nonstatic_byte_offset +
                                nonstatic_byte_count;

  // let oops jump before padding with this allocation style
  if( allocation_style == 1 ) {
    next_nonstatic_oop_offset = next_nonstatic_padded_offset;
    if( nonstatic_oop_count > 0 ) {
      next_nonstatic_oop_offset = align_size_up(next_nonstatic_oop_offset, heapOopSize);
    }
    next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
  }

  // Iterate over fields again and compute correct offsets.
  // The field allocation type was temporarily stored in the offset slot.
  // oop fields are located before non-oop fields (static and non-static).
  for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {

    // skip already laid out fields
    if (fs.is_offset_set()) continue;

    // contended instance fields are handled below
    if (fs.is_contended() && !fs.access_flags().is_static()) continue;

3456
    int real_offset = 0;
3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496
    FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();

    // pack the rest of the fields
    switch (atype) {
      case STATIC_OOP:
        real_offset = next_static_oop_offset;
        next_static_oop_offset += heapOopSize;
        break;
      case STATIC_BYTE:
        real_offset = next_static_byte_offset;
        next_static_byte_offset += 1;
        break;
      case STATIC_SHORT:
        real_offset = next_static_short_offset;
        next_static_short_offset += BytesPerShort;
        break;
      case STATIC_WORD:
        real_offset = next_static_word_offset;
        next_static_word_offset += BytesPerInt;
        break;
      case STATIC_DOUBLE:
        real_offset = next_static_double_offset;
        next_static_double_offset += BytesPerLong;
        break;
      case NONSTATIC_OOP:
        if( nonstatic_oop_space_count > 0 ) {
          real_offset = nonstatic_oop_space_offset;
          nonstatic_oop_space_offset += heapOopSize;
          nonstatic_oop_space_count  -= 1;
        } else {
          real_offset = next_nonstatic_oop_offset;
          next_nonstatic_oop_offset += heapOopSize;
        }
        // Update oop maps
        if( nonstatic_oop_map_count > 0 &&
            nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
            real_offset -
            int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
            heapOopSize ) {
          // Extend current oop map
3497
          assert(nonstatic_oop_map_count - 1 < max_nonstatic_oop_maps, "range check");
3498 3499 3500
          nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
        } else {
          // Create new oop map
3501
          assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
          nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
          nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
          nonstatic_oop_map_count += 1;
          if( first_nonstatic_oop_offset == 0 ) { // Undefined
            first_nonstatic_oop_offset = real_offset;
          }
        }
        break;
      case NONSTATIC_BYTE:
        if( nonstatic_byte_space_count > 0 ) {
          real_offset = nonstatic_byte_space_offset;
          nonstatic_byte_space_offset += 1;
          nonstatic_byte_space_count  -= 1;
        } else {
          real_offset = next_nonstatic_byte_offset;
          next_nonstatic_byte_offset += 1;
        }
        break;
      case NONSTATIC_SHORT:
        if( nonstatic_short_space_count > 0 ) {
          real_offset = nonstatic_short_space_offset;
          nonstatic_short_space_offset += BytesPerShort;
          nonstatic_short_space_count  -= 1;
        } else {
          real_offset = next_nonstatic_short_offset;
          next_nonstatic_short_offset += BytesPerShort;
        }
        break;
      case NONSTATIC_WORD:
        if( nonstatic_word_space_count > 0 ) {
          real_offset = nonstatic_word_space_offset;
          nonstatic_word_space_offset += BytesPerInt;
          nonstatic_word_space_count  -= 1;
        } else {
          real_offset = next_nonstatic_word_offset;
          next_nonstatic_word_offset += BytesPerInt;
        }
        break;
      case NONSTATIC_DOUBLE:
        real_offset = next_nonstatic_double_offset;
        next_nonstatic_double_offset += BytesPerLong;
        break;
      default:
        ShouldNotReachHere();
    }
    fs.set_offset(real_offset);
  }


  // Handle the contended cases.
  //
  // Each contended field should not intersect the cache line with another contended field.
  // In the absence of alignment information, we end up with pessimistically separating
  // the fields with full-width padding.
  //
  // Additionally, this should not break alignment for the fields, so we round the alignment up
  // for each field.
3559
  if (nonstatic_contended_count > 0) {
3560 3561

    // if there is at least one contended field, we need to have pre-padding for them
3562
    next_nonstatic_padded_offset += ContendedPaddingWidth;
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588

    // collect all contended groups
    BitMap bm(_cp->size());
    for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
      // skip already laid out fields
      if (fs.is_offset_set()) continue;

      if (fs.is_contended()) {
        bm.set_bit(fs.contended_group());
      }
    }

    int current_group = -1;
    while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {

      for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {

        // skip already laid out fields
        if (fs.is_offset_set()) continue;

        // skip non-contended fields and fields from different group
        if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;

        // handle statics below
        if (fs.access_flags().is_static()) continue;

3589
        int real_offset = 0;
3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
        FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();

        switch (atype) {
          case NONSTATIC_BYTE:
            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, 1);
            real_offset = next_nonstatic_padded_offset;
            next_nonstatic_padded_offset += 1;
            break;

          case NONSTATIC_SHORT:
            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerShort);
            real_offset = next_nonstatic_padded_offset;
            next_nonstatic_padded_offset += BytesPerShort;
            break;

          case NONSTATIC_WORD:
            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerInt);
            real_offset = next_nonstatic_padded_offset;
            next_nonstatic_padded_offset += BytesPerInt;
            break;

          case NONSTATIC_DOUBLE:
            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerLong);
            real_offset = next_nonstatic_padded_offset;
            next_nonstatic_padded_offset += BytesPerLong;
            break;

          case NONSTATIC_OOP:
            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, heapOopSize);
            real_offset = next_nonstatic_padded_offset;
            next_nonstatic_padded_offset += heapOopSize;

            // Create new oop map
3623
            assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");
3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
            nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
            nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
            nonstatic_oop_map_count += 1;
            if( first_nonstatic_oop_offset == 0 ) { // Undefined
              first_nonstatic_oop_offset = real_offset;
            }
            break;

          default:
            ShouldNotReachHere();
        }

        if (fs.contended_group() == 0) {
          // Contended group defines the equivalence class over the fields:
          // the fields within the same contended group are not inter-padded.
          // The only exception is default group, which does not incur the
          // equivalence, and so requires intra-padding.
3641
          next_nonstatic_padded_offset += ContendedPaddingWidth;
3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652
        }

        fs.set_offset(real_offset);
      } // for

      // Start laying out the next group.
      // Note that this will effectively pad the last group in the back;
      // this is expected to alleviate memory contention effects for
      // subclass fields and/or adjacent object.
      // If this was the default group, the padding is already in place.
      if (current_group != 0) {
3653
        next_nonstatic_padded_offset += ContendedPaddingWidth;
3654 3655 3656 3657 3658 3659 3660 3661 3662
      }
    }

    // handle static fields
  }

  // Entire class is contended, pad in the back.
  // This helps to alleviate memory contention effects for subclass fields
  // and/or adjacent object.
3663 3664
  if (is_contended_class) {
    next_nonstatic_padded_offset += ContendedPaddingWidth;
3665 3666
  }

3667 3668 3669 3670
  int notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;

  int nonstatic_fields_end      = align_size_up(notaligned_nonstatic_fields_end, heapOopSize);
  int instance_end              = align_size_up(notaligned_nonstatic_fields_end, wordSize);
3671
  int static_fields_end         = align_size_up(next_static_byte_offset, wordSize);
3672

3673 3674 3675 3676
  int static_field_size         = (static_fields_end -
                                   InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
  nonstatic_field_size          = nonstatic_field_size +
                                  (nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;
3677

3678
  int instance_size             = align_object_size(instance_end / wordSize);
3679 3680

  assert(instance_size == align_object_size(align_size_up(
3681
         (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize),
3682 3683
          wordSize) / wordSize), "consistent layout helper value");

3684 3685 3686 3687 3688 3689 3690 3691
  // Invariant: nonstatic_field end/start should only change if there are
  // nonstatic fields in the class, or if the class is contended. We compare
  // against the non-aligned value, so that end alignment will not fail the
  // assert without actually having the fields.
  assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||
         is_contended_class ||
         (nonstatic_fields_count > 0), "double-check nonstatic start/end");

3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702
  // Number of non-static oop map blocks allocated at end of klass.
  const unsigned int total_oop_map_count =
    compute_oop_map_count(_super_klass, nonstatic_oop_map_count,
                          first_nonstatic_oop_offset);

#ifndef PRODUCT
  if (PrintFieldLayout) {
    print_field_layout(_class_name,
          _fields,
          _cp,
          instance_size,
3703 3704 3705
          nonstatic_fields_start,
          nonstatic_fields_end,
          static_fields_end);
3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720
  }

#endif
  // Pass back information needed for InstanceKlass creation
  info->nonstatic_oop_offsets = nonstatic_oop_offsets;
  info->nonstatic_oop_counts = nonstatic_oop_counts;
  info->nonstatic_oop_map_count = nonstatic_oop_map_count;
  info->total_oop_map_count = total_oop_map_count;
  info->instance_size = instance_size;
  info->static_field_size = static_field_size;
  info->nonstatic_field_size = nonstatic_field_size;
  info->has_nonstatic_fields = has_nonstatic_fields;
}


3721
instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name,
3722
                                                    ClassLoaderData* loader_data,
D
duke 已提交
3723
                                                    Handle protection_domain,
3724
                                                    KlassHandle host_klass,
3725
                                                    GrowableArray<Handle>* cp_patches,
3726
                                                    TempNewSymbol& parsed_name,
3727
                                                    bool verify,
D
duke 已提交
3728
                                                    TRAPS) {
3729

3730 3731 3732 3733 3734
  // When a retransformable agent is attached, JVMTI caches the
  // class bytes that existed before the first retransformation.
  // If RedefineClasses() was used before the retransformable
  // agent attached, then the cached class bytes may not be the
  // original class bytes.
3735
  JvmtiCachedClassFileData *cached_class_file = NULL;
3736
  Handle class_loader(THREAD, loader_data->class_loader());
3737
  bool has_default_methods = false;
3738
  bool declares_default_methods = false;
3739
  ResourceMark rm(THREAD);
D
duke 已提交
3740 3741 3742

  ClassFileStream* cfs = stream();
  // Timing
3743 3744 3745 3746 3747 3748 3749 3750 3751
  assert(THREAD->is_Java_thread(), "must be a JavaThread");
  JavaThread* jt = (JavaThread*) THREAD;

  PerfClassTraceTime ctimer(ClassLoader::perf_class_parse_time(),
                            ClassLoader::perf_class_parse_selftime(),
                            NULL,
                            jt->get_thread_stat()->perf_recursion_counts_addr(),
                            jt->get_thread_stat()->perf_timers_addr(),
                            PerfClassTraceTime::PARSE_CLASS);
D
duke 已提交
3752

3753
  init_parsed_class_attributes(loader_data);
D
duke 已提交
3754 3755

  if (JvmtiExport::should_post_class_file_load_hook()) {
3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767
    // Get the cached class file bytes (if any) from the class that
    // is being redefined or retransformed. We use jvmti_thread_state()
    // instead of JvmtiThreadState::state_for(jt) so we don't allocate
    // a JvmtiThreadState any earlier than necessary. This will help
    // avoid the bug described by 7126851.
    JvmtiThreadState *state = jt->jvmti_thread_state();
    if (state != NULL) {
      KlassHandle *h_class_being_redefined =
                     state->get_class_being_redefined();
      if (h_class_being_redefined != NULL) {
        instanceKlassHandle ikh_class_being_redefined =
          instanceKlassHandle(THREAD, (*h_class_being_redefined)());
3768
        cached_class_file = ikh_class_being_redefined->get_cached_class_file();
3769
      }
3770 3771
    }

D
duke 已提交
3772 3773 3774
    unsigned char* ptr = cfs->buffer();
    unsigned char* end_ptr = cfs->buffer() + cfs->length();

3775
    JvmtiExport::post_class_file_load_hook(name, class_loader(), protection_domain,
3776
                                           &ptr, &end_ptr, &cached_class_file);
D
duke 已提交
3777 3778 3779 3780 3781 3782 3783 3784 3785 3786

    if (ptr != cfs->buffer()) {
      // JVMTI agent has modified class file data.
      // Set new class file stream using JVMTI agent modified
      // class file data.
      cfs = new ClassFileStream(ptr, end_ptr - ptr, cfs->source());
      set_stream(cfs);
    }
  }

3787
  _host_klass = host_klass;
3788
  _cp_patches = cp_patches;
D
duke 已提交
3789 3790 3791 3792

  instanceKlassHandle nullHandle;

  // Figure out whether we can skip format checking (matching classic VM behavior)
3793 3794 3795 3796 3797 3798 3799 3800 3801
  if (DumpSharedSpaces) {
    // verify == true means it's a 'remote' class (i.e., non-boot class)
    // Verification decision is based on BytecodeVerificationRemote flag
    // for those classes.
    _need_verify = (verify) ? BytecodeVerificationRemote :
                              BytecodeVerificationLocal;
  } else {
    _need_verify = Verifier::should_verify_for(class_loader(), verify);
  }
D
duke 已提交
3802 3803 3804 3805 3806

  // Set the verify flag in stream
  cfs->set_verify(_need_verify);

  // Save the class file name for easier error message printing.
3807
  _class_name = (name != NULL) ? name : vmSymbols::unknown_class_name();
D
duke 已提交
3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819

  cfs->guarantee_more(8, CHECK_(nullHandle));  // magic, major, minor
  // Magic value
  u4 magic = cfs->get_u4_fast();
  guarantee_property(magic == JAVA_CLASSFILE_MAGIC,
                     "Incompatible magic value %u in class file %s",
                     magic, CHECK_(nullHandle));

  // Version numbers
  u2 minor_version = cfs->get_u2_fast();
  u2 major_version = cfs->get_u2_fast();

3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831
  if (DumpSharedSpaces && major_version < JAVA_1_5_VERSION) {
    ResourceMark rm;
    warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",
            major_version,  minor_version, name->as_C_string());
    Exceptions::fthrow(
      THREAD_AND_LOCATION,
      vmSymbols::java_lang_UnsupportedClassVersionError(),
      "Unsupported major.minor version for dump time %u.%u",
      major_version,
      minor_version);
  }

D
duke 已提交
3832 3833
  // Check version numbers - we check this even with verifier off
  if (!is_supported_version(major_version, minor_version)) {
3834
    if (name == NULL) {
D
duke 已提交
3835 3836
      Exceptions::fthrow(
        THREAD_AND_LOCATION,
3837
        vmSymbols::java_lang_UnsupportedClassVersionError(),
3838 3839
        "Unsupported class file version %u.%u, "
        "this version of the Java Runtime only recognizes class file versions up to %u.%u",
D
duke 已提交
3840
        major_version,
3841 3842 3843
        minor_version,
        JAVA_MAX_SUPPORTED_VERSION,
        JAVA_MAX_SUPPORTED_MINOR_VERSION);
D
duke 已提交
3844 3845 3846 3847
    } else {
      ResourceMark rm(THREAD);
      Exceptions::fthrow(
        THREAD_AND_LOCATION,
3848
        vmSymbols::java_lang_UnsupportedClassVersionError(),
3849 3850
        "%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "
        "this version of the Java Runtime only recognizes class file versions up to %u.%u",
D
duke 已提交
3851 3852
        name->as_C_string(),
        major_version,
3853 3854 3855
        minor_version,
        JAVA_MAX_SUPPORTED_VERSION,
        JAVA_MAX_SUPPORTED_MINOR_VERSION);
D
duke 已提交
3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868
    }
    return nullHandle;
  }

  _major_version = major_version;
  _minor_version = minor_version;


  // Check if verification needs to be relaxed for this class file
  // Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)
  _relax_verify = Verifier::relax_verify_for(class_loader());

  // Constant pool
3869
  constantPoolHandle cp = parse_constant_pool(CHECK_(nullHandle));
3870

D
duke 已提交
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893
  int cp_size = cp->length();

  cfs->guarantee_more(8, CHECK_(nullHandle));  // flags, this_class, super_class, infs_len

  // Access flags
  AccessFlags access_flags;
  jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;

  if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {
    // Set abstract bit for old class files for backward compatibility
    flags |= JVM_ACC_ABSTRACT;
  }
  verify_legal_class_modifiers(flags, CHECK_(nullHandle));
  access_flags.set_flags(flags);

  // This class and superclass
  u2 this_class_index = cfs->get_u2_fast();
  check_property(
    valid_cp_range(this_class_index, cp_size) &&
      cp->tag_at(this_class_index).is_unresolved_klass(),
    "Invalid this class index %u in constant pool in class file %s",
    this_class_index, CHECK_(nullHandle));

3894 3895
  Symbol*  class_name  = cp->unresolved_klass_at(this_class_index);
  assert(class_name != NULL, "class_name can't be null");
D
duke 已提交
3896 3897 3898 3899

  // It's important to set parsed_name *before* resolving the super class.
  // (it's used for cleanup by the caller if parsing fails)
  parsed_name = class_name;
3900 3901 3902
  // parsed_name is returned and can be used if there's an error, so add to
  // its reference count.  Caller will decrement the refcount.
  parsed_name->increment_refcount();
D
duke 已提交
3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915

  // Update _class_name which could be null previously to be class_name
  _class_name = class_name;

  // Don't need to check whether this class name is legal or not.
  // It has been checked when constant pool is parsed.
  // However, make sure it is not an array type.
  if (_need_verify) {
    guarantee_property(class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,
                       "Bad class name in class file %s",
                       CHECK_(nullHandle));
  }

3916
  Klass* preserve_this_klass;   // for storing result across HandleMark
D
duke 已提交
3917 3918 3919 3920 3921

  // release all handles when parsing is done
  { HandleMark hm(THREAD);

    // Checks if name in class file matches requested name
3922
    if (name != NULL && class_name != name) {
D
duke 已提交
3923 3924 3925
      ResourceMark rm(THREAD);
      Exceptions::fthrow(
        THREAD_AND_LOCATION,
3926
        vmSymbols::java_lang_NoClassDefFoundError(),
D
duke 已提交
3927 3928 3929 3930 3931 3932 3933 3934
        "%s (wrong name: %s)",
        name->as_C_string(),
        class_name->as_C_string()
      );
      return nullHandle;
    }

    if (TraceClassLoadingPreorder) {
3935
      tty->print("[Loading %s", (name != NULL) ? name->as_klass_external_name() : "NoName");
D
duke 已提交
3936 3937 3938
      if (cfs->source() != NULL) tty->print(" from %s", cfs->source());
      tty->print_cr("]");
    }
3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950
#if INCLUDE_CDS
    if (DumpLoadedClassList != NULL && cfs->source() != NULL && classlist_file->is_open()) {
      // Only dump the classes that can be stored into CDS archive
      if (SystemDictionaryShared::is_sharing_possible(loader_data)) {
        if (name != NULL) {
          ResourceMark rm(THREAD);
          classlist_file->print_cr("%s", name->as_C_string());
          classlist_file->flush();
        }
      }
    }
#endif
D
duke 已提交
3951 3952

    u2 super_class_index = cfs->get_u2_fast();
3953 3954
    instanceKlassHandle super_klass = parse_super_class(super_class_index,
                                                        CHECK_NULL);
D
duke 已提交
3955 3956 3957

    // Interfaces
    u2 itfs_len = cfs->get_u2_fast();
3958 3959 3960
    Array<Klass*>* local_interfaces =
      parse_interfaces(itfs_len, protection_domain, _class_name,
                       &has_default_methods, CHECK_(nullHandle));
D
duke 已提交
3961

3962
    u2 java_fields_count = 0;
D
duke 已提交
3963
    // Fields (offsets are filled in later)
3964
    FieldAllocationCount fac;
3965 3966 3967 3968
    Array<u2>* fields = parse_fields(class_name,
                                     access_flags.is_interface(),
                                     &fac, &java_fields_count,
                                     CHECK_(nullHandle));
D
duke 已提交
3969 3970 3971 3972
    // Methods
    bool has_final_method = false;
    AccessFlags promoted_flags;
    promoted_flags.set_flags(0);
3973
    Array<Method*>* methods = parse_methods(access_flags.is_interface(),
3974 3975
                                            &promoted_flags,
                                            &has_final_method,
3976
                                            &declares_default_methods,
3977
                                            CHECK_(nullHandle));
3978 3979 3980
    if (declares_default_methods) {
      has_default_methods = true;
    }
D
duke 已提交
3981

3982 3983
    // Additional attributes
    ClassAnnotationCollector parsed_annotations;
3984
    parse_classfile_attributes(&parsed_annotations, CHECK_(nullHandle));
3985

3986 3987 3988 3989
    // Finalize the Annotations metadata object,
    // now that all annotation arrays have been created.
    create_combined_annotations(CHECK_(nullHandle));

3990 3991 3992
    // Make sure this is the end of class file stream
    guarantee_property(cfs->at_eos(), "Extra bytes at the end of class file %s", CHECK_(nullHandle));

P
poonam 已提交
3993 3994 3995 3996 3997
    if (_class_name == vmSymbols::java_lang_Object()) {
      check_property(_local_interfaces == Universe::the_empty_klass_array(),
                     "java.lang.Object cannot implement an interface in class file %s",
                     CHECK_(nullHandle));
    }
D
duke 已提交
3998
    // We check super class after class file is parsed and format is checked
3999
    if (super_class_index > 0 && super_klass.is_null()) {
4000
      Symbol*  sk  = cp->klass_name_at(super_class_index);
D
duke 已提交
4001 4002 4003
      if (access_flags.is_interface()) {
        // Before attempting to resolve the superclass, check for class format
        // errors not checked yet.
4004
        guarantee_property(sk == vmSymbols::java_lang_Object(),
D
duke 已提交
4005 4006 4007
                           "Interfaces must have java.lang.Object as superclass in class file %s",
                           CHECK_(nullHandle));
      }
4008 4009 4010 4011 4012
      Klass* k = SystemDictionary::resolve_super_or_fail(class_name, sk,
                                                         class_loader,
                                                         protection_domain,
                                                         true,
                                                         CHECK_(nullHandle));
4013

D
duke 已提交
4014 4015
      KlassHandle kh (THREAD, k);
      super_klass = instanceKlassHandle(THREAD, kh());
4016 4017
    }
    if (super_klass.not_null()) {
4018 4019 4020 4021 4022

      if (super_klass->has_default_methods()) {
        has_default_methods = true;
      }

D
duke 已提交
4023 4024 4025 4026
      if (super_klass->is_interface()) {
        ResourceMark rm(THREAD);
        Exceptions::fthrow(
          THREAD_AND_LOCATION,
4027
          vmSymbols::java_lang_IncompatibleClassChangeError(),
D
duke 已提交
4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039
          "class %s has interface %s as super class",
          class_name->as_klass_external_name(),
          super_klass->external_name()
        );
        return nullHandle;
      }
      // Make sure super class is not final
      if (super_klass->is_final()) {
        THROW_MSG_(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class", nullHandle);
      }
    }

4040 4041 4042
    // save super klass for error handling.
    _super_klass = super_klass;

D
duke 已提交
4043
    // Compute the transitive list of all unique interfaces implemented by this class
4044 4045
    _transitive_interfaces =
          compute_transitive_interfaces(super_klass, local_interfaces, CHECK_(nullHandle));
D
duke 已提交
4046 4047

    // sort methods
4048
    intArray* method_ordering = sort_methods(methods);
D
duke 已提交
4049 4050 4051 4052 4053 4054 4055 4056 4057

    // promote flags from parse_methods() to the klass' flags
    access_flags.add_promoted_flags(promoted_flags.as_int());

    // Size of Java vtable (in words)
    int vtable_size = 0;
    int itable_size = 0;
    int num_miranda_methods = 0;

4058 4059 4060 4061 4062
    GrowableArray<Method*> all_mirandas(20);

    klassVtable::compute_vtable_size_and_num_mirandas(
        &vtable_size, &num_miranda_methods, &all_mirandas, super_klass(), methods,
        access_flags, class_loader, class_name, local_interfaces,
4063
                                                      CHECK_(nullHandle));
D
duke 已提交
4064 4065

    // Size of Java itable (in words)
4066
    itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(_transitive_interfaces);
D
duke 已提交
4067

4068 4069
    FieldLayoutInfo info;
    layout_fields(class_loader, &fac, &parsed_annotations, &info, CHECK_NULL);
D
duke 已提交
4070

4071 4072
    int total_oop_map_size2 =
          InstanceKlass::nonstatic_oop_map_size(info.total_oop_map_count);
D
duke 已提交
4073 4074 4075 4076 4077 4078 4079 4080 4081

    // Compute reference type
    ReferenceType rt;
    if (super_klass() == NULL) {
      rt = REF_NONE;
    } else {
      rt = super_klass->reference_type();
    }

4082
    // We can now create the basic Klass* for this klass
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
    _klass = InstanceKlass::allocate_instance_klass(loader_data,
                                                    vtable_size,
                                                    itable_size,
                                                    info.static_field_size,
                                                    total_oop_map_size2,
                                                    rt,
                                                    access_flags,
                                                    name,
                                                    super_klass(),
                                                    !host_klass.is_null(),
                                                    CHECK_(nullHandle));
    instanceKlassHandle this_klass (THREAD, _klass);

    assert(this_klass->static_field_size() == info.static_field_size, "sanity");
    assert(this_klass->nonstatic_oop_map_count() == info.total_oop_map_count,
4098
           "sanity");
D
duke 已提交
4099 4100

    // Fill in information already parsed
4101
    this_klass->set_should_verify_class(verify);
4102
    jint lh = Klass::instance_layout_helper(info.instance_size, false);
D
duke 已提交
4103 4104
    this_klass->set_layout_helper(lh);
    assert(this_klass->oop_is_instance(), "layout is correct");
4105
    assert(this_klass->size_helper() == info.instance_size, "correct size_helper");
D
duke 已提交
4106 4107
    // Not yet: supers are done below to support the new subtype-checking fields
    //this_klass->set_super(super_klass());
4108
    this_klass->set_class_loader_data(loader_data);
4109 4110
    this_klass->set_nonstatic_field_size(info.nonstatic_field_size);
    this_klass->set_has_nonstatic_fields(info.has_nonstatic_fields);
4111
    this_klass->set_static_oop_field_count(fac.count[STATIC_OOP]);
4112 4113 4114

    apply_parsed_class_metadata(this_klass, java_fields_count, CHECK_NULL);

D
duke 已提交
4115 4116 4117
    if (has_final_method) {
      this_klass->set_has_final_method();
    }
4118
    this_klass->copy_method_ordering(method_ordering, CHECK_NULL);
4119 4120
    // The InstanceKlass::_methods_jmethod_ids cache
    // is managed on the assumption that the initial cache
4121
    // size is equal to the number of methods in the class. If
4122
    // that changes, then InstanceKlass::idnum_can_increment()
4123
    // has to be changed accordingly.
D
duke 已提交
4124 4125
    this_klass->set_initial_method_idnum(methods->length());
    this_klass->set_name(cp->klass_name_at(this_class_index));
T
twisti 已提交
4126
    if (is_anonymous())  // I am well known to myself
4127
      cp->klass_at_put(this_class_index, this_klass()); // eagerly resolve
4128

D
duke 已提交
4129 4130
    this_klass->set_minor_version(minor_version);
    this_klass->set_major_version(major_version);
4131
    this_klass->set_has_default_methods(has_default_methods);
4132
    this_klass->set_declares_default_methods(declares_default_methods);
D
duke 已提交
4133

4134 4135 4136 4137 4138
    if (!host_klass.is_null()) {
      assert (this_klass->is_anonymous(), "should be the same");
      this_klass->set_host_klass(host_klass());
    }

4139
    // Set up Method*::intrinsic_id as soon as we know the names of methods.
4140 4141 4142
    // (We used to do this lazily, but now we query it in Rewriter,
    // which is eagerly done for every method, so we might as well do it now,
    // when everything is fresh in memory.)
4143
    if (Method::klass_id_for_intrinsics(this_klass()) != vmSymbols::NO_SID) {
4144
      for (int j = 0; j < methods->length(); j++) {
4145
        methods->at(j)->init_intrinsic_id();
4146 4147 4148
      }
    }

4149
    if (cached_class_file != NULL) {
4150
      // JVMTI: we have an InstanceKlass now, tell it about the cached bytes
4151
      this_klass->set_cached_class_file(cached_class_file);
D
duke 已提交
4152 4153
    }

4154
    // Fill in field values obtained by parse_classfile_attributes
4155
    if (parsed_annotations.has_any_annotations())
4156 4157
      parsed_annotations.apply_to(this_klass);
    apply_parsed_class_attributes(this_klass);
D
duke 已提交
4158

4159 4160 4161 4162 4163 4164 4165 4166 4167
    // Miranda methods
    if ((num_miranda_methods > 0) ||
        // if this class introduced new miranda methods or
        (super_klass.not_null() && (super_klass->has_miranda_methods()))
        // super class exists and this class inherited miranda methods
        ) {
      this_klass->set_has_miranda_methods(); // then set a flag
    }

D
duke 已提交
4168 4169 4170 4171 4172 4173
    // Fill in information needed to compute superclasses.
    this_klass->initialize_supers(super_klass(), CHECK_(nullHandle));

    // Initialize itable offset tables
    klassItable::setup_itable_offset_table(this_klass);

4174
    // Compute transitive closure of interfaces this class implements
D
duke 已提交
4175
    // Do final class setup
4176
    fill_oop_maps(this_klass, info.nonstatic_oop_map_count, info.nonstatic_oop_offsets, info.nonstatic_oop_counts);
D
duke 已提交
4177

4178
    // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
D
duke 已提交
4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
    set_precomputed_flags(this_klass);

    // reinitialize modifiers, using the InnerClasses attribute
    int computed_modifiers = this_klass->compute_modifier_flags(CHECK_(nullHandle));
    this_klass->set_modifier_flags(computed_modifiers);

    // check if this class can access its super class
    check_super_class_access(this_klass, CHECK_(nullHandle));

    // check if this class can access its superinterfaces
    check_super_interface_access(this_klass, CHECK_(nullHandle));

    // check if this class overrides any final method
    check_final_method_override(this_klass, CHECK_(nullHandle));

    // check that if this class is an interface then it doesn't have static methods
    if (this_klass->is_interface()) {
4196 4197 4198 4199
      /* An interface in a JAVA 8 classfile can be static */
      if (_major_version < JAVA_8_VERSION) {
        check_illegal_static_method(this_klass, CHECK_(nullHandle));
      }
D
duke 已提交
4200 4201
    }

4202
    // Allocate mirror and initialize static fields
4203 4204
    java_lang_Class::create_mirror(this_klass, class_loader, protection_domain,
                                   CHECK_(nullHandle));
4205 4206 4207

    // Generate any default methods - default methods are interface methods
    // that have a default implementation.  This is new with Lambda project.
4208
    if (has_default_methods ) {
4209 4210 4211 4212
      DefaultMethods::generate_default_methods(
          this_klass(), &all_mirandas, CHECK_(nullHandle));
    }

4213 4214 4215 4216
    // Update the loader_data graph.
    record_defined_class_dependencies(this_klass, CHECK_NULL);

    ClassLoadingService::notify_class_loaded(InstanceKlass::cast(this_klass()),
D
duke 已提交
4217 4218 4219
                                             false /* not shared class */);

    if (TraceClassLoading) {
4220
      ResourceMark rm;
D
duke 已提交
4221 4222 4223 4224 4225
      // print in a single call to reduce interleaving of output
      if (cfs->source() != NULL) {
        tty->print("[Loaded %s from %s]\n", this_klass->external_name(),
                   cfs->source());
      } else if (class_loader.is_null()) {
4226 4227 4228 4229 4230 4231
        Klass* caller =
            THREAD->is_Java_thread()
                ? ((JavaThread*)THREAD)->security_get_caller_class(1)
                : NULL;
        // caller can be NULL, for example, during a JVMTI VM_Init hook
        if (caller != NULL) {
D
duke 已提交
4232 4233
          tty->print("[Loaded %s by instance of %s]\n",
                     this_klass->external_name(),
4234
                     InstanceKlass::cast(caller)->external_name());
D
duke 已提交
4235 4236 4237 4238 4239
        } else {
          tty->print("[Loaded %s]\n", this_klass->external_name());
        }
      } else {
        tty->print("[Loaded %s from %s]\n", this_klass->external_name(),
4240
                   InstanceKlass::cast(class_loader->klass())->external_name());
D
duke 已提交
4241 4242 4243 4244
      }
    }

    if (TraceClassResolution) {
4245
      ResourceMark rm;
D
duke 已提交
4246
      // print out the superclass.
H
hseigel 已提交
4247
      const char * from = this_klass()->external_name();
D
duke 已提交
4248
      if (this_klass->java_super() != NULL) {
4249
        tty->print("RESOLVE %s %s (super)\n", from, InstanceKlass::cast(this_klass->java_super())->external_name());
D
duke 已提交
4250 4251
      }
      // print out each of the interface classes referred to by this class.
4252 4253
      Array<Klass*>* local_interfaces = this_klass->local_interfaces();
      if (local_interfaces != NULL) {
D
duke 已提交
4254 4255
        int length = local_interfaces->length();
        for (int i = 0; i < length; i++) {
4256 4257
          Klass* k = local_interfaces->at(i);
          InstanceKlass* to_class = InstanceKlass::cast(k);
D
duke 已提交
4258
          const char * to = to_class->external_name();
4259
          tty->print("RESOLVE %s %s (interface)\n", from, to);
D
duke 已提交
4260 4261 4262 4263 4264 4265 4266 4267
        }
      }
    }

    // preserve result across HandleMark
    preserve_this_klass = this_klass();
  }

4268 4269
  // Create new handle outside HandleMark (might be needed for
  // Extended Class Redefinition)
D
duke 已提交
4270
  instanceKlassHandle this_klass (THREAD, preserve_this_klass);
4271
  debug_only(this_klass->verify();)
D
duke 已提交
4272

4273 4274
  // Clear class if no error has occurred so destructor doesn't deallocate it
  _klass = NULL;
D
duke 已提交
4275 4276 4277
  return this_klass;
}

4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294
// Destructor to clean up if there's an error
ClassFileParser::~ClassFileParser() {
  MetadataFactory::free_metadata(_loader_data, _cp);
  MetadataFactory::free_array<u2>(_loader_data, _fields);

  // Free methods
  InstanceKlass::deallocate_methods(_loader_data, _methods);

  // beware of the Universe::empty_blah_array!!
  if (_inner_classes != Universe::the_empty_short_array()) {
    MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
  }

  // Free interfaces
  InstanceKlass::deallocate_interfaces(_loader_data, _super_klass(),
                                       _local_interfaces, _transitive_interfaces);

4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315
  if (_combined_annotations != NULL) {
    // After all annotations arrays have been created, they are installed into the
    // Annotations object that will be assigned to the InstanceKlass being created.

    // Deallocate the Annotations object and the installed annotations arrays.
    _combined_annotations->deallocate_contents(_loader_data);

    // If the _combined_annotations pointer is non-NULL,
    // then the other annotations fields should have been cleared.
    assert(_annotations             == NULL, "Should have been cleared");
    assert(_type_annotations        == NULL, "Should have been cleared");
    assert(_fields_annotations      == NULL, "Should have been cleared");
    assert(_fields_type_annotations == NULL, "Should have been cleared");
  } else {
    // If the annotations arrays were not installed into the Annotations object,
    // then they have to be deallocated explicitly.
    MetadataFactory::free_array<u1>(_loader_data, _annotations);
    MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
    Annotations::free_contents(_loader_data, _fields_annotations);
    Annotations::free_contents(_loader_data, _fields_type_annotations);
  }
4316 4317 4318

  clear_class_metadata();

4319 4320 4321 4322 4323 4324
  // deallocate the klass if already created.  Don't directly deallocate, but add
  // to the deallocate list so that the klass is removed from the CLD::_klasses list
  // at a safepoint.
  if (_klass != NULL) {
    _loader_data->add_to_deallocate_list(_klass);
  }
4325 4326 4327
  _klass = NULL;
}

4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359
void ClassFileParser::print_field_layout(Symbol* name,
                                         Array<u2>* fields,
                                         constantPoolHandle cp,
                                         int instance_size,
                                         int instance_fields_start,
                                         int instance_fields_end,
                                         int static_fields_end) {
  tty->print("%s: field layout\n", name->as_klass_external_name());
  tty->print("  @%3d %s\n", instance_fields_start, "--- instance fields start ---");
  for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
    if (!fs.access_flags().is_static()) {
      tty->print("  @%3d \"%s\" %s\n",
          fs.offset(),
          fs.name()->as_klass_external_name(),
          fs.signature()->as_klass_external_name());
    }
  }
  tty->print("  @%3d %s\n", instance_fields_end, "--- instance fields end ---");
  tty->print("  @%3d %s\n", instance_size * wordSize, "--- instance ends ---");
  tty->print("  @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");
  for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
    if (fs.access_flags().is_static()) {
      tty->print("  @%3d \"%s\" %s\n",
          fs.offset(),
          fs.name()->as_klass_external_name(),
          fs.signature()->as_klass_external_name());
    }
  }
  tty->print("  @%3d %s\n", static_fields_end, "--- static fields end ---");
  tty->print("\n");
}

4360 4361 4362 4363 4364 4365
unsigned int
ClassFileParser::compute_oop_map_count(instanceKlassHandle super,
                                       unsigned int nonstatic_oop_map_count,
                                       int first_nonstatic_oop_offset) {
  unsigned int map_count =
    super.is_null() ? 0 : super->nonstatic_oop_map_count();
D
duke 已提交
4366 4367
  if (nonstatic_oop_map_count > 0) {
    // We have oops to add to map
4368 4369
    if (map_count == 0) {
      map_count = nonstatic_oop_map_count;
D
duke 已提交
4370
    } else {
4371 4372 4373 4374
      // Check whether we should add a new map block or whether the last one can
      // be extended
      OopMapBlock* const first_map = super->start_of_nonstatic_oop_maps();
      OopMapBlock* const last_map = first_map + map_count - 1;
D
duke 已提交
4375

4376
      int next_offset = last_map->offset() + last_map->count() * heapOopSize;
D
duke 已提交
4377 4378 4379 4380 4381 4382
      if (next_offset == first_nonstatic_oop_offset) {
        // There is no gap bettwen superklass's last oop field and first
        // local oop field, merge maps.
        nonstatic_oop_map_count -= 1;
      } else {
        // Superklass didn't end with a oop field, add extra maps
4383
        assert(next_offset < first_nonstatic_oop_offset, "just checking");
D
duke 已提交
4384
      }
4385
      map_count += nonstatic_oop_map_count;
D
duke 已提交
4386 4387
    }
  }
4388
  return map_count;
D
duke 已提交
4389 4390 4391 4392
}


void ClassFileParser::fill_oop_maps(instanceKlassHandle k,
4393 4394 4395
                                    unsigned int nonstatic_oop_map_count,
                                    int* nonstatic_oop_offsets,
                                    unsigned int* nonstatic_oop_counts) {
D
duke 已提交
4396
  OopMapBlock* this_oop_map = k->start_of_nonstatic_oop_maps();
4397
  const InstanceKlass* const super = k->superklass();
4398
  const unsigned int super_count = super ? super->nonstatic_oop_map_count() : 0;
4399
  if (super_count > 0) {
D
duke 已提交
4400
    // Copy maps from superklass
4401
    OopMapBlock* super_oop_map = super->start_of_nonstatic_oop_maps();
4402
    for (unsigned int i = 0; i < super_count; ++i) {
D
duke 已提交
4403 4404 4405
      *this_oop_map++ = *super_oop_map++;
    }
  }
4406

D
duke 已提交
4407
  if (nonstatic_oop_map_count > 0) {
4408 4409 4410
    if (super_count + nonstatic_oop_map_count > k->nonstatic_oop_map_count()) {
      // The counts differ because there is no gap between superklass's last oop
      // field and the first local oop field.  Extend the last oop map copied
D
duke 已提交
4411 4412 4413 4414
      // from the superklass instead of creating new one.
      nonstatic_oop_map_count--;
      nonstatic_oop_offsets++;
      this_oop_map--;
4415
      this_oop_map->set_count(this_oop_map->count() + *nonstatic_oop_counts++);
D
duke 已提交
4416 4417
      this_oop_map++;
    }
4418

D
duke 已提交
4419 4420 4421
    // Add new map blocks, fill them
    while (nonstatic_oop_map_count-- > 0) {
      this_oop_map->set_offset(*nonstatic_oop_offsets++);
4422
      this_oop_map->set_count(*nonstatic_oop_counts++);
D
duke 已提交
4423 4424
      this_oop_map++;
    }
4425 4426
    assert(k->start_of_nonstatic_oop_maps() + k->nonstatic_oop_map_count() ==
           this_oop_map, "sanity");
D
duke 已提交
4427 4428 4429 4430 4431
  }
}


void ClassFileParser::set_precomputed_flags(instanceKlassHandle k) {
4432
  Klass* super = k->super();
D
duke 已提交
4433 4434 4435 4436 4437

  // Check if this klass has an empty finalize method (i.e. one with return bytecode only),
  // in which case we don't have to register objects as finalizable
  if (!_has_empty_finalizer) {
    if (_has_finalizer ||
4438
        (super != NULL && super->has_finalizer())) {
D
duke 已提交
4439 4440 4441 4442 4443 4444
      k->set_has_finalizer();
    }
  }

#ifdef ASSERT
  bool f = false;
4445
  Method* m = k->lookup_method(vmSymbols::finalize_method_name(),
D
duke 已提交
4446 4447
                                 vmSymbols::void_method_signature());
  if (m != NULL && !m->is_empty_method()) {
4448 4449 4450 4451 4452 4453 4454 4455
      f = true;
  }

  // Spec doesn't prevent agent from redefinition of empty finalizer.
  // Despite the fact that it's generally bad idea and redefined finalizer
  // will not work as expected we shouldn't abort vm in this case
  if (!k->has_redefined_this_or_super()) {
    assert(f == k->has_finalizer(), "inconsistent has_finalizer");
D
duke 已提交
4456 4457 4458 4459
  }
#endif

  // Check if this klass supports the java.lang.Cloneable interface
4460 4461
  if (SystemDictionary::Cloneable_klass_loaded()) {
    if (k->is_subtype_of(SystemDictionary::Cloneable_klass())) {
D
duke 已提交
4462 4463 4464 4465 4466 4467 4468 4469 4470
      k->set_is_cloneable();
    }
  }

  // Check if this klass has a vanilla default constructor
  if (super == NULL) {
    // java.lang.Object has empty default constructor
    k->set_has_vanilla_constructor();
  } else {
H
hseigel 已提交
4471
    if (super->has_vanilla_constructor() &&
D
duke 已提交
4472 4473 4474 4475 4476
        _has_vanilla_constructor) {
      k->set_has_vanilla_constructor();
    }
#ifdef ASSERT
    bool v = false;
H
hseigel 已提交
4477
    if (super->has_vanilla_constructor()) {
4478
      Method* constructor = k->find_method(vmSymbols::object_initializer_name(
D
duke 已提交
4479 4480 4481 4482 4483 4484 4485 4486 4487 4488
), vmSymbols::void_method_signature());
      if (constructor != NULL && constructor->is_vanilla_constructor()) {
        v = true;
      }
    }
    assert(v == k->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");
#endif
  }

  // If it cannot be fast-path allocated, set a bit in the layout helper.
4489
  // See documentation of InstanceKlass::can_be_fastpath_allocated().
D
duke 已提交
4490 4491 4492
  assert(k->size_helper() > 0, "layout_helper is initialized");
  if ((!RegisterFinalizersAtInit && k->has_finalizer())
      || k->is_abstract() || k->is_interface()
4493
      || (k->name() == vmSymbols::java_lang_Class() && k->class_loader() == NULL)
D
duke 已提交
4494 4495 4496 4497 4498 4499 4500
      || k->size_helper() >= FastAllocateSizeLimit) {
    // Forbid fast-path allocation.
    jint lh = Klass::instance_layout_helper(k->size_helper(), true);
    k->set_layout_helper(lh);
  }
}

4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523
// Attach super classes and interface classes to class loader data
void ClassFileParser::record_defined_class_dependencies(instanceKlassHandle defined_klass, TRAPS) {
  ClassLoaderData * defining_loader_data = defined_klass->class_loader_data();
  if (defining_loader_data->is_the_null_class_loader_data()) {
      // Dependencies to null class loader data are implicit.
      return;
  } else {
    // add super class dependency
    Klass* super = defined_klass->super();
    if (super != NULL) {
      defining_loader_data->record_dependency(super, CHECK);
    }

    // add super interface dependencies
    Array<Klass*>* local_interfaces = defined_klass->local_interfaces();
    if (local_interfaces != NULL) {
      int length = local_interfaces->length();
      for (int i = 0; i < length; i++) {
        defining_loader_data->record_dependency(local_interfaces->at(i), CHECK);
      }
    }
  }
}
D
duke 已提交
4524

4525
// utility methods for appending an array with check for duplicates
D
duke 已提交
4526

4527
void append_interfaces(GrowableArray<Klass*>* result, Array<Klass*>* ifs) {
D
duke 已提交
4528 4529
  // iterate over new interfaces
  for (int i = 0; i < ifs->length(); i++) {
4530 4531
    Klass* e = ifs->at(i);
    assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");
D
duke 已提交
4532
    // add new interface
4533
    result->append_if_missing(e);
D
duke 已提交
4534 4535 4536
  }
}

4537 4538 4539
Array<Klass*>* ClassFileParser::compute_transitive_interfaces(
                                        instanceKlassHandle super,
                                        Array<Klass*>* local_ifs, TRAPS) {
D
duke 已提交
4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550
  // Compute maximum size for transitive interfaces
  int max_transitive_size = 0;
  int super_size = 0;
  // Add superclass transitive interfaces size
  if (super.not_null()) {
    super_size = super->transitive_interfaces()->length();
    max_transitive_size += super_size;
  }
  // Add local interfaces' super interfaces
  int local_size = local_ifs->length();
  for (int i = 0; i < local_size; i++) {
4551 4552
    Klass* l = local_ifs->at(i);
    max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();
D
duke 已提交
4553 4554 4555 4556 4557 4558
  }
  // Finally add local interfaces
  max_transitive_size += local_size;
  // Construct array
  if (max_transitive_size == 0) {
    // no interfaces, use canonicalized array
4559
    return Universe::the_empty_klass_array();
D
duke 已提交
4560 4561
  } else if (max_transitive_size == super_size) {
    // no new local interfaces added, share superklass' transitive interface array
4562
    return super->transitive_interfaces();
D
duke 已提交
4563 4564
  } else if (max_transitive_size == local_size) {
    // only local interfaces added, share local interface array
4565
    return local_ifs;
D
duke 已提交
4566
  } else {
4567 4568 4569
    ResourceMark rm;
    GrowableArray<Klass*>* result = new GrowableArray<Klass*>(max_transitive_size);

D
duke 已提交
4570 4571
    // Copy down from superclass
    if (super.not_null()) {
4572
      append_interfaces(result, super->transitive_interfaces());
D
duke 已提交
4573
    }
4574

D
duke 已提交
4575 4576
    // Copy down from local interfaces' superinterfaces
    for (int i = 0; i < local_ifs->length(); i++) {
4577 4578
      Klass* l = local_ifs->at(i);
      append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());
D
duke 已提交
4579 4580
    }
    // Finally add local interfaces
4581 4582 4583 4584 4585
    append_interfaces(result, local_ifs);

    // length will be less than the max_transitive_size if duplicates were removed
    int length = result->length();
    assert(length <= max_transitive_size, "just checking");
4586
    Array<Klass*>* new_result = MetadataFactory::new_array<Klass*>(_loader_data, length, CHECK_NULL);
4587 4588
    for (int i = 0; i < length; i++) {
      Klass* e = result->at(i);
D
duke 已提交
4589
        assert(e != NULL, "just checking");
4590
      new_result->at_put(i, e);
D
duke 已提交
4591
    }
4592
    return new_result;
D
duke 已提交
4593 4594 4595 4596
  }
}

void ClassFileParser::check_super_class_access(instanceKlassHandle this_klass, TRAPS) {
4597
  Klass* super = this_klass->super();
D
duke 已提交
4598
  if ((super != NULL) &&
4599
      (!Reflection::verify_class_access(this_klass(), super, false))) {
D
duke 已提交
4600 4601 4602
    ResourceMark rm(THREAD);
    Exceptions::fthrow(
      THREAD_AND_LOCATION,
4603
      vmSymbols::java_lang_IllegalAccessError(),
D
duke 已提交
4604 4605
      "class %s cannot access its superclass %s",
      this_klass->external_name(),
4606
      InstanceKlass::cast(super)->external_name()
D
duke 已提交
4607 4608 4609 4610 4611 4612 4613
    );
    return;
  }
}


void ClassFileParser::check_super_interface_access(instanceKlassHandle this_klass, TRAPS) {
4614
  Array<Klass*>* local_interfaces = this_klass->local_interfaces();
D
duke 已提交
4615 4616
  int lng = local_interfaces->length();
  for (int i = lng - 1; i >= 0; i--) {
4617
    Klass* k = local_interfaces->at(i);
H
hseigel 已提交
4618
    assert (k != NULL && k->is_interface(), "invalid interface");
4619
    if (!Reflection::verify_class_access(this_klass(), k, false)) {
D
duke 已提交
4620 4621 4622
      ResourceMark rm(THREAD);
      Exceptions::fthrow(
        THREAD_AND_LOCATION,
4623
        vmSymbols::java_lang_IllegalAccessError(),
D
duke 已提交
4624 4625
        "class %s cannot access its superinterface %s",
        this_klass->external_name(),
4626
        InstanceKlass::cast(k)->external_name()
D
duke 已提交
4627 4628 4629 4630 4631 4632 4633 4634
      );
      return;
    }
  }
}


void ClassFileParser::check_final_method_override(instanceKlassHandle this_klass, TRAPS) {
4635
  Array<Method*>* methods = this_klass->methods();
D
duke 已提交
4636 4637 4638 4639
  int num_methods = methods->length();

  // go thru each method and check if it overrides a final method
  for (int index = 0; index < num_methods; index++) {
4640
    Method* m = methods->at(index);
D
duke 已提交
4641

4642 4643
    // skip private, static, and <init> methods
    if ((!m->is_private() && !m->is_static()) &&
D
duke 已提交
4644 4645
        (m->name() != vmSymbols::object_initializer_name())) {

4646 4647
      Symbol* name = m->name();
      Symbol* signature = m->signature();
4648 4649
      Klass* k = this_klass->super();
      Method* super_m = NULL;
D
duke 已提交
4650 4651
      while (k != NULL) {
        // skip supers that don't have final methods.
4652
        if (k->has_final_method()) {
D
duke 已提交
4653
          // lookup a matching method in the super class hierarchy
4654
          super_m = InstanceKlass::cast(k)->lookup_method(name, signature);
D
duke 已提交
4655 4656 4657 4658
          if (super_m == NULL) {
            break; // didn't find any match; get out
          }

4659 4660
          if (super_m->is_final() && !super_m->is_static() &&
              // matching method in super is final, and not static
4661
              (Reflection::verify_field_access(this_klass(),
D
duke 已提交
4662 4663 4664 4665 4666 4667 4668 4669
                                               super_m->method_holder(),
                                               super_m->method_holder(),
                                               super_m->access_flags(), false))
            // this class can access super final method and therefore override
            ) {
            ResourceMark rm(THREAD);
            Exceptions::fthrow(
              THREAD_AND_LOCATION,
4670
              vmSymbols::java_lang_VerifyError(),
D
duke 已提交
4671 4672 4673 4674 4675 4676 4677 4678 4679
              "class %s overrides final method %s.%s",
              this_klass->external_name(),
              name->as_C_string(),
              signature->as_C_string()
            );
            return;
          }

          // continue to look from super_m's holder's super.
4680
          k = super_m->method_holder()->super();
D
duke 已提交
4681 4682 4683
          continue;
        }

4684
        k = k->super();
D
duke 已提交
4685 4686 4687 4688 4689 4690 4691 4692 4693
      }
    }
  }
}


// assumes that this_klass is an interface
void ClassFileParser::check_illegal_static_method(instanceKlassHandle this_klass, TRAPS) {
  assert(this_klass->is_interface(), "not an interface");
4694
  Array<Method*>* methods = this_klass->methods();
D
duke 已提交
4695 4696 4697
  int num_methods = methods->length();

  for (int index = 0; index < num_methods; index++) {
4698
    Method* m = methods->at(index);
D
duke 已提交
4699 4700 4701 4702 4703
    // if m is static and not the init method, throw a verify error
    if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {
      ResourceMark rm(THREAD);
      Exceptions::fthrow(
        THREAD_AND_LOCATION,
4704
        vmSymbols::java_lang_VerifyError(),
D
duke 已提交
4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733
        "Illegal static method %s in interface %s",
        m->name()->as_C_string(),
        this_klass->external_name()
      );
      return;
    }
  }
}

// utility methods for format checking

void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) {
  if (!_need_verify) { return; }

  const bool is_interface  = (flags & JVM_ACC_INTERFACE)  != 0;
  const bool is_abstract   = (flags & JVM_ACC_ABSTRACT)   != 0;
  const bool is_final      = (flags & JVM_ACC_FINAL)      != 0;
  const bool is_super      = (flags & JVM_ACC_SUPER)      != 0;
  const bool is_enum       = (flags & JVM_ACC_ENUM)       != 0;
  const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;
  const bool major_gte_15  = _major_version >= JAVA_1_5_VERSION;

  if ((is_abstract && is_final) ||
      (is_interface && !is_abstract) ||
      (is_interface && major_gte_15 && (is_super || is_enum)) ||
      (!is_interface && major_gte_15 && is_annotation)) {
    ResourceMark rm(THREAD);
    Exceptions::fthrow(
      THREAD_AND_LOCATION,
4734
      vmSymbols::java_lang_ClassFormatError(),
D
duke 已提交
4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752
      "Illegal class modifiers in class %s: 0x%X",
      _class_name->as_C_string(), flags
    );
    return;
  }
}

bool ClassFileParser::has_illegal_visibility(jint flags) {
  const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
  const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
  const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;

  return ((is_public && is_protected) ||
          (is_public && is_private) ||
          (is_protected && is_private));
}

bool ClassFileParser::is_supported_version(u2 major, u2 minor) {
4753 4754 4755
  u2 max_version =
    JDK_Version::is_gte_jdk17x_version() ? JAVA_MAX_SUPPORTED_VERSION :
    (JDK_Version::is_gte_jdk16x_version() ? JAVA_6_VERSION : JAVA_1_5_VERSION);
D
duke 已提交
4756
  return (major >= JAVA_MIN_SUPPORTED_VERSION) &&
4757 4758
         (major <= max_version) &&
         ((major != max_version) ||
D
duke 已提交
4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793
          (minor <= JAVA_MAX_SUPPORTED_MINOR_VERSION));
}

void ClassFileParser::verify_legal_field_modifiers(
    jint flags, bool is_interface, TRAPS) {
  if (!_need_verify) { return; }

  const bool is_public    = (flags & JVM_ACC_PUBLIC)    != 0;
  const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;
  const bool is_private   = (flags & JVM_ACC_PRIVATE)   != 0;
  const bool is_static    = (flags & JVM_ACC_STATIC)    != 0;
  const bool is_final     = (flags & JVM_ACC_FINAL)     != 0;
  const bool is_volatile  = (flags & JVM_ACC_VOLATILE)  != 0;
  const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;
  const bool is_enum      = (flags & JVM_ACC_ENUM)      != 0;
  const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;

  bool is_illegal = false;

  if (is_interface) {
    if (!is_public || !is_static || !is_final || is_private ||
        is_protected || is_volatile || is_transient ||
        (major_gte_15 && is_enum)) {
      is_illegal = true;
    }
  } else { // not interface
    if (has_illegal_visibility(flags) || (is_final && is_volatile)) {
      is_illegal = true;
    }
  }

  if (is_illegal) {
    ResourceMark rm(THREAD);
    Exceptions::fthrow(
      THREAD_AND_LOCATION,
4794
      vmSymbols::java_lang_ClassFormatError(),
D
duke 已提交
4795 4796 4797 4798 4799 4800 4801
      "Illegal field modifiers in class %s: 0x%X",
      _class_name->as_C_string(), flags);
    return;
  }
}

void ClassFileParser::verify_legal_method_modifiers(
4802
    jint flags, bool is_interface, Symbol* name, TRAPS) {
D
duke 已提交
4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813
  if (!_need_verify) { return; }

  const bool is_public       = (flags & JVM_ACC_PUBLIC)       != 0;
  const bool is_private      = (flags & JVM_ACC_PRIVATE)      != 0;
  const bool is_static       = (flags & JVM_ACC_STATIC)       != 0;
  const bool is_final        = (flags & JVM_ACC_FINAL)        != 0;
  const bool is_native       = (flags & JVM_ACC_NATIVE)       != 0;
  const bool is_abstract     = (flags & JVM_ACC_ABSTRACT)     != 0;
  const bool is_bridge       = (flags & JVM_ACC_BRIDGE)       != 0;
  const bool is_strict       = (flags & JVM_ACC_STRICT)       != 0;
  const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;
4814
  const bool is_protected    = (flags & JVM_ACC_PROTECTED)    != 0;
D
duke 已提交
4815
  const bool major_gte_15    = _major_version >= JAVA_1_5_VERSION;
4816
  const bool major_gte_8     = _major_version >= JAVA_8_VERSION;
D
duke 已提交
4817 4818 4819 4820 4821
  const bool is_initializer  = (name == vmSymbols::object_initializer_name());

  bool is_illegal = false;

  if (is_interface) {
4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848
    if (major_gte_8) {
      // Class file version is JAVA_8_VERSION or later Methods of
      // interfaces may set any of the flags except ACC_PROTECTED,
      // ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must
      // have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.
      if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */
          (is_native || is_protected || is_final || is_synchronized) ||
          // If a specific method of a class or interface has its
          // ACC_ABSTRACT flag set, it must not have any of its
          // ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,
          // ACC_STRICT, or ACC_SYNCHRONIZED flags set.  No need to
          // check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as
          // those flags are illegal irrespective of ACC_ABSTRACT being set or not.
          (is_abstract && (is_private || is_static || is_strict))) {
        is_illegal = true;
      }
    } else if (major_gte_15) {
      // Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)
      if (!is_public || is_static || is_final || is_synchronized ||
          is_native || !is_abstract || is_strict) {
        is_illegal = true;
      }
    } else {
      // Class file version is pre-JAVA_1_5_VERSION
      if (!is_public || is_static || is_final || is_native || !is_abstract) {
        is_illegal = true;
      }
D
duke 已提交
4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872
    }
  } else { // not interface
    if (is_initializer) {
      if (is_static || is_final || is_synchronized || is_native ||
          is_abstract || (major_gte_15 && is_bridge)) {
        is_illegal = true;
      }
    } else { // not initializer
      if (is_abstract) {
        if ((is_final || is_native || is_private || is_static ||
            (major_gte_15 && (is_synchronized || is_strict)))) {
          is_illegal = true;
        }
      }
      if (has_illegal_visibility(flags)) {
        is_illegal = true;
      }
    }
  }

  if (is_illegal) {
    ResourceMark rm(THREAD);
    Exceptions::fthrow(
      THREAD_AND_LOCATION,
4873
      vmSymbols::java_lang_ClassFormatError(),
D
duke 已提交
4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943
      "Method %s in class %s has illegal modifiers: 0x%X",
      name->as_C_string(), _class_name->as_C_string(), flags);
    return;
  }
}

void ClassFileParser::verify_legal_utf8(const unsigned char* buffer, int length, TRAPS) {
  assert(_need_verify, "only called when _need_verify is true");
  int i = 0;
  int count = length >> 2;
  for (int k=0; k<count; k++) {
    unsigned char b0 = buffer[i];
    unsigned char b1 = buffer[i+1];
    unsigned char b2 = buffer[i+2];
    unsigned char b3 = buffer[i+3];
    // For an unsigned char v,
    // (v | v - 1) is < 128 (highest bit 0) for 0 < v < 128;
    // (v | v - 1) is >= 128 (highest bit 1) for v == 0 or v >= 128.
    unsigned char res = b0 | b0 - 1 |
                        b1 | b1 - 1 |
                        b2 | b2 - 1 |
                        b3 | b3 - 1;
    if (res >= 128) break;
    i += 4;
  }
  for(; i < length; i++) {
    unsigned short c;
    // no embedded zeros
    guarantee_property((buffer[i] != 0), "Illegal UTF8 string in constant pool in class file %s", CHECK);
    if(buffer[i] < 128) {
      continue;
    }
    if ((i + 5) < length) { // see if it's legal supplementary character
      if (UTF8::is_supplementary_character(&buffer[i])) {
        c = UTF8::get_supplementary_character(&buffer[i]);
        i += 5;
        continue;
      }
    }
    switch (buffer[i] >> 4) {
      default: break;
      case 0x8: case 0x9: case 0xA: case 0xB: case 0xF:
        classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
      case 0xC: case 0xD:  // 110xxxxx  10xxxxxx
        c = (buffer[i] & 0x1F) << 6;
        i++;
        if ((i < length) && ((buffer[i] & 0xC0) == 0x80)) {
          c += buffer[i] & 0x3F;
          if (_major_version <= 47 || c == 0 || c >= 0x80) {
            // for classes with major > 47, c must a null or a character in its shortest form
            break;
          }
        }
        classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
      case 0xE:  // 1110xxxx 10xxxxxx 10xxxxxx
        c = (buffer[i] & 0xF) << 12;
        i += 2;
        if ((i < length) && ((buffer[i-1] & 0xC0) == 0x80) && ((buffer[i] & 0xC0) == 0x80)) {
          c += ((buffer[i-1] & 0x3F) << 6) + (buffer[i] & 0x3F);
          if (_major_version <= 47 || c >= 0x800) {
            // for classes with major > 47, c must be in its shortest form
            break;
          }
        }
        classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);
    }  // end of switch
  } // end of for
}

// Checks if name is a legal class name.
4944
void ClassFileParser::verify_legal_class_name(Symbol* name, TRAPS) {
D
duke 已提交
4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973
  if (!_need_verify || _relax_verify) { return; }

  char buf[fixed_buffer_size];
  char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
  unsigned int length = name->utf8_length();
  bool legal = false;

  if (length > 0) {
    char* p;
    if (bytes[0] == JVM_SIGNATURE_ARRAY) {
      p = skip_over_field_signature(bytes, false, length, CHECK);
      legal = (p != NULL) && ((p - bytes) == (int)length);
    } else if (_major_version < JAVA_1_5_VERSION) {
      if (bytes[0] != '<') {
        p = skip_over_field_name(bytes, true, length);
        legal = (p != NULL) && ((p - bytes) == (int)length);
      }
    } else {
      // 4900761: relax the constraints based on JSR202 spec
      // Class names may be drawn from the entire Unicode character set.
      // Identifiers between '/' must be unqualified names.
      // The utf8 string has been verified when parsing cpool entries.
      legal = verify_unqualified_name(bytes, length, LegalClass);
    }
  }
  if (!legal) {
    ResourceMark rm(THREAD);
    Exceptions::fthrow(
      THREAD_AND_LOCATION,
4974
      vmSymbols::java_lang_ClassFormatError(),
D
duke 已提交
4975 4976 4977 4978 4979 4980 4981 4982
      "Illegal class name \"%s\" in class file %s", bytes,
      _class_name->as_C_string()
    );
    return;
  }
}

// Checks if name is a legal field name.
4983
void ClassFileParser::verify_legal_field_name(Symbol* name, TRAPS) {
D
duke 已提交
4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006
  if (!_need_verify || _relax_verify) { return; }

  char buf[fixed_buffer_size];
  char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
  unsigned int length = name->utf8_length();
  bool legal = false;

  if (length > 0) {
    if (_major_version < JAVA_1_5_VERSION) {
      if (bytes[0] != '<') {
        char* p = skip_over_field_name(bytes, false, length);
        legal = (p != NULL) && ((p - bytes) == (int)length);
      }
    } else {
      // 4881221: relax the constraints based on JSR202 spec
      legal = verify_unqualified_name(bytes, length, LegalField);
    }
  }

  if (!legal) {
    ResourceMark rm(THREAD);
    Exceptions::fthrow(
      THREAD_AND_LOCATION,
5007
      vmSymbols::java_lang_ClassFormatError(),
D
duke 已提交
5008 5009 5010 5011 5012 5013 5014 5015
      "Illegal field name \"%s\" in class %s", bytes,
      _class_name->as_C_string()
    );
    return;
  }
}

// Checks if name is a legal method name.
5016
void ClassFileParser::verify_legal_method_name(Symbol* name, TRAPS) {
D
duke 已提交
5017 5018
  if (!_need_verify || _relax_verify) { return; }

5019
  assert(name != NULL, "method name is null");
D
duke 已提交
5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043
  char buf[fixed_buffer_size];
  char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
  unsigned int length = name->utf8_length();
  bool legal = false;

  if (length > 0) {
    if (bytes[0] == '<') {
      if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {
        legal = true;
      }
    } else if (_major_version < JAVA_1_5_VERSION) {
      char* p;
      p = skip_over_field_name(bytes, false, length);
      legal = (p != NULL) && ((p - bytes) == (int)length);
    } else {
      // 4881221: relax the constraints based on JSR202 spec
      legal = verify_unqualified_name(bytes, length, LegalMethod);
    }
  }

  if (!legal) {
    ResourceMark rm(THREAD);
    Exceptions::fthrow(
      THREAD_AND_LOCATION,
5044
      vmSymbols::java_lang_ClassFormatError(),
D
duke 已提交
5045 5046 5047 5048 5049 5050 5051 5052 5053
      "Illegal method name \"%s\" in class %s", bytes,
      _class_name->as_C_string()
    );
    return;
  }
}


// Checks if signature is a legal field signature.
5054
void ClassFileParser::verify_legal_field_signature(Symbol* name, Symbol* signature, TRAPS) {
D
duke 已提交
5055 5056 5057 5058 5059 5060 5061 5062
  if (!_need_verify) { return; }

  char buf[fixed_buffer_size];
  char* bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
  unsigned int length = signature->utf8_length();
  char* p = skip_over_field_signature(bytes, false, length, CHECK);

  if (p == NULL || (p - bytes) != (int)length) {
5063
    throwIllegalSignature("Field", name, signature, CHECK);
D
duke 已提交
5064 5065 5066 5067 5068
  }
}

// Checks if signature is a legal method signature.
// Returns number of parameters
5069
int ClassFileParser::verify_legal_method_signature(Symbol* name, Symbol* signature, TRAPS) {
D
duke 已提交
5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113
  if (!_need_verify) {
    // make sure caller's args_size will be less than 0 even for non-static
    // method so it will be recomputed in compute_size_of_parameters().
    return -2;
  }

  unsigned int args_size = 0;
  char buf[fixed_buffer_size];
  char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);
  unsigned int length = signature->utf8_length();
  char* nextp;

  // The first character must be a '('
  if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {
    length--;
    // Skip over legal field signatures
    nextp = skip_over_field_signature(p, false, length, CHECK_0);
    while ((length > 0) && (nextp != NULL)) {
      args_size++;
      if (p[0] == 'J' || p[0] == 'D') {
        args_size++;
      }
      length -= nextp - p;
      p = nextp;
      nextp = skip_over_field_signature(p, false, length, CHECK_0);
    }
    // The first non-signature thing better be a ')'
    if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {
      length--;
      if (name->utf8_length() > 0 && name->byte_at(0) == '<') {
        // All internal methods must return void
        if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {
          return args_size;
        }
      } else {
        // Now we better just have a return value
        nextp = skip_over_field_signature(p, true, length, CHECK_0);
        if (nextp && ((int)length == (nextp - p))) {
          return args_size;
        }
      }
    }
  }
  // Report error
5114
  throwIllegalSignature("Method", name, signature, CHECK_0);
D
duke 已提交
5115 5116 5117 5118
  return 0;
}


5119 5120 5121 5122 5123 5124 5125
// Unqualified names may not contain the characters '.', ';', '[', or '/'.
// Method names also may not contain the characters '<' or '>', unless <init>
// or <clinit>.  Note that method names may not be <init> or <clinit> in this
// method.  Because these names have been checked as special cases before
// calling this method in verify_legal_method_name.
bool ClassFileParser::verify_unqualified_name(
    char* name, unsigned int length, int type) {
D
duke 已提交
5126 5127 5128 5129 5130 5131
  jchar ch;

  for (char* p = name; p != name + length; ) {
    ch = *p;
    if (ch < 128) {
      p++;
5132 5133
      if (ch == '.' || ch == ';' || ch == '[' ) {
        return false;   // do not permit '.', ';', or '['
D
duke 已提交
5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189
      }
      if (type != LegalClass && ch == '/') {
        return false;   // do not permit '/' unless it's class name
      }
      if (type == LegalMethod && (ch == '<' || ch == '>')) {
        return false;   // do not permit '<' or '>' in method names
      }
    } else {
      char* tmp_p = UTF8::next(p, &ch);
      p = tmp_p;
    }
  }
  return true;
}


// Take pointer to a string. Skip over the longest part of the string that could
// be taken as a fieldname. Allow '/' if slash_ok is true.
// Return a pointer to just past the fieldname.
// Return NULL if no fieldname at all was found, or in the case of slash_ok
// being true, we saw consecutive slashes (meaning we were looking for a
// qualified path but found something that was badly-formed).
char* ClassFileParser::skip_over_field_name(char* name, bool slash_ok, unsigned int length) {
  char* p;
  jchar ch;
  jboolean last_is_slash = false;
  jboolean not_first_ch = false;

  for (p = name; p != name + length; not_first_ch = true) {
    char* old_p = p;
    ch = *p;
    if (ch < 128) {
      p++;
      // quick check for ascii
      if ((ch >= 'a' && ch <= 'z') ||
          (ch >= 'A' && ch <= 'Z') ||
          (ch == '_' || ch == '$') ||
          (not_first_ch && ch >= '0' && ch <= '9')) {
        last_is_slash = false;
        continue;
      }
      if (slash_ok && ch == '/') {
        if (last_is_slash) {
          return NULL;  // Don't permit consecutive slashes
        }
        last_is_slash = true;
        continue;
      }
    } else {
      jint unicode_ch;
      char* tmp_p = UTF8::next_character(p, &unicode_ch);
      p = tmp_p;
      last_is_slash = false;
      // Check if ch is Java identifier start or is Java identifier part
      // 4672820: call java.lang.Character methods directly without generating separate tables.
      EXCEPTION_MARK;
5190
      instanceKlassHandle klass (THREAD, SystemDictionary::Character_klass());
D
duke 已提交
5191 5192 5193 5194 5195 5196 5197 5198 5199 5200

      // return value
      JavaValue result(T_BOOLEAN);
      // Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart
      JavaCallArguments args;
      args.push_int(unicode_ch);

      // public static boolean isJavaIdentifierStart(char ch);
      JavaCalls::call_static(&result,
                             klass,
5201 5202
                             vmSymbols::isJavaIdentifierStart_name(),
                             vmSymbols::int_bool_signature(),
D
duke 已提交
5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217
                             &args,
                             THREAD);

      if (HAS_PENDING_EXCEPTION) {
        CLEAR_PENDING_EXCEPTION;
        return 0;
      }
      if (result.get_jboolean()) {
        continue;
      }

      if (not_first_ch) {
        // public static boolean isJavaIdentifierPart(char ch);
        JavaCalls::call_static(&result,
                               klass,
5218 5219
                               vmSymbols::isJavaIdentifierPart_name(),
                               vmSymbols::int_bool_signature(),
D
duke 已提交
5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302
                               &args,
                               THREAD);

        if (HAS_PENDING_EXCEPTION) {
          CLEAR_PENDING_EXCEPTION;
          return 0;
        }

        if (result.get_jboolean()) {
          continue;
        }
      }
    }
    return (not_first_ch) ? old_p : NULL;
  }
  return (not_first_ch) ? p : NULL;
}


// Take pointer to a string. Skip over the longest part of the string that could
// be taken as a field signature. Allow "void" if void_ok.
// Return a pointer to just past the signature.
// Return NULL if no legal signature is found.
char* ClassFileParser::skip_over_field_signature(char* signature,
                                                 bool void_ok,
                                                 unsigned int length,
                                                 TRAPS) {
  unsigned int array_dim = 0;
  while (length > 0) {
    switch (signature[0]) {
      case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }
      case JVM_SIGNATURE_BOOLEAN:
      case JVM_SIGNATURE_BYTE:
      case JVM_SIGNATURE_CHAR:
      case JVM_SIGNATURE_SHORT:
      case JVM_SIGNATURE_INT:
      case JVM_SIGNATURE_FLOAT:
      case JVM_SIGNATURE_LONG:
      case JVM_SIGNATURE_DOUBLE:
        return signature + 1;
      case JVM_SIGNATURE_CLASS: {
        if (_major_version < JAVA_1_5_VERSION) {
          // Skip over the class name if one is there
          char* p = skip_over_field_name(signature + 1, true, --length);

          // The next character better be a semicolon
          if (p && (p - signature) > 1 && p[0] == ';') {
            return p + 1;
          }
        } else {
          // 4900761: For class version > 48, any unicode is allowed in class name.
          length--;
          signature++;
          while (length > 0 && signature[0] != ';') {
            if (signature[0] == '.') {
              classfile_parse_error("Class name contains illegal character '.' in descriptor in class file %s", CHECK_0);
            }
            length--;
            signature++;
          }
          if (signature[0] == ';') { return signature + 1; }
        }

        return NULL;
      }
      case JVM_SIGNATURE_ARRAY:
        array_dim++;
        if (array_dim > 255) {
          // 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.
          classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);
        }
        // The rest of what's there better be a legal signature
        signature++;
        length--;
        void_ok = false;
        break;

      default:
        return NULL;
    }
  }
  return NULL;
}