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