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