Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/classfile/classFileParser.cpp
32285 views
/*1* Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/classFileParser.hpp"26#include "classfile/classLoader.hpp"27#include "classfile/classLoaderData.hpp"28#include "classfile/classLoaderData.inline.hpp"29#include "classfile/defaultMethods.hpp"30#include "classfile/javaClasses.hpp"31#include "classfile/symbolTable.hpp"32#include "classfile/systemDictionary.hpp"33#if INCLUDE_CDS34#include "classfile/systemDictionaryShared.hpp"35#endif36#include "classfile/verificationType.hpp"37#include "classfile/verifier.hpp"38#include "classfile/vmSymbols.hpp"39#include "memory/allocation.hpp"40#include "memory/gcLocker.hpp"41#include "memory/metadataFactory.hpp"42#include "memory/oopFactory.hpp"43#include "memory/referenceType.hpp"44#include "memory/universe.inline.hpp"45#include "oops/constantPool.hpp"46#include "oops/fieldStreams.hpp"47#include "oops/instanceKlass.hpp"48#include "oops/instanceMirrorKlass.hpp"49#include "oops/klass.inline.hpp"50#include "oops/klassVtable.hpp"51#include "oops/method.hpp"52#include "oops/symbol.hpp"53#include "prims/jvm.h"54#include "prims/jvmtiExport.hpp"55#include "prims/jvmtiThreadState.hpp"56#include "runtime/javaCalls.hpp"57#include "runtime/perfData.hpp"58#include "runtime/reflection.hpp"59#include "runtime/signature.hpp"60#include "runtime/timer.hpp"61#include "services/classLoadingService.hpp"62#include "services/threadService.hpp"63#include "utilities/array.hpp"64#include "utilities/globalDefinitions.hpp"65#include "utilities/ostream.hpp"6667// We generally try to create the oops directly when parsing, rather than68// allocating temporary data structures and copying the bytes twice. A69// temporary area is only needed when parsing utf8 entries in the constant70// pool and when parsing line number tables.7172// We add assert in debug mode when class format is not checked.7374#define JAVA_CLASSFILE_MAGIC 0xCAFEBABE75#define JAVA_MIN_SUPPORTED_VERSION 4576#define JAVA_MAX_SUPPORTED_VERSION 5277#define JAVA_MAX_SUPPORTED_MINOR_VERSION 07879// Used for two backward compatibility reasons:80// - to check for new additions to the class file format in JDK1.581// - to check for bug fixes in the format checker in JDK1.582#define JAVA_1_5_VERSION 498384// Used for backward compatibility reasons:85// - to check for javac bug fixes that happened after 1.586// - also used as the max version when running in jdk687#define JAVA_6_VERSION 508889// Used for backward compatibility reasons:90// - to check NameAndType_info signatures more aggressively91#define JAVA_7_VERSION 519293// Extension method support.94#define JAVA_8_VERSION 529596void ClassFileParser::parse_constant_pool_entries(int length, TRAPS) {97// Use a local copy of ClassFileStream. It helps the C++ compiler to optimize98// this function (_current can be allocated in a register, with scalar99// replacement of aggregates). The _current pointer is copied back to100// stream() when this function returns. DON'T call another method within101// this method that uses stream().102ClassFileStream* cfs0 = stream();103ClassFileStream cfs1 = *cfs0;104ClassFileStream* cfs = &cfs1;105#ifdef ASSERT106assert(cfs->allocated_on_stack(),"should be local");107u1* old_current = cfs0->current();108#endif109Handle class_loader(THREAD, _loader_data->class_loader());110111// Used for batching symbol allocations.112const char* names[SymbolTable::symbol_alloc_batch_size];113int lengths[SymbolTable::symbol_alloc_batch_size];114int indices[SymbolTable::symbol_alloc_batch_size];115unsigned int hashValues[SymbolTable::symbol_alloc_batch_size];116int names_count = 0;117118// parsing Index 0 is unused119for (int index = 1; index < length; index++) {120// Each of the following case guarantees one more byte in the stream121// for the following tag or the access_flags following constant pool,122// so we don't need bounds-check for reading tag.123u1 tag = cfs->get_u1_fast();124switch (tag) {125case JVM_CONSTANT_Class :126{127cfs->guarantee_more(3, CHECK); // name_index, tag/access_flags128u2 name_index = cfs->get_u2_fast();129_cp->klass_index_at_put(index, name_index);130}131break;132case JVM_CONSTANT_Fieldref :133{134cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags135u2 class_index = cfs->get_u2_fast();136u2 name_and_type_index = cfs->get_u2_fast();137_cp->field_at_put(index, class_index, name_and_type_index);138}139break;140case JVM_CONSTANT_Methodref :141{142cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags143u2 class_index = cfs->get_u2_fast();144u2 name_and_type_index = cfs->get_u2_fast();145_cp->method_at_put(index, class_index, name_and_type_index);146}147break;148case JVM_CONSTANT_InterfaceMethodref :149{150cfs->guarantee_more(5, CHECK); // class_index, name_and_type_index, tag/access_flags151u2 class_index = cfs->get_u2_fast();152u2 name_and_type_index = cfs->get_u2_fast();153_cp->interface_method_at_put(index, class_index, name_and_type_index);154}155break;156case JVM_CONSTANT_String :157{158cfs->guarantee_more(3, CHECK); // string_index, tag/access_flags159u2 string_index = cfs->get_u2_fast();160_cp->string_index_at_put(index, string_index);161}162break;163case JVM_CONSTANT_MethodHandle :164case JVM_CONSTANT_MethodType :165if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {166classfile_parse_error(167"Class file version does not support constant tag %u in class file %s",168tag, CHECK);169}170if (!EnableInvokeDynamic) {171classfile_parse_error(172"This JVM does not support constant tag %u in class file %s",173tag, CHECK);174}175if (tag == JVM_CONSTANT_MethodHandle) {176cfs->guarantee_more(4, CHECK); // ref_kind, method_index, tag/access_flags177u1 ref_kind = cfs->get_u1_fast();178u2 method_index = cfs->get_u2_fast();179_cp->method_handle_index_at_put(index, ref_kind, method_index);180} else if (tag == JVM_CONSTANT_MethodType) {181cfs->guarantee_more(3, CHECK); // signature_index, tag/access_flags182u2 signature_index = cfs->get_u2_fast();183_cp->method_type_index_at_put(index, signature_index);184} else {185ShouldNotReachHere();186}187break;188case JVM_CONSTANT_InvokeDynamic :189{190if (_major_version < Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {191classfile_parse_error(192"Class file version does not support constant tag %u in class file %s",193tag, CHECK);194}195if (!EnableInvokeDynamic) {196classfile_parse_error(197"This JVM does not support constant tag %u in class file %s",198tag, CHECK);199}200cfs->guarantee_more(5, CHECK); // bsm_index, nt, tag/access_flags201u2 bootstrap_specifier_index = cfs->get_u2_fast();202u2 name_and_type_index = cfs->get_u2_fast();203if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index)204_max_bootstrap_specifier_index = (int) bootstrap_specifier_index; // collect for later205_cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);206}207break;208case JVM_CONSTANT_Integer :209{210cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags211u4 bytes = cfs->get_u4_fast();212_cp->int_at_put(index, (jint) bytes);213}214break;215case JVM_CONSTANT_Float :216{217cfs->guarantee_more(5, CHECK); // bytes, tag/access_flags218u4 bytes = cfs->get_u4_fast();219_cp->float_at_put(index, *(jfloat*)&bytes);220}221break;222case JVM_CONSTANT_Long :223// A mangled type might cause you to overrun allocated memory224guarantee_property(index+1 < length,225"Invalid constant pool entry %u in class file %s",226index, CHECK);227{228cfs->guarantee_more(9, CHECK); // bytes, tag/access_flags229u8 bytes = cfs->get_u8_fast();230_cp->long_at_put(index, bytes);231}232index++; // Skip entry following eigth-byte constant, see JVM book p. 98233break;234case JVM_CONSTANT_Double :235// A mangled type might cause you to overrun allocated memory236guarantee_property(index+1 < length,237"Invalid constant pool entry %u in class file %s",238index, CHECK);239{240cfs->guarantee_more(9, CHECK); // bytes, tag/access_flags241u8 bytes = cfs->get_u8_fast();242_cp->double_at_put(index, *(jdouble*)&bytes);243}244index++; // Skip entry following eigth-byte constant, see JVM book p. 98245break;246case JVM_CONSTANT_NameAndType :247{248cfs->guarantee_more(5, CHECK); // name_index, signature_index, tag/access_flags249u2 name_index = cfs->get_u2_fast();250u2 signature_index = cfs->get_u2_fast();251_cp->name_and_type_at_put(index, name_index, signature_index);252}253break;254case JVM_CONSTANT_Utf8 :255{256cfs->guarantee_more(2, CHECK); // utf8_length257u2 utf8_length = cfs->get_u2_fast();258u1* utf8_buffer = cfs->get_u1_buffer();259assert(utf8_buffer != NULL, "null utf8 buffer");260// Got utf8 string, guarantee utf8_length+1 bytes, set stream position forward.261cfs->guarantee_more(utf8_length+1, CHECK); // utf8 string, tag/access_flags262cfs->skip_u1_fast(utf8_length);263264// Before storing the symbol, make sure it's legal265if (_need_verify) {266verify_legal_utf8((unsigned char*)utf8_buffer, utf8_length, CHECK);267}268269if (EnableInvokeDynamic && has_cp_patch_at(index)) {270Handle patch = clear_cp_patch_at(index);271guarantee_property(java_lang_String::is_instance(patch()),272"Illegal utf8 patch at %d in class file %s",273index, CHECK);274char* str = java_lang_String::as_utf8_string(patch());275// (could use java_lang_String::as_symbol instead, but might as well batch them)276utf8_buffer = (u1*) str;277utf8_length = (u2) strlen(str);278}279280unsigned int hash;281Symbol* result = SymbolTable::lookup_only((char*)utf8_buffer, utf8_length, hash);282if (result == NULL) {283names[names_count] = (char*)utf8_buffer;284lengths[names_count] = utf8_length;285indices[names_count] = index;286hashValues[names_count++] = hash;287if (names_count == SymbolTable::symbol_alloc_batch_size) {288SymbolTable::new_symbols(_loader_data, _cp, names_count, names, lengths, indices, hashValues, CHECK);289names_count = 0;290}291} else {292_cp->symbol_at_put(index, result);293}294}295break;296default:297classfile_parse_error(298"Unknown constant tag %u in class file %s", tag, CHECK);299break;300}301}302303// Allocate the remaining symbols304if (names_count > 0) {305SymbolTable::new_symbols(_loader_data, _cp, names_count, names, lengths, indices, hashValues, CHECK);306}307308// Copy _current pointer of local copy back to stream().309#ifdef ASSERT310assert(cfs0->current() == old_current, "non-exclusive use of stream()");311#endif312cfs0->set_current(cfs1.current());313}314315bool inline valid_cp_range(int index, int length) { return (index > 0 && index < length); }316317inline Symbol* check_symbol_at(constantPoolHandle cp, int index) {318if (valid_cp_range(index, cp->length()) && cp->tag_at(index).is_utf8())319return cp->symbol_at(index);320else321return NULL;322}323324constantPoolHandle ClassFileParser::parse_constant_pool(TRAPS) {325ClassFileStream* cfs = stream();326constantPoolHandle nullHandle;327328cfs->guarantee_more(3, CHECK_(nullHandle)); // length, first cp tag329u2 length = cfs->get_u2_fast();330guarantee_property(331length >= 1, "Illegal constant pool size %u in class file %s",332length, CHECK_(nullHandle));333ConstantPool* constant_pool = ConstantPool::allocate(_loader_data, length,334CHECK_(nullHandle));335_cp = constant_pool; // save in case of errors336constantPoolHandle cp (THREAD, constant_pool);337338// parsing constant pool entries339parse_constant_pool_entries(length, CHECK_(nullHandle));340341int index = 1; // declared outside of loops for portability342343// first verification pass - validate cross references and fixup class and string constants344for (index = 1; index < length; index++) { // Index 0 is unused345jbyte tag = cp->tag_at(index).value();346switch (tag) {347case JVM_CONSTANT_Class :348ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present349break;350case JVM_CONSTANT_Fieldref :351// fall through352case JVM_CONSTANT_Methodref :353// fall through354case JVM_CONSTANT_InterfaceMethodref : {355if (!_need_verify) break;356int klass_ref_index = cp->klass_ref_index_at(index);357int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);358check_property(valid_klass_reference_at(klass_ref_index),359"Invalid constant pool index %u in class file %s",360klass_ref_index,361CHECK_(nullHandle));362check_property(valid_cp_range(name_and_type_ref_index, length) &&363cp->tag_at(name_and_type_ref_index).is_name_and_type(),364"Invalid constant pool index %u in class file %s",365name_and_type_ref_index,366CHECK_(nullHandle));367break;368}369case JVM_CONSTANT_String :370ShouldNotReachHere(); // Only JVM_CONSTANT_StringIndex should be present371break;372case JVM_CONSTANT_Integer :373break;374case JVM_CONSTANT_Float :375break;376case JVM_CONSTANT_Long :377case JVM_CONSTANT_Double :378index++;379check_property(380(index < length && cp->tag_at(index).is_invalid()),381"Improper constant pool long/double index %u in class file %s",382index, CHECK_(nullHandle));383break;384case JVM_CONSTANT_NameAndType : {385if (!_need_verify) break;386int name_ref_index = cp->name_ref_index_at(index);387int signature_ref_index = cp->signature_ref_index_at(index);388check_property(valid_symbol_at(name_ref_index),389"Invalid constant pool index %u in class file %s",390name_ref_index, CHECK_(nullHandle));391check_property(valid_symbol_at(signature_ref_index),392"Invalid constant pool index %u in class file %s",393signature_ref_index, CHECK_(nullHandle));394break;395}396case JVM_CONSTANT_Utf8 :397break;398case JVM_CONSTANT_UnresolvedClass : // fall-through399case JVM_CONSTANT_UnresolvedClassInError:400ShouldNotReachHere(); // Only JVM_CONSTANT_ClassIndex should be present401break;402case JVM_CONSTANT_ClassIndex :403{404int class_index = cp->klass_index_at(index);405check_property(valid_symbol_at(class_index),406"Invalid constant pool index %u in class file %s",407class_index, CHECK_(nullHandle));408cp->unresolved_klass_at_put(index, cp->symbol_at(class_index));409}410break;411case JVM_CONSTANT_StringIndex :412{413int string_index = cp->string_index_at(index);414check_property(valid_symbol_at(string_index),415"Invalid constant pool index %u in class file %s",416string_index, CHECK_(nullHandle));417Symbol* sym = cp->symbol_at(string_index);418cp->unresolved_string_at_put(index, sym);419}420break;421case JVM_CONSTANT_MethodHandle :422{423int ref_index = cp->method_handle_index_at(index);424check_property(425valid_cp_range(ref_index, length) &&426EnableInvokeDynamic,427"Invalid constant pool index %u in class file %s",428ref_index, CHECK_(nullHandle));429constantTag tag = cp->tag_at(ref_index);430int ref_kind = cp->method_handle_ref_kind_at(index);431switch (ref_kind) {432case JVM_REF_getField:433case JVM_REF_getStatic:434case JVM_REF_putField:435case JVM_REF_putStatic:436check_property(437tag.is_field(),438"Invalid constant pool index %u in class file %s (not a field)",439ref_index, CHECK_(nullHandle));440break;441case JVM_REF_invokeVirtual:442case JVM_REF_newInvokeSpecial:443check_property(444tag.is_method(),445"Invalid constant pool index %u in class file %s (not a method)",446ref_index, CHECK_(nullHandle));447break;448case JVM_REF_invokeStatic:449case JVM_REF_invokeSpecial:450check_property(tag.is_method() ||451((_major_version >= JAVA_8_VERSION) && tag.is_interface_method()),452"Invalid constant pool index %u in class file %s (not a method)",453ref_index, CHECK_(nullHandle));454break;455case JVM_REF_invokeInterface:456check_property(457tag.is_interface_method(),458"Invalid constant pool index %u in class file %s (not an interface method)",459ref_index, CHECK_(nullHandle));460break;461default:462classfile_parse_error(463"Bad method handle kind at constant pool index %u in class file %s",464index, CHECK_(nullHandle));465}466// Keep the ref_index unchanged. It will be indirected at link-time.467}468break;469case JVM_CONSTANT_MethodType :470{471int ref_index = cp->method_type_index_at(index);472check_property(valid_symbol_at(ref_index) && EnableInvokeDynamic,473"Invalid constant pool index %u in class file %s",474ref_index, CHECK_(nullHandle));475}476break;477case JVM_CONSTANT_InvokeDynamic :478{479int name_and_type_ref_index = cp->invoke_dynamic_name_and_type_ref_index_at(index);480check_property(valid_cp_range(name_and_type_ref_index, length) &&481cp->tag_at(name_and_type_ref_index).is_name_and_type(),482"Invalid constant pool index %u in class file %s",483name_and_type_ref_index,484CHECK_(nullHandle));485// bootstrap specifier index must be checked later, when BootstrapMethods attr is available486break;487}488default:489fatal(err_msg("bad constant pool tag value %u",490cp->tag_at(index).value()));491ShouldNotReachHere();492break;493} // end of switch494} // end of for495496if (_cp_patches != NULL) {497// need to treat this_class specially...498assert(EnableInvokeDynamic, "");499int this_class_index;500{501cfs->guarantee_more(8, CHECK_(nullHandle)); // flags, this_class, super_class, infs_len502u1* mark = cfs->current();503u2 flags = cfs->get_u2_fast();504this_class_index = cfs->get_u2_fast();505cfs->set_current(mark); // revert to mark506}507508for (index = 1; index < length; index++) { // Index 0 is unused509if (has_cp_patch_at(index)) {510guarantee_property(index != this_class_index,511"Illegal constant pool patch to self at %d in class file %s",512index, CHECK_(nullHandle));513patch_constant_pool(cp, index, cp_patch_at(index), CHECK_(nullHandle));514}515}516}517518if (!_need_verify) {519return cp;520}521522// second verification pass - checks the strings are of the right format.523// but not yet to the other entries524for (index = 1; index < length; index++) {525jbyte tag = cp->tag_at(index).value();526switch (tag) {527case JVM_CONSTANT_UnresolvedClass: {528Symbol* class_name = cp->unresolved_klass_at(index);529// check the name, even if _cp_patches will overwrite it530verify_legal_class_name(class_name, CHECK_(nullHandle));531break;532}533case JVM_CONSTANT_NameAndType: {534if (_need_verify && _major_version >= JAVA_7_VERSION) {535int sig_index = cp->signature_ref_index_at(index);536int name_index = cp->name_ref_index_at(index);537Symbol* name = cp->symbol_at(name_index);538Symbol* sig = cp->symbol_at(sig_index);539guarantee_property(sig->utf8_length() != 0,540"Illegal zero length constant pool entry at %d in class %s",541sig_index, CHECK_(nullHandle));542if (sig->byte_at(0) == JVM_SIGNATURE_FUNC) {543verify_legal_method_signature(name, sig, CHECK_(nullHandle));544} else {545verify_legal_field_signature(name, sig, CHECK_(nullHandle));546}547}548break;549}550case JVM_CONSTANT_InvokeDynamic:551case JVM_CONSTANT_Fieldref:552case JVM_CONSTANT_Methodref:553case JVM_CONSTANT_InterfaceMethodref: {554int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);555// already verified to be utf8556int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);557// already verified to be utf8558int signature_ref_index = cp->signature_ref_index_at(name_and_type_ref_index);559Symbol* name = cp->symbol_at(name_ref_index);560Symbol* signature = cp->symbol_at(signature_ref_index);561if (tag == JVM_CONSTANT_Fieldref) {562verify_legal_field_name(name, CHECK_(nullHandle));563if (_need_verify && _major_version >= JAVA_7_VERSION) {564// Signature is verified above, when iterating NameAndType_info.565// Need only to be sure it's non-zero length and the right type.566if (signature->utf8_length() == 0 ||567signature->byte_at(0) == JVM_SIGNATURE_FUNC) {568throwIllegalSignature(569"Field", name, signature, CHECK_(nullHandle));570}571} else {572verify_legal_field_signature(name, signature, CHECK_(nullHandle));573}574} else {575verify_legal_method_name(name, CHECK_(nullHandle));576if (_need_verify && _major_version >= JAVA_7_VERSION) {577// Signature is verified above, when iterating NameAndType_info.578// Need only to be sure it's non-zero length and the right type.579if (signature->utf8_length() == 0 ||580signature->byte_at(0) != JVM_SIGNATURE_FUNC) {581throwIllegalSignature(582"Method", name, signature, CHECK_(nullHandle));583}584} else {585verify_legal_method_signature(name, signature, CHECK_(nullHandle));586}587if (tag == JVM_CONSTANT_Methodref) {588// 4509014: If a class method name begins with '<', it must be "<init>".589assert(name != NULL, "method name in constant pool is null");590unsigned int name_len = name->utf8_length();591if (name_len != 0 && name->byte_at(0) == '<') {592if (name != vmSymbols::object_initializer_name()) {593classfile_parse_error(594"Bad method name at constant pool index %u in class file %s",595name_ref_index, CHECK_(nullHandle));596}597}598}599}600break;601}602case JVM_CONSTANT_MethodHandle: {603int ref_index = cp->method_handle_index_at(index);604int ref_kind = cp->method_handle_ref_kind_at(index);605switch (ref_kind) {606case JVM_REF_invokeVirtual:607case JVM_REF_invokeStatic:608case JVM_REF_invokeSpecial:609case JVM_REF_newInvokeSpecial:610{611int name_and_type_ref_index = cp->name_and_type_ref_index_at(ref_index);612int name_ref_index = cp->name_ref_index_at(name_and_type_ref_index);613Symbol* name = cp->symbol_at(name_ref_index);614if (ref_kind == JVM_REF_newInvokeSpecial) {615if (name != vmSymbols::object_initializer_name()) {616classfile_parse_error(617"Bad constructor name at constant pool index %u in class file %s",618name_ref_index, CHECK_(nullHandle));619}620} else {621if (name == vmSymbols::object_initializer_name()) {622classfile_parse_error(623"Bad method name at constant pool index %u in class file %s",624name_ref_index, CHECK_(nullHandle));625}626}627}628break;629// Other ref_kinds are already fully checked in previous pass.630}631break;632}633case JVM_CONSTANT_MethodType: {634Symbol* no_name = vmSymbols::type_name(); // place holder635Symbol* signature = cp->method_type_signature_at(index);636verify_legal_method_signature(no_name, signature, CHECK_(nullHandle));637break;638}639case JVM_CONSTANT_Utf8: {640assert(cp->symbol_at(index)->refcount() != 0, "count corrupted");641}642} // end of switch643} // end of for644645return cp;646}647648649void ClassFileParser::patch_constant_pool(constantPoolHandle cp, int index, Handle patch, TRAPS) {650assert(EnableInvokeDynamic, "");651BasicType patch_type = T_VOID;652653switch (cp->tag_at(index).value()) {654655case JVM_CONSTANT_UnresolvedClass :656// Patching a class means pre-resolving it.657// The name in the constant pool is ignored.658if (java_lang_Class::is_instance(patch())) {659guarantee_property(!java_lang_Class::is_primitive(patch()),660"Illegal class patch at %d in class file %s",661index, CHECK);662cp->klass_at_put(index, java_lang_Class::as_Klass(patch()));663} else {664guarantee_property(java_lang_String::is_instance(patch()),665"Illegal class patch at %d in class file %s",666index, CHECK);667Symbol* name = java_lang_String::as_symbol(patch(), CHECK);668cp->unresolved_klass_at_put(index, name);669}670break;671672case JVM_CONSTANT_String :673// skip this patch and don't clear it. Needs the oop array for resolved674// references to be created first.675return;676677case JVM_CONSTANT_Integer : patch_type = T_INT; goto patch_prim;678case JVM_CONSTANT_Float : patch_type = T_FLOAT; goto patch_prim;679case JVM_CONSTANT_Long : patch_type = T_LONG; goto patch_prim;680case JVM_CONSTANT_Double : patch_type = T_DOUBLE; goto patch_prim;681patch_prim:682{683jvalue value;684BasicType value_type = java_lang_boxing_object::get_value(patch(), &value);685guarantee_property(value_type == patch_type,686"Illegal primitive patch at %d in class file %s",687index, CHECK);688switch (value_type) {689case T_INT: cp->int_at_put(index, value.i); break;690case T_FLOAT: cp->float_at_put(index, value.f); break;691case T_LONG: cp->long_at_put(index, value.j); break;692case T_DOUBLE: cp->double_at_put(index, value.d); break;693default: assert(false, "");694}695}696break;697698default:699// %%% TODO: put method handles into CONSTANT_InterfaceMethodref, etc.700guarantee_property(!has_cp_patch_at(index),701"Illegal unexpected patch at %d in class file %s",702index, CHECK);703return;704}705706// On fall-through, mark the patch as used.707clear_cp_patch_at(index);708}709710711712class NameSigHash: public ResourceObj {713public:714Symbol* _name; // name715Symbol* _sig; // signature716NameSigHash* _next; // Next entry in hash table717};718719720#define HASH_ROW_SIZE 256721722unsigned int hash(Symbol* name, Symbol* sig) {723unsigned int raw_hash = 0;724raw_hash += ((unsigned int)(uintptr_t)name) >> (LogHeapWordSize + 2);725raw_hash += ((unsigned int)(uintptr_t)sig) >> LogHeapWordSize;726727return (raw_hash + (unsigned int)(uintptr_t)name) % HASH_ROW_SIZE;728}729730731void initialize_hashtable(NameSigHash** table) {732memset((void*)table, 0, sizeof(NameSigHash*) * HASH_ROW_SIZE);733}734735// Return false if the name/sig combination is found in table.736// Return true if no duplicate is found. And name/sig is added as a new entry in table.737// The old format checker uses heap sort to find duplicates.738// NOTE: caller should guarantee that GC doesn't happen during the life cycle739// of table since we don't expect Symbol*'s to move.740bool put_after_lookup(Symbol* name, Symbol* sig, NameSigHash** table) {741assert(name != NULL, "name in constant pool is NULL");742743// First lookup for duplicates744int index = hash(name, sig);745NameSigHash* entry = table[index];746while (entry != NULL) {747if (entry->_name == name && entry->_sig == sig) {748return false;749}750entry = entry->_next;751}752753// No duplicate is found, allocate a new entry and fill it.754entry = new NameSigHash();755entry->_name = name;756entry->_sig = sig;757758// Insert into hash table759entry->_next = table[index];760table[index] = entry;761762return true;763}764765766Array<Klass*>* ClassFileParser::parse_interfaces(int length,767Handle protection_domain,768Symbol* class_name,769bool* has_default_methods,770TRAPS) {771if (length == 0) {772_local_interfaces = Universe::the_empty_klass_array();773} else {774ClassFileStream* cfs = stream();775assert(length > 0, "only called for length>0");776_local_interfaces = MetadataFactory::new_array<Klass*>(_loader_data, length, NULL, CHECK_NULL);777778int index;779for (index = 0; index < length; index++) {780u2 interface_index = cfs->get_u2(CHECK_NULL);781KlassHandle interf;782check_property(783valid_klass_reference_at(interface_index),784"Interface name has bad constant pool index %u in class file %s",785interface_index, CHECK_NULL);786if (_cp->tag_at(interface_index).is_klass()) {787interf = KlassHandle(THREAD, _cp->resolved_klass_at(interface_index));788} else {789Symbol* unresolved_klass = _cp->klass_name_at(interface_index);790791// Don't need to check legal name because it's checked when parsing constant pool.792// But need to make sure it's not an array type.793guarantee_property(unresolved_klass->byte_at(0) != JVM_SIGNATURE_ARRAY,794"Bad interface name in class file %s", CHECK_NULL);795Handle class_loader(THREAD, _loader_data->class_loader());796797// Call resolve_super so classcircularity is checked798Klass* k = SystemDictionary::resolve_super_or_fail(class_name,799unresolved_klass, class_loader, protection_domain,800false, CHECK_NULL);801interf = KlassHandle(THREAD, k);802}803804if (!interf()->is_interface()) {805THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(), "Implementing class", NULL);806}807if (InstanceKlass::cast(interf())->has_default_methods()) {808*has_default_methods = true;809}810_local_interfaces->at_put(index, interf());811}812813if (!_need_verify || length <= 1) {814return _local_interfaces;815}816817// Check if there's any duplicates in interfaces818ResourceMark rm(THREAD);819NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(820THREAD, NameSigHash*, HASH_ROW_SIZE);821initialize_hashtable(interface_names);822bool dup = false;823Symbol* name = NULL;824{825debug_only(No_Safepoint_Verifier nsv;)826for (index = 0; index < length; index++) {827Klass* k = _local_interfaces->at(index);828name = InstanceKlass::cast(k)->name();829// If no duplicates, add (name, NULL) in hashtable interface_names.830if (!put_after_lookup(name, NULL, interface_names)) {831dup = true;832break;833}834}835}836if (dup) {837classfile_parse_error("Duplicate interface name \"%s\" in class file %s",838name->as_C_string(), CHECK_NULL);839}840}841return _local_interfaces;842}843844845void ClassFileParser::verify_constantvalue(int constantvalue_index, int signature_index, TRAPS) {846// Make sure the constant pool entry is of a type appropriate to this field847guarantee_property(848(constantvalue_index > 0 &&849constantvalue_index < _cp->length()),850"Bad initial value index %u in ConstantValue attribute in class file %s",851constantvalue_index, CHECK);852constantTag value_type = _cp->tag_at(constantvalue_index);853switch ( _cp->basic_type_for_signature_at(signature_index) ) {854case T_LONG:855guarantee_property(value_type.is_long(), "Inconsistent constant value type in class file %s", CHECK);856break;857case T_FLOAT:858guarantee_property(value_type.is_float(), "Inconsistent constant value type in class file %s", CHECK);859break;860case T_DOUBLE:861guarantee_property(value_type.is_double(), "Inconsistent constant value type in class file %s", CHECK);862break;863case T_BYTE: case T_CHAR: case T_SHORT: case T_BOOLEAN: case T_INT:864guarantee_property(value_type.is_int(), "Inconsistent constant value type in class file %s", CHECK);865break;866case T_OBJECT:867guarantee_property((_cp->symbol_at(signature_index)->equals("Ljava/lang/String;")868&& value_type.is_string()),869"Bad string initial value in class file %s", CHECK);870break;871default:872classfile_parse_error(873"Unable to set initial value %u in class file %s",874constantvalue_index, CHECK);875}876}877878879// Parse attributes for a field.880void ClassFileParser::parse_field_attributes(u2 attributes_count,881bool is_static, u2 signature_index,882u2* constantvalue_index_addr,883bool* is_synthetic_addr,884u2* generic_signature_index_addr,885ClassFileParser::FieldAnnotationCollector* parsed_annotations,886TRAPS) {887ClassFileStream* cfs = stream();888assert(attributes_count > 0, "length should be greater than 0");889u2 constantvalue_index = 0;890u2 generic_signature_index = 0;891bool is_synthetic = false;892u1* runtime_visible_annotations = NULL;893int runtime_visible_annotations_length = 0;894u1* runtime_invisible_annotations = NULL;895int runtime_invisible_annotations_length = 0;896u1* runtime_visible_type_annotations = NULL;897int runtime_visible_type_annotations_length = 0;898u1* runtime_invisible_type_annotations = NULL;899int runtime_invisible_type_annotations_length = 0;900bool runtime_invisible_type_annotations_exists = false;901while (attributes_count--) {902cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length903u2 attribute_name_index = cfs->get_u2_fast();904u4 attribute_length = cfs->get_u4_fast();905check_property(valid_symbol_at(attribute_name_index),906"Invalid field attribute index %u in class file %s",907attribute_name_index,908CHECK);909Symbol* attribute_name = _cp->symbol_at(attribute_name_index);910if (is_static && attribute_name == vmSymbols::tag_constant_value()) {911// ignore if non-static912if (constantvalue_index != 0) {913classfile_parse_error("Duplicate ConstantValue attribute in class file %s", CHECK);914}915check_property(916attribute_length == 2,917"Invalid ConstantValue field attribute length %u in class file %s",918attribute_length, CHECK);919constantvalue_index = cfs->get_u2(CHECK);920if (_need_verify) {921verify_constantvalue(constantvalue_index, signature_index, CHECK);922}923} else if (attribute_name == vmSymbols::tag_synthetic()) {924if (attribute_length != 0) {925classfile_parse_error(926"Invalid Synthetic field attribute length %u in class file %s",927attribute_length, CHECK);928}929is_synthetic = true;930} else if (attribute_name == vmSymbols::tag_deprecated()) { // 4276120931if (attribute_length != 0) {932classfile_parse_error(933"Invalid Deprecated field attribute length %u in class file %s",934attribute_length, CHECK);935}936} else if (_major_version >= JAVA_1_5_VERSION) {937if (attribute_name == vmSymbols::tag_signature()) {938if (attribute_length != 2) {939classfile_parse_error(940"Wrong size %u for field's Signature attribute in class file %s",941attribute_length, CHECK);942}943generic_signature_index = parse_generic_signature_attribute(CHECK);944} else if (attribute_name == vmSymbols::tag_runtime_visible_annotations()) {945runtime_visible_annotations_length = attribute_length;946runtime_visible_annotations = cfs->get_u1_buffer();947assert(runtime_visible_annotations != NULL, "null visible annotations");948cfs->guarantee_more(runtime_visible_annotations_length, CHECK);949parse_annotations(runtime_visible_annotations,950runtime_visible_annotations_length,951parsed_annotations,952CHECK);953cfs->skip_u1_fast(runtime_visible_annotations_length);954} else if (PreserveAllAnnotations && attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {955runtime_invisible_annotations_length = attribute_length;956runtime_invisible_annotations = cfs->get_u1_buffer();957assert(runtime_invisible_annotations != NULL, "null invisible annotations");958cfs->skip_u1(runtime_invisible_annotations_length, CHECK);959} else if (attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {960if (runtime_visible_type_annotations != NULL) {961classfile_parse_error(962"Multiple RuntimeVisibleTypeAnnotations attributes for field in class file %s", CHECK);963}964runtime_visible_type_annotations_length = attribute_length;965runtime_visible_type_annotations = cfs->get_u1_buffer();966assert(runtime_visible_type_annotations != NULL, "null visible type annotations");967cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);968} else if (attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {969if (runtime_invisible_type_annotations_exists) {970classfile_parse_error(971"Multiple RuntimeInvisibleTypeAnnotations attributes for field in class file %s", CHECK);972} else {973runtime_invisible_type_annotations_exists = true;974}975if (PreserveAllAnnotations) {976runtime_invisible_type_annotations_length = attribute_length;977runtime_invisible_type_annotations = cfs->get_u1_buffer();978assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");979}980cfs->skip_u1(attribute_length, CHECK);981} else {982cfs->skip_u1(attribute_length, CHECK); // Skip unknown attributes983}984} else {985cfs->skip_u1(attribute_length, CHECK); // Skip unknown attributes986}987}988989*constantvalue_index_addr = constantvalue_index;990*is_synthetic_addr = is_synthetic;991*generic_signature_index_addr = generic_signature_index;992AnnotationArray* a = assemble_annotations(runtime_visible_annotations,993runtime_visible_annotations_length,994runtime_invisible_annotations,995runtime_invisible_annotations_length,996CHECK);997parsed_annotations->set_field_annotations(a);998a = assemble_annotations(runtime_visible_type_annotations,999runtime_visible_type_annotations_length,1000runtime_invisible_type_annotations,1001runtime_invisible_type_annotations_length,1002CHECK);1003parsed_annotations->set_field_type_annotations(a);1004return;1005}100610071008// Field allocation types. Used for computing field offsets.10091010enum FieldAllocationType {1011STATIC_OOP, // Oops1012STATIC_BYTE, // Boolean, Byte, char1013STATIC_SHORT, // shorts1014STATIC_WORD, // ints1015STATIC_DOUBLE, // aligned long or double1016NONSTATIC_OOP,1017NONSTATIC_BYTE,1018NONSTATIC_SHORT,1019NONSTATIC_WORD,1020NONSTATIC_DOUBLE,1021MAX_FIELD_ALLOCATION_TYPE,1022BAD_ALLOCATION_TYPE = -11023};10241025static FieldAllocationType _basic_type_to_atype[2 * (T_CONFLICT + 1)] = {1026BAD_ALLOCATION_TYPE, // 01027BAD_ALLOCATION_TYPE, // 11028BAD_ALLOCATION_TYPE, // 21029BAD_ALLOCATION_TYPE, // 31030NONSTATIC_BYTE , // T_BOOLEAN = 4,1031NONSTATIC_SHORT, // T_CHAR = 5,1032NONSTATIC_WORD, // T_FLOAT = 6,1033NONSTATIC_DOUBLE, // T_DOUBLE = 7,1034NONSTATIC_BYTE, // T_BYTE = 8,1035NONSTATIC_SHORT, // T_SHORT = 9,1036NONSTATIC_WORD, // T_INT = 10,1037NONSTATIC_DOUBLE, // T_LONG = 11,1038NONSTATIC_OOP, // T_OBJECT = 12,1039NONSTATIC_OOP, // T_ARRAY = 13,1040BAD_ALLOCATION_TYPE, // T_VOID = 14,1041BAD_ALLOCATION_TYPE, // T_ADDRESS = 15,1042BAD_ALLOCATION_TYPE, // T_NARROWOOP = 16,1043BAD_ALLOCATION_TYPE, // T_METADATA = 17,1044BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,1045BAD_ALLOCATION_TYPE, // T_CONFLICT = 19,1046BAD_ALLOCATION_TYPE, // 01047BAD_ALLOCATION_TYPE, // 11048BAD_ALLOCATION_TYPE, // 21049BAD_ALLOCATION_TYPE, // 31050STATIC_BYTE , // T_BOOLEAN = 4,1051STATIC_SHORT, // T_CHAR = 5,1052STATIC_WORD, // T_FLOAT = 6,1053STATIC_DOUBLE, // T_DOUBLE = 7,1054STATIC_BYTE, // T_BYTE = 8,1055STATIC_SHORT, // T_SHORT = 9,1056STATIC_WORD, // T_INT = 10,1057STATIC_DOUBLE, // T_LONG = 11,1058STATIC_OOP, // T_OBJECT = 12,1059STATIC_OOP, // T_ARRAY = 13,1060BAD_ALLOCATION_TYPE, // T_VOID = 14,1061BAD_ALLOCATION_TYPE, // T_ADDRESS = 15,1062BAD_ALLOCATION_TYPE, // T_NARROWOOP = 16,1063BAD_ALLOCATION_TYPE, // T_METADATA = 17,1064BAD_ALLOCATION_TYPE, // T_NARROWKLASS = 18,1065BAD_ALLOCATION_TYPE, // T_CONFLICT = 19,1066};10671068static FieldAllocationType basic_type_to_atype(bool is_static, BasicType type) {1069assert(type >= T_BOOLEAN && type < T_VOID, "only allowable values");1070FieldAllocationType result = _basic_type_to_atype[type + (is_static ? (T_CONFLICT + 1) : 0)];1071assert(result != BAD_ALLOCATION_TYPE, "bad type");1072return result;1073}10741075class FieldAllocationCount: public ResourceObj {1076public:1077u2 count[MAX_FIELD_ALLOCATION_TYPE];10781079FieldAllocationCount() {1080for (int i = 0; i < MAX_FIELD_ALLOCATION_TYPE; i++) {1081count[i] = 0;1082}1083}10841085FieldAllocationType update(bool is_static, BasicType type) {1086FieldAllocationType atype = basic_type_to_atype(is_static, type);1087// Make sure there is no overflow with injected fields.1088assert(count[atype] < 0xFFFF, "More than 65535 fields");1089count[atype]++;1090return atype;1091}1092};10931094Array<u2>* ClassFileParser::parse_fields(Symbol* class_name,1095bool is_interface,1096FieldAllocationCount *fac,1097u2* java_fields_count_ptr, TRAPS) {1098ClassFileStream* cfs = stream();1099cfs->guarantee_more(2, CHECK_NULL); // length1100u2 length = cfs->get_u2_fast();1101*java_fields_count_ptr = length;11021103int num_injected = 0;1104InjectedField* injected = JavaClasses::get_injected(class_name, &num_injected);1105int total_fields = length + num_injected;11061107// The field array starts with tuples of shorts1108// [access, name index, sig index, initial value index, byte offset].1109// A generic signature slot only exists for field with generic1110// signature attribute. And the access flag is set with1111// JVM_ACC_FIELD_HAS_GENERIC_SIGNATURE for that field. The generic1112// signature slots are at the end of the field array and after all1113// other fields data.1114//1115// f1: [access, name index, sig index, initial value index, low_offset, high_offset]1116// f2: [access, name index, sig index, initial value index, low_offset, high_offset]1117// ...1118// fn: [access, name index, sig index, initial value index, low_offset, high_offset]1119// [generic signature index]1120// [generic signature index]1121// ...1122//1123// Allocate a temporary resource array for field data. For each field,1124// a slot is reserved in the temporary array for the generic signature1125// index. After parsing all fields, the data are copied to a permanent1126// array and any unused slots will be discarded.1127ResourceMark rm(THREAD);1128u2* fa = NEW_RESOURCE_ARRAY_IN_THREAD(1129THREAD, u2, total_fields * (FieldInfo::field_slots + 1));11301131// The generic signature slots start after all other fields' data.1132int generic_signature_slot = total_fields * FieldInfo::field_slots;1133int num_generic_signature = 0;1134for (int n = 0; n < length; n++) {1135cfs->guarantee_more(8, CHECK_NULL); // access_flags, name_index, descriptor_index, attributes_count11361137AccessFlags access_flags;1138jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_FIELD_MODIFIERS;1139verify_legal_field_modifiers(flags, is_interface, CHECK_NULL);1140access_flags.set_flags(flags);11411142u2 name_index = cfs->get_u2_fast();1143int cp_size = _cp->length();1144check_property(valid_symbol_at(name_index),1145"Invalid constant pool index %u for field name in class file %s",1146name_index,1147CHECK_NULL);1148Symbol* name = _cp->symbol_at(name_index);1149verify_legal_field_name(name, CHECK_NULL);11501151u2 signature_index = cfs->get_u2_fast();1152check_property(valid_symbol_at(signature_index),1153"Invalid constant pool index %u for field signature in class file %s",1154signature_index, CHECK_NULL);1155Symbol* sig = _cp->symbol_at(signature_index);1156verify_legal_field_signature(name, sig, CHECK_NULL);11571158u2 constantvalue_index = 0;1159bool is_synthetic = false;1160u2 generic_signature_index = 0;1161bool is_static = access_flags.is_static();1162FieldAnnotationCollector parsed_annotations(_loader_data);11631164u2 attributes_count = cfs->get_u2_fast();1165if (attributes_count > 0) {1166parse_field_attributes(attributes_count, is_static, signature_index,1167&constantvalue_index, &is_synthetic,1168&generic_signature_index, &parsed_annotations,1169CHECK_NULL);1170if (parsed_annotations.field_annotations() != NULL) {1171if (_fields_annotations == NULL) {1172_fields_annotations = MetadataFactory::new_array<AnnotationArray*>(1173_loader_data, length, NULL,1174CHECK_NULL);1175}1176_fields_annotations->at_put(n, parsed_annotations.field_annotations());1177parsed_annotations.set_field_annotations(NULL);1178}1179if (parsed_annotations.field_type_annotations() != NULL) {1180if (_fields_type_annotations == NULL) {1181_fields_type_annotations = MetadataFactory::new_array<AnnotationArray*>(1182_loader_data, length, NULL,1183CHECK_NULL);1184}1185_fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());1186parsed_annotations.set_field_type_annotations(NULL);1187}11881189if (is_synthetic) {1190access_flags.set_is_synthetic();1191}1192if (generic_signature_index != 0) {1193access_flags.set_field_has_generic_signature();1194fa[generic_signature_slot] = generic_signature_index;1195generic_signature_slot ++;1196num_generic_signature ++;1197}1198}11991200FieldInfo* field = FieldInfo::from_field_array(fa, n);1201field->initialize(access_flags.as_short(),1202name_index,1203signature_index,1204constantvalue_index);1205BasicType type = _cp->basic_type_for_signature_at(signature_index);12061207// Remember how many oops we encountered and compute allocation type1208FieldAllocationType atype = fac->update(is_static, type);1209field->set_allocation_type(atype);12101211// After field is initialized with type, we can augment it with aux info1212if (parsed_annotations.has_any_annotations())1213parsed_annotations.apply_to(field);1214}12151216int index = length;1217if (num_injected != 0) {1218for (int n = 0; n < num_injected; n++) {1219// Check for duplicates1220if (injected[n].may_be_java) {1221Symbol* name = injected[n].name();1222Symbol* signature = injected[n].signature();1223bool duplicate = false;1224for (int i = 0; i < length; i++) {1225FieldInfo* f = FieldInfo::from_field_array(fa, i);1226if (name == _cp->symbol_at(f->name_index()) &&1227signature == _cp->symbol_at(f->signature_index())) {1228// Symbol is desclared in Java so skip this one1229duplicate = true;1230break;1231}1232}1233if (duplicate) {1234// These will be removed from the field array at the end1235continue;1236}1237}12381239// Injected field1240FieldInfo* field = FieldInfo::from_field_array(fa, index);1241field->initialize(JVM_ACC_FIELD_INTERNAL,1242injected[n].name_index,1243injected[n].signature_index,12440);12451246BasicType type = FieldType::basic_type(injected[n].signature());12471248// Remember how many oops we encountered and compute allocation type1249FieldAllocationType atype = fac->update(false, type);1250field->set_allocation_type(atype);1251index++;1252}1253}12541255// Now copy the fields' data from the temporary resource array.1256// Sometimes injected fields already exist in the Java source so1257// the fields array could be too long. In that case the1258// fields array is trimed. Also unused slots that were reserved1259// for generic signature indexes are discarded.1260Array<u2>* fields = MetadataFactory::new_array<u2>(1261_loader_data, index * FieldInfo::field_slots + num_generic_signature,1262CHECK_NULL);1263_fields = fields; // save in case of error1264{1265int i = 0;1266for (; i < index * FieldInfo::field_slots; i++) {1267fields->at_put(i, fa[i]);1268}1269for (int j = total_fields * FieldInfo::field_slots;1270j < generic_signature_slot; j++) {1271fields->at_put(i++, fa[j]);1272}1273assert(i == fields->length(), "");1274}12751276if (_need_verify && length > 1) {1277// Check duplicated fields1278ResourceMark rm(THREAD);1279NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(1280THREAD, NameSigHash*, HASH_ROW_SIZE);1281initialize_hashtable(names_and_sigs);1282bool dup = false;1283Symbol* name = NULL;1284Symbol* sig = NULL;1285{1286debug_only(No_Safepoint_Verifier nsv;)1287for (AllFieldStream fs(fields, _cp); !fs.done(); fs.next()) {1288name = fs.name();1289sig = fs.signature();1290// If no duplicates, add name/signature in hashtable names_and_sigs.1291if (!put_after_lookup(name, sig, names_and_sigs)) {1292dup = true;1293break;1294}1295}1296}1297if (dup) {1298classfile_parse_error("Duplicate field name \"%s\" with signature \"%s\" in class file %s",1299name->as_C_string(), sig->as_klass_external_name(), CHECK_NULL);1300}1301}13021303return fields;1304}130513061307static void copy_u2_with_conversion(u2* dest, u2* src, int length) {1308while (length-- > 0) {1309*dest++ = Bytes::get_Java_u2((u1*) (src++));1310}1311}131213131314u2* ClassFileParser::parse_exception_table(u4 code_length,1315u4 exception_table_length,1316TRAPS) {1317ClassFileStream* cfs = stream();13181319u2* exception_table_start = cfs->get_u2_buffer();1320assert(exception_table_start != NULL, "null exception table");1321cfs->guarantee_more(8 * exception_table_length, CHECK_NULL); // start_pc, end_pc, handler_pc, catch_type_index1322// Will check legal target after parsing code array in verifier.1323if (_need_verify) {1324for (unsigned int i = 0; i < exception_table_length; i++) {1325u2 start_pc = cfs->get_u2_fast();1326u2 end_pc = cfs->get_u2_fast();1327u2 handler_pc = cfs->get_u2_fast();1328u2 catch_type_index = cfs->get_u2_fast();1329guarantee_property((start_pc < end_pc) && (end_pc <= code_length),1330"Illegal exception table range in class file %s",1331CHECK_NULL);1332guarantee_property(handler_pc < code_length,1333"Illegal exception table handler in class file %s",1334CHECK_NULL);1335if (catch_type_index != 0) {1336guarantee_property(valid_klass_reference_at(catch_type_index),1337"Catch type in exception table has bad constant type in class file %s", CHECK_NULL);1338}1339}1340} else {1341cfs->skip_u2_fast(exception_table_length * 4);1342}1343return exception_table_start;1344}13451346void ClassFileParser::parse_linenumber_table(1347u4 code_attribute_length, u4 code_length,1348CompressedLineNumberWriteStream** write_stream, TRAPS) {1349ClassFileStream* cfs = stream();1350unsigned int num_entries = cfs->get_u2(CHECK);13511352// Each entry is a u2 start_pc, and a u2 line_number1353unsigned int length_in_bytes = num_entries * (sizeof(u2) + sizeof(u2));13541355// Verify line number attribute and table length1356check_property(1357code_attribute_length == sizeof(u2) + length_in_bytes,1358"LineNumberTable attribute has wrong length in class file %s", CHECK);13591360cfs->guarantee_more(length_in_bytes, CHECK);13611362if ((*write_stream) == NULL) {1363if (length_in_bytes > fixed_buffer_size) {1364(*write_stream) = new CompressedLineNumberWriteStream(length_in_bytes);1365} else {1366(*write_stream) = new CompressedLineNumberWriteStream(1367linenumbertable_buffer, fixed_buffer_size);1368}1369}13701371while (num_entries-- > 0) {1372u2 bci = cfs->get_u2_fast(); // start_pc1373u2 line = cfs->get_u2_fast(); // line_number1374guarantee_property(bci < code_length,1375"Invalid pc in LineNumberTable in class file %s", CHECK);1376(*write_stream)->write_pair(bci, line);1377}1378}137913801381// Class file LocalVariableTable elements.1382class Classfile_LVT_Element VALUE_OBJ_CLASS_SPEC {1383public:1384u2 start_bci;1385u2 length;1386u2 name_cp_index;1387u2 descriptor_cp_index;1388u2 slot;1389};139013911392class LVT_Hash: public CHeapObj<mtClass> {1393public:1394LocalVariableTableElement *_elem; // element1395LVT_Hash* _next; // Next entry in hash table1396};13971398unsigned int hash(LocalVariableTableElement *elem) {1399unsigned int raw_hash = elem->start_bci;14001401raw_hash = elem->length + raw_hash * 37;1402raw_hash = elem->name_cp_index + raw_hash * 37;1403raw_hash = elem->slot + raw_hash * 37;14041405return raw_hash % HASH_ROW_SIZE;1406}14071408void initialize_hashtable(LVT_Hash** table) {1409for (int i = 0; i < HASH_ROW_SIZE; i++) {1410table[i] = NULL;1411}1412}14131414void clear_hashtable(LVT_Hash** table) {1415for (int i = 0; i < HASH_ROW_SIZE; i++) {1416LVT_Hash* current = table[i];1417LVT_Hash* next;1418while (current != NULL) {1419next = current->_next;1420current->_next = NULL;1421delete(current);1422current = next;1423}1424table[i] = NULL;1425}1426}14271428LVT_Hash* LVT_lookup(LocalVariableTableElement *elem, int index, LVT_Hash** table) {1429LVT_Hash* entry = table[index];14301431/*1432* 3-tuple start_bci/length/slot has to be unique key,1433* so the following comparison seems to be redundant:1434* && elem->name_cp_index == entry->_elem->name_cp_index1435*/1436while (entry != NULL) {1437if (elem->start_bci == entry->_elem->start_bci1438&& elem->length == entry->_elem->length1439&& elem->name_cp_index == entry->_elem->name_cp_index1440&& elem->slot == entry->_elem->slot1441) {1442return entry;1443}1444entry = entry->_next;1445}1446return NULL;1447}14481449// Return false if the local variable is found in table.1450// Return true if no duplicate is found.1451// And local variable is added as a new entry in table.1452bool LVT_put_after_lookup(LocalVariableTableElement *elem, LVT_Hash** table) {1453// First lookup for duplicates1454int index = hash(elem);1455LVT_Hash* entry = LVT_lookup(elem, index, table);14561457if (entry != NULL) {1458return false;1459}1460// No duplicate is found, allocate a new entry and fill it.1461if ((entry = new LVT_Hash()) == NULL) {1462return false;1463}1464entry->_elem = elem;14651466// Insert into hash table1467entry->_next = table[index];1468table[index] = entry;14691470return true;1471}14721473void copy_lvt_element(Classfile_LVT_Element *src, LocalVariableTableElement *lvt) {1474lvt->start_bci = Bytes::get_Java_u2((u1*) &src->start_bci);1475lvt->length = Bytes::get_Java_u2((u1*) &src->length);1476lvt->name_cp_index = Bytes::get_Java_u2((u1*) &src->name_cp_index);1477lvt->descriptor_cp_index = Bytes::get_Java_u2((u1*) &src->descriptor_cp_index);1478lvt->signature_cp_index = 0;1479lvt->slot = Bytes::get_Java_u2((u1*) &src->slot);1480}14811482// Function is used to parse both attributes:1483// LocalVariableTable (LVT) and LocalVariableTypeTable (LVTT)1484u2* ClassFileParser::parse_localvariable_table(u4 code_length,1485u2 max_locals,1486u4 code_attribute_length,1487u2* localvariable_table_length,1488bool isLVTT,1489TRAPS) {1490ClassFileStream* cfs = stream();1491const char * tbl_name = (isLVTT) ? "LocalVariableTypeTable" : "LocalVariableTable";1492*localvariable_table_length = cfs->get_u2(CHECK_NULL);1493unsigned int size = (*localvariable_table_length) * sizeof(Classfile_LVT_Element) / sizeof(u2);1494// Verify local variable table attribute has right length1495if (_need_verify) {1496guarantee_property(code_attribute_length == (sizeof(*localvariable_table_length) + size * sizeof(u2)),1497"%s has wrong length in class file %s", tbl_name, CHECK_NULL);1498}1499u2* localvariable_table_start = cfs->get_u2_buffer();1500assert(localvariable_table_start != NULL, "null local variable table");1501if (!_need_verify) {1502cfs->skip_u2_fast(size);1503} else {1504cfs->guarantee_more(size * 2, CHECK_NULL);1505for(int i = 0; i < (*localvariable_table_length); i++) {1506u2 start_pc = cfs->get_u2_fast();1507u2 length = cfs->get_u2_fast();1508u2 name_index = cfs->get_u2_fast();1509u2 descriptor_index = cfs->get_u2_fast();1510u2 index = cfs->get_u2_fast();1511// Assign to a u4 to avoid overflow1512u4 end_pc = (u4)start_pc + (u4)length;15131514if (start_pc >= code_length) {1515classfile_parse_error(1516"Invalid start_pc %u in %s in class file %s",1517start_pc, tbl_name, CHECK_NULL);1518}1519if (end_pc > code_length) {1520classfile_parse_error(1521"Invalid length %u in %s in class file %s",1522length, tbl_name, CHECK_NULL);1523}1524int cp_size = _cp->length();1525guarantee_property(valid_symbol_at(name_index),1526"Name index %u in %s has bad constant type in class file %s",1527name_index, tbl_name, CHECK_NULL);1528guarantee_property(valid_symbol_at(descriptor_index),1529"Signature index %u in %s has bad constant type in class file %s",1530descriptor_index, tbl_name, CHECK_NULL);15311532Symbol* name = _cp->symbol_at(name_index);1533Symbol* sig = _cp->symbol_at(descriptor_index);1534verify_legal_field_name(name, CHECK_NULL);1535u2 extra_slot = 0;1536if (!isLVTT) {1537verify_legal_field_signature(name, sig, CHECK_NULL);15381539// 4894874: check special cases for double and long local variables1540if (sig == vmSymbols::type_signature(T_DOUBLE) ||1541sig == vmSymbols::type_signature(T_LONG)) {1542extra_slot = 1;1543}1544}1545guarantee_property((index + extra_slot) < max_locals,1546"Invalid index %u in %s in class file %s",1547index, tbl_name, CHECK_NULL);1548}1549}1550return localvariable_table_start;1551}155215531554void ClassFileParser::parse_type_array(u2 array_length, u4 code_length, u4* u1_index, u4* u2_index,1555u1* u1_array, u2* u2_array, TRAPS) {1556ClassFileStream* cfs = stream();1557u2 index = 0; // index in the array with long/double occupying two slots1558u4 i1 = *u1_index;1559u4 i2 = *u2_index + 1;1560for(int i = 0; i < array_length; i++) {1561u1 tag = u1_array[i1++] = cfs->get_u1(CHECK);1562index++;1563if (tag == ITEM_Long || tag == ITEM_Double) {1564index++;1565} else if (tag == ITEM_Object) {1566u2 class_index = u2_array[i2++] = cfs->get_u2(CHECK);1567guarantee_property(valid_klass_reference_at(class_index),1568"Bad class index %u in StackMap in class file %s",1569class_index, CHECK);1570} else if (tag == ITEM_Uninitialized) {1571u2 offset = u2_array[i2++] = cfs->get_u2(CHECK);1572guarantee_property(1573offset < code_length,1574"Bad uninitialized type offset %u in StackMap in class file %s",1575offset, CHECK);1576} else {1577guarantee_property(1578tag <= (u1)ITEM_Uninitialized,1579"Unknown variable type %u in StackMap in class file %s",1580tag, CHECK);1581}1582}1583u2_array[*u2_index] = index;1584*u1_index = i1;1585*u2_index = i2;1586}15871588u1* ClassFileParser::parse_stackmap_table(1589u4 code_attribute_length, TRAPS) {1590if (code_attribute_length == 0)1591return NULL;15921593ClassFileStream* cfs = stream();1594u1* stackmap_table_start = cfs->get_u1_buffer();1595assert(stackmap_table_start != NULL, "null stackmap table");15961597// check code_attribute_length first1598stream()->skip_u1(code_attribute_length, CHECK_NULL);15991600if (!_need_verify && !DumpSharedSpaces) {1601return NULL;1602}1603return stackmap_table_start;1604}16051606u2* ClassFileParser::parse_checked_exceptions(u2* checked_exceptions_length,1607u4 method_attribute_length,1608TRAPS) {1609ClassFileStream* cfs = stream();1610cfs->guarantee_more(2, CHECK_NULL); // checked_exceptions_length1611*checked_exceptions_length = cfs->get_u2_fast();1612unsigned int size = (*checked_exceptions_length) * sizeof(CheckedExceptionElement) / sizeof(u2);1613u2* checked_exceptions_start = cfs->get_u2_buffer();1614assert(checked_exceptions_start != NULL, "null checked exceptions");1615if (!_need_verify) {1616cfs->skip_u2_fast(size);1617} else {1618// Verify each value in the checked exception table1619u2 checked_exception;1620u2 len = *checked_exceptions_length;1621cfs->guarantee_more(2 * len, CHECK_NULL);1622for (int i = 0; i < len; i++) {1623checked_exception = cfs->get_u2_fast();1624check_property(1625valid_klass_reference_at(checked_exception),1626"Exception name has bad type at constant pool %u in class file %s",1627checked_exception, CHECK_NULL);1628}1629}1630// check exceptions attribute length1631if (_need_verify) {1632guarantee_property(method_attribute_length == (sizeof(*checked_exceptions_length) +1633sizeof(u2) * size),1634"Exceptions attribute has wrong length in class file %s", CHECK_NULL);1635}1636return checked_exceptions_start;1637}16381639void ClassFileParser::throwIllegalSignature(1640const char* type, Symbol* name, Symbol* sig, TRAPS) {1641ResourceMark rm(THREAD);1642Exceptions::fthrow(THREAD_AND_LOCATION,1643vmSymbols::java_lang_ClassFormatError(),1644"%s \"%s\" in class %s has illegal signature \"%s\"", type,1645name->as_C_string(), _class_name->as_C_string(), sig->as_C_string());1646}16471648// Skip an annotation. Return >=limit if there is any problem.1649int ClassFileParser::skip_annotation(u1* buffer, int limit, int index) {1650// annotation := atype:u2 do(nmem:u2) {member:u2 value}1651// value := switch (tag:u1) { ... }1652index += 2; // skip atype1653if ((index += 2) >= limit) return limit; // read nmem1654int nmem = Bytes::get_Java_u2(buffer+index-2);1655while (--nmem >= 0 && index < limit) {1656index += 2; // skip member1657index = skip_annotation_value(buffer, limit, index);1658}1659return index;1660}16611662// Safely increment index by val if does not pass limit1663#define SAFE_ADD(index, limit, val) \1664if (index >= limit - val) return limit; \1665index += val;16661667// Skip an annotation value. Return >=limit if there is any problem.1668int ClassFileParser::skip_annotation_value(u1* buffer, int limit, int index) {1669// value := switch (tag:u1) {1670// case B, C, I, S, Z, D, F, J, c: con:u2;1671// case e: e_class:u2 e_name:u2;1672// case s: s_con:u2;1673// case [: do(nval:u2) {value};1674// case @: annotation;1675// case s: s_con:u2;1676// }1677SAFE_ADD(index, limit, 1); // read tag1678u1 tag = buffer[index-1];1679switch (tag) {1680case 'B': case 'C': case 'I': case 'S': case 'Z':1681case 'D': case 'F': case 'J': case 'c': case 's':1682SAFE_ADD(index, limit, 2); // skip con or s_con1683break;1684case 'e':1685SAFE_ADD(index, limit, 4); // skip e_class, e_name1686break;1687case '[':1688{1689SAFE_ADD(index, limit, 2); // read nval1690int nval = Bytes::get_Java_u2(buffer+index-2);1691while (--nval >= 0 && index < limit) {1692index = skip_annotation_value(buffer, limit, index);1693}1694}1695break;1696case '@':1697index = skip_annotation(buffer, limit, index);1698break;1699default:1700assert(false, "annotation tag");1701return limit; // bad tag byte1702}1703return index;1704}17051706// Sift through annotations, looking for those significant to the VM:1707void ClassFileParser::parse_annotations(u1* buffer, int limit,1708ClassFileParser::AnnotationCollector* coll,1709TRAPS) {1710// annotations := do(nann:u2) {annotation}1711int index = 2;1712if (index >= limit) return; // read nann1713int nann = Bytes::get_Java_u2(buffer+index-2);1714enum { // initial annotation layout1715atype_off = 0, // utf8 such as 'Ljava/lang/annotation/Retention;'1716count_off = 2, // u2 such as 1 (one value)1717member_off = 4, // utf8 such as 'value'1718tag_off = 6, // u1 such as 'c' (type) or 'e' (enum)1719e_tag_val = 'e',1720e_type_off = 7, // utf8 such as 'Ljava/lang/annotation/RetentionPolicy;'1721e_con_off = 9, // utf8 payload, such as 'SOURCE', 'CLASS', 'RUNTIME'1722e_size = 11, // end of 'e' annotation1723c_tag_val = 'c', // payload is type1724c_con_off = 7, // utf8 payload, such as 'I'1725c_size = 9, // end of 'c' annotation1726s_tag_val = 's', // payload is String1727s_con_off = 7, // utf8 payload, such as 'Ljava/lang/String;'1728s_size = 9,1729min_size = 6 // smallest possible size (zero members)1730};1731// Cannot add min_size to index in case of overflow MAX_INT1732while ((--nann) >= 0 && (index-2 <= limit - min_size)) {1733int index0 = index;1734index = skip_annotation(buffer, limit, index);1735u1* abase = buffer + index0;1736int atype = Bytes::get_Java_u2(abase + atype_off);1737int count = Bytes::get_Java_u2(abase + count_off);1738Symbol* aname = check_symbol_at(_cp, atype);1739if (aname == NULL) break; // invalid annotation name1740Symbol* member = NULL;1741if (count >= 1) {1742int member_index = Bytes::get_Java_u2(abase + member_off);1743member = check_symbol_at(_cp, member_index);1744if (member == NULL) break; // invalid member name1745}17461747// Here is where parsing particular annotations will take place.1748AnnotationCollector::ID id = coll->annotation_index(_loader_data, aname);1749if (id == AnnotationCollector::_unknown) continue;1750coll->set_annotation(id);17511752if (id == AnnotationCollector::_sun_misc_Contended) {1753// @Contended can optionally specify the contention group.1754//1755// Contended group defines the equivalence class over the fields:1756// the fields within the same contended group are not treated distinct.1757// The only exception is default group, which does not incur the1758// equivalence. Naturally, contention group for classes is meaningless.1759//1760// While the contention group is specified as String, annotation1761// values are already interned, and we might as well use the constant1762// pool index as the group tag.1763//1764u2 group_index = 0; // default contended group1765if (count == 11766&& s_size == (index - index0) // match size1767&& s_tag_val == *(abase + tag_off)1768&& member == vmSymbols::value_name()) {1769group_index = Bytes::get_Java_u2(abase + s_con_off);1770if (_cp->symbol_at(group_index)->utf8_length() == 0) {1771group_index = 0; // default contended group1772}1773}1774coll->set_contended_group(group_index);1775}1776}1777}17781779ClassFileParser::AnnotationCollector::ID1780ClassFileParser::AnnotationCollector::annotation_index(ClassLoaderData* loader_data,1781Symbol* name) {1782vmSymbols::SID sid = vmSymbols::find_sid(name);1783// Privileged code can use all annotations. Other code silently drops some.1784const bool privileged = loader_data->is_the_null_class_loader_data() ||1785loader_data->is_ext_class_loader_data() ||1786loader_data->is_anonymous();1787switch (sid) {1788case vmSymbols::VM_SYMBOL_ENUM_NAME(sun_reflect_CallerSensitive_signature):1789if (_location != _in_method) break; // only allow for methods1790if (!privileged) break; // only allow in privileged code1791return _method_CallerSensitive;1792case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_ForceInline_signature):1793if (_location != _in_method) break; // only allow for methods1794if (!privileged) break; // only allow in privileged code1795return _method_ForceInline;1796case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_DontInline_signature):1797if (_location != _in_method) break; // only allow for methods1798if (!privileged) break; // only allow in privileged code1799return _method_DontInline;1800case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_InjectedProfile_signature):1801if (_location != _in_method) break; // only allow for methods1802if (!privileged) break; // only allow in privileged code1803return _method_InjectedProfile;1804case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Compiled_signature):1805if (_location != _in_method) break; // only allow for methods1806if (!privileged) break; // only allow in privileged code1807return _method_LambdaForm_Compiled;1808case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_LambdaForm_Hidden_signature):1809if (_location != _in_method) break; // only allow for methods1810if (!privileged) break; // only allow in privileged code1811return _method_LambdaForm_Hidden;1812case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_Stable_signature):1813if (_location != _in_field) break; // only allow for fields1814if (!privileged) break; // only allow in privileged code1815return _field_Stable;1816case vmSymbols::VM_SYMBOL_ENUM_NAME(sun_misc_Contended_signature):1817if (_location != _in_field && _location != _in_class) break; // only allow for fields and classes1818if (!EnableContended || (RestrictContended && !privileged)) break; // honor privileges1819return _sun_misc_Contended;1820default: break;1821}1822return AnnotationCollector::_unknown;1823}18241825void ClassFileParser::FieldAnnotationCollector::apply_to(FieldInfo* f) {1826if (is_contended())1827f->set_contended_group(contended_group());1828if (is_stable())1829f->set_stable(true);1830}18311832ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {1833// If there's an error deallocate metadata for field annotations1834MetadataFactory::free_array<u1>(_loader_data, _field_annotations);1835MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);1836}18371838void ClassFileParser::MethodAnnotationCollector::apply_to(methodHandle m) {1839if (has_annotation(_method_CallerSensitive))1840m->set_caller_sensitive(true);1841if (has_annotation(_method_ForceInline))1842m->set_force_inline(true);1843if (has_annotation(_method_DontInline))1844m->set_dont_inline(true);1845if (has_annotation(_method_InjectedProfile))1846m->set_has_injected_profile(true);1847if (has_annotation(_method_LambdaForm_Compiled) && m->intrinsic_id() == vmIntrinsics::_none)1848m->set_intrinsic_id(vmIntrinsics::_compiledLambdaForm);1849if (has_annotation(_method_LambdaForm_Hidden))1850m->set_hidden(true);1851}18521853void ClassFileParser::ClassAnnotationCollector::apply_to(instanceKlassHandle k) {1854k->set_is_contended(is_contended());1855}185618571858#define MAX_ARGS_SIZE 2551859#define MAX_CODE_SIZE 655351860#define INITIAL_MAX_LVT_NUMBER 25618611862/* Copy class file LVT's/LVTT's into the HotSpot internal LVT.1863*1864* Rules for LVT's and LVTT's are:1865* - There can be any number of LVT's and LVTT's.1866* - If there are n LVT's, it is the same as if there was just1867* one LVT containing all the entries from the n LVT's.1868* - There may be no more than one LVT entry per local variable.1869* Two LVT entries are 'equal' if these fields are the same:1870* start_pc, length, name, slot1871* - There may be no more than one LVTT entry per each LVT entry.1872* Each LVTT entry has to match some LVT entry.1873* - HotSpot internal LVT keeps natural ordering of class file LVT entries.1874*/1875void ClassFileParser::copy_localvariable_table(ConstMethod* cm,1876int lvt_cnt,1877u2* localvariable_table_length,1878u2** localvariable_table_start,1879int lvtt_cnt,1880u2* localvariable_type_table_length,1881u2** localvariable_type_table_start,1882TRAPS) {18831884LVT_Hash** lvt_Hash = NEW_RESOURCE_ARRAY(LVT_Hash*, HASH_ROW_SIZE);1885initialize_hashtable(lvt_Hash);18861887// To fill LocalVariableTable in1888Classfile_LVT_Element* cf_lvt;1889LocalVariableTableElement* lvt = cm->localvariable_table_start();18901891for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {1892cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];1893for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {1894copy_lvt_element(&cf_lvt[idx], lvt);1895// If no duplicates, add LVT elem in hashtable lvt_Hash.1896if (LVT_put_after_lookup(lvt, lvt_Hash) == false1897&& _need_verify1898&& _major_version >= JAVA_1_5_VERSION) {1899clear_hashtable(lvt_Hash);1900classfile_parse_error("Duplicated LocalVariableTable attribute "1901"entry for '%s' in class file %s",1902_cp->symbol_at(lvt->name_cp_index)->as_utf8(),1903CHECK);1904}1905}1906}19071908// To merge LocalVariableTable and LocalVariableTypeTable1909Classfile_LVT_Element* cf_lvtt;1910LocalVariableTableElement lvtt_elem;19111912for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {1913cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];1914for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {1915copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);1916int index = hash(&lvtt_elem);1917LVT_Hash* entry = LVT_lookup(&lvtt_elem, index, lvt_Hash);1918if (entry == NULL) {1919if (_need_verify) {1920clear_hashtable(lvt_Hash);1921classfile_parse_error("LVTT entry for '%s' in class file %s "1922"does not match any LVT entry",1923_cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),1924CHECK);1925}1926} else if (entry->_elem->signature_cp_index != 0 && _need_verify) {1927clear_hashtable(lvt_Hash);1928classfile_parse_error("Duplicated LocalVariableTypeTable attribute "1929"entry for '%s' in class file %s",1930_cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),1931CHECK);1932} else {1933// to add generic signatures into LocalVariableTable1934entry->_elem->signature_cp_index = lvtt_elem.descriptor_cp_index;1935}1936}1937}1938clear_hashtable(lvt_Hash);1939}194019411942void ClassFileParser::copy_method_annotations(ConstMethod* cm,1943u1* runtime_visible_annotations,1944int runtime_visible_annotations_length,1945u1* runtime_invisible_annotations,1946int runtime_invisible_annotations_length,1947u1* runtime_visible_parameter_annotations,1948int runtime_visible_parameter_annotations_length,1949u1* runtime_invisible_parameter_annotations,1950int runtime_invisible_parameter_annotations_length,1951u1* runtime_visible_type_annotations,1952int runtime_visible_type_annotations_length,1953u1* runtime_invisible_type_annotations,1954int runtime_invisible_type_annotations_length,1955u1* annotation_default,1956int annotation_default_length,1957TRAPS) {19581959AnnotationArray* a;19601961if (runtime_visible_annotations_length +1962runtime_invisible_annotations_length > 0) {1963a = assemble_annotations(runtime_visible_annotations,1964runtime_visible_annotations_length,1965runtime_invisible_annotations,1966runtime_invisible_annotations_length,1967CHECK);1968cm->set_method_annotations(a);1969}19701971if (runtime_visible_parameter_annotations_length +1972runtime_invisible_parameter_annotations_length > 0) {1973a = assemble_annotations(runtime_visible_parameter_annotations,1974runtime_visible_parameter_annotations_length,1975runtime_invisible_parameter_annotations,1976runtime_invisible_parameter_annotations_length,1977CHECK);1978cm->set_parameter_annotations(a);1979}19801981if (annotation_default_length > 0) {1982a = assemble_annotations(annotation_default,1983annotation_default_length,1984NULL,19850,1986CHECK);1987cm->set_default_annotations(a);1988}19891990if (runtime_visible_type_annotations_length +1991runtime_invisible_type_annotations_length > 0) {1992a = assemble_annotations(runtime_visible_type_annotations,1993runtime_visible_type_annotations_length,1994runtime_invisible_type_annotations,1995runtime_invisible_type_annotations_length,1996CHECK);1997cm->set_type_annotations(a);1998}1999}200020012002// Note: the parse_method below is big and clunky because all parsing of the code and exceptions2003// attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the2004// Method* to save footprint, so we only know the size of the resulting Method* when the2005// entire method attribute is parsed.2006//2007// The promoted_flags parameter is used to pass relevant access_flags2008// from the method back up to the containing klass. These flag values2009// are added to klass's access_flags.20102011methodHandle ClassFileParser::parse_method(bool is_interface,2012AccessFlags *promoted_flags,2013TRAPS) {2014ClassFileStream* cfs = stream();2015methodHandle nullHandle;2016ResourceMark rm(THREAD);2017// Parse fixed parts2018cfs->guarantee_more(8, CHECK_(nullHandle)); // access_flags, name_index, descriptor_index, attributes_count20192020int flags = cfs->get_u2_fast();2021u2 name_index = cfs->get_u2_fast();2022int cp_size = _cp->length();2023check_property(2024valid_symbol_at(name_index),2025"Illegal constant pool index %u for method name in class file %s",2026name_index, CHECK_(nullHandle));2027Symbol* name = _cp->symbol_at(name_index);2028verify_legal_method_name(name, CHECK_(nullHandle));20292030u2 signature_index = cfs->get_u2_fast();2031guarantee_property(2032valid_symbol_at(signature_index),2033"Illegal constant pool index %u for method signature in class file %s",2034signature_index, CHECK_(nullHandle));2035Symbol* signature = _cp->symbol_at(signature_index);20362037AccessFlags access_flags;2038if (name == vmSymbols::class_initializer_name()) {2039// We ignore the other access flags for a valid class initializer.2040// (JVM Spec 2nd ed., chapter 4.6)2041if (_major_version < 51) { // backward compatibility2042flags = JVM_ACC_STATIC;2043} else if ((flags & JVM_ACC_STATIC) == JVM_ACC_STATIC) {2044flags &= JVM_ACC_STATIC | JVM_ACC_STRICT;2045}2046} else {2047verify_legal_method_modifiers(flags, is_interface, name, CHECK_(nullHandle));2048}20492050int args_size = -1; // only used when _need_verify is true2051if (_need_verify) {2052args_size = ((flags & JVM_ACC_STATIC) ? 0 : 1) +2053verify_legal_method_signature(name, signature, CHECK_(nullHandle));2054if (args_size > MAX_ARGS_SIZE) {2055classfile_parse_error("Too many arguments in method signature in class file %s", CHECK_(nullHandle));2056}2057}20582059access_flags.set_flags(flags & JVM_RECOGNIZED_METHOD_MODIFIERS);20602061// Default values for code and exceptions attribute elements2062u2 max_stack = 0;2063u2 max_locals = 0;2064u4 code_length = 0;2065u1* code_start = 0;2066u2 exception_table_length = 0;2067u2* exception_table_start = NULL;2068Array<int>* exception_handlers = Universe::the_empty_int_array();2069u2 checked_exceptions_length = 0;2070u2* checked_exceptions_start = NULL;2071CompressedLineNumberWriteStream* linenumber_table = NULL;2072int linenumber_table_length = 0;2073int total_lvt_length = 0;2074u2 lvt_cnt = 0;2075u2 lvtt_cnt = 0;2076bool lvt_allocated = false;2077u2 max_lvt_cnt = INITIAL_MAX_LVT_NUMBER;2078u2 max_lvtt_cnt = INITIAL_MAX_LVT_NUMBER;2079u2* localvariable_table_length;2080u2** localvariable_table_start;2081u2* localvariable_type_table_length;2082u2** localvariable_type_table_start;2083u2 method_parameters_length = 0;2084u1* method_parameters_data = NULL;2085bool method_parameters_seen = false;2086bool parsed_code_attribute = false;2087bool parsed_checked_exceptions_attribute = false;2088bool parsed_stackmap_attribute = false;2089// stackmap attribute - JDK1.52090u1* stackmap_data = NULL;2091int stackmap_data_length = 0;2092u2 generic_signature_index = 0;2093MethodAnnotationCollector parsed_annotations;2094u1* runtime_visible_annotations = NULL;2095int runtime_visible_annotations_length = 0;2096u1* runtime_invisible_annotations = NULL;2097int runtime_invisible_annotations_length = 0;2098u1* runtime_visible_parameter_annotations = NULL;2099int runtime_visible_parameter_annotations_length = 0;2100u1* runtime_invisible_parameter_annotations = NULL;2101int runtime_invisible_parameter_annotations_length = 0;2102u1* runtime_visible_type_annotations = NULL;2103int runtime_visible_type_annotations_length = 0;2104u1* runtime_invisible_type_annotations = NULL;2105int runtime_invisible_type_annotations_length = 0;2106bool runtime_invisible_type_annotations_exists = false;2107u1* annotation_default = NULL;2108int annotation_default_length = 0;21092110// Parse code and exceptions attribute2111u2 method_attributes_count = cfs->get_u2_fast();2112while (method_attributes_count--) {2113cfs->guarantee_more(6, CHECK_(nullHandle)); // method_attribute_name_index, method_attribute_length2114u2 method_attribute_name_index = cfs->get_u2_fast();2115u4 method_attribute_length = cfs->get_u4_fast();2116check_property(2117valid_symbol_at(method_attribute_name_index),2118"Invalid method attribute name index %u in class file %s",2119method_attribute_name_index, CHECK_(nullHandle));21202121Symbol* method_attribute_name = _cp->symbol_at(method_attribute_name_index);2122if (method_attribute_name == vmSymbols::tag_code()) {2123// Parse Code attribute2124if (_need_verify) {2125guarantee_property(2126!access_flags.is_native() && !access_flags.is_abstract(),2127"Code attribute in native or abstract methods in class file %s",2128CHECK_(nullHandle));2129}2130if (parsed_code_attribute) {2131classfile_parse_error("Multiple Code attributes in class file %s", CHECK_(nullHandle));2132}2133parsed_code_attribute = true;21342135// Stack size, locals size, and code size2136if (_major_version == 45 && _minor_version <= 2) {2137cfs->guarantee_more(4, CHECK_(nullHandle));2138max_stack = cfs->get_u1_fast();2139max_locals = cfs->get_u1_fast();2140code_length = cfs->get_u2_fast();2141} else {2142cfs->guarantee_more(8, CHECK_(nullHandle));2143max_stack = cfs->get_u2_fast();2144max_locals = cfs->get_u2_fast();2145code_length = cfs->get_u4_fast();2146}2147if (_need_verify) {2148guarantee_property(args_size <= max_locals,2149"Arguments can't fit into locals in class file %s", CHECK_(nullHandle));2150guarantee_property(code_length > 0 && code_length <= MAX_CODE_SIZE,2151"Invalid method Code length %u in class file %s",2152code_length, CHECK_(nullHandle));2153}2154// Code pointer2155code_start = cfs->get_u1_buffer();2156assert(code_start != NULL, "null code start");2157cfs->guarantee_more(code_length, CHECK_(nullHandle));2158cfs->skip_u1_fast(code_length);21592160// Exception handler table2161cfs->guarantee_more(2, CHECK_(nullHandle)); // exception_table_length2162exception_table_length = cfs->get_u2_fast();2163if (exception_table_length > 0) {2164exception_table_start =2165parse_exception_table(code_length, exception_table_length, CHECK_(nullHandle));2166}21672168// Parse additional attributes in code attribute2169cfs->guarantee_more(2, CHECK_(nullHandle)); // code_attributes_count2170u2 code_attributes_count = cfs->get_u2_fast();21712172unsigned int calculated_attribute_length = 0;21732174if (_major_version > 45 || (_major_version == 45 && _minor_version > 2)) {2175calculated_attribute_length =2176sizeof(max_stack) + sizeof(max_locals) + sizeof(code_length);2177} else {2178// max_stack, locals and length are smaller in pre-version 45.2 classes2179calculated_attribute_length = sizeof(u1) + sizeof(u1) + sizeof(u2);2180}2181calculated_attribute_length +=2182code_length +2183sizeof(exception_table_length) +2184sizeof(code_attributes_count) +2185exception_table_length *2186( sizeof(u2) + // start_pc2187sizeof(u2) + // end_pc2188sizeof(u2) + // handler_pc2189sizeof(u2) ); // catch_type_index21902191while (code_attributes_count--) {2192cfs->guarantee_more(6, CHECK_(nullHandle)); // code_attribute_name_index, code_attribute_length2193u2 code_attribute_name_index = cfs->get_u2_fast();2194u4 code_attribute_length = cfs->get_u4_fast();2195calculated_attribute_length += code_attribute_length +2196sizeof(code_attribute_name_index) +2197sizeof(code_attribute_length);2198check_property(valid_symbol_at(code_attribute_name_index),2199"Invalid code attribute name index %u in class file %s",2200code_attribute_name_index,2201CHECK_(nullHandle));2202if (LoadLineNumberTables &&2203_cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {2204// Parse and compress line number table2205parse_linenumber_table(code_attribute_length, code_length,2206&linenumber_table, CHECK_(nullHandle));22072208} else if (LoadLocalVariableTables &&2209_cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {2210// Parse local variable table2211if (!lvt_allocated) {2212localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(2213THREAD, u2, INITIAL_MAX_LVT_NUMBER);2214localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(2215THREAD, u2*, INITIAL_MAX_LVT_NUMBER);2216localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(2217THREAD, u2, INITIAL_MAX_LVT_NUMBER);2218localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(2219THREAD, u2*, INITIAL_MAX_LVT_NUMBER);2220lvt_allocated = true;2221}2222if (lvt_cnt == max_lvt_cnt) {2223max_lvt_cnt <<= 1;2224localvariable_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_table_length, lvt_cnt, max_lvt_cnt);2225localvariable_table_start = REALLOC_RESOURCE_ARRAY(u2*, localvariable_table_start, lvt_cnt, max_lvt_cnt);2226}2227localvariable_table_start[lvt_cnt] =2228parse_localvariable_table(code_length,2229max_locals,2230code_attribute_length,2231&localvariable_table_length[lvt_cnt],2232false, // is not LVTT2233CHECK_(nullHandle));2234total_lvt_length += localvariable_table_length[lvt_cnt];2235lvt_cnt++;2236} else if (LoadLocalVariableTypeTables &&2237_major_version >= JAVA_1_5_VERSION &&2238_cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {2239if (!lvt_allocated) {2240localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(2241THREAD, u2, INITIAL_MAX_LVT_NUMBER);2242localvariable_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(2243THREAD, u2*, INITIAL_MAX_LVT_NUMBER);2244localvariable_type_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(2245THREAD, u2, INITIAL_MAX_LVT_NUMBER);2246localvariable_type_table_start = NEW_RESOURCE_ARRAY_IN_THREAD(2247THREAD, u2*, INITIAL_MAX_LVT_NUMBER);2248lvt_allocated = true;2249}2250// Parse local variable type table2251if (lvtt_cnt == max_lvtt_cnt) {2252max_lvtt_cnt <<= 1;2253localvariable_type_table_length = REALLOC_RESOURCE_ARRAY(u2, localvariable_type_table_length, lvtt_cnt, max_lvtt_cnt);2254localvariable_type_table_start = REALLOC_RESOURCE_ARRAY(u2*, localvariable_type_table_start, lvtt_cnt, max_lvtt_cnt);2255}2256localvariable_type_table_start[lvtt_cnt] =2257parse_localvariable_table(code_length,2258max_locals,2259code_attribute_length,2260&localvariable_type_table_length[lvtt_cnt],2261true, // is LVTT2262CHECK_(nullHandle));2263lvtt_cnt++;2264} else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&2265_cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {2266// Stack map is only needed by the new verifier in JDK1.5.2267if (parsed_stackmap_attribute) {2268classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_(nullHandle));2269}2270stackmap_data = parse_stackmap_table(code_attribute_length, CHECK_(nullHandle));2271stackmap_data_length = code_attribute_length;2272parsed_stackmap_attribute = true;2273} else {2274// Skip unknown attributes2275cfs->skip_u1(code_attribute_length, CHECK_(nullHandle));2276}2277}2278// check method attribute length2279if (_need_verify) {2280guarantee_property(method_attribute_length == calculated_attribute_length,2281"Code segment has wrong length in class file %s", CHECK_(nullHandle));2282}2283} else if (method_attribute_name == vmSymbols::tag_exceptions()) {2284// Parse Exceptions attribute2285if (parsed_checked_exceptions_attribute) {2286classfile_parse_error("Multiple Exceptions attributes in class file %s", CHECK_(nullHandle));2287}2288parsed_checked_exceptions_attribute = true;2289checked_exceptions_start =2290parse_checked_exceptions(&checked_exceptions_length,2291method_attribute_length,2292CHECK_(nullHandle));2293} else if (method_attribute_name == vmSymbols::tag_method_parameters()) {2294// reject multiple method parameters2295if (method_parameters_seen) {2296classfile_parse_error("Multiple MethodParameters attributes in class file %s", CHECK_(nullHandle));2297}2298method_parameters_seen = true;2299method_parameters_length = cfs->get_u1_fast();2300if (method_attribute_length != (method_parameters_length * 4u) + 1u) {2301classfile_parse_error(2302"Invalid MethodParameters method attribute length %u in class file",2303method_attribute_length, CHECK_(nullHandle));2304}2305method_parameters_data = cfs->get_u1_buffer();2306cfs->skip_u2_fast(method_parameters_length);2307cfs->skip_u2_fast(method_parameters_length);2308// ignore this attribute if it cannot be reflected2309if (!SystemDictionary::Parameter_klass_loaded())2310method_parameters_length = 0;2311} else if (method_attribute_name == vmSymbols::tag_synthetic()) {2312if (method_attribute_length != 0) {2313classfile_parse_error(2314"Invalid Synthetic method attribute length %u in class file %s",2315method_attribute_length, CHECK_(nullHandle));2316}2317// Should we check that there hasn't already been a synthetic attribute?2318access_flags.set_is_synthetic();2319} else if (method_attribute_name == vmSymbols::tag_deprecated()) { // 42761202320if (method_attribute_length != 0) {2321classfile_parse_error(2322"Invalid Deprecated method attribute length %u in class file %s",2323method_attribute_length, CHECK_(nullHandle));2324}2325} else if (_major_version >= JAVA_1_5_VERSION) {2326if (method_attribute_name == vmSymbols::tag_signature()) {2327if (method_attribute_length != 2) {2328classfile_parse_error(2329"Invalid Signature attribute length %u in class file %s",2330method_attribute_length, CHECK_(nullHandle));2331}2332generic_signature_index = parse_generic_signature_attribute(CHECK_(nullHandle));2333} else if (method_attribute_name == vmSymbols::tag_runtime_visible_annotations()) {2334runtime_visible_annotations_length = method_attribute_length;2335runtime_visible_annotations = cfs->get_u1_buffer();2336assert(runtime_visible_annotations != NULL, "null visible annotations");2337cfs->guarantee_more(runtime_visible_annotations_length, CHECK_(nullHandle));2338parse_annotations(runtime_visible_annotations,2339runtime_visible_annotations_length, &parsed_annotations,2340CHECK_(nullHandle));2341cfs->skip_u1_fast(runtime_visible_annotations_length);2342} else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {2343runtime_invisible_annotations_length = method_attribute_length;2344runtime_invisible_annotations = cfs->get_u1_buffer();2345assert(runtime_invisible_annotations != NULL, "null invisible annotations");2346cfs->skip_u1(runtime_invisible_annotations_length, CHECK_(nullHandle));2347} else if (method_attribute_name == vmSymbols::tag_runtime_visible_parameter_annotations()) {2348runtime_visible_parameter_annotations_length = method_attribute_length;2349runtime_visible_parameter_annotations = cfs->get_u1_buffer();2350assert(runtime_visible_parameter_annotations != NULL, "null visible parameter annotations");2351cfs->skip_u1(runtime_visible_parameter_annotations_length, CHECK_(nullHandle));2352} else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_parameter_annotations()) {2353runtime_invisible_parameter_annotations_length = method_attribute_length;2354runtime_invisible_parameter_annotations = cfs->get_u1_buffer();2355assert(runtime_invisible_parameter_annotations != NULL, "null invisible parameter annotations");2356cfs->skip_u1(runtime_invisible_parameter_annotations_length, CHECK_(nullHandle));2357} else if (method_attribute_name == vmSymbols::tag_annotation_default()) {2358annotation_default_length = method_attribute_length;2359annotation_default = cfs->get_u1_buffer();2360assert(annotation_default != NULL, "null annotation default");2361cfs->skip_u1(annotation_default_length, CHECK_(nullHandle));2362} else if (method_attribute_name == vmSymbols::tag_runtime_visible_type_annotations()) {2363if (runtime_visible_type_annotations != NULL) {2364classfile_parse_error(2365"Multiple RuntimeVisibleTypeAnnotations attributes for method in class file %s",2366CHECK_(nullHandle));2367}2368runtime_visible_type_annotations_length = method_attribute_length;2369runtime_visible_type_annotations = cfs->get_u1_buffer();2370assert(runtime_visible_type_annotations != NULL, "null visible type annotations");2371// No need for the VM to parse Type annotations2372cfs->skip_u1(runtime_visible_type_annotations_length, CHECK_(nullHandle));2373} else if (method_attribute_name == vmSymbols::tag_runtime_invisible_type_annotations()) {2374if (runtime_invisible_type_annotations_exists) {2375classfile_parse_error(2376"Multiple RuntimeInvisibleTypeAnnotations attributes for method in class file %s",2377CHECK_(nullHandle));2378} else {2379runtime_invisible_type_annotations_exists = true;2380}2381if (PreserveAllAnnotations) {2382runtime_invisible_type_annotations_length = method_attribute_length;2383runtime_invisible_type_annotations = cfs->get_u1_buffer();2384assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");2385}2386cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));2387} else {2388// Skip unknown attributes2389cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));2390}2391} else {2392// Skip unknown attributes2393cfs->skip_u1(method_attribute_length, CHECK_(nullHandle));2394}2395}23962397if (linenumber_table != NULL) {2398linenumber_table->write_terminator();2399linenumber_table_length = linenumber_table->position();2400}24012402// Make sure there's at least one Code attribute in non-native/non-abstract method2403if (_need_verify) {2404guarantee_property(access_flags.is_native() || access_flags.is_abstract() || parsed_code_attribute,2405"Absent Code attribute in method that is not native or abstract in class file %s", CHECK_(nullHandle));2406}24072408// All sizing information for a Method* is finally available, now create it2409InlineTableSizes sizes(2410total_lvt_length,2411linenumber_table_length,2412exception_table_length,2413checked_exceptions_length,2414method_parameters_length,2415generic_signature_index,2416runtime_visible_annotations_length +2417runtime_invisible_annotations_length,2418runtime_visible_parameter_annotations_length +2419runtime_invisible_parameter_annotations_length,2420runtime_visible_type_annotations_length +2421runtime_invisible_type_annotations_length,2422annotation_default_length,24230);24242425Method* m = Method::allocate(2426_loader_data, code_length, access_flags, &sizes,2427ConstMethod::NORMAL, CHECK_(nullHandle));24282429ClassLoadingService::add_class_method_size(m->size()*HeapWordSize);24302431// Fill in information from fixed part (access_flags already set)2432m->set_constants(_cp);2433m->set_name_index(name_index);2434m->set_signature_index(signature_index);24352436ResultTypeFinder rtf(_cp->symbol_at(signature_index));2437m->constMethod()->set_result_type(rtf.type());24382439if (args_size >= 0) {2440m->set_size_of_parameters(args_size);2441} else {2442m->compute_size_of_parameters(THREAD);2443}2444#ifdef ASSERT2445if (args_size >= 0) {2446m->compute_size_of_parameters(THREAD);2447assert(args_size == m->size_of_parameters(), "");2448}2449#endif24502451// Fill in code attribute information2452m->set_max_stack(max_stack);2453m->set_max_locals(max_locals);2454if (stackmap_data != NULL) {2455m->constMethod()->copy_stackmap_data(_loader_data, stackmap_data,2456stackmap_data_length, CHECK_NULL);2457}24582459// Copy byte codes2460m->set_code(code_start);24612462// Copy line number table2463if (linenumber_table != NULL) {2464memcpy(m->compressed_linenumber_table(),2465linenumber_table->buffer(), linenumber_table_length);2466}24672468// Copy exception table2469if (exception_table_length > 0) {2470int size =2471exception_table_length * sizeof(ExceptionTableElement) / sizeof(u2);2472copy_u2_with_conversion((u2*) m->exception_table_start(),2473exception_table_start, size);2474}24752476// Copy method parameters2477if (method_parameters_length > 0) {2478MethodParametersElement* elem = m->constMethod()->method_parameters_start();2479for (int i = 0; i < method_parameters_length; i++) {2480elem[i].name_cp_index = Bytes::get_Java_u2(method_parameters_data);2481method_parameters_data += 2;2482elem[i].flags = Bytes::get_Java_u2(method_parameters_data);2483method_parameters_data += 2;2484}2485}24862487// Copy checked exceptions2488if (checked_exceptions_length > 0) {2489int size = checked_exceptions_length * sizeof(CheckedExceptionElement) / sizeof(u2);2490copy_u2_with_conversion((u2*) m->checked_exceptions_start(), checked_exceptions_start, size);2491}24922493// Copy class file LVT's/LVTT's into the HotSpot internal LVT.2494if (total_lvt_length > 0) {2495promoted_flags->set_has_localvariable_table();2496copy_localvariable_table(m->constMethod(), lvt_cnt,2497localvariable_table_length,2498localvariable_table_start,2499lvtt_cnt,2500localvariable_type_table_length,2501localvariable_type_table_start, CHECK_NULL);2502}25032504if (parsed_annotations.has_any_annotations())2505parsed_annotations.apply_to(m);25062507// Copy annotations2508copy_method_annotations(m->constMethod(),2509runtime_visible_annotations,2510runtime_visible_annotations_length,2511runtime_invisible_annotations,2512runtime_invisible_annotations_length,2513runtime_visible_parameter_annotations,2514runtime_visible_parameter_annotations_length,2515runtime_invisible_parameter_annotations,2516runtime_invisible_parameter_annotations_length,2517runtime_visible_type_annotations,2518runtime_visible_type_annotations_length,2519runtime_invisible_type_annotations,2520runtime_invisible_type_annotations_length,2521annotation_default,2522annotation_default_length,2523CHECK_NULL);25242525if (name == vmSymbols::finalize_method_name() &&2526signature == vmSymbols::void_method_signature()) {2527if (m->is_empty_method()) {2528_has_empty_finalizer = true;2529} else {2530_has_finalizer = true;2531}2532}2533if (name == vmSymbols::object_initializer_name() &&2534signature == vmSymbols::void_method_signature() &&2535m->is_vanilla_constructor()) {2536_has_vanilla_constructor = true;2537}25382539NOT_PRODUCT(m->verify());2540return m;2541}254225432544// The promoted_flags parameter is used to pass relevant access_flags2545// from the methods back up to the containing klass. These flag values2546// are added to klass's access_flags.25472548Array<Method*>* ClassFileParser::parse_methods(bool is_interface,2549AccessFlags* promoted_flags,2550bool* has_final_method,2551bool* declares_default_methods,2552TRAPS) {2553ClassFileStream* cfs = stream();2554cfs->guarantee_more(2, CHECK_NULL); // length2555u2 length = cfs->get_u2_fast();2556if (length == 0) {2557_methods = Universe::the_empty_method_array();2558} else {2559_methods = MetadataFactory::new_array<Method*>(_loader_data, length, NULL, CHECK_NULL);25602561HandleMark hm(THREAD);2562for (int index = 0; index < length; index++) {2563methodHandle method = parse_method(is_interface,2564promoted_flags,2565CHECK_NULL);25662567if (method->is_final()) {2568*has_final_method = true;2569}2570// declares_default_methods: declares concrete instance methods, any access flags2571// used for interface initialization, and default method inheritance analysis2572if (is_interface && !(*declares_default_methods)2573&& !method->is_abstract() && !method->is_static()) {2574*declares_default_methods = true;2575}2576_methods->at_put(index, method());2577}25782579if (_need_verify && length > 1) {2580// Check duplicated methods2581ResourceMark rm(THREAD);2582NameSigHash** names_and_sigs = NEW_RESOURCE_ARRAY_IN_THREAD(2583THREAD, NameSigHash*, HASH_ROW_SIZE);2584initialize_hashtable(names_and_sigs);2585bool dup = false;2586Symbol* name = NULL;2587Symbol* sig = NULL;2588{2589debug_only(No_Safepoint_Verifier nsv;)2590for (int i = 0; i < length; i++) {2591Method* m = _methods->at(i);2592name = m->name();2593sig = m->signature();2594// If no duplicates, add name/signature in hashtable names_and_sigs.2595if (!put_after_lookup(name, sig, names_and_sigs)) {2596dup = true;2597break;2598}2599}2600}2601if (dup) {2602classfile_parse_error("Duplicate method name \"%s\" with signature \"%s\" in class file %s",2603name->as_C_string(), sig->as_klass_external_name(), CHECK_NULL);2604}2605}2606}2607return _methods;2608}260926102611intArray* ClassFileParser::sort_methods(Array<Method*>* methods) {2612int length = methods->length();2613// If JVMTI original method ordering or sharing is enabled we have to2614// remember the original class file ordering.2615// We temporarily use the vtable_index field in the Method* to store the2616// class file index, so we can read in after calling qsort.2617// Put the method ordering in the shared archive.2618if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {2619for (int index = 0; index < length; index++) {2620Method* m = methods->at(index);2621assert(!m->valid_vtable_index(), "vtable index should not be set");2622m->set_vtable_index(index);2623}2624}2625// Sort method array by ascending method name (for faster lookups & vtable construction)2626// Note that the ordering is not alphabetical, see Symbol::fast_compare2627Method::sort_methods(methods);26282629intArray* method_ordering = NULL;2630// If JVMTI original method ordering or sharing is enabled construct int2631// array remembering the original ordering2632if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {2633method_ordering = new intArray(length);2634for (int index = 0; index < length; index++) {2635Method* m = methods->at(index);2636int old_index = m->vtable_index();2637assert(old_index >= 0 && old_index < length, "invalid method index");2638method_ordering->at_put(index, old_index);2639m->set_vtable_index(Method::invalid_vtable_index);2640}2641}2642return method_ordering;2643}26442645// Parse generic_signature attribute for methods and fields2646u2 ClassFileParser::parse_generic_signature_attribute(TRAPS) {2647ClassFileStream* cfs = stream();2648cfs->guarantee_more(2, CHECK_0); // generic_signature_index2649u2 generic_signature_index = cfs->get_u2_fast();2650check_property(2651valid_symbol_at(generic_signature_index),2652"Invalid Signature attribute at constant pool index %u in class file %s",2653generic_signature_index, CHECK_0);2654return generic_signature_index;2655}26562657void ClassFileParser::parse_classfile_sourcefile_attribute(TRAPS) {2658ClassFileStream* cfs = stream();2659cfs->guarantee_more(2, CHECK); // sourcefile_index2660u2 sourcefile_index = cfs->get_u2_fast();2661check_property(2662valid_symbol_at(sourcefile_index),2663"Invalid SourceFile attribute at constant pool index %u in class file %s",2664sourcefile_index, CHECK);2665set_class_sourcefile_index(sourcefile_index);2666}2667266826692670void ClassFileParser::parse_classfile_source_debug_extension_attribute(int length, TRAPS) {2671ClassFileStream* cfs = stream();2672u1* sde_buffer = cfs->get_u1_buffer();2673assert(sde_buffer != NULL, "null sde buffer");26742675// Don't bother storing it if there is no way to retrieve it2676if (JvmtiExport::can_get_source_debug_extension()) {2677assert((length+1) > length, "Overflow checking");2678u1* sde = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, u1, length+1);2679for (int i = 0; i < length; i++) {2680sde[i] = sde_buffer[i];2681}2682sde[length] = '\0';2683set_class_sde_buffer((char*)sde, length);2684}2685// Got utf8 string, set stream position forward2686cfs->skip_u1(length, CHECK);2687}268826892690// Inner classes can be static, private or protected (classic VM does this)2691#define RECOGNIZED_INNER_CLASS_MODIFIERS (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED | JVM_ACC_STATIC)26922693// Find index of the InnerClasses entry for the specified inner_class_info_index.2694// Return -1 if none is found.2695static int inner_classes_find_index(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {2696Symbol* cp_klass_name = cp->klass_name_at(inner);2697for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {2698int idx_inner = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);2699if (cp->klass_name_at(idx_inner) == cp_klass_name) {2700return idx;2701}2702}2703return -1;2704}27052706// Return the outer_class_info_index for the InnerClasses entry containing the2707// specified inner_class_info_index. Return -1 if no InnerClasses entry is found.2708static int inner_classes_jump_to_outer(const Array<u2>* inner_classes, int inner, const ConstantPool* cp, int length) {2709if (inner == 0) return -1;2710int idx = inner_classes_find_index(inner_classes, inner, cp, length);2711if (idx == -1) return -1;2712int result = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);2713return result;2714}27152716// Return true if circularity is found, false if no circularity is found.2717// Use Floyd's cycle finding algorithm.2718static bool inner_classes_check_loop_through_outer(const Array<u2>* inner_classes, int idx, const ConstantPool* cp, int length) {2719int slow = inner_classes->at(idx + InstanceKlass::inner_class_inner_class_info_offset);2720int fast = inner_classes->at(idx + InstanceKlass::inner_class_outer_class_info_offset);2721while (fast != -1 && fast != 0) {2722if (slow != 0 && (cp->klass_name_at(slow) == cp->klass_name_at(fast))) {2723return true; // found a circularity2724}2725fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);2726if (fast == -1) return false;2727fast = inner_classes_jump_to_outer(inner_classes, fast, cp, length);2728if (fast == -1) return false;2729slow = inner_classes_jump_to_outer(inner_classes, slow, cp, length);2730assert(slow != -1, "sanity check");2731}2732return false;2733}27342735// Loop through each InnerClasses entry checking for circularities and duplications2736// with other entries. If duplicate entries are found then throw CFE. Otherwise,2737// return true if a circularity or entries with duplicate inner_class_info_indexes2738// are found.2739bool ClassFileParser::check_inner_classes_circularity(const ConstantPool* cp, int length, TRAPS) {2740// Loop through each InnerClasses entry.2741for (int idx = 0; idx < length; idx += InstanceKlass::inner_class_next_offset) {2742// Return true if there are circular entries.2743if (inner_classes_check_loop_through_outer(_inner_classes, idx, cp, length)) {2744return true;2745}2746// Check if there are duplicate entries or entries with the same inner_class_info_index.2747for (int y = idx + InstanceKlass::inner_class_next_offset; y < length;2748y += InstanceKlass::inner_class_next_offset) {27492750// To maintain compatibility, throw an exception if duplicate inner classes2751// entries are found.2752guarantee_property((_inner_classes->at(idx) != _inner_classes->at(y) ||2753_inner_classes->at(idx+1) != _inner_classes->at(y+1) ||2754_inner_classes->at(idx+2) != _inner_classes->at(y+2) ||2755_inner_classes->at(idx+3) != _inner_classes->at(y+3)),2756"Duplicate entry in InnerClasses attribute in class file %s",2757CHECK_(true));2758// Return true if there are two entries with the same inner_class_info_index.2759if (_inner_classes->at(y) == _inner_classes->at(idx)) {2760return true;2761}2762}2763}2764return false;2765}27662767// Return number of classes in the inner classes attribute table2768u2 ClassFileParser::parse_classfile_inner_classes_attribute(const ConstantPool* cp,2769u1* inner_classes_attribute_start,2770bool parsed_enclosingmethod_attribute,2771u2 enclosing_method_class_index,2772u2 enclosing_method_method_index,2773TRAPS) {2774ClassFileStream* cfs = stream();2775u1* current_mark = cfs->current();2776u2 length = 0;2777if (inner_classes_attribute_start != NULL) {2778cfs->set_current(inner_classes_attribute_start);2779cfs->guarantee_more(2, CHECK_0); // length2780length = cfs->get_u2_fast();2781}27822783// 4-tuples of shorts of inner classes data and 2 shorts of enclosing2784// method data:2785// [inner_class_info_index,2786// outer_class_info_index,2787// inner_name_index,2788// inner_class_access_flags,2789// ...2790// enclosing_method_class_index,2791// enclosing_method_method_index]2792int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);2793Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);2794_inner_classes = inner_classes;27952796int index = 0;2797int cp_size = _cp->length();2798cfs->guarantee_more(8 * length, CHECK_0); // 4-tuples of u22799for (int n = 0; n < length; n++) {2800// Inner class index2801u2 inner_class_info_index = cfs->get_u2_fast();2802check_property(2803inner_class_info_index == 0 ||2804valid_klass_reference_at(inner_class_info_index),2805"inner_class_info_index %u has bad constant type in class file %s",2806inner_class_info_index, CHECK_0);2807// Outer class index2808u2 outer_class_info_index = cfs->get_u2_fast();2809check_property(2810outer_class_info_index == 0 ||2811valid_klass_reference_at(outer_class_info_index),2812"outer_class_info_index %u has bad constant type in class file %s",2813outer_class_info_index, CHECK_0);2814// Inner class name2815u2 inner_name_index = cfs->get_u2_fast();2816check_property(2817inner_name_index == 0 || valid_symbol_at(inner_name_index),2818"inner_name_index %u has bad constant type in class file %s",2819inner_name_index, CHECK_0);2820if (_need_verify) {2821guarantee_property(inner_class_info_index != outer_class_info_index,2822"Class is both outer and inner class in class file %s", CHECK_0);2823}2824// Access flags2825AccessFlags inner_access_flags;2826jint flags = cfs->get_u2_fast() & RECOGNIZED_INNER_CLASS_MODIFIERS;2827if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {2828// Set abstract bit for old class files for backward compatibility2829flags |= JVM_ACC_ABSTRACT;2830}2831verify_legal_class_modifiers(flags, CHECK_0);2832inner_access_flags.set_flags(flags);28332834inner_classes->at_put(index++, inner_class_info_index);2835inner_classes->at_put(index++, outer_class_info_index);2836inner_classes->at_put(index++, inner_name_index);2837inner_classes->at_put(index++, inner_access_flags.as_short());2838}28392840// 4347400: make sure there's no duplicate entry in the classes array2841// Also, check for circular entries.2842bool has_circularity = false;2843if (_need_verify && _major_version >= JAVA_1_5_VERSION) {2844has_circularity = check_inner_classes_circularity(cp, length * 4, CHECK_0);2845if (has_circularity) {2846// If circularity check failed then ignore InnerClasses attribute.2847MetadataFactory::free_array<u2>(_loader_data, _inner_classes);2848index = 0;2849if (parsed_enclosingmethod_attribute) {2850inner_classes = MetadataFactory::new_array<u2>(_loader_data, 2, CHECK_0);2851_inner_classes = inner_classes;2852} else {2853_inner_classes = Universe::the_empty_short_array();2854}2855}2856}2857// Set EnclosingMethod class and method indexes.2858if (parsed_enclosingmethod_attribute) {2859inner_classes->at_put(index++, enclosing_method_class_index);2860inner_classes->at_put(index++, enclosing_method_method_index);2861}2862assert(index == size || has_circularity, "wrong size");28632864// Restore buffer's current position.2865cfs->set_current(current_mark);28662867return length;2868}28692870void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {2871set_class_synthetic_flag(true);2872}28732874void ClassFileParser::parse_classfile_signature_attribute(TRAPS) {2875ClassFileStream* cfs = stream();2876u2 signature_index = cfs->get_u2(CHECK);2877check_property(2878valid_symbol_at(signature_index),2879"Invalid constant pool index %u in Signature attribute in class file %s",2880signature_index, CHECK);2881set_class_generic_signature_index(signature_index);2882}28832884void ClassFileParser::parse_classfile_bootstrap_methods_attribute(u4 attribute_byte_length, TRAPS) {2885ClassFileStream* cfs = stream();2886u1* current_start = cfs->current();28872888guarantee_property(attribute_byte_length >= sizeof(u2),2889"Invalid BootstrapMethods attribute length %u in class file %s",2890attribute_byte_length,2891CHECK);28922893cfs->guarantee_more(attribute_byte_length, CHECK);28942895int attribute_array_length = cfs->get_u2_fast();28962897guarantee_property(_max_bootstrap_specifier_index < attribute_array_length,2898"Short length on BootstrapMethods in class file %s",2899CHECK);29002901// The attribute contains a counted array of counted tuples of shorts,2902// represending bootstrap specifiers:2903// length*{bootstrap_method_index, argument_count*{argument_index}}2904int operand_count = (attribute_byte_length - sizeof(u2)) / sizeof(u2);2905// operand_count = number of shorts in attr, except for leading length29062907// The attribute is copied into a short[] array.2908// The array begins with a series of short[2] pairs, one for each tuple.2909int index_size = (attribute_array_length * 2);29102911Array<u2>* operands = MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);29122913// Eagerly assign operands so they will be deallocated with the constant2914// pool if there is an error.2915_cp->set_operands(operands);29162917int operand_fill_index = index_size;2918int cp_size = _cp->length();29192920for (int n = 0; n < attribute_array_length; n++) {2921// Store a 32-bit offset into the header of the operand array.2922ConstantPool::operand_offset_at_put(operands, n, operand_fill_index);29232924// Read a bootstrap specifier.2925cfs->guarantee_more(sizeof(u2) * 2, CHECK); // bsm, argc2926u2 bootstrap_method_index = cfs->get_u2_fast();2927u2 argument_count = cfs->get_u2_fast();2928check_property(2929valid_cp_range(bootstrap_method_index, cp_size) &&2930_cp->tag_at(bootstrap_method_index).is_method_handle(),2931"bootstrap_method_index %u has bad constant type in class file %s",2932bootstrap_method_index,2933CHECK);29342935guarantee_property((operand_fill_index + 1 + argument_count) < operands->length(),2936"Invalid BootstrapMethods num_bootstrap_methods or num_bootstrap_arguments value in class file %s",2937CHECK);29382939operands->at_put(operand_fill_index++, bootstrap_method_index);2940operands->at_put(operand_fill_index++, argument_count);29412942cfs->guarantee_more(sizeof(u2) * argument_count, CHECK); // argv[argc]2943for (int j = 0; j < argument_count; j++) {2944u2 argument_index = cfs->get_u2_fast();2945check_property(2946valid_cp_range(argument_index, cp_size) &&2947_cp->tag_at(argument_index).is_loadable_constant(),2948"argument_index %u has bad constant type in class file %s",2949argument_index,2950CHECK);2951operands->at_put(operand_fill_index++, argument_index);2952}2953}29542955assert(operand_fill_index == operands->length(), "exact fill");29562957u1* current_end = cfs->current();2958guarantee_property(current_end == current_start + attribute_byte_length,2959"Bad length on BootstrapMethods in class file %s",2960CHECK);2961}29622963void ClassFileParser::parse_classfile_attributes(ClassFileParser::ClassAnnotationCollector* parsed_annotations,2964TRAPS) {2965ClassFileStream* cfs = stream();2966// Set inner classes attribute to default sentinel2967_inner_classes = Universe::the_empty_short_array();2968cfs->guarantee_more(2, CHECK); // attributes_count2969u2 attributes_count = cfs->get_u2_fast();2970bool parsed_sourcefile_attribute = false;2971bool parsed_innerclasses_attribute = false;2972bool parsed_enclosingmethod_attribute = false;2973bool parsed_bootstrap_methods_attribute = false;2974u1* runtime_visible_annotations = NULL;2975int runtime_visible_annotations_length = 0;2976u1* runtime_invisible_annotations = NULL;2977int runtime_invisible_annotations_length = 0;2978u1* runtime_visible_type_annotations = NULL;2979int runtime_visible_type_annotations_length = 0;2980u1* runtime_invisible_type_annotations = NULL;2981int runtime_invisible_type_annotations_length = 0;2982bool runtime_invisible_type_annotations_exists = false;2983u1* inner_classes_attribute_start = NULL;2984u4 inner_classes_attribute_length = 0;2985u2 enclosing_method_class_index = 0;2986u2 enclosing_method_method_index = 0;2987// Iterate over attributes2988while (attributes_count--) {2989cfs->guarantee_more(6, CHECK); // attribute_name_index, attribute_length2990u2 attribute_name_index = cfs->get_u2_fast();2991u4 attribute_length = cfs->get_u4_fast();2992check_property(2993valid_symbol_at(attribute_name_index),2994"Attribute name has bad constant pool index %u in class file %s",2995attribute_name_index, CHECK);2996Symbol* tag = _cp->symbol_at(attribute_name_index);2997if (tag == vmSymbols::tag_source_file()) {2998// Check for SourceFile tag2999if (_need_verify) {3000guarantee_property(attribute_length == 2, "Wrong SourceFile attribute length in class file %s", CHECK);3001}3002if (parsed_sourcefile_attribute) {3003classfile_parse_error("Multiple SourceFile attributes in class file %s", CHECK);3004} else {3005parsed_sourcefile_attribute = true;3006}3007parse_classfile_sourcefile_attribute(CHECK);3008} else if (tag == vmSymbols::tag_source_debug_extension()) {3009// Check for SourceDebugExtension tag3010parse_classfile_source_debug_extension_attribute((int)attribute_length, CHECK);3011} else if (tag == vmSymbols::tag_inner_classes()) {3012// Check for InnerClasses tag3013if (parsed_innerclasses_attribute) {3014classfile_parse_error("Multiple InnerClasses attributes in class file %s", CHECK);3015} else {3016parsed_innerclasses_attribute = true;3017}3018inner_classes_attribute_start = cfs->get_u1_buffer();3019inner_classes_attribute_length = attribute_length;3020cfs->skip_u1(inner_classes_attribute_length, CHECK);3021} else if (tag == vmSymbols::tag_synthetic()) {3022// Check for Synthetic tag3023// Shouldn't we check that the synthetic flags wasn't already set? - not required in spec3024if (attribute_length != 0) {3025classfile_parse_error(3026"Invalid Synthetic classfile attribute length %u in class file %s",3027attribute_length, CHECK);3028}3029parse_classfile_synthetic_attribute(CHECK);3030} else if (tag == vmSymbols::tag_deprecated()) {3031// Check for Deprecatd tag - 42761203032if (attribute_length != 0) {3033classfile_parse_error(3034"Invalid Deprecated classfile attribute length %u in class file %s",3035attribute_length, CHECK);3036}3037} else if (_major_version >= JAVA_1_5_VERSION) {3038if (tag == vmSymbols::tag_signature()) {3039if (attribute_length != 2) {3040classfile_parse_error(3041"Wrong Signature attribute length %u in class file %s",3042attribute_length, CHECK);3043}3044parse_classfile_signature_attribute(CHECK);3045} else if (tag == vmSymbols::tag_runtime_visible_annotations()) {3046runtime_visible_annotations_length = attribute_length;3047runtime_visible_annotations = cfs->get_u1_buffer();3048assert(runtime_visible_annotations != NULL, "null visible annotations");3049cfs->guarantee_more(runtime_visible_annotations_length, CHECK);3050parse_annotations(runtime_visible_annotations,3051runtime_visible_annotations_length,3052parsed_annotations,3053CHECK);3054cfs->skip_u1_fast(runtime_visible_annotations_length);3055} else if (PreserveAllAnnotations && tag == vmSymbols::tag_runtime_invisible_annotations()) {3056runtime_invisible_annotations_length = attribute_length;3057runtime_invisible_annotations = cfs->get_u1_buffer();3058assert(runtime_invisible_annotations != NULL, "null invisible annotations");3059cfs->skip_u1(runtime_invisible_annotations_length, CHECK);3060} else if (tag == vmSymbols::tag_enclosing_method()) {3061if (parsed_enclosingmethod_attribute) {3062classfile_parse_error("Multiple EnclosingMethod attributes in class file %s", CHECK);3063} else {3064parsed_enclosingmethod_attribute = true;3065}3066cfs->guarantee_more(4, CHECK); // class_index, method_index3067enclosing_method_class_index = cfs->get_u2_fast();3068enclosing_method_method_index = cfs->get_u2_fast();3069if (enclosing_method_class_index == 0) {3070classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);3071}3072// Validate the constant pool indices and types3073check_property(valid_klass_reference_at(enclosing_method_class_index),3074"Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);3075if (enclosing_method_method_index != 0 &&3076(!_cp->is_within_bounds(enclosing_method_method_index) ||3077!_cp->tag_at(enclosing_method_method_index).is_name_and_type())) {3078classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);3079}3080} else if (tag == vmSymbols::tag_bootstrap_methods() &&3081_major_version >= Verifier::INVOKEDYNAMIC_MAJOR_VERSION) {3082if (parsed_bootstrap_methods_attribute)3083classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);3084parsed_bootstrap_methods_attribute = true;3085parse_classfile_bootstrap_methods_attribute(attribute_length, CHECK);3086} else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {3087if (runtime_visible_type_annotations != NULL) {3088classfile_parse_error(3089"Multiple RuntimeVisibleTypeAnnotations attributes in class file %s", CHECK);3090}3091runtime_visible_type_annotations_length = attribute_length;3092runtime_visible_type_annotations = cfs->get_u1_buffer();3093assert(runtime_visible_type_annotations != NULL, "null visible type annotations");3094// No need for the VM to parse Type annotations3095cfs->skip_u1(runtime_visible_type_annotations_length, CHECK);3096} else if (tag == vmSymbols::tag_runtime_invisible_type_annotations()) {3097if (runtime_invisible_type_annotations_exists) {3098classfile_parse_error(3099"Multiple RuntimeInvisibleTypeAnnotations attributes in class file %s", CHECK);3100} else {3101runtime_invisible_type_annotations_exists = true;3102}3103if (PreserveAllAnnotations) {3104runtime_invisible_type_annotations_length = attribute_length;3105runtime_invisible_type_annotations = cfs->get_u1_buffer();3106assert(runtime_invisible_type_annotations != NULL, "null invisible type annotations");3107}3108cfs->skip_u1(attribute_length, CHECK);3109} else {3110// Unknown attribute3111cfs->skip_u1(attribute_length, CHECK);3112}3113} else {3114// Unknown attribute3115cfs->skip_u1(attribute_length, CHECK);3116}3117}3118_annotations = assemble_annotations(runtime_visible_annotations,3119runtime_visible_annotations_length,3120runtime_invisible_annotations,3121runtime_invisible_annotations_length,3122CHECK);3123_type_annotations = assemble_annotations(runtime_visible_type_annotations,3124runtime_visible_type_annotations_length,3125runtime_invisible_type_annotations,3126runtime_invisible_type_annotations_length,3127CHECK);31283129if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {3130u2 num_of_classes = parse_classfile_inner_classes_attribute(3131_cp,3132inner_classes_attribute_start,3133parsed_innerclasses_attribute,3134enclosing_method_class_index,3135enclosing_method_method_index,3136CHECK);3137if (parsed_innerclasses_attribute &&_need_verify && _major_version >= JAVA_1_5_VERSION) {3138guarantee_property(3139inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,3140"Wrong InnerClasses attribute length in class file %s", CHECK);3141}3142}31433144if (_max_bootstrap_specifier_index >= 0) {3145guarantee_property(parsed_bootstrap_methods_attribute,3146"Missing BootstrapMethods attribute in class file %s", CHECK);3147}3148}31493150void ClassFileParser::apply_parsed_class_attributes(instanceKlassHandle k) {3151if (_synthetic_flag)3152k->set_is_synthetic();3153if (_sourcefile_index != 0) {3154k->set_source_file_name_index(_sourcefile_index);3155}3156if (_generic_signature_index != 0) {3157k->set_generic_signature_index(_generic_signature_index);3158}3159if (_sde_buffer != NULL) {3160k->set_source_debug_extension(_sde_buffer, _sde_length);3161}3162}31633164// Create the Annotations object that will3165// hold the annotations array for the Klass.3166void ClassFileParser::create_combined_annotations(TRAPS) {3167if (_annotations == NULL &&3168_type_annotations == NULL &&3169_fields_annotations == NULL &&3170_fields_type_annotations == NULL) {3171// Don't create the Annotations object unnecessarily.3172return;3173}31743175Annotations* annotations = Annotations::allocate(_loader_data, CHECK);3176annotations->set_class_annotations(_annotations);3177annotations->set_class_type_annotations(_type_annotations);3178annotations->set_fields_annotations(_fields_annotations);3179annotations->set_fields_type_annotations(_fields_type_annotations);31803181// This is the Annotations object that will be3182// assigned to InstanceKlass being constructed.3183_combined_annotations = annotations;31843185// The annotations arrays below has been transfered the3186// _combined_annotations so these fields can now be cleared.3187_annotations = NULL;3188_type_annotations = NULL;3189_fields_annotations = NULL;3190_fields_type_annotations = NULL;3191}31923193// Transfer ownership of metadata allocated to the InstanceKlass.3194void ClassFileParser::apply_parsed_class_metadata(3195instanceKlassHandle this_klass,3196int java_fields_count, TRAPS) {3197_cp->set_pool_holder(this_klass());3198this_klass->set_constants(_cp);3199this_klass->set_fields(_fields, java_fields_count);3200this_klass->set_methods(_methods);3201this_klass->set_inner_classes(_inner_classes);3202this_klass->set_local_interfaces(_local_interfaces);3203this_klass->set_transitive_interfaces(_transitive_interfaces);3204this_klass->set_annotations(_combined_annotations);32053206// Clear out these fields so they don't get deallocated by the destructor3207clear_class_metadata();3208}32093210AnnotationArray* ClassFileParser::assemble_annotations(u1* runtime_visible_annotations,3211int runtime_visible_annotations_length,3212u1* runtime_invisible_annotations,3213int runtime_invisible_annotations_length, TRAPS) {3214AnnotationArray* annotations = NULL;3215if (runtime_visible_annotations != NULL ||3216runtime_invisible_annotations != NULL) {3217annotations = MetadataFactory::new_array<u1>(_loader_data,3218runtime_visible_annotations_length +3219runtime_invisible_annotations_length,3220CHECK_(annotations));3221if (runtime_visible_annotations != NULL) {3222for (int i = 0; i < runtime_visible_annotations_length; i++) {3223annotations->at_put(i, runtime_visible_annotations[i]);3224}3225}3226if (runtime_invisible_annotations != NULL) {3227for (int i = 0; i < runtime_invisible_annotations_length; i++) {3228int append = runtime_visible_annotations_length+i;3229annotations->at_put(append, runtime_invisible_annotations[i]);3230}3231}3232}3233return annotations;3234}32353236instanceKlassHandle ClassFileParser::parse_super_class(int super_class_index,3237TRAPS) {3238instanceKlassHandle super_klass;3239if (super_class_index == 0) {3240check_property(_class_name == vmSymbols::java_lang_Object(),3241"Invalid superclass index %u in class file %s",3242super_class_index,3243CHECK_NULL);3244} else {3245check_property(valid_klass_reference_at(super_class_index),3246"Invalid superclass index %u in class file %s",3247super_class_index,3248CHECK_NULL);3249// The class name should be legal because it is checked when parsing constant pool.3250// However, make sure it is not an array type.3251bool is_array = false;3252if (_cp->tag_at(super_class_index).is_klass()) {3253super_klass = instanceKlassHandle(THREAD, _cp->resolved_klass_at(super_class_index));3254if (_need_verify)3255is_array = super_klass->oop_is_array();3256} else if (_need_verify) {3257is_array = (_cp->unresolved_klass_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);3258}3259if (_need_verify) {3260guarantee_property(!is_array,3261"Bad superclass name in class file %s", CHECK_NULL);3262}3263}3264return super_klass;3265}326632673268// Values needed for oopmap and InstanceKlass creation3269class FieldLayoutInfo : public StackObj {3270public:3271int* nonstatic_oop_offsets;3272unsigned int* nonstatic_oop_counts;3273unsigned int nonstatic_oop_map_count;3274unsigned int total_oop_map_count;3275int instance_size;3276int nonstatic_field_size;3277int static_field_size;3278bool has_nonstatic_fields;3279};32803281// Layout fields and fill in FieldLayoutInfo. Could use more refactoring!3282void ClassFileParser::layout_fields(Handle class_loader,3283FieldAllocationCount* fac,3284ClassAnnotationCollector* parsed_annotations,3285FieldLayoutInfo* info,3286TRAPS) {32873288// Field size and offset computation3289int nonstatic_field_size = _super_klass() == NULL ? 0 : _super_klass()->nonstatic_field_size();3290int next_static_oop_offset = 0;3291int next_static_double_offset = 0;3292int next_static_word_offset = 0;3293int next_static_short_offset = 0;3294int next_static_byte_offset = 0;3295int next_nonstatic_oop_offset = 0;3296int next_nonstatic_double_offset = 0;3297int next_nonstatic_word_offset = 0;3298int next_nonstatic_short_offset = 0;3299int next_nonstatic_byte_offset = 0;3300int first_nonstatic_oop_offset = 0;3301int next_nonstatic_field_offset = 0;3302int next_nonstatic_padded_offset = 0;33033304// Count the contended fields by type.3305//3306// We ignore static fields, because @Contended is not supported for them.3307// The layout code below will also ignore the static fields.3308int nonstatic_contended_count = 0;3309FieldAllocationCount fac_contended;3310for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {3311FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();3312if (fs.is_contended()) {3313fac_contended.count[atype]++;3314if (!fs.access_flags().is_static()) {3315nonstatic_contended_count++;3316}3317}3318}331933203321// Calculate the starting byte offsets3322next_static_oop_offset = InstanceMirrorKlass::offset_of_static_fields();3323next_static_double_offset = next_static_oop_offset +3324((fac->count[STATIC_OOP]) * heapOopSize);3325if ( fac->count[STATIC_DOUBLE] &&3326(Universe::field_type_should_be_aligned(T_DOUBLE) ||3327Universe::field_type_should_be_aligned(T_LONG)) ) {3328next_static_double_offset = align_size_up(next_static_double_offset, BytesPerLong);3329}33303331next_static_word_offset = next_static_double_offset +3332((fac->count[STATIC_DOUBLE]) * BytesPerLong);3333next_static_short_offset = next_static_word_offset +3334((fac->count[STATIC_WORD]) * BytesPerInt);3335next_static_byte_offset = next_static_short_offset +3336((fac->count[STATIC_SHORT]) * BytesPerShort);33373338int nonstatic_fields_start = instanceOopDesc::base_offset_in_bytes() +3339nonstatic_field_size * heapOopSize;33403341next_nonstatic_field_offset = nonstatic_fields_start;33423343bool is_contended_class = parsed_annotations->is_contended();33443345// Class is contended, pad before all the fields3346if (is_contended_class) {3347next_nonstatic_field_offset += ContendedPaddingWidth;3348}33493350// Compute the non-contended fields count.3351// The packing code below relies on these counts to determine if some field3352// can be squeezed into the alignment gap. Contended fields are obviously3353// exempt from that.3354unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];3355unsigned int nonstatic_word_count = fac->count[NONSTATIC_WORD] - fac_contended.count[NONSTATIC_WORD];3356unsigned int nonstatic_short_count = fac->count[NONSTATIC_SHORT] - fac_contended.count[NONSTATIC_SHORT];3357unsigned int nonstatic_byte_count = fac->count[NONSTATIC_BYTE] - fac_contended.count[NONSTATIC_BYTE];3358unsigned int nonstatic_oop_count = fac->count[NONSTATIC_OOP] - fac_contended.count[NONSTATIC_OOP];33593360// Total non-static fields count, including every contended field3361unsigned int nonstatic_fields_count = fac->count[NONSTATIC_DOUBLE] + fac->count[NONSTATIC_WORD] +3362fac->count[NONSTATIC_SHORT] + fac->count[NONSTATIC_BYTE] +3363fac->count[NONSTATIC_OOP];33643365bool super_has_nonstatic_fields =3366(_super_klass() != NULL && _super_klass->has_nonstatic_fields());3367bool has_nonstatic_fields = super_has_nonstatic_fields || (nonstatic_fields_count != 0);336833693370// Prepare list of oops for oop map generation.3371//3372// "offset" and "count" lists are describing the set of contiguous oop3373// regions. offset[i] is the start of the i-th region, which then has3374// count[i] oops following. Before we know how many regions are required,3375// we pessimistically allocate the maps to fit all the oops into the3376// distinct regions.3377//3378// TODO: We add +1 to always allocate non-zero resource arrays; we need3379// to figure out if we still need to do this.3380int* nonstatic_oop_offsets;3381unsigned int* nonstatic_oop_counts;3382unsigned int nonstatic_oop_map_count = 0;3383unsigned int max_nonstatic_oop_maps = fac->count[NONSTATIC_OOP] + 1;33843385nonstatic_oop_offsets = NEW_RESOURCE_ARRAY_IN_THREAD(3386THREAD, int, max_nonstatic_oop_maps);3387nonstatic_oop_counts = NEW_RESOURCE_ARRAY_IN_THREAD(3388THREAD, unsigned int, max_nonstatic_oop_maps);33893390first_nonstatic_oop_offset = 0; // will be set for first oop field33913392bool compact_fields = CompactFields;3393int allocation_style = FieldsAllocationStyle;3394if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?3395assert(false, "0 <= FieldsAllocationStyle <= 2");3396allocation_style = 1; // Optimistic3397}33983399// The next classes have predefined hard-coded fields offsets3400// (see in JavaClasses::compute_hard_coded_offsets()).3401// Use default fields allocation order for them.3402if( (allocation_style != 0 || compact_fields ) && class_loader.is_null() &&3403(_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||3404_class_name == vmSymbols::java_lang_Class() ||3405_class_name == vmSymbols::java_lang_ClassLoader() ||3406_class_name == vmSymbols::java_lang_ref_Reference() ||3407_class_name == vmSymbols::java_lang_ref_SoftReference() ||3408_class_name == vmSymbols::java_lang_StackTraceElement() ||3409_class_name == vmSymbols::java_lang_String() ||3410_class_name == vmSymbols::java_lang_Throwable() ||3411_class_name == vmSymbols::java_lang_Boolean() ||3412_class_name == vmSymbols::java_lang_Character() ||3413_class_name == vmSymbols::java_lang_Float() ||3414_class_name == vmSymbols::java_lang_Double() ||3415_class_name == vmSymbols::java_lang_Byte() ||3416_class_name == vmSymbols::java_lang_Short() ||3417_class_name == vmSymbols::java_lang_Integer() ||3418_class_name == vmSymbols::java_lang_Long())) {3419allocation_style = 0; // Allocate oops first3420compact_fields = false; // Don't compact fields3421}34223423// Rearrange fields for a given allocation style3424if( allocation_style == 0 ) {3425// Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields3426next_nonstatic_oop_offset = next_nonstatic_field_offset;3427next_nonstatic_double_offset = next_nonstatic_oop_offset +3428(nonstatic_oop_count * heapOopSize);3429} else if( allocation_style == 1 ) {3430// Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields3431next_nonstatic_double_offset = next_nonstatic_field_offset;3432} else if( allocation_style == 2 ) {3433// Fields allocation: oops fields in super and sub classes are together.3434if( nonstatic_field_size > 0 && _super_klass() != NULL &&3435_super_klass->nonstatic_oop_map_size() > 0 ) {3436unsigned int map_count = _super_klass->nonstatic_oop_map_count();3437OopMapBlock* first_map = _super_klass->start_of_nonstatic_oop_maps();3438OopMapBlock* last_map = first_map + map_count - 1;3439int next_offset = last_map->offset() + (last_map->count() * heapOopSize);3440if (next_offset == next_nonstatic_field_offset) {3441allocation_style = 0; // allocate oops first3442next_nonstatic_oop_offset = next_nonstatic_field_offset;3443next_nonstatic_double_offset = next_nonstatic_oop_offset +3444(nonstatic_oop_count * heapOopSize);3445}3446}3447if( allocation_style == 2 ) {3448allocation_style = 1; // allocate oops last3449next_nonstatic_double_offset = next_nonstatic_field_offset;3450}3451} else {3452ShouldNotReachHere();3453}34543455int nonstatic_oop_space_count = 0;3456int nonstatic_word_space_count = 0;3457int nonstatic_short_space_count = 0;3458int nonstatic_byte_space_count = 0;3459int nonstatic_oop_space_offset = 0;3460int nonstatic_word_space_offset = 0;3461int nonstatic_short_space_offset = 0;3462int nonstatic_byte_space_offset = 0;34633464// Try to squeeze some of the fields into the gaps due to3465// long/double alignment.3466if( nonstatic_double_count > 0 ) {3467int offset = next_nonstatic_double_offset;3468next_nonstatic_double_offset = align_size_up(offset, BytesPerLong);3469if( compact_fields && offset != next_nonstatic_double_offset ) {3470// Allocate available fields into the gap before double field.3471int length = next_nonstatic_double_offset - offset;3472assert(length == BytesPerInt, "");3473nonstatic_word_space_offset = offset;3474if( nonstatic_word_count > 0 ) {3475nonstatic_word_count -= 1;3476nonstatic_word_space_count = 1; // Only one will fit3477length -= BytesPerInt;3478offset += BytesPerInt;3479}3480nonstatic_short_space_offset = offset;3481while( length >= BytesPerShort && nonstatic_short_count > 0 ) {3482nonstatic_short_count -= 1;3483nonstatic_short_space_count += 1;3484length -= BytesPerShort;3485offset += BytesPerShort;3486}3487nonstatic_byte_space_offset = offset;3488while( length > 0 && nonstatic_byte_count > 0 ) {3489nonstatic_byte_count -= 1;3490nonstatic_byte_space_count += 1;3491length -= 1;3492}3493// Allocate oop field in the gap if there are no other fields for that.3494nonstatic_oop_space_offset = offset;3495if( length >= heapOopSize && nonstatic_oop_count > 0 &&3496allocation_style != 0 ) { // when oop fields not first3497nonstatic_oop_count -= 1;3498nonstatic_oop_space_count = 1; // Only one will fit3499length -= heapOopSize;3500offset += heapOopSize;3501}3502}3503}35043505next_nonstatic_word_offset = next_nonstatic_double_offset +3506(nonstatic_double_count * BytesPerLong);3507next_nonstatic_short_offset = next_nonstatic_word_offset +3508(nonstatic_word_count * BytesPerInt);3509next_nonstatic_byte_offset = next_nonstatic_short_offset +3510(nonstatic_short_count * BytesPerShort);3511next_nonstatic_padded_offset = next_nonstatic_byte_offset +3512nonstatic_byte_count;35133514// let oops jump before padding with this allocation style3515if( allocation_style == 1 ) {3516next_nonstatic_oop_offset = next_nonstatic_padded_offset;3517if( nonstatic_oop_count > 0 ) {3518next_nonstatic_oop_offset = align_size_up(next_nonstatic_oop_offset, heapOopSize);3519}3520next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);3521}35223523// Iterate over fields again and compute correct offsets.3524// The field allocation type was temporarily stored in the offset slot.3525// oop fields are located before non-oop fields (static and non-static).3526for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {35273528// skip already laid out fields3529if (fs.is_offset_set()) continue;35303531// contended instance fields are handled below3532if (fs.is_contended() && !fs.access_flags().is_static()) continue;35333534int real_offset = 0;3535FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();35363537// pack the rest of the fields3538switch (atype) {3539case STATIC_OOP:3540real_offset = next_static_oop_offset;3541next_static_oop_offset += heapOopSize;3542break;3543case STATIC_BYTE:3544real_offset = next_static_byte_offset;3545next_static_byte_offset += 1;3546break;3547case STATIC_SHORT:3548real_offset = next_static_short_offset;3549next_static_short_offset += BytesPerShort;3550break;3551case STATIC_WORD:3552real_offset = next_static_word_offset;3553next_static_word_offset += BytesPerInt;3554break;3555case STATIC_DOUBLE:3556real_offset = next_static_double_offset;3557next_static_double_offset += BytesPerLong;3558break;3559case NONSTATIC_OOP:3560if( nonstatic_oop_space_count > 0 ) {3561real_offset = nonstatic_oop_space_offset;3562nonstatic_oop_space_offset += heapOopSize;3563nonstatic_oop_space_count -= 1;3564} else {3565real_offset = next_nonstatic_oop_offset;3566next_nonstatic_oop_offset += heapOopSize;3567}3568// Update oop maps3569if( nonstatic_oop_map_count > 0 &&3570nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==3571real_offset -3572int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *3573heapOopSize ) {3574// Extend current oop map3575assert(nonstatic_oop_map_count - 1 < max_nonstatic_oop_maps, "range check");3576nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;3577} else {3578// Create new oop map3579assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");3580nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;3581nonstatic_oop_counts [nonstatic_oop_map_count] = 1;3582nonstatic_oop_map_count += 1;3583if( first_nonstatic_oop_offset == 0 ) { // Undefined3584first_nonstatic_oop_offset = real_offset;3585}3586}3587break;3588case NONSTATIC_BYTE:3589if( nonstatic_byte_space_count > 0 ) {3590real_offset = nonstatic_byte_space_offset;3591nonstatic_byte_space_offset += 1;3592nonstatic_byte_space_count -= 1;3593} else {3594real_offset = next_nonstatic_byte_offset;3595next_nonstatic_byte_offset += 1;3596}3597break;3598case NONSTATIC_SHORT:3599if( nonstatic_short_space_count > 0 ) {3600real_offset = nonstatic_short_space_offset;3601nonstatic_short_space_offset += BytesPerShort;3602nonstatic_short_space_count -= 1;3603} else {3604real_offset = next_nonstatic_short_offset;3605next_nonstatic_short_offset += BytesPerShort;3606}3607break;3608case NONSTATIC_WORD:3609if( nonstatic_word_space_count > 0 ) {3610real_offset = nonstatic_word_space_offset;3611nonstatic_word_space_offset += BytesPerInt;3612nonstatic_word_space_count -= 1;3613} else {3614real_offset = next_nonstatic_word_offset;3615next_nonstatic_word_offset += BytesPerInt;3616}3617break;3618case NONSTATIC_DOUBLE:3619real_offset = next_nonstatic_double_offset;3620next_nonstatic_double_offset += BytesPerLong;3621break;3622default:3623ShouldNotReachHere();3624}3625fs.set_offset(real_offset);3626}362736283629// Handle the contended cases.3630//3631// Each contended field should not intersect the cache line with another contended field.3632// In the absence of alignment information, we end up with pessimistically separating3633// the fields with full-width padding.3634//3635// Additionally, this should not break alignment for the fields, so we round the alignment up3636// for each field.3637if (nonstatic_contended_count > 0) {36383639// if there is at least one contended field, we need to have pre-padding for them3640next_nonstatic_padded_offset += ContendedPaddingWidth;36413642// collect all contended groups3643BitMap bm(_cp->size());3644for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {3645// skip already laid out fields3646if (fs.is_offset_set()) continue;36473648if (fs.is_contended()) {3649bm.set_bit(fs.contended_group());3650}3651}36523653int current_group = -1;3654while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {36553656for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {36573658// skip already laid out fields3659if (fs.is_offset_set()) continue;36603661// skip non-contended fields and fields from different group3662if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;36633664// handle statics below3665if (fs.access_flags().is_static()) continue;36663667int real_offset = 0;3668FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();36693670switch (atype) {3671case NONSTATIC_BYTE:3672next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, 1);3673real_offset = next_nonstatic_padded_offset;3674next_nonstatic_padded_offset += 1;3675break;36763677case NONSTATIC_SHORT:3678next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerShort);3679real_offset = next_nonstatic_padded_offset;3680next_nonstatic_padded_offset += BytesPerShort;3681break;36823683case NONSTATIC_WORD:3684next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerInt);3685real_offset = next_nonstatic_padded_offset;3686next_nonstatic_padded_offset += BytesPerInt;3687break;36883689case NONSTATIC_DOUBLE:3690next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerLong);3691real_offset = next_nonstatic_padded_offset;3692next_nonstatic_padded_offset += BytesPerLong;3693break;36943695case NONSTATIC_OOP:3696next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, heapOopSize);3697real_offset = next_nonstatic_padded_offset;3698next_nonstatic_padded_offset += heapOopSize;36993700// Create new oop map3701assert(nonstatic_oop_map_count < max_nonstatic_oop_maps, "range check");3702nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;3703nonstatic_oop_counts [nonstatic_oop_map_count] = 1;3704nonstatic_oop_map_count += 1;3705if( first_nonstatic_oop_offset == 0 ) { // Undefined3706first_nonstatic_oop_offset = real_offset;3707}3708break;37093710default:3711ShouldNotReachHere();3712}37133714if (fs.contended_group() == 0) {3715// Contended group defines the equivalence class over the fields:3716// the fields within the same contended group are not inter-padded.3717// The only exception is default group, which does not incur the3718// equivalence, and so requires intra-padding.3719next_nonstatic_padded_offset += ContendedPaddingWidth;3720}37213722fs.set_offset(real_offset);3723} // for37243725// Start laying out the next group.3726// Note that this will effectively pad the last group in the back;3727// this is expected to alleviate memory contention effects for3728// subclass fields and/or adjacent object.3729// If this was the default group, the padding is already in place.3730if (current_group != 0) {3731next_nonstatic_padded_offset += ContendedPaddingWidth;3732}3733}37343735// handle static fields3736}37373738// Entire class is contended, pad in the back.3739// This helps to alleviate memory contention effects for subclass fields3740// and/or adjacent object.3741if (is_contended_class) {3742next_nonstatic_padded_offset += ContendedPaddingWidth;3743}37443745int notaligned_nonstatic_fields_end = next_nonstatic_padded_offset;37463747int nonstatic_fields_end = align_size_up(notaligned_nonstatic_fields_end, heapOopSize);3748int instance_end = align_size_up(notaligned_nonstatic_fields_end, wordSize);3749int static_fields_end = align_size_up(next_static_byte_offset, wordSize);37503751int static_field_size = (static_fields_end -3752InstanceMirrorKlass::offset_of_static_fields()) / wordSize;3753nonstatic_field_size = nonstatic_field_size +3754(nonstatic_fields_end - nonstatic_fields_start) / heapOopSize;37553756int instance_size = align_object_size(instance_end / wordSize);37573758assert(instance_size == align_object_size(align_size_up(3759(instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize),3760wordSize) / wordSize), "consistent layout helper value");37613762// Invariant: nonstatic_field end/start should only change if there are3763// nonstatic fields in the class, or if the class is contended. We compare3764// against the non-aligned value, so that end alignment will not fail the3765// assert without actually having the fields.3766assert((notaligned_nonstatic_fields_end == nonstatic_fields_start) ||3767is_contended_class ||3768(nonstatic_fields_count > 0), "double-check nonstatic start/end");37693770// Number of non-static oop map blocks allocated at end of klass.3771const unsigned int total_oop_map_count =3772compute_oop_map_count(_super_klass, nonstatic_oop_map_count,3773first_nonstatic_oop_offset);37743775#ifndef PRODUCT3776if (PrintFieldLayout) {3777print_field_layout(_class_name,3778_fields,3779_cp,3780instance_size,3781nonstatic_fields_start,3782nonstatic_fields_end,3783static_fields_end);3784}37853786#endif3787// Pass back information needed for InstanceKlass creation3788info->nonstatic_oop_offsets = nonstatic_oop_offsets;3789info->nonstatic_oop_counts = nonstatic_oop_counts;3790info->nonstatic_oop_map_count = nonstatic_oop_map_count;3791info->total_oop_map_count = total_oop_map_count;3792info->instance_size = instance_size;3793info->static_field_size = static_field_size;3794info->nonstatic_field_size = nonstatic_field_size;3795info->has_nonstatic_fields = has_nonstatic_fields;3796}37973798static bool relax_format_check_for(ClassLoaderData* loader_data) {3799bool trusted = (loader_data->is_the_null_class_loader_data() ||3800SystemDictionary::is_ext_class_loader(loader_data->class_loader()));3801bool need_verify =3802// verifyAll3803(BytecodeVerificationLocal && BytecodeVerificationRemote) ||3804// verifyRemote3805(!BytecodeVerificationLocal && BytecodeVerificationRemote && !trusted);3806return !need_verify;3807}38083809instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name,3810ClassLoaderData* loader_data,3811Handle protection_domain,3812KlassHandle host_klass,3813GrowableArray<Handle>* cp_patches,3814TempNewSymbol& parsed_name,3815bool verify,3816TRAPS) {38173818// When a retransformable agent is attached, JVMTI caches the3819// class bytes that existed before the first retransformation.3820// If RedefineClasses() was used before the retransformable3821// agent attached, then the cached class bytes may not be the3822// original class bytes.3823JvmtiCachedClassFileData *cached_class_file = NULL;3824Handle class_loader(THREAD, loader_data->class_loader());3825bool has_default_methods = false;3826bool declares_default_methods = false;3827// JDK-8252904:3828// The stream (resource) attached to the instance klass may3829// be reallocated by this method. When JFR is included the3830// stream may need to survive beyond the end of the call. So,3831// the caller is expected to declare the ResourceMark that3832// determines the lifetime of resources allocated under this3833// call.38343835ClassFileStream* cfs = stream();3836// Timing3837assert(THREAD->is_Java_thread(), "must be a JavaThread");3838JavaThread* jt = (JavaThread*) THREAD;38393840PerfClassTraceTime ctimer(ClassLoader::perf_class_parse_time(),3841ClassLoader::perf_class_parse_selftime(),3842NULL,3843jt->get_thread_stat()->perf_recursion_counts_addr(),3844jt->get_thread_stat()->perf_timers_addr(),3845PerfClassTraceTime::PARSE_CLASS);38463847init_parsed_class_attributes(loader_data);38483849if (JvmtiExport::should_post_class_file_load_hook()) {3850// Get the cached class file bytes (if any) from the class that3851// is being redefined or retransformed. We use jvmti_thread_state()3852// instead of JvmtiThreadState::state_for(jt) so we don't allocate3853// a JvmtiThreadState any earlier than necessary. This will help3854// avoid the bug described by 7126851.3855JvmtiThreadState *state = jt->jvmti_thread_state();3856if (state != NULL) {3857KlassHandle *h_class_being_redefined =3858state->get_class_being_redefined();3859if (h_class_being_redefined != NULL) {3860instanceKlassHandle ikh_class_being_redefined =3861instanceKlassHandle(THREAD, (*h_class_being_redefined)());3862cached_class_file = ikh_class_being_redefined->get_cached_class_file();3863}3864}38653866unsigned char* ptr = cfs->buffer();3867unsigned char* end_ptr = cfs->buffer() + cfs->length();38683869JvmtiExport::post_class_file_load_hook(name, class_loader(), protection_domain,3870&ptr, &end_ptr, &cached_class_file);38713872if (ptr != cfs->buffer()) {3873// JVMTI agent has modified class file data.3874// Set new class file stream using JVMTI agent modified3875// class file data.3876cfs = new ClassFileStream(ptr, end_ptr - ptr, cfs->source());3877set_stream(cfs);3878}3879}38803881_host_klass = host_klass;3882_cp_patches = cp_patches;38833884instanceKlassHandle nullHandle;38853886// Figure out whether we can skip format checking (matching classic VM behavior)3887if (DumpSharedSpaces) {3888// verify == true means it's a 'remote' class (i.e., non-boot class)3889// Verification decision is based on BytecodeVerificationRemote flag3890// for those classes.3891_need_verify = (verify) ? BytecodeVerificationRemote :3892BytecodeVerificationLocal;3893} else {3894_need_verify = Verifier::should_verify_for(class_loader(), verify);3895}38963897// Set the verify flag in stream3898cfs->set_verify(_need_verify);38993900// Save the class file name for easier error message printing.3901_class_name = (name != NULL) ? name : vmSymbols::unknown_class_name();39023903cfs->guarantee_more(8, CHECK_(nullHandle)); // magic, major, minor3904// Magic value3905u4 magic = cfs->get_u4_fast();3906guarantee_property(magic == JAVA_CLASSFILE_MAGIC,3907"Incompatible magic value %u in class file %s",3908magic, CHECK_(nullHandle));39093910// Version numbers3911u2 minor_version = cfs->get_u2_fast();3912u2 major_version = cfs->get_u2_fast();39133914if (DumpSharedSpaces && major_version < JAVA_1_5_VERSION) {3915ResourceMark rm;3916warning("Pre JDK 1.5 class not supported by CDS: %u.%u %s",3917major_version, minor_version, name->as_C_string());3918Exceptions::fthrow(3919THREAD_AND_LOCATION,3920vmSymbols::java_lang_UnsupportedClassVersionError(),3921"Unsupported major.minor version for dump time %u.%u",3922major_version,3923minor_version);3924}39253926// Check version numbers - we check this even with verifier off3927if (!is_supported_version(major_version, minor_version)) {3928if (name == NULL) {3929Exceptions::fthrow(3930THREAD_AND_LOCATION,3931vmSymbols::java_lang_UnsupportedClassVersionError(),3932"Unsupported class file version %u.%u, "3933"this version of the Java Runtime only recognizes class file versions up to %u.%u",3934major_version,3935minor_version,3936JAVA_MAX_SUPPORTED_VERSION,3937JAVA_MAX_SUPPORTED_MINOR_VERSION);3938} else {3939ResourceMark rm(THREAD);3940Exceptions::fthrow(3941THREAD_AND_LOCATION,3942vmSymbols::java_lang_UnsupportedClassVersionError(),3943"%s has been compiled by a more recent version of the Java Runtime (class file version %u.%u), "3944"this version of the Java Runtime only recognizes class file versions up to %u.%u",3945name->as_C_string(),3946major_version,3947minor_version,3948JAVA_MAX_SUPPORTED_VERSION,3949JAVA_MAX_SUPPORTED_MINOR_VERSION);3950}3951return nullHandle;3952}39533954_major_version = major_version;3955_minor_version = minor_version;395639573958// Check if verification needs to be relaxed for this class file3959// Do not restrict it to jdk1.0 or jdk1.1 to maintain backward compatibility (4982376)3960_relax_verify = relax_format_check_for(_loader_data);39613962// Constant pool3963constantPoolHandle cp = parse_constant_pool(CHECK_(nullHandle));39643965int cp_size = cp->length();39663967cfs->guarantee_more(8, CHECK_(nullHandle)); // flags, this_class, super_class, infs_len39683969// Access flags3970AccessFlags access_flags;3971jint flags = cfs->get_u2_fast() & JVM_RECOGNIZED_CLASS_MODIFIERS;39723973if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) {3974// Set abstract bit for old class files for backward compatibility3975flags |= JVM_ACC_ABSTRACT;3976}3977verify_legal_class_modifiers(flags, CHECK_(nullHandle));3978access_flags.set_flags(flags);39793980// This class and superclass3981_this_class_index = cfs->get_u2_fast();3982check_property(3983valid_cp_range(_this_class_index, cp_size) &&3984cp->tag_at(_this_class_index).is_unresolved_klass(),3985"Invalid this class index %u in constant pool in class file %s",3986_this_class_index, CHECK_(nullHandle));39873988Symbol* class_name = cp->unresolved_klass_at(_this_class_index);3989assert(class_name != NULL, "class_name can't be null");39903991// It's important to set parsed_name *before* resolving the super class.3992// (it's used for cleanup by the caller if parsing fails)3993parsed_name = class_name;3994// parsed_name is returned and can be used if there's an error, so add to3995// its reference count. Caller will decrement the refcount.3996parsed_name->increment_refcount();39973998// Update _class_name which could be null previously to be class_name3999_class_name = class_name;40004001// Don't need to check whether this class name is legal or not.4002// It has been checked when constant pool is parsed.4003// However, make sure it is not an array type.4004if (_need_verify) {4005guarantee_property(class_name->byte_at(0) != JVM_SIGNATURE_ARRAY,4006"Bad class name in class file %s",4007CHECK_(nullHandle));4008}40094010Klass* preserve_this_klass; // for storing result across HandleMark40114012// release all handles when parsing is done4013{ HandleMark hm(THREAD);40144015// Checks if name in class file matches requested name4016if (name != NULL && class_name != name) {4017ResourceMark rm(THREAD);4018Exceptions::fthrow(4019THREAD_AND_LOCATION,4020vmSymbols::java_lang_NoClassDefFoundError(),4021"%s (wrong name: %s)",4022name->as_C_string(),4023class_name->as_C_string()4024);4025return nullHandle;4026}40274028if (TraceClassLoadingPreorder) {4029tty->print("[Loading %s", (name != NULL) ? name->as_klass_external_name() : "NoName");4030if (cfs->source() != NULL) tty->print(" from %s", cfs->source());4031tty->print_cr("]");4032}4033#if INCLUDE_CDS4034if (DumpLoadedClassList != NULL && cfs->source() != NULL && classlist_file->is_open()) {4035// Only dump the classes that can be stored into CDS archive4036if (SystemDictionaryShared::is_sharing_possible(loader_data)) {4037if (name != NULL) {4038ResourceMark rm(THREAD);4039classlist_file->print_cr("%s", name->as_C_string());4040classlist_file->flush();4041}4042}4043}4044#endif40454046u2 super_class_index = cfs->get_u2_fast();4047instanceKlassHandle super_klass = parse_super_class(super_class_index,4048CHECK_NULL);40494050// Interfaces4051u2 itfs_len = cfs->get_u2_fast();4052Array<Klass*>* local_interfaces =4053parse_interfaces(itfs_len, protection_domain, _class_name,4054&has_default_methods, CHECK_(nullHandle));40554056u2 java_fields_count = 0;4057// Fields (offsets are filled in later)4058FieldAllocationCount fac;4059Array<u2>* fields = parse_fields(class_name,4060access_flags.is_interface(),4061&fac, &java_fields_count,4062CHECK_(nullHandle));4063// Methods4064bool has_final_method = false;4065AccessFlags promoted_flags;4066promoted_flags.set_flags(0);4067Array<Method*>* methods = parse_methods(access_flags.is_interface(),4068&promoted_flags,4069&has_final_method,4070&declares_default_methods,4071CHECK_(nullHandle));4072if (declares_default_methods) {4073has_default_methods = true;4074}40754076// Additional attributes4077ClassAnnotationCollector parsed_annotations;4078parse_classfile_attributes(&parsed_annotations, CHECK_(nullHandle));40794080// Finalize the Annotations metadata object,4081// now that all annotation arrays have been created.4082create_combined_annotations(CHECK_(nullHandle));40834084// Make sure this is the end of class file stream4085guarantee_property(cfs->at_eos(), "Extra bytes at the end of class file %s", CHECK_(nullHandle));40864087if (_class_name == vmSymbols::java_lang_Object()) {4088check_property(_local_interfaces == Universe::the_empty_klass_array(),4089"java.lang.Object cannot implement an interface in class file %s",4090CHECK_(nullHandle));4091}4092// We check super class after class file is parsed and format is checked4093if (super_class_index > 0 && super_klass.is_null()) {4094Symbol* sk = cp->klass_name_at(super_class_index);4095if (access_flags.is_interface()) {4096// Before attempting to resolve the superclass, check for class format4097// errors not checked yet.4098guarantee_property(sk == vmSymbols::java_lang_Object(),4099"Interfaces must have java.lang.Object as superclass in class file %s",4100CHECK_(nullHandle));4101}4102Klass* k = SystemDictionary::resolve_super_or_fail(class_name, sk,4103class_loader,4104protection_domain,4105true,4106CHECK_(nullHandle));41074108KlassHandle kh (THREAD, k);4109super_klass = instanceKlassHandle(THREAD, kh());4110}4111if (super_klass.not_null()) {41124113if (super_klass->has_default_methods()) {4114has_default_methods = true;4115}41164117if (super_klass->is_interface()) {4118ResourceMark rm(THREAD);4119Exceptions::fthrow(4120THREAD_AND_LOCATION,4121vmSymbols::java_lang_IncompatibleClassChangeError(),4122"class %s has interface %s as super class",4123class_name->as_klass_external_name(),4124super_klass->external_name()4125);4126return nullHandle;4127}4128// Make sure super class is not final4129if (super_klass->is_final()) {4130THROW_MSG_(vmSymbols::java_lang_VerifyError(), "Cannot inherit from final class", nullHandle);4131}4132}41334134// save super klass for error handling.4135_super_klass = super_klass;41364137// Compute the transitive list of all unique interfaces implemented by this class4138_transitive_interfaces =4139compute_transitive_interfaces(super_klass, local_interfaces, CHECK_(nullHandle));41404141// sort methods4142intArray* method_ordering = sort_methods(methods);41434144// promote flags from parse_methods() to the klass' flags4145access_flags.add_promoted_flags(promoted_flags.as_int());41464147// Size of Java vtable (in words)4148int vtable_size = 0;4149int itable_size = 0;4150int num_miranda_methods = 0;41514152GrowableArray<Method*> all_mirandas(20);41534154klassVtable::compute_vtable_size_and_num_mirandas(4155&vtable_size, &num_miranda_methods, &all_mirandas, super_klass(), methods,4156access_flags, class_loader, class_name, local_interfaces,4157CHECK_(nullHandle));41584159// Size of Java itable (in words)4160itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(_transitive_interfaces);41614162FieldLayoutInfo info;4163layout_fields(class_loader, &fac, &parsed_annotations, &info, CHECK_NULL);41644165int total_oop_map_size2 =4166InstanceKlass::nonstatic_oop_map_size(info.total_oop_map_count);41674168// Compute reference type4169ReferenceType rt;4170if (super_klass() == NULL) {4171rt = REF_NONE;4172} else {4173rt = super_klass->reference_type();4174}41754176// We can now create the basic Klass* for this klass4177_klass = InstanceKlass::allocate_instance_klass(loader_data,4178vtable_size,4179itable_size,4180info.static_field_size,4181total_oop_map_size2,4182rt,4183access_flags,4184name,4185super_klass(),4186!host_klass.is_null(),4187CHECK_(nullHandle));4188instanceKlassHandle this_klass (THREAD, _klass);41894190assert(this_klass->static_field_size() == info.static_field_size, "sanity");4191assert(this_klass->nonstatic_oop_map_count() == info.total_oop_map_count,4192"sanity");41934194// Fill in information already parsed4195this_klass->set_should_verify_class(verify);4196jint lh = Klass::instance_layout_helper(info.instance_size, false);4197this_klass->set_layout_helper(lh);4198assert(this_klass->oop_is_instance(), "layout is correct");4199assert(this_klass->size_helper() == info.instance_size, "correct size_helper");4200// Not yet: supers are done below to support the new subtype-checking fields4201//this_klass->set_super(super_klass());4202this_klass->set_class_loader_data(loader_data);4203this_klass->set_nonstatic_field_size(info.nonstatic_field_size);4204this_klass->set_has_nonstatic_fields(info.has_nonstatic_fields);4205this_klass->set_static_oop_field_count(fac.count[STATIC_OOP]);42064207apply_parsed_class_metadata(this_klass, java_fields_count, CHECK_NULL);42084209if (has_final_method) {4210this_klass->set_has_final_method();4211}4212this_klass->copy_method_ordering(method_ordering, CHECK_NULL);4213// The InstanceKlass::_methods_jmethod_ids cache4214// is managed on the assumption that the initial cache4215// size is equal to the number of methods in the class. If4216// that changes, then InstanceKlass::idnum_can_increment()4217// has to be changed accordingly.4218this_klass->set_initial_method_idnum(methods->length());4219this_klass->set_name(cp->klass_name_at(_this_class_index));4220if (is_anonymous()) // I am well known to myself4221cp->klass_at_put(_this_class_index, this_klass()); // eagerly resolve42224223this_klass->set_minor_version(minor_version);4224this_klass->set_major_version(major_version);4225this_klass->set_has_default_methods(has_default_methods);4226this_klass->set_declares_default_methods(declares_default_methods);42274228if (!host_klass.is_null()) {4229assert (this_klass->is_anonymous(), "should be the same");4230this_klass->set_host_klass(host_klass());4231}42324233// Set up Method*::intrinsic_id as soon as we know the names of methods.4234// (We used to do this lazily, but now we query it in Rewriter,4235// which is eagerly done for every method, so we might as well do it now,4236// when everything is fresh in memory.)4237if (Method::klass_id_for_intrinsics(this_klass()) != vmSymbols::NO_SID) {4238for (int j = 0; j < methods->length(); j++) {4239methods->at(j)->init_intrinsic_id();4240}4241}42424243if (cached_class_file != NULL) {4244// JVMTI: we have an InstanceKlass now, tell it about the cached bytes4245this_klass->set_cached_class_file(cached_class_file);4246}42474248// Fill in field values obtained by parse_classfile_attributes4249if (parsed_annotations.has_any_annotations())4250parsed_annotations.apply_to(this_klass);4251apply_parsed_class_attributes(this_klass);42524253// Miranda methods4254if ((num_miranda_methods > 0) ||4255// if this class introduced new miranda methods or4256(super_klass.not_null() && (super_klass->has_miranda_methods()))4257// super class exists and this class inherited miranda methods4258) {4259this_klass->set_has_miranda_methods(); // then set a flag4260}42614262// Fill in information needed to compute superclasses.4263this_klass->initialize_supers(super_klass(), CHECK_(nullHandle));42644265// Initialize itable offset tables4266klassItable::setup_itable_offset_table(this_klass);42674268// Compute transitive closure of interfaces this class implements4269// Do final class setup4270fill_oop_maps(this_klass, info.nonstatic_oop_map_count, info.nonstatic_oop_offsets, info.nonstatic_oop_counts);42714272// Fill in has_finalizer, has_vanilla_constructor, and layout_helper4273set_precomputed_flags(this_klass);42744275// reinitialize modifiers, using the InnerClasses attribute4276int computed_modifiers = this_klass->compute_modifier_flags(CHECK_(nullHandle));4277this_klass->set_modifier_flags(computed_modifiers);42784279// check if this class can access its super class4280check_super_class_access(this_klass, CHECK_(nullHandle));42814282// check if this class can access its superinterfaces4283check_super_interface_access(this_klass, CHECK_(nullHandle));42844285// check if this class overrides any final method4286check_final_method_override(this_klass, CHECK_(nullHandle));42874288// check that if this class is an interface then it doesn't have static methods4289if (this_klass->is_interface()) {4290/* An interface in a JAVA 8 classfile can be static */4291if (_major_version < JAVA_8_VERSION) {4292check_illegal_static_method(this_klass, CHECK_(nullHandle));4293}4294}42954296// Allocate mirror and initialize static fields4297java_lang_Class::create_mirror(this_klass, class_loader, protection_domain,4298CHECK_(nullHandle));42994300// Generate any default methods - default methods are interface methods4301// that have a default implementation. This is new with Lambda project.4302if (has_default_methods ) {4303DefaultMethods::generate_default_methods(4304this_klass(), &all_mirandas, CHECK_(nullHandle));4305}43064307ClassLoadingService::notify_class_loaded(InstanceKlass::cast(this_klass()),4308false /* not shared class */);43094310if (TraceClassLoading) {4311ResourceMark rm;4312// print in a single call to reduce interleaving of output4313if (cfs->source() != NULL) {4314tty->print("[Loaded %s from %s]\n", this_klass->external_name(),4315cfs->source());4316} else if (class_loader.is_null()) {4317Klass* caller =4318THREAD->is_Java_thread()4319? ((JavaThread*)THREAD)->security_get_caller_class(1)4320: NULL;4321// caller can be NULL, for example, during a JVMTI VM_Init hook4322if (caller != NULL) {4323tty->print("[Loaded %s by instance of %s]\n",4324this_klass->external_name(),4325InstanceKlass::cast(caller)->external_name());4326} else {4327tty->print("[Loaded %s]\n", this_klass->external_name());4328}4329} else {4330tty->print("[Loaded %s from %s]\n", this_klass->external_name(),4331InstanceKlass::cast(class_loader->klass())->external_name());4332}4333}43344335if (TraceClassResolution) {4336ResourceMark rm;4337// print out the superclass.4338const char * from = this_klass()->external_name();4339if (this_klass->java_super() != NULL) {4340tty->print("RESOLVE %s %s (super)\n", from, InstanceKlass::cast(this_klass->java_super())->external_name());4341}4342// print out each of the interface classes referred to by this class.4343Array<Klass*>* local_interfaces = this_klass->local_interfaces();4344if (local_interfaces != NULL) {4345int length = local_interfaces->length();4346for (int i = 0; i < length; i++) {4347Klass* k = local_interfaces->at(i);4348InstanceKlass* to_class = InstanceKlass::cast(k);4349const char * to = to_class->external_name();4350tty->print("RESOLVE %s %s (interface)\n", from, to);4351}4352}4353}43544355// preserve result across HandleMark4356preserve_this_klass = this_klass();4357}43584359JFR_ONLY(INIT_ID(preserve_this_klass);)43604361// Create new handle outside HandleMark (might be needed for4362// Extended Class Redefinition)4363instanceKlassHandle this_klass (THREAD, preserve_this_klass);4364debug_only(this_klass->verify();)43654366// Clear class if no error has occurred so destructor doesn't deallocate it4367_klass = NULL;4368return this_klass;4369}43704371// Destructor to clean up if there's an error4372ClassFileParser::~ClassFileParser() {4373MetadataFactory::free_metadata(_loader_data, _cp);4374MetadataFactory::free_array<u2>(_loader_data, _fields);43754376// Free methods4377InstanceKlass::deallocate_methods(_loader_data, _methods);43784379// beware of the Universe::empty_blah_array!!4380if (_inner_classes != Universe::the_empty_short_array()) {4381MetadataFactory::free_array<u2>(_loader_data, _inner_classes);4382}43834384// Free interfaces4385InstanceKlass::deallocate_interfaces(_loader_data, _super_klass(),4386_local_interfaces, _transitive_interfaces);43874388if (_combined_annotations != NULL) {4389// After all annotations arrays have been created, they are installed into the4390// Annotations object that will be assigned to the InstanceKlass being created.43914392// Deallocate the Annotations object and the installed annotations arrays.4393_combined_annotations->deallocate_contents(_loader_data);43944395// If the _combined_annotations pointer is non-NULL,4396// then the other annotations fields should have been cleared.4397assert(_annotations == NULL, "Should have been cleared");4398assert(_type_annotations == NULL, "Should have been cleared");4399assert(_fields_annotations == NULL, "Should have been cleared");4400assert(_fields_type_annotations == NULL, "Should have been cleared");4401} else {4402// If the annotations arrays were not installed into the Annotations object,4403// then they have to be deallocated explicitly.4404MetadataFactory::free_array<u1>(_loader_data, _annotations);4405MetadataFactory::free_array<u1>(_loader_data, _type_annotations);4406Annotations::free_contents(_loader_data, _fields_annotations);4407Annotations::free_contents(_loader_data, _fields_type_annotations);4408}44094410clear_class_metadata();44114412// deallocate the klass if already created. Don't directly deallocate, but add4413// to the deallocate list so that the klass is removed from the CLD::_klasses list4414// at a safepoint.4415if (_klass != NULL) {4416_loader_data->add_to_deallocate_list(_klass);4417}4418_klass = NULL;4419}44204421void ClassFileParser::print_field_layout(Symbol* name,4422Array<u2>* fields,4423constantPoolHandle cp,4424int instance_size,4425int instance_fields_start,4426int instance_fields_end,4427int static_fields_end) {4428tty->print("%s: field layout\n", name->as_klass_external_name());4429tty->print(" @%3d %s\n", instance_fields_start, "--- instance fields start ---");4430for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {4431if (!fs.access_flags().is_static()) {4432tty->print(" @%3d \"%s\" %s\n",4433fs.offset(),4434fs.name()->as_klass_external_name(),4435fs.signature()->as_klass_external_name());4436}4437}4438tty->print(" @%3d %s\n", instance_fields_end, "--- instance fields end ---");4439tty->print(" @%3d %s\n", instance_size * wordSize, "--- instance ends ---");4440tty->print(" @%3d %s\n", InstanceMirrorKlass::offset_of_static_fields(), "--- static fields start ---");4441for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {4442if (fs.access_flags().is_static()) {4443tty->print(" @%3d \"%s\" %s\n",4444fs.offset(),4445fs.name()->as_klass_external_name(),4446fs.signature()->as_klass_external_name());4447}4448}4449tty->print(" @%3d %s\n", static_fields_end, "--- static fields end ---");4450tty->print("\n");4451}44524453unsigned int4454ClassFileParser::compute_oop_map_count(instanceKlassHandle super,4455unsigned int nonstatic_oop_map_count,4456int first_nonstatic_oop_offset) {4457unsigned int map_count =4458super.is_null() ? 0 : super->nonstatic_oop_map_count();4459if (nonstatic_oop_map_count > 0) {4460// We have oops to add to map4461if (map_count == 0) {4462map_count = nonstatic_oop_map_count;4463} else {4464// Check whether we should add a new map block or whether the last one can4465// be extended4466OopMapBlock* const first_map = super->start_of_nonstatic_oop_maps();4467OopMapBlock* const last_map = first_map + map_count - 1;44684469int next_offset = last_map->offset() + last_map->count() * heapOopSize;4470if (next_offset == first_nonstatic_oop_offset) {4471// There is no gap bettwen superklass's last oop field and first4472// local oop field, merge maps.4473nonstatic_oop_map_count -= 1;4474} else {4475// Superklass didn't end with a oop field, add extra maps4476assert(next_offset < first_nonstatic_oop_offset, "just checking");4477}4478map_count += nonstatic_oop_map_count;4479}4480}4481return map_count;4482}448344844485void ClassFileParser::fill_oop_maps(instanceKlassHandle k,4486unsigned int nonstatic_oop_map_count,4487int* nonstatic_oop_offsets,4488unsigned int* nonstatic_oop_counts) {4489OopMapBlock* this_oop_map = k->start_of_nonstatic_oop_maps();4490const InstanceKlass* const super = k->superklass();4491const unsigned int super_count = super ? super->nonstatic_oop_map_count() : 0;4492if (super_count > 0) {4493// Copy maps from superklass4494OopMapBlock* super_oop_map = super->start_of_nonstatic_oop_maps();4495for (unsigned int i = 0; i < super_count; ++i) {4496*this_oop_map++ = *super_oop_map++;4497}4498}44994500if (nonstatic_oop_map_count > 0) {4501if (super_count + nonstatic_oop_map_count > k->nonstatic_oop_map_count()) {4502// The counts differ because there is no gap between superklass's last oop4503// field and the first local oop field. Extend the last oop map copied4504// from the superklass instead of creating new one.4505nonstatic_oop_map_count--;4506nonstatic_oop_offsets++;4507this_oop_map--;4508this_oop_map->set_count(this_oop_map->count() + *nonstatic_oop_counts++);4509this_oop_map++;4510}45114512// Add new map blocks, fill them4513while (nonstatic_oop_map_count-- > 0) {4514this_oop_map->set_offset(*nonstatic_oop_offsets++);4515this_oop_map->set_count(*nonstatic_oop_counts++);4516this_oop_map++;4517}4518assert(k->start_of_nonstatic_oop_maps() + k->nonstatic_oop_map_count() ==4519this_oop_map, "sanity");4520}4521}452245234524void ClassFileParser::set_precomputed_flags(instanceKlassHandle k) {4525Klass* super = k->super();45264527// Check if this klass has an empty finalize method (i.e. one with return bytecode only),4528// in which case we don't have to register objects as finalizable4529if (!_has_empty_finalizer) {4530if (_has_finalizer ||4531(super != NULL && super->has_finalizer())) {4532k->set_has_finalizer();4533}4534}45354536#ifdef ASSERT4537bool f = false;4538Method* m = k->lookup_method(vmSymbols::finalize_method_name(),4539vmSymbols::void_method_signature());4540if (m != NULL && !m->is_empty_method()) {4541f = true;4542}45434544// Spec doesn't prevent agent from redefinition of empty finalizer.4545// Despite the fact that it's generally bad idea and redefined finalizer4546// will not work as expected we shouldn't abort vm in this case4547if (!k->has_redefined_this_or_super()) {4548assert(f == k->has_finalizer(), "inconsistent has_finalizer");4549}4550#endif45514552// Check if this klass supports the java.lang.Cloneable interface4553if (SystemDictionary::Cloneable_klass_loaded()) {4554if (k->is_subtype_of(SystemDictionary::Cloneable_klass())) {4555k->set_is_cloneable();4556}4557}45584559// Check if this klass has a vanilla default constructor4560if (super == NULL) {4561// java.lang.Object has empty default constructor4562k->set_has_vanilla_constructor();4563} else {4564if (super->has_vanilla_constructor() &&4565_has_vanilla_constructor) {4566k->set_has_vanilla_constructor();4567}4568#ifdef ASSERT4569bool v = false;4570if (super->has_vanilla_constructor()) {4571Method* constructor = k->find_method(vmSymbols::object_initializer_name(4572), vmSymbols::void_method_signature());4573if (constructor != NULL && constructor->is_vanilla_constructor()) {4574v = true;4575}4576}4577assert(v == k->has_vanilla_constructor(), "inconsistent has_vanilla_constructor");4578#endif4579}45804581// If it cannot be fast-path allocated, set a bit in the layout helper.4582// See documentation of InstanceKlass::can_be_fastpath_allocated().4583assert(k->size_helper() > 0, "layout_helper is initialized");4584if ((!RegisterFinalizersAtInit && k->has_finalizer())4585|| k->is_abstract() || k->is_interface()4586|| (k->name() == vmSymbols::java_lang_Class() && k->class_loader() == NULL)4587|| k->size_helper() >= FastAllocateSizeLimit) {4588// Forbid fast-path allocation.4589jint lh = Klass::instance_layout_helper(k->size_helper(), true);4590k->set_layout_helper(lh);4591}4592}45934594// utility methods for appending an array with check for duplicates45954596void append_interfaces(GrowableArray<Klass*>* result, Array<Klass*>* ifs) {4597// iterate over new interfaces4598for (int i = 0; i < ifs->length(); i++) {4599Klass* e = ifs->at(i);4600assert(e->is_klass() && InstanceKlass::cast(e)->is_interface(), "just checking");4601// add new interface4602result->append_if_missing(e);4603}4604}46054606Array<Klass*>* ClassFileParser::compute_transitive_interfaces(4607instanceKlassHandle super,4608Array<Klass*>* local_ifs, TRAPS) {4609// Compute maximum size for transitive interfaces4610int max_transitive_size = 0;4611int super_size = 0;4612// Add superclass transitive interfaces size4613if (super.not_null()) {4614super_size = super->transitive_interfaces()->length();4615max_transitive_size += super_size;4616}4617// Add local interfaces' super interfaces4618int local_size = local_ifs->length();4619for (int i = 0; i < local_size; i++) {4620Klass* l = local_ifs->at(i);4621max_transitive_size += InstanceKlass::cast(l)->transitive_interfaces()->length();4622}4623// Finally add local interfaces4624max_transitive_size += local_size;4625// Construct array4626if (max_transitive_size == 0) {4627// no interfaces, use canonicalized array4628return Universe::the_empty_klass_array();4629} else if (max_transitive_size == super_size) {4630// no new local interfaces added, share superklass' transitive interface array4631return super->transitive_interfaces();4632} else if (max_transitive_size == local_size) {4633// only local interfaces added, share local interface array4634return local_ifs;4635} else {4636ResourceMark rm;4637GrowableArray<Klass*>* result = new GrowableArray<Klass*>(max_transitive_size);46384639// Copy down from superclass4640if (super.not_null()) {4641append_interfaces(result, super->transitive_interfaces());4642}46434644// Copy down from local interfaces' superinterfaces4645for (int i = 0; i < local_ifs->length(); i++) {4646Klass* l = local_ifs->at(i);4647append_interfaces(result, InstanceKlass::cast(l)->transitive_interfaces());4648}4649// Finally add local interfaces4650append_interfaces(result, local_ifs);46514652// length will be less than the max_transitive_size if duplicates were removed4653int length = result->length();4654assert(length <= max_transitive_size, "just checking");4655Array<Klass*>* new_result = MetadataFactory::new_array<Klass*>(_loader_data, length, CHECK_NULL);4656for (int i = 0; i < length; i++) {4657Klass* e = result->at(i);4658assert(e != NULL, "just checking");4659new_result->at_put(i, e);4660}4661return new_result;4662}4663}46644665void ClassFileParser::check_super_class_access(instanceKlassHandle this_klass, TRAPS) {4666Klass* super = this_klass->super();4667if ((super != NULL) &&4668(!Reflection::verify_class_access(this_klass(), super, false))) {4669ResourceMark rm(THREAD);4670Exceptions::fthrow(4671THREAD_AND_LOCATION,4672vmSymbols::java_lang_IllegalAccessError(),4673"class %s cannot access its superclass %s",4674this_klass->external_name(),4675InstanceKlass::cast(super)->external_name()4676);4677return;4678}4679}468046814682void ClassFileParser::check_super_interface_access(instanceKlassHandle this_klass, TRAPS) {4683Array<Klass*>* local_interfaces = this_klass->local_interfaces();4684int lng = local_interfaces->length();4685for (int i = lng - 1; i >= 0; i--) {4686Klass* k = local_interfaces->at(i);4687assert (k != NULL && k->is_interface(), "invalid interface");4688if (!Reflection::verify_class_access(this_klass(), k, false)) {4689ResourceMark rm(THREAD);4690Exceptions::fthrow(4691THREAD_AND_LOCATION,4692vmSymbols::java_lang_IllegalAccessError(),4693"class %s cannot access its superinterface %s",4694this_klass->external_name(),4695InstanceKlass::cast(k)->external_name()4696);4697return;4698}4699}4700}470147024703void ClassFileParser::check_final_method_override(instanceKlassHandle this_klass, TRAPS) {4704Array<Method*>* methods = this_klass->methods();4705int num_methods = methods->length();47064707// go thru each method and check if it overrides a final method4708for (int index = 0; index < num_methods; index++) {4709Method* m = methods->at(index);47104711// skip private, static, and <init> methods4712if ((!m->is_private() && !m->is_static()) &&4713(m->name() != vmSymbols::object_initializer_name())) {47144715Symbol* name = m->name();4716Symbol* signature = m->signature();4717Klass* k = this_klass->super();4718Method* super_m = NULL;4719while (k != NULL) {4720// skip supers that don't have final methods.4721if (k->has_final_method()) {4722// lookup a matching method in the super class hierarchy4723super_m = InstanceKlass::cast(k)->lookup_method(name, signature);4724if (super_m == NULL) {4725break; // didn't find any match; get out4726}47274728if (super_m->is_final() && !super_m->is_static() &&4729// matching method in super is final, and not static4730(Reflection::verify_field_access(this_klass(),4731super_m->method_holder(),4732super_m->method_holder(),4733super_m->access_flags(), false))4734// this class can access super final method and therefore override4735) {4736ResourceMark rm(THREAD);4737Exceptions::fthrow(4738THREAD_AND_LOCATION,4739vmSymbols::java_lang_VerifyError(),4740"class %s overrides final method %s.%s",4741this_klass->external_name(),4742name->as_C_string(),4743signature->as_C_string()4744);4745return;4746}47474748// continue to look from super_m's holder's super.4749k = super_m->method_holder()->super();4750continue;4751}47524753k = k->super();4754}4755}4756}4757}475847594760// assumes that this_klass is an interface4761void ClassFileParser::check_illegal_static_method(instanceKlassHandle this_klass, TRAPS) {4762assert(this_klass->is_interface(), "not an interface");4763Array<Method*>* methods = this_klass->methods();4764int num_methods = methods->length();47654766for (int index = 0; index < num_methods; index++) {4767Method* m = methods->at(index);4768// if m is static and not the init method, throw a verify error4769if ((m->is_static()) && (m->name() != vmSymbols::class_initializer_name())) {4770ResourceMark rm(THREAD);4771Exceptions::fthrow(4772THREAD_AND_LOCATION,4773vmSymbols::java_lang_VerifyError(),4774"Illegal static method %s in interface %s",4775m->name()->as_C_string(),4776this_klass->external_name()4777);4778return;4779}4780}4781}47824783// utility methods for format checking47844785void ClassFileParser::verify_legal_class_modifiers(jint flags, TRAPS) {4786if (!_need_verify) { return; }47874788const bool is_interface = (flags & JVM_ACC_INTERFACE) != 0;4789const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;4790const bool is_final = (flags & JVM_ACC_FINAL) != 0;4791const bool is_super = (flags & JVM_ACC_SUPER) != 0;4792const bool is_enum = (flags & JVM_ACC_ENUM) != 0;4793const bool is_annotation = (flags & JVM_ACC_ANNOTATION) != 0;4794const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;47954796if ((is_abstract && is_final) ||4797(is_interface && !is_abstract) ||4798(is_interface && major_gte_15 && (is_super || is_enum)) ||4799(!is_interface && major_gte_15 && is_annotation)) {4800ResourceMark rm(THREAD);4801Exceptions::fthrow(4802THREAD_AND_LOCATION,4803vmSymbols::java_lang_ClassFormatError(),4804"Illegal class modifiers in class %s: 0x%X",4805_class_name->as_C_string(), flags4806);4807return;4808}4809}48104811bool ClassFileParser::has_illegal_visibility(jint flags) {4812const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;4813const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;4814const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;48154816return ((is_public && is_protected) ||4817(is_public && is_private) ||4818(is_protected && is_private));4819}48204821bool ClassFileParser::is_supported_version(u2 major, u2 minor) {4822u2 max_version =4823JDK_Version::is_gte_jdk17x_version() ? JAVA_MAX_SUPPORTED_VERSION :4824(JDK_Version::is_gte_jdk16x_version() ? JAVA_6_VERSION : JAVA_1_5_VERSION);4825return (major >= JAVA_MIN_SUPPORTED_VERSION) &&4826(major <= max_version) &&4827((major != max_version) ||4828(minor <= JAVA_MAX_SUPPORTED_MINOR_VERSION));4829}48304831void ClassFileParser::verify_legal_field_modifiers(4832jint flags, bool is_interface, TRAPS) {4833if (!_need_verify) { return; }48344835const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;4836const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;4837const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;4838const bool is_static = (flags & JVM_ACC_STATIC) != 0;4839const bool is_final = (flags & JVM_ACC_FINAL) != 0;4840const bool is_volatile = (flags & JVM_ACC_VOLATILE) != 0;4841const bool is_transient = (flags & JVM_ACC_TRANSIENT) != 0;4842const bool is_enum = (flags & JVM_ACC_ENUM) != 0;4843const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;48444845bool is_illegal = false;48464847if (is_interface) {4848if (!is_public || !is_static || !is_final || is_private ||4849is_protected || is_volatile || is_transient ||4850(major_gte_15 && is_enum)) {4851is_illegal = true;4852}4853} else { // not interface4854if (has_illegal_visibility(flags) || (is_final && is_volatile)) {4855is_illegal = true;4856}4857}48584859if (is_illegal) {4860ResourceMark rm(THREAD);4861Exceptions::fthrow(4862THREAD_AND_LOCATION,4863vmSymbols::java_lang_ClassFormatError(),4864"Illegal field modifiers in class %s: 0x%X",4865_class_name->as_C_string(), flags);4866return;4867}4868}48694870void ClassFileParser::verify_legal_method_modifiers(4871jint flags, bool is_interface, Symbol* name, TRAPS) {4872if (!_need_verify) { return; }48734874const bool is_public = (flags & JVM_ACC_PUBLIC) != 0;4875const bool is_private = (flags & JVM_ACC_PRIVATE) != 0;4876const bool is_static = (flags & JVM_ACC_STATIC) != 0;4877const bool is_final = (flags & JVM_ACC_FINAL) != 0;4878const bool is_native = (flags & JVM_ACC_NATIVE) != 0;4879const bool is_abstract = (flags & JVM_ACC_ABSTRACT) != 0;4880const bool is_bridge = (flags & JVM_ACC_BRIDGE) != 0;4881const bool is_strict = (flags & JVM_ACC_STRICT) != 0;4882const bool is_synchronized = (flags & JVM_ACC_SYNCHRONIZED) != 0;4883const bool is_protected = (flags & JVM_ACC_PROTECTED) != 0;4884const bool major_gte_15 = _major_version >= JAVA_1_5_VERSION;4885const bool major_gte_8 = _major_version >= JAVA_8_VERSION;4886const bool is_initializer = (name == vmSymbols::object_initializer_name());48874888bool is_illegal = false;48894890if (is_interface) {4891if (major_gte_8) {4892// Class file version is JAVA_8_VERSION or later Methods of4893// interfaces may set any of the flags except ACC_PROTECTED,4894// ACC_FINAL, ACC_NATIVE, and ACC_SYNCHRONIZED; they must4895// have exactly one of the ACC_PUBLIC or ACC_PRIVATE flags set.4896if ((is_public == is_private) || /* Only one of private and public should be true - XNOR */4897(is_native || is_protected || is_final || is_synchronized) ||4898// If a specific method of a class or interface has its4899// ACC_ABSTRACT flag set, it must not have any of its4900// ACC_FINAL, ACC_NATIVE, ACC_PRIVATE, ACC_STATIC,4901// ACC_STRICT, or ACC_SYNCHRONIZED flags set. No need to4902// check for ACC_FINAL, ACC_NATIVE or ACC_SYNCHRONIZED as4903// those flags are illegal irrespective of ACC_ABSTRACT being set or not.4904(is_abstract && (is_private || is_static || is_strict))) {4905is_illegal = true;4906}4907} else if (major_gte_15) {4908// Class file version in the interval [JAVA_1_5_VERSION, JAVA_8_VERSION)4909if (!is_public || is_static || is_final || is_synchronized ||4910is_native || !is_abstract || is_strict) {4911is_illegal = true;4912}4913} else {4914// Class file version is pre-JAVA_1_5_VERSION4915if (!is_public || is_static || is_final || is_native || !is_abstract) {4916is_illegal = true;4917}4918}4919} else { // not interface4920if (is_initializer) {4921if (is_static || is_final || is_synchronized || is_native ||4922is_abstract || (major_gte_15 && is_bridge)) {4923is_illegal = true;4924}4925} else { // not initializer4926if (is_abstract) {4927if ((is_final || is_native || is_private || is_static ||4928(major_gte_15 && (is_synchronized || is_strict)))) {4929is_illegal = true;4930}4931}4932if (has_illegal_visibility(flags)) {4933is_illegal = true;4934}4935}4936}49374938if (is_illegal) {4939ResourceMark rm(THREAD);4940Exceptions::fthrow(4941THREAD_AND_LOCATION,4942vmSymbols::java_lang_ClassFormatError(),4943"Method %s in class %s has illegal modifiers: 0x%X",4944name->as_C_string(), _class_name->as_C_string(), flags);4945return;4946}4947}49484949void ClassFileParser::verify_legal_utf8(const unsigned char* buffer, int length, TRAPS) {4950assert(_need_verify, "only called when _need_verify is true");4951int i = 0;4952int count = length >> 2;4953for (int k=0; k<count; k++) {4954unsigned char b0 = buffer[i];4955unsigned char b1 = buffer[i+1];4956unsigned char b2 = buffer[i+2];4957unsigned char b3 = buffer[i+3];4958// For an unsigned char v,4959// (v | v - 1) is < 128 (highest bit 0) for 0 < v < 128;4960// (v | v - 1) is >= 128 (highest bit 1) for v == 0 or v >= 128.4961unsigned char res = b0 | b0 - 1 |4962b1 | b1 - 1 |4963b2 | b2 - 1 |4964b3 | b3 - 1;4965if (res >= 128) break;4966i += 4;4967}4968for(; i < length; i++) {4969unsigned short c;4970// no embedded zeros4971guarantee_property((buffer[i] != 0), "Illegal UTF8 string in constant pool in class file %s", CHECK);4972if(buffer[i] < 128) {4973continue;4974}4975if ((i + 5) < length) { // see if it's legal supplementary character4976if (UTF8::is_supplementary_character(&buffer[i])) {4977c = UTF8::get_supplementary_character(&buffer[i]);4978i += 5;4979continue;4980}4981}4982switch (buffer[i] >> 4) {4983default: break;4984case 0x8: case 0x9: case 0xA: case 0xB: case 0xF:4985classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);4986case 0xC: case 0xD: // 110xxxxx 10xxxxxx4987c = (buffer[i] & 0x1F) << 6;4988i++;4989if ((i < length) && ((buffer[i] & 0xC0) == 0x80)) {4990c += buffer[i] & 0x3F;4991if (_major_version <= 47 || c == 0 || c >= 0x80) {4992// for classes with major > 47, c must a null or a character in its shortest form4993break;4994}4995}4996classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);4997case 0xE: // 1110xxxx 10xxxxxx 10xxxxxx4998c = (buffer[i] & 0xF) << 12;4999i += 2;5000if ((i < length) && ((buffer[i-1] & 0xC0) == 0x80) && ((buffer[i] & 0xC0) == 0x80)) {5001c += ((buffer[i-1] & 0x3F) << 6) + (buffer[i] & 0x3F);5002if (_major_version <= 47 || c >= 0x800) {5003// for classes with major > 47, c must be in its shortest form5004break;5005}5006}5007classfile_parse_error("Illegal UTF8 string in constant pool in class file %s", CHECK);5008} // end of switch5009} // end of for5010}50115012// Checks if name is a legal class name.5013void ClassFileParser::verify_legal_class_name(Symbol* name, TRAPS) {5014if (!_need_verify || _relax_verify) { return; }50155016char buf[fixed_buffer_size];5017char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);5018unsigned int length = name->utf8_length();5019bool legal = false;50205021if (length > 0) {5022char* p;5023if (bytes[0] == JVM_SIGNATURE_ARRAY) {5024p = skip_over_field_signature(bytes, false, length, CHECK);5025legal = (p != NULL) && ((p - bytes) == (int)length);5026} else if (_major_version < JAVA_1_5_VERSION) {5027if (bytes[0] != '<') {5028p = skip_over_field_name(bytes, true, length);5029legal = (p != NULL) && ((p - bytes) == (int)length);5030}5031} else {5032// 4900761: relax the constraints based on JSR202 spec5033// Class names may be drawn from the entire Unicode character set.5034// Identifiers between '/' must be unqualified names.5035// The utf8 string has been verified when parsing cpool entries.5036legal = verify_unqualified_name(bytes, length, LegalClass);5037}5038}5039if (!legal) {5040ResourceMark rm(THREAD);5041Exceptions::fthrow(5042THREAD_AND_LOCATION,5043vmSymbols::java_lang_ClassFormatError(),5044"Illegal class name \"%s\" in class file %s", bytes,5045_class_name->as_C_string()5046);5047return;5048}5049}50505051// Checks if name is a legal field name.5052void ClassFileParser::verify_legal_field_name(Symbol* name, TRAPS) {5053if (!_need_verify || _relax_verify) { return; }50545055char buf[fixed_buffer_size];5056char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);5057unsigned int length = name->utf8_length();5058bool legal = false;50595060if (length > 0) {5061if (_major_version < JAVA_1_5_VERSION) {5062if (bytes[0] != '<') {5063char* p = skip_over_field_name(bytes, false, length);5064legal = (p != NULL) && ((p - bytes) == (int)length);5065}5066} else {5067// 4881221: relax the constraints based on JSR202 spec5068legal = verify_unqualified_name(bytes, length, LegalField);5069}5070}50715072if (!legal) {5073ResourceMark rm(THREAD);5074Exceptions::fthrow(5075THREAD_AND_LOCATION,5076vmSymbols::java_lang_ClassFormatError(),5077"Illegal field name \"%s\" in class %s", bytes,5078_class_name->as_C_string()5079);5080return;5081}5082}50835084// Checks if name is a legal method name.5085void ClassFileParser::verify_legal_method_name(Symbol* name, TRAPS) {5086if (!_need_verify || _relax_verify) { return; }50875088assert(name != NULL, "method name is null");5089char buf[fixed_buffer_size];5090char* bytes = name->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);5091unsigned int length = name->utf8_length();5092bool legal = false;50935094if (length > 0) {5095if (bytes[0] == '<') {5096if (name == vmSymbols::object_initializer_name() || name == vmSymbols::class_initializer_name()) {5097legal = true;5098}5099} else if (_major_version < JAVA_1_5_VERSION) {5100char* p;5101p = skip_over_field_name(bytes, false, length);5102legal = (p != NULL) && ((p - bytes) == (int)length);5103} else {5104// 4881221: relax the constraints based on JSR202 spec5105legal = verify_unqualified_name(bytes, length, LegalMethod);5106}5107}51085109if (!legal) {5110ResourceMark rm(THREAD);5111Exceptions::fthrow(5112THREAD_AND_LOCATION,5113vmSymbols::java_lang_ClassFormatError(),5114"Illegal method name \"%s\" in class %s", bytes,5115_class_name->as_C_string()5116);5117return;5118}5119}512051215122// Checks if signature is a legal field signature.5123void ClassFileParser::verify_legal_field_signature(Symbol* name, Symbol* signature, TRAPS) {5124if (!_need_verify) { return; }51255126char buf[fixed_buffer_size];5127char* bytes = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);5128unsigned int length = signature->utf8_length();5129char* p = skip_over_field_signature(bytes, false, length, CHECK);51305131if (p == NULL || (p - bytes) != (int)length) {5132throwIllegalSignature("Field", name, signature, CHECK);5133}5134}51355136// Checks if signature is a legal method signature.5137// Returns number of parameters5138int ClassFileParser::verify_legal_method_signature(Symbol* name, Symbol* signature, TRAPS) {5139if (!_need_verify) {5140// make sure caller's args_size will be less than 0 even for non-static5141// method so it will be recomputed in compute_size_of_parameters().5142return -2;5143}51445145unsigned int args_size = 0;5146char buf[fixed_buffer_size];5147char* p = signature->as_utf8_flexible_buffer(THREAD, buf, fixed_buffer_size);5148unsigned int length = signature->utf8_length();5149char* nextp;51505151// The first character must be a '('5152if ((length > 0) && (*p++ == JVM_SIGNATURE_FUNC)) {5153length--;5154// Skip over legal field signatures5155nextp = skip_over_field_signature(p, false, length, CHECK_0);5156while ((length > 0) && (nextp != NULL)) {5157args_size++;5158if (p[0] == 'J' || p[0] == 'D') {5159args_size++;5160}5161length -= nextp - p;5162p = nextp;5163nextp = skip_over_field_signature(p, false, length, CHECK_0);5164}5165// The first non-signature thing better be a ')'5166if ((length > 0) && (*p++ == JVM_SIGNATURE_ENDFUNC)) {5167length--;5168if (name->utf8_length() > 0 && name->byte_at(0) == '<') {5169// All internal methods must return void5170if ((length == 1) && (p[0] == JVM_SIGNATURE_VOID)) {5171return args_size;5172}5173} else {5174// Now we better just have a return value5175nextp = skip_over_field_signature(p, true, length, CHECK_0);5176if (nextp && ((int)length == (nextp - p))) {5177return args_size;5178}5179}5180}5181}5182// Report error5183throwIllegalSignature("Method", name, signature, CHECK_0);5184return 0;5185}518651875188// Unqualified names may not contain the characters '.', ';', '[', or '/'.5189// Method names also may not contain the characters '<' or '>', unless <init>5190// or <clinit>. Note that method names may not be <init> or <clinit> in this5191// method. Because these names have been checked as special cases before5192// calling this method in verify_legal_method_name.5193bool ClassFileParser::verify_unqualified_name(5194char* name, unsigned int length, int type) {5195jchar ch;51965197for (char* p = name; p != name + length; ) {5198ch = *p;5199if (ch < 128) {5200p++;5201if (ch == '.' || ch == ';' || ch == '[' ) {5202return false; // do not permit '.', ';', or '['5203}5204if (type != LegalClass && ch == '/') {5205return false; // do not permit '/' unless it's class name5206}5207if (type == LegalMethod && (ch == '<' || ch == '>')) {5208return false; // do not permit '<' or '>' in method names5209}5210} else {5211char* tmp_p = UTF8::next(p, &ch);5212p = tmp_p;5213}5214}5215return true;5216}521752185219// Take pointer to a string. Skip over the longest part of the string that could5220// be taken as a fieldname. Allow '/' if slash_ok is true.5221// Return a pointer to just past the fieldname.5222// Return NULL if no fieldname at all was found, or in the case of slash_ok5223// being true, we saw consecutive slashes (meaning we were looking for a5224// qualified path but found something that was badly-formed).5225char* ClassFileParser::skip_over_field_name(char* name, bool slash_ok, unsigned int length) {5226char* p;5227jchar ch;5228jboolean last_is_slash = false;5229jboolean not_first_ch = false;52305231for (p = name; p != name + length; not_first_ch = true) {5232char* old_p = p;5233ch = *p;5234if (ch < 128) {5235p++;5236// quick check for ascii5237if ((ch >= 'a' && ch <= 'z') ||5238(ch >= 'A' && ch <= 'Z') ||5239(ch == '_' || ch == '$') ||5240(not_first_ch && ch >= '0' && ch <= '9')) {5241last_is_slash = false;5242continue;5243}5244if (slash_ok && ch == '/') {5245if (last_is_slash) {5246return NULL; // Don't permit consecutive slashes5247}5248last_is_slash = true;5249continue;5250}5251} else {5252jint unicode_ch;5253char* tmp_p = UTF8::next_character(p, &unicode_ch);5254p = tmp_p;5255last_is_slash = false;5256// Check if ch is Java identifier start or is Java identifier part5257// 4672820: call java.lang.Character methods directly without generating separate tables.5258EXCEPTION_MARK;5259instanceKlassHandle klass (THREAD, SystemDictionary::Character_klass());52605261// return value5262JavaValue result(T_BOOLEAN);5263// Set up the arguments to isJavaIdentifierStart and isJavaIdentifierPart5264JavaCallArguments args;5265args.push_int(unicode_ch);52665267// public static boolean isJavaIdentifierStart(char ch);5268JavaCalls::call_static(&result,5269klass,5270vmSymbols::isJavaIdentifierStart_name(),5271vmSymbols::int_bool_signature(),5272&args,5273THREAD);52745275if (HAS_PENDING_EXCEPTION) {5276CLEAR_PENDING_EXCEPTION;5277return 0;5278}5279if (result.get_jboolean()) {5280continue;5281}52825283if (not_first_ch) {5284// public static boolean isJavaIdentifierPart(char ch);5285JavaCalls::call_static(&result,5286klass,5287vmSymbols::isJavaIdentifierPart_name(),5288vmSymbols::int_bool_signature(),5289&args,5290THREAD);52915292if (HAS_PENDING_EXCEPTION) {5293CLEAR_PENDING_EXCEPTION;5294return 0;5295}52965297if (result.get_jboolean()) {5298continue;5299}5300}5301}5302return (not_first_ch) ? old_p : NULL;5303}5304return (not_first_ch) ? p : NULL;5305}530653075308// Take pointer to a string. Skip over the longest part of the string that could5309// be taken as a field signature. Allow "void" if void_ok.5310// Return a pointer to just past the signature.5311// Return NULL if no legal signature is found.5312char* ClassFileParser::skip_over_field_signature(char* signature,5313bool void_ok,5314unsigned int length,5315TRAPS) {5316unsigned int array_dim = 0;5317while (length > 0) {5318switch (signature[0]) {5319case JVM_SIGNATURE_VOID: if (!void_ok) { return NULL; }5320case JVM_SIGNATURE_BOOLEAN:5321case JVM_SIGNATURE_BYTE:5322case JVM_SIGNATURE_CHAR:5323case JVM_SIGNATURE_SHORT:5324case JVM_SIGNATURE_INT:5325case JVM_SIGNATURE_FLOAT:5326case JVM_SIGNATURE_LONG:5327case JVM_SIGNATURE_DOUBLE:5328return signature + 1;5329case JVM_SIGNATURE_CLASS: {5330if (_major_version < JAVA_1_5_VERSION) {5331// Skip over the class name if one is there5332char* p = skip_over_field_name(signature + 1, true, --length);53335334// The next character better be a semicolon5335if (p && (p - signature) > 1 && p[0] == ';') {5336return p + 1;5337}5338} else {5339// 4900761: For class version > 48, any unicode is allowed in class name.5340length--;5341signature++;5342while (length > 0 && signature[0] != ';') {5343if (signature[0] == '.') {5344classfile_parse_error("Class name contains illegal character '.' in descriptor in class file %s", CHECK_0);5345}5346length--;5347signature++;5348}5349if (signature[0] == ';') { return signature + 1; }5350}53515352return NULL;5353}5354case JVM_SIGNATURE_ARRAY:5355array_dim++;5356if (array_dim > 255) {5357// 4277370: array descriptor is valid only if it represents 255 or fewer dimensions.5358classfile_parse_error("Array type descriptor has more than 255 dimensions in class file %s", CHECK_0);5359}5360// The rest of what's there better be a legal signature5361signature++;5362length--;5363void_ok = false;5364break;53655366default:5367return NULL;5368}5369}5370return NULL;5371}53725373#if INCLUDE_JFR53745375// Caller responsible for ResourceMark5376// clone stream with rewound position5377ClassFileStream* ClassFileParser::clone_stream() const {5378assert(_stream != NULL, "invariant");53795380return _stream->clone();5381}53825383void ClassFileParser::set_klass_to_deallocate(InstanceKlass* klass) {5384#ifdef ASSERT5385if (klass != NULL) {5386assert(NULL == _klass, "leaking?");5387}5388#endif53895390_klass = klass;5391}53925393#endif // INCLUDE_JFR539453955396