Path: blob/master/src/hotspot/share/oops/constantPool.cpp
64440 views
/*1* Copyright (c) 1997, 2021, 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 "jvm.h"26#include "cds/heapShared.hpp"27#include "classfile/classLoaderData.hpp"28#include "classfile/javaClasses.inline.hpp"29#include "classfile/metadataOnStackMark.hpp"30#include "classfile/stringTable.hpp"31#include "classfile/systemDictionary.hpp"32#include "classfile/vmClasses.hpp"33#include "classfile/vmSymbols.hpp"34#include "interpreter/bootstrapInfo.hpp"35#include "interpreter/linkResolver.hpp"36#include "logging/log.hpp"37#include "logging/logStream.hpp"38#include "memory/allocation.inline.hpp"39#include "memory/metadataFactory.hpp"40#include "memory/metaspaceClosure.hpp"41#include "memory/oopFactory.hpp"42#include "memory/resourceArea.hpp"43#include "memory/universe.hpp"44#include "oops/array.hpp"45#include "oops/constantPool.inline.hpp"46#include "oops/cpCache.inline.hpp"47#include "oops/instanceKlass.hpp"48#include "oops/klass.inline.hpp"49#include "oops/objArrayKlass.hpp"50#include "oops/objArrayOop.inline.hpp"51#include "oops/oop.inline.hpp"52#include "oops/typeArrayOop.inline.hpp"53#include "prims/jvmtiExport.hpp"54#include "runtime/atomic.hpp"55#include "runtime/handles.inline.hpp"56#include "runtime/init.hpp"57#include "runtime/javaCalls.hpp"58#include "runtime/signature.hpp"59#include "runtime/thread.inline.hpp"60#include "runtime/vframe.inline.hpp"61#include "utilities/copy.hpp"6263ConstantPool* ConstantPool::allocate(ClassLoaderData* loader_data, int length, TRAPS) {64Array<u1>* tags = MetadataFactory::new_array<u1>(loader_data, length, 0, CHECK_NULL);65int size = ConstantPool::size(length);66return new (loader_data, size, MetaspaceObj::ConstantPoolType, THREAD) ConstantPool(tags);67}6869void ConstantPool::copy_fields(const ConstantPool* orig) {70// Preserve dynamic constant information from the original pool71if (orig->has_dynamic_constant()) {72set_has_dynamic_constant();73}7475set_major_version(orig->major_version());76set_minor_version(orig->minor_version());7778set_source_file_name_index(orig->source_file_name_index());79set_generic_signature_index(orig->generic_signature_index());80}8182#ifdef ASSERT8384// MetaspaceObj allocation invariant is calloc equivalent memory85// simple verification of this here (JVM_CONSTANT_Invalid == 0 )86static bool tag_array_is_zero_initialized(Array<u1>* tags) {87assert(tags != NULL, "invariant");88const int length = tags->length();89for (int index = 0; index < length; ++index) {90if (JVM_CONSTANT_Invalid != tags->at(index)) {91return false;92}93}94return true;95}9697#endif9899ConstantPool::ConstantPool(Array<u1>* tags) :100_tags(tags),101_length(tags->length()) {102103assert(_tags != NULL, "invariant");104assert(tags->length() == _length, "invariant");105assert(tag_array_is_zero_initialized(tags), "invariant");106assert(0 == flags(), "invariant");107assert(0 == version(), "invariant");108assert(NULL == _pool_holder, "invariant");109}110111void ConstantPool::deallocate_contents(ClassLoaderData* loader_data) {112if (cache() != NULL) {113MetadataFactory::free_metadata(loader_data, cache());114set_cache(NULL);115}116117MetadataFactory::free_array<Klass*>(loader_data, resolved_klasses());118set_resolved_klasses(NULL);119120MetadataFactory::free_array<jushort>(loader_data, operands());121set_operands(NULL);122123release_C_heap_structures();124125// free tag array126MetadataFactory::free_array<u1>(loader_data, tags());127set_tags(NULL);128}129130void ConstantPool::release_C_heap_structures() {131// walk constant pool and decrement symbol reference counts132unreference_symbols();133}134135void ConstantPool::metaspace_pointers_do(MetaspaceClosure* it) {136log_trace(cds)("Iter(ConstantPool): %p", this);137138it->push(&_tags, MetaspaceClosure::_writable);139it->push(&_cache);140it->push(&_pool_holder);141it->push(&_operands);142it->push(&_resolved_klasses, MetaspaceClosure::_writable);143144for (int i = 0; i < length(); i++) {145// The only MSO's embedded in the CP entries are Symbols:146// JVM_CONSTANT_String (normal and pseudo)147// JVM_CONSTANT_Utf8148constantTag ctag = tag_at(i);149if (ctag.is_string() || ctag.is_utf8()) {150it->push(symbol_at_addr(i));151}152}153}154155objArrayOop ConstantPool::resolved_references() const {156return (objArrayOop)_cache->resolved_references();157}158159// Called from outside constant pool resolution where a resolved_reference array160// may not be present.161objArrayOop ConstantPool::resolved_references_or_null() const {162if (_cache == NULL) {163return NULL;164} else {165return (objArrayOop)_cache->resolved_references();166}167}168169// Create resolved_references array and mapping array for original cp indexes170// The ldc bytecode was rewritten to have the resolved reference array index so need a way171// to map it back for resolving and some unlikely miscellaneous uses.172// The objects created by invokedynamic are appended to this list.173void ConstantPool::initialize_resolved_references(ClassLoaderData* loader_data,174const intStack& reference_map,175int constant_pool_map_length,176TRAPS) {177// Initialized the resolved object cache.178int map_length = reference_map.length();179if (map_length > 0) {180// Only need mapping back to constant pool entries. The map isn't used for181// invokedynamic resolved_reference entries. For invokedynamic entries,182// the constant pool cache index has the mapping back to both the constant183// pool and to the resolved reference index.184if (constant_pool_map_length > 0) {185Array<u2>* om = MetadataFactory::new_array<u2>(loader_data, constant_pool_map_length, CHECK);186187for (int i = 0; i < constant_pool_map_length; i++) {188int x = reference_map.at(i);189assert(x == (int)(jushort) x, "klass index is too big");190om->at_put(i, (jushort)x);191}192set_reference_map(om);193}194195// Create Java array for holding resolved strings, methodHandles,196// methodTypes, invokedynamic and invokehandle appendix objects, etc.197objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);198Handle refs_handle (THREAD, stom); // must handleize.199set_resolved_references(loader_data->add_handle(refs_handle));200}201}202203void ConstantPool::allocate_resolved_klasses(ClassLoaderData* loader_data, int num_klasses, TRAPS) {204// A ConstantPool can't possibly have 0xffff valid class entries,205// because entry #0 must be CONSTANT_Invalid, and each class entry must refer to a UTF8206// entry for the class's name. So at most we will have 0xfffe class entries.207// This allows us to use 0xffff (ConstantPool::_temp_resolved_klass_index) to indicate208// UnresolvedKlass entries that are temporarily created during class redefinition.209assert(num_klasses < CPKlassSlot::_temp_resolved_klass_index, "sanity");210assert(resolved_klasses() == NULL, "sanity");211Array<Klass*>* rk = MetadataFactory::new_array<Klass*>(loader_data, num_klasses, CHECK);212set_resolved_klasses(rk);213}214215void ConstantPool::initialize_unresolved_klasses(ClassLoaderData* loader_data, TRAPS) {216int len = length();217int num_klasses = 0;218for (int i = 1; i <len; i++) {219switch (tag_at(i).value()) {220case JVM_CONSTANT_ClassIndex:221{222const int class_index = klass_index_at(i);223unresolved_klass_at_put(i, class_index, num_klasses++);224}225break;226#ifndef PRODUCT227case JVM_CONSTANT_Class:228case JVM_CONSTANT_UnresolvedClass:229case JVM_CONSTANT_UnresolvedClassInError:230// All of these should have been reverted back to ClassIndex before calling231// this function.232ShouldNotReachHere();233#endif234}235}236allocate_resolved_klasses(loader_data, num_klasses, THREAD);237}238239// Hidden class support:240void ConstantPool::klass_at_put(int class_index, Klass* k) {241assert(k != NULL, "must be valid klass");242CPKlassSlot kslot = klass_slot_at(class_index);243int resolved_klass_index = kslot.resolved_klass_index();244Klass** adr = resolved_klasses()->adr_at(resolved_klass_index);245Atomic::release_store(adr, k);246247// The interpreter assumes when the tag is stored, the klass is resolved248// and the Klass* non-NULL, so we need hardware store ordering here.249release_tag_at_put(class_index, JVM_CONSTANT_Class);250}251252#if INCLUDE_CDS_JAVA_HEAP253// Archive the resolved references254void ConstantPool::archive_resolved_references() {255if (_cache == NULL) {256return; // nothing to do257}258259InstanceKlass *ik = pool_holder();260if (!(ik->is_shared_boot_class() || ik->is_shared_platform_class() ||261ik->is_shared_app_class())) {262// Archiving resolved references for classes from non-builtin loaders263// is not yet supported.264return;265}266267objArrayOop rr = resolved_references();268Array<u2>* ref_map = reference_map();269if (rr != NULL) {270int ref_map_len = ref_map == NULL ? 0 : ref_map->length();271int rr_len = rr->length();272for (int i = 0; i < rr_len; i++) {273oop obj = rr->obj_at(i);274rr->obj_at_put(i, NULL);275if (obj != NULL && i < ref_map_len) {276int index = object_to_cp_index(i);277if (tag_at(index).is_string()) {278oop archived_string = HeapShared::find_archived_heap_object(obj);279// Update the reference to point to the archived copy280// of this string.281// If the string is too large to archive, NULL is282// stored into rr. At run time, string_at_impl() will create and intern283// the string.284rr->obj_at_put(i, archived_string);285}286}287}288289oop archived = HeapShared::archive_heap_object(rr);290// If the resolved references array is not archived (too large),291// the 'archived' object is NULL. No need to explicitly check292// the return value of archive_heap_object here. At runtime, the293// resolved references will be created using the normal process294// when there is no archived value.295_cache->set_archived_references(archived);296}297}298299void ConstantPool::resolve_class_constants(TRAPS) {300assert(DumpSharedSpaces, "used during dump time only");301// The _cache may be NULL if the _pool_holder klass fails verification302// at dump time due to missing dependencies.303if (cache() == NULL || reference_map() == NULL) {304return; // nothing to do305}306307constantPoolHandle cp(THREAD, this);308for (int index = 1; index < length(); index++) { // Index 0 is unused309if (tag_at(index).is_string()) {310int cache_index = cp->cp_to_object_index(index);311string_at_impl(cp, index, cache_index, CHECK);312}313}314}315316void ConstantPool::add_dumped_interned_strings() {317objArrayOop rr = resolved_references();318if (rr != NULL) {319int rr_len = rr->length();320for (int i = 0; i < rr_len; i++) {321oop p = rr->obj_at(i);322if (java_lang_String::is_instance(p)) {323HeapShared::add_to_dumped_interned_strings(p);324}325}326}327}328#endif329330// CDS support. Create a new resolved_references array.331void ConstantPool::restore_unshareable_info(TRAPS) {332if (!_pool_holder->is_linked() && !_pool_holder->is_rewritten()) {333return;334}335assert(is_constantPool(), "ensure C++ vtable is restored");336assert(on_stack(), "should always be set for shared constant pools");337assert(is_shared(), "should always be set for shared constant pools");338assert(_cache != NULL, "constant pool _cache should not be NULL");339340// Only create the new resolved references array if it hasn't been attempted before341if (resolved_references() != NULL) return;342343// restore the C++ vtable from the shared archive344restore_vtable();345346if (vmClasses::Object_klass_loaded()) {347ClassLoaderData* loader_data = pool_holder()->class_loader_data();348#if INCLUDE_CDS_JAVA_HEAP349if (HeapShared::open_archive_heap_region_mapped() &&350_cache->archived_references() != NULL) {351oop archived = _cache->archived_references();352// Create handle for the archived resolved reference array object353Handle refs_handle(THREAD, archived);354set_resolved_references(loader_data->add_handle(refs_handle));355_cache->clear_archived_references();356} else357#endif358{359// No mapped archived resolved reference array360// Recreate the object array and add to ClassLoaderData.361int map_length = resolved_reference_length();362if (map_length > 0) {363objArrayOop stom = oopFactory::new_objArray(vmClasses::Object_klass(), map_length, CHECK);364Handle refs_handle(THREAD, stom); // must handleize.365set_resolved_references(loader_data->add_handle(refs_handle));366}367}368}369}370371void ConstantPool::remove_unshareable_info() {372if (!_pool_holder->is_linked() && !_pool_holder->verified_at_dump_time()) {373return;374}375// Resolved references are not in the shared archive.376// Save the length for restoration. It is not necessarily the same length377// as reference_map.length() if invokedynamic is saved. It is needed when378// re-creating the resolved reference array if archived heap data cannot be map379// at runtime.380set_resolved_reference_length(381resolved_references() != NULL ? resolved_references()->length() : 0);382set_resolved_references(OopHandle());383384// Shared ConstantPools are in the RO region, so the _flags cannot be modified.385// The _on_stack flag is used to prevent ConstantPools from deallocation during386// class redefinition. Since shared ConstantPools cannot be deallocated anyway,387// we always set _on_stack to true to avoid having to change _flags during runtime.388_flags |= (_on_stack | _is_shared);389int num_klasses = 0;390for (int index = 1; index < length(); index++) { // Index 0 is unused391if (tag_at(index).is_unresolved_klass_in_error()) {392tag_at_put(index, JVM_CONSTANT_UnresolvedClass);393} else if (tag_at(index).is_method_handle_in_error()) {394tag_at_put(index, JVM_CONSTANT_MethodHandle);395} else if (tag_at(index).is_method_type_in_error()) {396tag_at_put(index, JVM_CONSTANT_MethodType);397} else if (tag_at(index).is_dynamic_constant_in_error()) {398tag_at_put(index, JVM_CONSTANT_Dynamic);399}400if (tag_at(index).is_klass()) {401// This class was resolved as a side effect of executing Java code402// during dump time. We need to restore it back to an UnresolvedClass,403// so that the proper class loading and initialization can happen404// at runtime.405bool clear_it = true;406if (pool_holder()->is_hidden() && index == pool_holder()->this_class_index()) {407// All references to a hidden class's own field/methods are through this408// index. We cannot clear it. See comments in ClassFileParser::fill_instance_klass.409clear_it = false;410}411if (clear_it) {412CPKlassSlot kslot = klass_slot_at(index);413int resolved_klass_index = kslot.resolved_klass_index();414int name_index = kslot.name_index();415assert(tag_at(name_index).is_symbol(), "sanity");416resolved_klasses()->at_put(resolved_klass_index, NULL);417tag_at_put(index, JVM_CONSTANT_UnresolvedClass);418assert(klass_name_at(index) == symbol_at(name_index), "sanity");419}420}421}422if (cache() != NULL) {423cache()->remove_unshareable_info();424}425}426427int ConstantPool::cp_to_object_index(int cp_index) {428// this is harder don't do this so much.429int i = reference_map()->find(cp_index);430// We might not find the index for jsr292 call.431return (i < 0) ? _no_index_sentinel : i;432}433434void ConstantPool::string_at_put(int which, int obj_index, oop str) {435resolved_references()->obj_at_put(obj_index, str);436}437438void ConstantPool::trace_class_resolution(const constantPoolHandle& this_cp, Klass* k) {439ResourceMark rm;440int line_number = -1;441const char * source_file = NULL;442if (JavaThread::current()->has_last_Java_frame()) {443// try to identify the method which called this function.444vframeStream vfst(JavaThread::current());445if (!vfst.at_end()) {446line_number = vfst.method()->line_number_from_bci(vfst.bci());447Symbol* s = vfst.method()->method_holder()->source_file_name();448if (s != NULL) {449source_file = s->as_C_string();450}451}452}453if (k != this_cp->pool_holder()) {454// only print something if the classes are different455if (source_file != NULL) {456log_debug(class, resolve)("%s %s %s:%d",457this_cp->pool_holder()->external_name(),458k->external_name(), source_file, line_number);459} else {460log_debug(class, resolve)("%s %s",461this_cp->pool_holder()->external_name(),462k->external_name());463}464}465}466467Klass* ConstantPool::klass_at_impl(const constantPoolHandle& this_cp, int which,468TRAPS) {469JavaThread* javaThread = THREAD;470471// A resolved constantPool entry will contain a Klass*, otherwise a Symbol*.472// It is not safe to rely on the tag bit's here, since we don't have a lock, and473// the entry and tag is not updated atomicly.474CPKlassSlot kslot = this_cp->klass_slot_at(which);475int resolved_klass_index = kslot.resolved_klass_index();476int name_index = kslot.name_index();477assert(this_cp->tag_at(name_index).is_symbol(), "sanity");478479// The tag must be JVM_CONSTANT_Class in order to read the correct value from480// the unresolved_klasses() array.481if (this_cp->tag_at(which).is_klass()) {482Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);483if (klass != NULL) {484return klass;485}486}487488// This tag doesn't change back to unresolved class unless at a safepoint.489if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {490// The original attempt to resolve this constant pool entry failed so find the491// class of the original error and throw another error of the same class492// (JVMS 5.4.3).493// If there is a detail message, pass that detail message to the error.494// The JVMS does not strictly require us to duplicate the same detail message,495// or any internal exception fields such as cause or stacktrace. But since the496// detail message is often a class name or other literal string, we will repeat it497// if we can find it in the symbol table.498throw_resolution_error(this_cp, which, CHECK_NULL);499ShouldNotReachHere();500}501502Handle mirror_handle;503Symbol* name = this_cp->symbol_at(name_index);504Handle loader (THREAD, this_cp->pool_holder()->class_loader());505Handle protection_domain (THREAD, this_cp->pool_holder()->protection_domain());506507Klass* k;508{509// Turn off the single stepping while doing class resolution510JvmtiHideSingleStepping jhss(javaThread);511k = SystemDictionary::resolve_or_fail(name, loader, protection_domain, true, THREAD);512} // JvmtiHideSingleStepping jhss(javaThread);513514if (!HAS_PENDING_EXCEPTION) {515// preserve the resolved klass from unloading516mirror_handle = Handle(THREAD, k->java_mirror());517// Do access check for klasses518verify_constant_pool_resolve(this_cp, k, THREAD);519}520521// Failed to resolve class. We must record the errors so that subsequent attempts522// to resolve this constant pool entry fail with the same error (JVMS 5.4.3).523if (HAS_PENDING_EXCEPTION) {524save_and_throw_exception(this_cp, which, constantTag(JVM_CONSTANT_UnresolvedClass), CHECK_NULL);525// If CHECK_NULL above doesn't return the exception, that means that526// some other thread has beaten us and has resolved the class.527// To preserve old behavior, we return the resolved class.528Klass* klass = this_cp->resolved_klasses()->at(resolved_klass_index);529assert(klass != NULL, "must be resolved if exception was cleared");530return klass;531}532533// logging for class+resolve.534if (log_is_enabled(Debug, class, resolve)){535trace_class_resolution(this_cp, k);536}537538Klass** adr = this_cp->resolved_klasses()->adr_at(resolved_klass_index);539Atomic::release_store(adr, k);540// The interpreter assumes when the tag is stored, the klass is resolved541// and the Klass* stored in _resolved_klasses is non-NULL, so we need542// hardware store ordering here.543// We also need to CAS to not overwrite an error from a racing thread.544545jbyte old_tag = Atomic::cmpxchg((jbyte*)this_cp->tag_addr_at(which),546(jbyte)JVM_CONSTANT_UnresolvedClass,547(jbyte)JVM_CONSTANT_Class);548549// We need to recheck exceptions from racing thread and return the same.550if (old_tag == JVM_CONSTANT_UnresolvedClassInError) {551// Remove klass.552this_cp->resolved_klasses()->at_put(resolved_klass_index, NULL);553throw_resolution_error(this_cp, which, CHECK_NULL);554}555556return k;557}558559560// Does not update ConstantPool* - to avoid any exception throwing. Used561// by compiler and exception handling. Also used to avoid classloads for562// instanceof operations. Returns NULL if the class has not been loaded or563// if the verification of constant pool failed564Klass* ConstantPool::klass_at_if_loaded(const constantPoolHandle& this_cp, int which) {565CPKlassSlot kslot = this_cp->klass_slot_at(which);566int resolved_klass_index = kslot.resolved_klass_index();567int name_index = kslot.name_index();568assert(this_cp->tag_at(name_index).is_symbol(), "sanity");569570if (this_cp->tag_at(which).is_klass()) {571Klass* k = this_cp->resolved_klasses()->at(resolved_klass_index);572assert(k != NULL, "should be resolved");573return k;574} else if (this_cp->tag_at(which).is_unresolved_klass_in_error()) {575return NULL;576} else {577Thread* current = Thread::current();578Symbol* name = this_cp->symbol_at(name_index);579oop loader = this_cp->pool_holder()->class_loader();580oop protection_domain = this_cp->pool_holder()->protection_domain();581Handle h_prot (current, protection_domain);582Handle h_loader (current, loader);583Klass* k = SystemDictionary::find_instance_klass(name, h_loader, h_prot);584585// Avoid constant pool verification at a safepoint, as it takes the Module_lock.586if (k != NULL && current->is_Java_thread()) {587// Make sure that resolving is legal588JavaThread* THREAD = current->as_Java_thread(); // For exception macros.589ExceptionMark em(THREAD);590// return NULL if verification fails591verify_constant_pool_resolve(this_cp, k, THREAD);592if (HAS_PENDING_EXCEPTION) {593CLEAR_PENDING_EXCEPTION;594return NULL;595}596return k;597} else {598return k;599}600}601}602603Method* ConstantPool::method_at_if_loaded(const constantPoolHandle& cpool,604int which) {605if (cpool->cache() == NULL) return NULL; // nothing to load yet606int cache_index = decode_cpcache_index(which, true);607if (!(cache_index >= 0 && cache_index < cpool->cache()->length())) {608// FIXME: should be an assert609log_debug(class, resolve)("bad operand %d in:", which); cpool->print();610return NULL;611}612ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);613return e->method_if_resolved(cpool);614}615616617bool ConstantPool::has_appendix_at_if_loaded(const constantPoolHandle& cpool, int which) {618if (cpool->cache() == NULL) return false; // nothing to load yet619int cache_index = decode_cpcache_index(which, true);620ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);621return e->has_appendix();622}623624oop ConstantPool::appendix_at_if_loaded(const constantPoolHandle& cpool, int which) {625if (cpool->cache() == NULL) return NULL; // nothing to load yet626int cache_index = decode_cpcache_index(which, true);627ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);628return e->appendix_if_resolved(cpool);629}630631632bool ConstantPool::has_local_signature_at_if_loaded(const constantPoolHandle& cpool, int which) {633if (cpool->cache() == NULL) return false; // nothing to load yet634int cache_index = decode_cpcache_index(which, true);635ConstantPoolCacheEntry* e = cpool->cache()->entry_at(cache_index);636return e->has_local_signature();637}638639Symbol* ConstantPool::impl_name_ref_at(int which, bool uncached) {640int name_index = name_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));641return symbol_at(name_index);642}643644645Symbol* ConstantPool::impl_signature_ref_at(int which, bool uncached) {646int signature_index = signature_ref_index_at(impl_name_and_type_ref_index_at(which, uncached));647return symbol_at(signature_index);648}649650int ConstantPool::impl_name_and_type_ref_index_at(int which, bool uncached) {651int i = which;652if (!uncached && cache() != NULL) {653if (ConstantPool::is_invokedynamic_index(which)) {654// Invokedynamic index is index into the constant pool cache655int pool_index = invokedynamic_bootstrap_ref_index_at(which);656pool_index = bootstrap_name_and_type_ref_index_at(pool_index);657assert(tag_at(pool_index).is_name_and_type(), "");658return pool_index;659}660// change byte-ordering and go via cache661i = remap_instruction_operand_from_cache(which);662} else {663if (tag_at(which).has_bootstrap()) {664int pool_index = bootstrap_name_and_type_ref_index_at(which);665assert(tag_at(pool_index).is_name_and_type(), "");666return pool_index;667}668}669assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");670assert(!tag_at(i).has_bootstrap(), "Must be handled above");671jint ref_index = *int_at_addr(i);672return extract_high_short_from_int(ref_index);673}674675constantTag ConstantPool::impl_tag_ref_at(int which, bool uncached) {676int pool_index = which;677if (!uncached && cache() != NULL) {678if (ConstantPool::is_invokedynamic_index(which)) {679// Invokedynamic index is index into resolved_references680pool_index = invokedynamic_bootstrap_ref_index_at(which);681} else {682// change byte-ordering and go via cache683pool_index = remap_instruction_operand_from_cache(which);684}685}686return tag_at(pool_index);687}688689int ConstantPool::impl_klass_ref_index_at(int which, bool uncached) {690guarantee(!ConstantPool::is_invokedynamic_index(which),691"an invokedynamic instruction does not have a klass");692int i = which;693if (!uncached && cache() != NULL) {694// change byte-ordering and go via cache695i = remap_instruction_operand_from_cache(which);696}697assert(tag_at(i).is_field_or_method(), "Corrupted constant pool");698jint ref_index = *int_at_addr(i);699return extract_low_short_from_int(ref_index);700}701702703704int ConstantPool::remap_instruction_operand_from_cache(int operand) {705int cpc_index = operand;706DEBUG_ONLY(cpc_index -= CPCACHE_INDEX_TAG);707assert((int)(u2)cpc_index == cpc_index, "clean u2");708int member_index = cache()->entry_at(cpc_index)->constant_pool_index();709return member_index;710}711712713void ConstantPool::verify_constant_pool_resolve(const constantPoolHandle& this_cp, Klass* k, TRAPS) {714if (!(k->is_instance_klass() || k->is_objArray_klass())) {715return; // short cut, typeArray klass is always accessible716}717Klass* holder = this_cp->pool_holder();718LinkResolver::check_klass_accessibility(holder, k, CHECK);719}720721722int ConstantPool::name_ref_index_at(int which_nt) {723jint ref_index = name_and_type_at(which_nt);724return extract_low_short_from_int(ref_index);725}726727728int ConstantPool::signature_ref_index_at(int which_nt) {729jint ref_index = name_and_type_at(which_nt);730return extract_high_short_from_int(ref_index);731}732733734Klass* ConstantPool::klass_ref_at(int which, TRAPS) {735return klass_at(klass_ref_index_at(which), THREAD);736}737738Symbol* ConstantPool::klass_name_at(int which) const {739return symbol_at(klass_slot_at(which).name_index());740}741742Symbol* ConstantPool::klass_ref_at_noresolve(int which) {743jint ref_index = klass_ref_index_at(which);744return klass_at_noresolve(ref_index);745}746747Symbol* ConstantPool::uncached_klass_ref_at_noresolve(int which) {748jint ref_index = uncached_klass_ref_index_at(which);749return klass_at_noresolve(ref_index);750}751752char* ConstantPool::string_at_noresolve(int which) {753return unresolved_string_at(which)->as_C_string();754}755756BasicType ConstantPool::basic_type_for_signature_at(int which) const {757return Signature::basic_type(symbol_at(which));758}759760761void ConstantPool::resolve_string_constants_impl(const constantPoolHandle& this_cp, TRAPS) {762for (int index = 1; index < this_cp->length(); index++) { // Index 0 is unused763if (this_cp->tag_at(index).is_string()) {764this_cp->string_at(index, CHECK);765}766}767}768769static Symbol* exception_message(const constantPoolHandle& this_cp, int which, constantTag tag, oop pending_exception) {770// Dig out the detailed message to reuse if possible771Symbol* message = java_lang_Throwable::detail_message(pending_exception);772if (message != NULL) {773return message;774}775776// Return specific message for the tag777switch (tag.value()) {778case JVM_CONSTANT_UnresolvedClass:779// return the class name in the error message780message = this_cp->klass_name_at(which);781break;782case JVM_CONSTANT_MethodHandle:783// return the method handle name in the error message784message = this_cp->method_handle_name_ref_at(which);785break;786case JVM_CONSTANT_MethodType:787// return the method type signature in the error message788message = this_cp->method_type_signature_at(which);789break;790case JVM_CONSTANT_Dynamic:791// return the name of the condy in the error message792message = this_cp->uncached_name_ref_at(which);793break;794default:795ShouldNotReachHere();796}797798return message;799}800801static void add_resolution_error(const constantPoolHandle& this_cp, int which,802constantTag tag, oop pending_exception) {803804Symbol* error = pending_exception->klass()->name();805oop cause = java_lang_Throwable::cause(pending_exception);806807// Also dig out the exception cause, if present.808Symbol* cause_sym = NULL;809Symbol* cause_msg = NULL;810if (cause != NULL && cause != pending_exception) {811cause_sym = cause->klass()->name();812cause_msg = java_lang_Throwable::detail_message(cause);813}814815Symbol* message = exception_message(this_cp, which, tag, pending_exception);816SystemDictionary::add_resolution_error(this_cp, which, error, message, cause_sym, cause_msg);817}818819820void ConstantPool::throw_resolution_error(const constantPoolHandle& this_cp, int which, TRAPS) {821ResourceMark rm(THREAD);822Symbol* message = NULL;823Symbol* cause = NULL;824Symbol* cause_msg = NULL;825Symbol* error = SystemDictionary::find_resolution_error(this_cp, which, &message, &cause, &cause_msg);826assert(error != NULL, "checking");827const char* cause_str = cause_msg != NULL ? cause_msg->as_C_string() : NULL;828829CLEAR_PENDING_EXCEPTION;830if (message != NULL) {831char* msg = message->as_C_string();832if (cause != NULL) {833Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_str);834THROW_MSG_CAUSE(error, msg, h_cause);835} else {836THROW_MSG(error, msg);837}838} else {839if (cause != NULL) {840Handle h_cause = Exceptions::new_exception(THREAD, cause, cause_str);841THROW_CAUSE(error, h_cause);842} else {843THROW(error);844}845}846}847848// If resolution for Class, Dynamic constant, MethodHandle or MethodType fails, save the849// exception in the resolution error table, so that the same exception is thrown again.850void ConstantPool::save_and_throw_exception(const constantPoolHandle& this_cp, int which,851constantTag tag, TRAPS) {852853int error_tag = tag.error_value();854855if (!PENDING_EXCEPTION->856is_a(vmClasses::LinkageError_klass())) {857// Just throw the exception and don't prevent these classes from858// being loaded due to virtual machine errors like StackOverflow859// and OutOfMemoryError, etc, or if the thread was hit by stop()860// Needs clarification to section 5.4.3 of the VM spec (see 6308271)861} else if (this_cp->tag_at(which).value() != error_tag) {862add_resolution_error(this_cp, which, tag, PENDING_EXCEPTION);863// CAS in the tag. If a thread beat us to registering this error that's fine.864// If another thread resolved the reference, this is a race condition. This865// thread may have had a security manager or something temporary.866// This doesn't deterministically get an error. So why do we save this?867// We save this because jvmti can add classes to the bootclass path after868// this error, so it needs to get the same error if the error is first.869jbyte old_tag = Atomic::cmpxchg((jbyte*)this_cp->tag_addr_at(which),870(jbyte)tag.value(),871(jbyte)error_tag);872if (old_tag != error_tag && old_tag != tag.value()) {873// MethodHandles and MethodType doesn't change to resolved version.874assert(this_cp->tag_at(which).is_klass(), "Wrong tag value");875// Forget the exception and use the resolved class.876CLEAR_PENDING_EXCEPTION;877}878} else {879// some other thread put this in error state880throw_resolution_error(this_cp, which, CHECK);881}882}883884constantTag ConstantPool::constant_tag_at(int which) {885constantTag tag = tag_at(which);886if (tag.is_dynamic_constant()) {887BasicType bt = basic_type_for_constant_at(which);888return constantTag(constantTag::type2tag(bt));889}890return tag;891}892893BasicType ConstantPool::basic_type_for_constant_at(int which) {894constantTag tag = tag_at(which);895if (tag.is_dynamic_constant() ||896tag.is_dynamic_constant_in_error()) {897// have to look at the signature for this one898Symbol* constant_type = uncached_signature_ref_at(which);899return Signature::basic_type(constant_type);900}901return tag.basic_type();902}903904// Called to resolve constants in the constant pool and return an oop.905// Some constant pool entries cache their resolved oop. This is also906// called to create oops from constants to use in arguments for invokedynamic907oop ConstantPool::resolve_constant_at_impl(const constantPoolHandle& this_cp,908int index, int cache_index,909bool* status_return, TRAPS) {910oop result_oop = NULL;911Handle throw_exception;912913if (cache_index == _possible_index_sentinel) {914// It is possible that this constant is one which is cached in the objects.915// We'll do a linear search. This should be OK because this usage is rare.916// FIXME: If bootstrap specifiers stress this code, consider putting in917// a reverse index. Binary search over a short array should do it.918assert(index > 0, "valid index");919cache_index = this_cp->cp_to_object_index(index);920}921assert(cache_index == _no_index_sentinel || cache_index >= 0, "");922assert(index == _no_index_sentinel || index >= 0, "");923924if (cache_index >= 0) {925result_oop = this_cp->resolved_references()->obj_at(cache_index);926if (result_oop != NULL) {927if (result_oop == Universe::the_null_sentinel()) {928DEBUG_ONLY(int temp_index = (index >= 0 ? index : this_cp->object_to_cp_index(cache_index)));929assert(this_cp->tag_at(temp_index).is_dynamic_constant(), "only condy uses the null sentinel");930result_oop = NULL;931}932if (status_return != NULL) (*status_return) = true;933return result_oop;934// That was easy...935}936index = this_cp->object_to_cp_index(cache_index);937}938939jvalue prim_value; // temp used only in a few cases below940941constantTag tag = this_cp->tag_at(index);942943if (status_return != NULL) {944// don't trigger resolution if the constant might need it945switch (tag.value()) {946case JVM_CONSTANT_Class:947{948CPKlassSlot kslot = this_cp->klass_slot_at(index);949int resolved_klass_index = kslot.resolved_klass_index();950if (this_cp->resolved_klasses()->at(resolved_klass_index) == NULL) {951(*status_return) = false;952return NULL;953}954// the klass is waiting in the CP; go get it955break;956}957case JVM_CONSTANT_String:958case JVM_CONSTANT_Integer:959case JVM_CONSTANT_Float:960case JVM_CONSTANT_Long:961case JVM_CONSTANT_Double:962// these guys trigger OOM at worst963break;964default:965(*status_return) = false;966return NULL;967}968// from now on there is either success or an OOME969(*status_return) = true;970}971972switch (tag.value()) {973974case JVM_CONSTANT_UnresolvedClass:975case JVM_CONSTANT_Class:976{977assert(cache_index == _no_index_sentinel, "should not have been set");978Klass* resolved = klass_at_impl(this_cp, index, CHECK_NULL);979// ldc wants the java mirror.980result_oop = resolved->java_mirror();981break;982}983984case JVM_CONSTANT_Dynamic:985{986// Resolve the Dynamically-Computed constant to invoke the BSM in order to obtain the resulting oop.987BootstrapInfo bootstrap_specifier(this_cp, index);988989// The initial step in resolving an unresolved symbolic reference to a990// dynamically-computed constant is to resolve the symbolic reference to a991// method handle which will be the bootstrap method for the dynamically-computed992// constant. If resolution of the java.lang.invoke.MethodHandle for the bootstrap993// method fails, then a MethodHandleInError is stored at the corresponding994// bootstrap method's CP index for the CONSTANT_MethodHandle_info. No need to995// set a DynamicConstantInError here since any subsequent use of this996// bootstrap method will encounter the resolution of MethodHandleInError.997// Both the first, (resolution of the BSM and its static arguments), and the second tasks,998// (invocation of the BSM), of JVMS Section 5.4.3.6 occur within invoke_bootstrap_method()999// for the bootstrap_specifier created above.1000SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);1001Exceptions::wrap_dynamic_exception(/* is_indy */ false, THREAD);1002if (HAS_PENDING_EXCEPTION) {1003// Resolution failure of the dynamically-computed constant, save_and_throw_exception1004// will check for a LinkageError and store a DynamicConstantInError.1005save_and_throw_exception(this_cp, index, tag, CHECK_NULL);1006}1007result_oop = bootstrap_specifier.resolved_value()();1008BasicType type = Signature::basic_type(bootstrap_specifier.signature());1009if (!is_reference_type(type)) {1010// Make sure the primitive value is properly boxed.1011// This is a JDK responsibility.1012const char* fail = NULL;1013if (result_oop == NULL) {1014fail = "null result instead of box";1015} else if (!is_java_primitive(type)) {1016// FIXME: support value types via unboxing1017fail = "can only handle references and primitives";1018} else if (!java_lang_boxing_object::is_instance(result_oop, type)) {1019fail = "primitive is not properly boxed";1020}1021if (fail != NULL) {1022// Since this exception is not a LinkageError, throw exception1023// but do not save a DynamicInError resolution result.1024// See section 5.4.3 of the VM spec.1025THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), fail);1026}1027}10281029LogTarget(Debug, methodhandles, condy) lt_condy;1030if (lt_condy.is_enabled()) {1031LogStream ls(lt_condy);1032bootstrap_specifier.print_msg_on(&ls, "resolve_constant_at_impl");1033}1034break;1035}10361037case JVM_CONSTANT_String:1038assert(cache_index != _no_index_sentinel, "should have been set");1039result_oop = string_at_impl(this_cp, index, cache_index, CHECK_NULL);1040break;10411042case JVM_CONSTANT_MethodHandle:1043{1044int ref_kind = this_cp->method_handle_ref_kind_at(index);1045int callee_index = this_cp->method_handle_klass_index_at(index);1046Symbol* name = this_cp->method_handle_name_ref_at(index);1047Symbol* signature = this_cp->method_handle_signature_ref_at(index);1048constantTag m_tag = this_cp->tag_at(this_cp->method_handle_index_at(index));1049{ ResourceMark rm(THREAD);1050log_debug(class, resolve)("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",1051ref_kind, index, this_cp->method_handle_index_at(index),1052callee_index, name->as_C_string(), signature->as_C_string());1053}10541055Klass* callee = klass_at_impl(this_cp, callee_index, THREAD);1056if (HAS_PENDING_EXCEPTION) {1057save_and_throw_exception(this_cp, index, tag, CHECK_NULL);1058}10591060// Check constant pool method consistency1061if ((callee->is_interface() && m_tag.is_method()) ||1062(!callee->is_interface() && m_tag.is_interface_method())) {1063ResourceMark rm(THREAD);1064stringStream ss;1065ss.print("Inconsistent constant pool data in classfile for class %s. "1066"Method '", callee->name()->as_C_string());1067signature->print_as_signature_external_return_type(&ss);1068ss.print(" %s(", name->as_C_string());1069signature->print_as_signature_external_parameters(&ss);1070ss.print(")' at index %d is %s and should be %s",1071index,1072callee->is_interface() ? "CONSTANT_MethodRef" : "CONSTANT_InterfaceMethodRef",1073callee->is_interface() ? "CONSTANT_InterfaceMethodRef" : "CONSTANT_MethodRef");1074Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), "%s", ss.as_string());1075save_and_throw_exception(this_cp, index, tag, CHECK_NULL);1076}10771078Klass* klass = this_cp->pool_holder();1079Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,1080callee, name, signature,1081THREAD);1082if (HAS_PENDING_EXCEPTION) {1083save_and_throw_exception(this_cp, index, tag, CHECK_NULL);1084}1085result_oop = value();1086break;1087}10881089case JVM_CONSTANT_MethodType:1090{1091Symbol* signature = this_cp->method_type_signature_at(index);1092{ ResourceMark rm(THREAD);1093log_debug(class, resolve)("resolve JVM_CONSTANT_MethodType [%d/%d] %s",1094index, this_cp->method_type_index_at(index),1095signature->as_C_string());1096}1097Klass* klass = this_cp->pool_holder();1098Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);1099result_oop = value();1100if (HAS_PENDING_EXCEPTION) {1101save_and_throw_exception(this_cp, index, tag, CHECK_NULL);1102}1103break;1104}11051106case JVM_CONSTANT_Integer:1107assert(cache_index == _no_index_sentinel, "should not have been set");1108prim_value.i = this_cp->int_at(index);1109result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);1110break;11111112case JVM_CONSTANT_Float:1113assert(cache_index == _no_index_sentinel, "should not have been set");1114prim_value.f = this_cp->float_at(index);1115result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);1116break;11171118case JVM_CONSTANT_Long:1119assert(cache_index == _no_index_sentinel, "should not have been set");1120prim_value.j = this_cp->long_at(index);1121result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);1122break;11231124case JVM_CONSTANT_Double:1125assert(cache_index == _no_index_sentinel, "should not have been set");1126prim_value.d = this_cp->double_at(index);1127result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);1128break;11291130case JVM_CONSTANT_UnresolvedClassInError:1131case JVM_CONSTANT_DynamicInError:1132case JVM_CONSTANT_MethodHandleInError:1133case JVM_CONSTANT_MethodTypeInError:1134throw_resolution_error(this_cp, index, CHECK_NULL);1135break;11361137default:1138fatal("unexpected constant tag at CP %p[%d/%d] = %d", this_cp(), index, cache_index, tag.value());1139break;1140}11411142if (cache_index >= 0) {1143// Benign race condition: resolved_references may already be filled in.1144// The important thing here is that all threads pick up the same result.1145// It doesn't matter which racing thread wins, as long as only one1146// result is used by all threads, and all future queries.1147oop new_result = (result_oop == NULL ? Universe::the_null_sentinel() : result_oop);1148oop old_result = this_cp->resolved_references()1149->atomic_compare_exchange_oop(cache_index, new_result, NULL);1150if (old_result == NULL) {1151return result_oop; // was installed1152} else {1153// Return the winning thread's result. This can be different than1154// the result here for MethodHandles.1155if (old_result == Universe::the_null_sentinel())1156old_result = NULL;1157return old_result;1158}1159} else {1160assert(result_oop != Universe::the_null_sentinel(), "");1161return result_oop;1162}1163}11641165oop ConstantPool::uncached_string_at(int which, TRAPS) {1166Symbol* sym = unresolved_string_at(which);1167oop str = StringTable::intern(sym, CHECK_(NULL));1168assert(java_lang_String::is_instance(str), "must be string");1169return str;1170}11711172void ConstantPool::copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int index,1173int start_arg, int end_arg,1174objArrayHandle info, int pos,1175bool must_resolve, Handle if_not_available,1176TRAPS) {1177int argc;1178int limit = pos + end_arg - start_arg;1179// checks: index in range [0..this_cp->length),1180// tag at index, start..end in range [0..argc],1181// info array non-null, pos..limit in [0..info.length]1182if ((0 >= index || index >= this_cp->length()) ||1183!(this_cp->tag_at(index).is_invoke_dynamic() ||1184this_cp->tag_at(index).is_dynamic_constant()) ||1185(0 > start_arg || start_arg > end_arg) ||1186(end_arg > (argc = this_cp->bootstrap_argument_count_at(index))) ||1187(0 > pos || pos > limit) ||1188(info.is_null() || limit > info->length())) {1189// An index or something else went wrong; throw an error.1190// Since this is an internal API, we don't expect this,1191// so we don't bother to craft a nice message.1192THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");1193}1194// now we can loop safely1195int info_i = pos;1196for (int i = start_arg; i < end_arg; i++) {1197int arg_index = this_cp->bootstrap_argument_index_at(index, i);1198oop arg_oop;1199if (must_resolve) {1200arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);1201} else {1202bool found_it = false;1203arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);1204if (!found_it) arg_oop = if_not_available();1205}1206info->obj_at_put(info_i++, arg_oop);1207}1208}12091210oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int which, int obj_index, TRAPS) {1211// If the string has already been interned, this entry will be non-null1212oop str = this_cp->resolved_references()->obj_at(obj_index);1213assert(str != Universe::the_null_sentinel(), "");1214if (str != NULL) return str;1215Symbol* sym = this_cp->unresolved_string_at(which);1216str = StringTable::intern(sym, CHECK_(NULL));1217this_cp->string_at_put(which, obj_index, str);1218assert(java_lang_String::is_instance(str), "must be string");1219return str;1220}122112221223bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int which) {1224// Names are interned, so we can compare Symbol*s directly1225Symbol* cp_name = klass_name_at(which);1226return (cp_name == k->name());1227}122812291230// Iterate over symbols and decrement ones which are Symbol*s1231// This is done during GC.1232// Only decrement the UTF8 symbols. Strings point to1233// these symbols but didn't increment the reference count.1234void ConstantPool::unreference_symbols() {1235for (int index = 1; index < length(); index++) { // Index 0 is unused1236constantTag tag = tag_at(index);1237if (tag.is_symbol()) {1238symbol_at(index)->decrement_refcount();1239}1240}1241}124212431244// Compare this constant pool's entry at index1 to the constant pool1245// cp2's entry at index2.1246bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,1247int index2) {12481249// The error tags are equivalent to non-error tags when comparing1250jbyte t1 = tag_at(index1).non_error_value();1251jbyte t2 = cp2->tag_at(index2).non_error_value();12521253if (t1 != t2) {1254// Not the same entry type so there is nothing else to check. Note1255// that this style of checking will consider resolved/unresolved1256// class pairs as different.1257// From the ConstantPool* API point of view, this is correct1258// behavior. See VM_RedefineClasses::merge_constant_pools() to see how this1259// plays out in the context of ConstantPool* merging.1260return false;1261}12621263switch (t1) {1264case JVM_CONSTANT_Class:1265{1266Klass* k1 = resolved_klass_at(index1);1267Klass* k2 = cp2->resolved_klass_at(index2);1268if (k1 == k2) {1269return true;1270}1271} break;12721273case JVM_CONSTANT_ClassIndex:1274{1275int recur1 = klass_index_at(index1);1276int recur2 = cp2->klass_index_at(index2);1277if (compare_entry_to(recur1, cp2, recur2)) {1278return true;1279}1280} break;12811282case JVM_CONSTANT_Double:1283{1284jdouble d1 = double_at(index1);1285jdouble d2 = cp2->double_at(index2);1286if (d1 == d2) {1287return true;1288}1289} break;12901291case JVM_CONSTANT_Fieldref:1292case JVM_CONSTANT_InterfaceMethodref:1293case JVM_CONSTANT_Methodref:1294{1295int recur1 = uncached_klass_ref_index_at(index1);1296int recur2 = cp2->uncached_klass_ref_index_at(index2);1297bool match = compare_entry_to(recur1, cp2, recur2);1298if (match) {1299recur1 = uncached_name_and_type_ref_index_at(index1);1300recur2 = cp2->uncached_name_and_type_ref_index_at(index2);1301if (compare_entry_to(recur1, cp2, recur2)) {1302return true;1303}1304}1305} break;13061307case JVM_CONSTANT_Float:1308{1309jfloat f1 = float_at(index1);1310jfloat f2 = cp2->float_at(index2);1311if (f1 == f2) {1312return true;1313}1314} break;13151316case JVM_CONSTANT_Integer:1317{1318jint i1 = int_at(index1);1319jint i2 = cp2->int_at(index2);1320if (i1 == i2) {1321return true;1322}1323} break;13241325case JVM_CONSTANT_Long:1326{1327jlong l1 = long_at(index1);1328jlong l2 = cp2->long_at(index2);1329if (l1 == l2) {1330return true;1331}1332} break;13331334case JVM_CONSTANT_NameAndType:1335{1336int recur1 = name_ref_index_at(index1);1337int recur2 = cp2->name_ref_index_at(index2);1338if (compare_entry_to(recur1, cp2, recur2)) {1339recur1 = signature_ref_index_at(index1);1340recur2 = cp2->signature_ref_index_at(index2);1341if (compare_entry_to(recur1, cp2, recur2)) {1342return true;1343}1344}1345} break;13461347case JVM_CONSTANT_StringIndex:1348{1349int recur1 = string_index_at(index1);1350int recur2 = cp2->string_index_at(index2);1351if (compare_entry_to(recur1, cp2, recur2)) {1352return true;1353}1354} break;13551356case JVM_CONSTANT_UnresolvedClass:1357{1358Symbol* k1 = klass_name_at(index1);1359Symbol* k2 = cp2->klass_name_at(index2);1360if (k1 == k2) {1361return true;1362}1363} break;13641365case JVM_CONSTANT_MethodType:1366{1367int k1 = method_type_index_at(index1);1368int k2 = cp2->method_type_index_at(index2);1369if (compare_entry_to(k1, cp2, k2)) {1370return true;1371}1372} break;13731374case JVM_CONSTANT_MethodHandle:1375{1376int k1 = method_handle_ref_kind_at(index1);1377int k2 = cp2->method_handle_ref_kind_at(index2);1378if (k1 == k2) {1379int i1 = method_handle_index_at(index1);1380int i2 = cp2->method_handle_index_at(index2);1381if (compare_entry_to(i1, cp2, i2)) {1382return true;1383}1384}1385} break;13861387case JVM_CONSTANT_Dynamic:1388{1389int k1 = bootstrap_name_and_type_ref_index_at(index1);1390int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);1391int i1 = bootstrap_methods_attribute_index(index1);1392int i2 = cp2->bootstrap_methods_attribute_index(index2);1393bool match_entry = compare_entry_to(k1, cp2, k2);1394bool match_operand = compare_operand_to(i1, cp2, i2);1395return (match_entry && match_operand);1396} break;13971398case JVM_CONSTANT_InvokeDynamic:1399{1400int k1 = bootstrap_name_and_type_ref_index_at(index1);1401int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);1402int i1 = bootstrap_methods_attribute_index(index1);1403int i2 = cp2->bootstrap_methods_attribute_index(index2);1404bool match_entry = compare_entry_to(k1, cp2, k2);1405bool match_operand = compare_operand_to(i1, cp2, i2);1406return (match_entry && match_operand);1407} break;14081409case JVM_CONSTANT_String:1410{1411Symbol* s1 = unresolved_string_at(index1);1412Symbol* s2 = cp2->unresolved_string_at(index2);1413if (s1 == s2) {1414return true;1415}1416} break;14171418case JVM_CONSTANT_Utf8:1419{1420Symbol* s1 = symbol_at(index1);1421Symbol* s2 = cp2->symbol_at(index2);1422if (s1 == s2) {1423return true;1424}1425} break;14261427// Invalid is used as the tag for the second constant pool entry1428// occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should1429// not be seen by itself.1430case JVM_CONSTANT_Invalid: // fall through14311432default:1433ShouldNotReachHere();1434break;1435}14361437return false;1438} // end compare_entry_to()143914401441// Resize the operands array with delta_len and delta_size.1442// Used in RedefineClasses for CP merge.1443void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {1444int old_len = operand_array_length(operands());1445int new_len = old_len + delta_len;1446int min_len = (delta_len > 0) ? old_len : new_len;14471448int old_size = operands()->length();1449int new_size = old_size + delta_size;1450int min_size = (delta_size > 0) ? old_size : new_size;14511452ClassLoaderData* loader_data = pool_holder()->class_loader_data();1453Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);14541455// Set index in the resized array for existing elements only1456for (int idx = 0; idx < min_len; idx++) {1457int offset = operand_offset_at(idx); // offset in original array1458operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array1459}1460// Copy the bootstrap specifiers only1461Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),1462new_ops->adr_at(2*new_len),1463(min_size - 2*min_len) * sizeof(u2));1464// Explicitly deallocate old operands array.1465// Note, it is not needed for 7u backport.1466if ( operands() != NULL) { // the safety check1467MetadataFactory::free_array<u2>(loader_data, operands());1468}1469set_operands(new_ops);1470} // end resize_operands()147114721473// Extend the operands array with the length and size of the ext_cp operands.1474// Used in RedefineClasses for CP merge.1475void ConstantPool::extend_operands(const constantPoolHandle& ext_cp, TRAPS) {1476int delta_len = operand_array_length(ext_cp->operands());1477if (delta_len == 0) {1478return; // nothing to do1479}1480int delta_size = ext_cp->operands()->length();14811482assert(delta_len > 0 && delta_size > 0, "extended operands array must be bigger");14831484if (operand_array_length(operands()) == 0) {1485ClassLoaderData* loader_data = pool_holder()->class_loader_data();1486Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);1487// The first element index defines the offset of second part1488operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array1489set_operands(new_ops);1490} else {1491resize_operands(delta_len, delta_size, CHECK);1492}14931494} // end extend_operands()149514961497// Shrink the operands array to a smaller array with new_len length.1498// Used in RedefineClasses for CP merge.1499void ConstantPool::shrink_operands(int new_len, TRAPS) {1500int old_len = operand_array_length(operands());1501if (new_len == old_len) {1502return; // nothing to do1503}1504assert(new_len < old_len, "shrunken operands array must be smaller");15051506int free_base = operand_next_offset_at(new_len - 1);1507int delta_len = new_len - old_len;1508int delta_size = 2*delta_len + free_base - operands()->length();15091510resize_operands(delta_len, delta_size, CHECK);15111512} // end shrink_operands()151315141515void ConstantPool::copy_operands(const constantPoolHandle& from_cp,1516const constantPoolHandle& to_cp,1517TRAPS) {15181519int from_oplen = operand_array_length(from_cp->operands());1520int old_oplen = operand_array_length(to_cp->operands());1521if (from_oplen != 0) {1522ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();1523// append my operands to the target's operands array1524if (old_oplen == 0) {1525// Can't just reuse from_cp's operand list because of deallocation issues1526int len = from_cp->operands()->length();1527Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);1528Copy::conjoint_memory_atomic(1529from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));1530to_cp->set_operands(new_ops);1531} else {1532int old_len = to_cp->operands()->length();1533int from_len = from_cp->operands()->length();1534int old_off = old_oplen * sizeof(u2);1535int from_off = from_oplen * sizeof(u2);1536// Use the metaspace for the destination constant pool1537Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);1538int fillp = 0, len = 0;1539// first part of dest1540Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),1541new_operands->adr_at(fillp),1542(len = old_off) * sizeof(u2));1543fillp += len;1544// first part of src1545Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),1546new_operands->adr_at(fillp),1547(len = from_off) * sizeof(u2));1548fillp += len;1549// second part of dest1550Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),1551new_operands->adr_at(fillp),1552(len = old_len - old_off) * sizeof(u2));1553fillp += len;1554// second part of src1555Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),1556new_operands->adr_at(fillp),1557(len = from_len - from_off) * sizeof(u2));1558fillp += len;1559assert(fillp == new_operands->length(), "");15601561// Adjust indexes in the first part of the copied operands array.1562for (int j = 0; j < from_oplen; j++) {1563int offset = operand_offset_at(new_operands, old_oplen + j);1564assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");1565offset += old_len; // every new tuple is preceded by old_len extra u2's1566operand_offset_at_put(new_operands, old_oplen + j, offset);1567}15681569// replace target operands array with combined array1570to_cp->set_operands(new_operands);1571}1572}1573} // end copy_operands()157415751576// Copy this constant pool's entries at start_i to end_i (inclusive)1577// to the constant pool to_cp's entries starting at to_i. A total of1578// (end_i - start_i) + 1 entries are copied.1579void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,1580const constantPoolHandle& to_cp, int to_i, TRAPS) {158115821583int dest_i = to_i; // leave original alone for debug purposes15841585for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {1586copy_entry_to(from_cp, src_i, to_cp, dest_i);15871588switch (from_cp->tag_at(src_i).value()) {1589case JVM_CONSTANT_Double:1590case JVM_CONSTANT_Long:1591// double and long take two constant pool entries1592src_i += 2;1593dest_i += 2;1594break;15951596default:1597// all others take one constant pool entry1598src_i++;1599dest_i++;1600break;1601}1602}1603copy_operands(from_cp, to_cp, CHECK);16041605} // end copy_cp_to_impl()160616071608// Copy this constant pool's entry at from_i to the constant pool1609// to_cp's entry at to_i.1610void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,1611const constantPoolHandle& to_cp, int to_i) {16121613int tag = from_cp->tag_at(from_i).value();1614switch (tag) {1615case JVM_CONSTANT_ClassIndex:1616{1617jint ki = from_cp->klass_index_at(from_i);1618to_cp->klass_index_at_put(to_i, ki);1619} break;16201621case JVM_CONSTANT_Double:1622{1623jdouble d = from_cp->double_at(from_i);1624to_cp->double_at_put(to_i, d);1625// double takes two constant pool entries so init second entry's tag1626to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);1627} break;16281629case JVM_CONSTANT_Fieldref:1630{1631int class_index = from_cp->uncached_klass_ref_index_at(from_i);1632int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);1633to_cp->field_at_put(to_i, class_index, name_and_type_index);1634} break;16351636case JVM_CONSTANT_Float:1637{1638jfloat f = from_cp->float_at(from_i);1639to_cp->float_at_put(to_i, f);1640} break;16411642case JVM_CONSTANT_Integer:1643{1644jint i = from_cp->int_at(from_i);1645to_cp->int_at_put(to_i, i);1646} break;16471648case JVM_CONSTANT_InterfaceMethodref:1649{1650int class_index = from_cp->uncached_klass_ref_index_at(from_i);1651int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);1652to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);1653} break;16541655case JVM_CONSTANT_Long:1656{1657jlong l = from_cp->long_at(from_i);1658to_cp->long_at_put(to_i, l);1659// long takes two constant pool entries so init second entry's tag1660to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);1661} break;16621663case JVM_CONSTANT_Methodref:1664{1665int class_index = from_cp->uncached_klass_ref_index_at(from_i);1666int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);1667to_cp->method_at_put(to_i, class_index, name_and_type_index);1668} break;16691670case JVM_CONSTANT_NameAndType:1671{1672int name_ref_index = from_cp->name_ref_index_at(from_i);1673int signature_ref_index = from_cp->signature_ref_index_at(from_i);1674to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);1675} break;16761677case JVM_CONSTANT_StringIndex:1678{1679jint si = from_cp->string_index_at(from_i);1680to_cp->string_index_at_put(to_i, si);1681} break;16821683case JVM_CONSTANT_Class:1684case JVM_CONSTANT_UnresolvedClass:1685case JVM_CONSTANT_UnresolvedClassInError:1686{1687// Revert to JVM_CONSTANT_ClassIndex1688int name_index = from_cp->klass_slot_at(from_i).name_index();1689assert(from_cp->tag_at(name_index).is_symbol(), "sanity");1690to_cp->klass_index_at_put(to_i, name_index);1691} break;16921693case JVM_CONSTANT_String:1694{1695Symbol* s = from_cp->unresolved_string_at(from_i);1696to_cp->unresolved_string_at_put(to_i, s);1697} break;16981699case JVM_CONSTANT_Utf8:1700{1701Symbol* s = from_cp->symbol_at(from_i);1702// Need to increase refcount, the old one will be thrown away and deferenced1703s->increment_refcount();1704to_cp->symbol_at_put(to_i, s);1705} break;17061707case JVM_CONSTANT_MethodType:1708case JVM_CONSTANT_MethodTypeInError:1709{1710jint k = from_cp->method_type_index_at(from_i);1711to_cp->method_type_index_at_put(to_i, k);1712} break;17131714case JVM_CONSTANT_MethodHandle:1715case JVM_CONSTANT_MethodHandleInError:1716{1717int k1 = from_cp->method_handle_ref_kind_at(from_i);1718int k2 = from_cp->method_handle_index_at(from_i);1719to_cp->method_handle_index_at_put(to_i, k1, k2);1720} break;17211722case JVM_CONSTANT_Dynamic:1723case JVM_CONSTANT_DynamicInError:1724{1725int k1 = from_cp->bootstrap_methods_attribute_index(from_i);1726int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);1727k1 += operand_array_length(to_cp->operands()); // to_cp might already have operands1728to_cp->dynamic_constant_at_put(to_i, k1, k2);1729} break;17301731case JVM_CONSTANT_InvokeDynamic:1732{1733int k1 = from_cp->bootstrap_methods_attribute_index(from_i);1734int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);1735k1 += operand_array_length(to_cp->operands()); // to_cp might already have operands1736to_cp->invoke_dynamic_at_put(to_i, k1, k2);1737} break;17381739// Invalid is used as the tag for the second constant pool entry1740// occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should1741// not be seen by itself.1742case JVM_CONSTANT_Invalid: // fall through17431744default:1745{1746ShouldNotReachHere();1747} break;1748}1749} // end copy_entry_to()17501751// Search constant pool search_cp for an entry that matches this1752// constant pool's entry at pattern_i. Returns the index of a1753// matching entry or zero (0) if there is no matching entry.1754int ConstantPool::find_matching_entry(int pattern_i,1755const constantPoolHandle& search_cp) {17561757// index zero (0) is not used1758for (int i = 1; i < search_cp->length(); i++) {1759bool found = compare_entry_to(pattern_i, search_cp, i);1760if (found) {1761return i;1762}1763}17641765return 0; // entry not found; return unused index zero (0)1766} // end find_matching_entry()176717681769// Compare this constant pool's bootstrap specifier at idx1 to the constant pool1770// cp2's bootstrap specifier at idx2.1771bool ConstantPool::compare_operand_to(int idx1, const constantPoolHandle& cp2, int idx2) {1772int k1 = operand_bootstrap_method_ref_index_at(idx1);1773int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);1774bool match = compare_entry_to(k1, cp2, k2);17751776if (!match) {1777return false;1778}1779int argc = operand_argument_count_at(idx1);1780if (argc == cp2->operand_argument_count_at(idx2)) {1781for (int j = 0; j < argc; j++) {1782k1 = operand_argument_index_at(idx1, j);1783k2 = cp2->operand_argument_index_at(idx2, j);1784match = compare_entry_to(k1, cp2, k2);1785if (!match) {1786return false;1787}1788}1789return true; // got through loop; all elements equal1790}1791return false;1792} // end compare_operand_to()17931794// Search constant pool search_cp for a bootstrap specifier that matches1795// this constant pool's bootstrap specifier data at pattern_i index.1796// Return the index of a matching bootstrap attribute record or (-1) if there is no match.1797int ConstantPool::find_matching_operand(int pattern_i,1798const constantPoolHandle& search_cp, int search_len) {1799for (int i = 0; i < search_len; i++) {1800bool found = compare_operand_to(pattern_i, search_cp, i);1801if (found) {1802return i;1803}1804}1805return -1; // bootstrap specifier data not found; return unused index (-1)1806} // end find_matching_operand()180718081809#ifndef PRODUCT18101811const char* ConstantPool::printable_name_at(int which) {18121813constantTag tag = tag_at(which);18141815if (tag.is_string()) {1816return string_at_noresolve(which);1817} else if (tag.is_klass() || tag.is_unresolved_klass()) {1818return klass_name_at(which)->as_C_string();1819} else if (tag.is_symbol()) {1820return symbol_at(which)->as_C_string();1821}1822return "";1823}18241825#endif // PRODUCT182618271828// JVMTI GetConstantPool support18291830// For debugging of constant pool1831const bool debug_cpool = false;18321833#define DBG(code) do { if (debug_cpool) { (code); } } while(0)18341835static void print_cpool_bytes(jint cnt, u1 *bytes) {1836const char* WARN_MSG = "Must not be such entry!";1837jint size = 0;1838u2 idx1, idx2;18391840for (jint idx = 1; idx < cnt; idx++) {1841jint ent_size = 0;1842u1 tag = *bytes++;1843size++; // count tag18441845printf("const #%03d, tag: %02d ", idx, tag);1846switch(tag) {1847case JVM_CONSTANT_Invalid: {1848printf("Invalid");1849break;1850}1851case JVM_CONSTANT_Unicode: {1852printf("Unicode %s", WARN_MSG);1853break;1854}1855case JVM_CONSTANT_Utf8: {1856u2 len = Bytes::get_Java_u2(bytes);1857char str[128];1858if (len > 127) {1859len = 127;1860}1861strncpy(str, (char *) (bytes+2), len);1862str[len] = '\0';1863printf("Utf8 \"%s\"", str);1864ent_size = 2 + len;1865break;1866}1867case JVM_CONSTANT_Integer: {1868u4 val = Bytes::get_Java_u4(bytes);1869printf("int %d", *(int *) &val);1870ent_size = 4;1871break;1872}1873case JVM_CONSTANT_Float: {1874u4 val = Bytes::get_Java_u4(bytes);1875printf("float %5.3ff", *(float *) &val);1876ent_size = 4;1877break;1878}1879case JVM_CONSTANT_Long: {1880u8 val = Bytes::get_Java_u8(bytes);1881printf("long " INT64_FORMAT, (int64_t) *(jlong *) &val);1882ent_size = 8;1883idx++; // Long takes two cpool slots1884break;1885}1886case JVM_CONSTANT_Double: {1887u8 val = Bytes::get_Java_u8(bytes);1888printf("double %5.3fd", *(jdouble *)&val);1889ent_size = 8;1890idx++; // Double takes two cpool slots1891break;1892}1893case JVM_CONSTANT_Class: {1894idx1 = Bytes::get_Java_u2(bytes);1895printf("class #%03d", idx1);1896ent_size = 2;1897break;1898}1899case JVM_CONSTANT_String: {1900idx1 = Bytes::get_Java_u2(bytes);1901printf("String #%03d", idx1);1902ent_size = 2;1903break;1904}1905case JVM_CONSTANT_Fieldref: {1906idx1 = Bytes::get_Java_u2(bytes);1907idx2 = Bytes::get_Java_u2(bytes+2);1908printf("Field #%03d, #%03d", (int) idx1, (int) idx2);1909ent_size = 4;1910break;1911}1912case JVM_CONSTANT_Methodref: {1913idx1 = Bytes::get_Java_u2(bytes);1914idx2 = Bytes::get_Java_u2(bytes+2);1915printf("Method #%03d, #%03d", idx1, idx2);1916ent_size = 4;1917break;1918}1919case JVM_CONSTANT_InterfaceMethodref: {1920idx1 = Bytes::get_Java_u2(bytes);1921idx2 = Bytes::get_Java_u2(bytes+2);1922printf("InterfMethod #%03d, #%03d", idx1, idx2);1923ent_size = 4;1924break;1925}1926case JVM_CONSTANT_NameAndType: {1927idx1 = Bytes::get_Java_u2(bytes);1928idx2 = Bytes::get_Java_u2(bytes+2);1929printf("NameAndType #%03d, #%03d", idx1, idx2);1930ent_size = 4;1931break;1932}1933case JVM_CONSTANT_ClassIndex: {1934printf("ClassIndex %s", WARN_MSG);1935break;1936}1937case JVM_CONSTANT_UnresolvedClass: {1938printf("UnresolvedClass: %s", WARN_MSG);1939break;1940}1941case JVM_CONSTANT_UnresolvedClassInError: {1942printf("UnresolvedClassInErr: %s", WARN_MSG);1943break;1944}1945case JVM_CONSTANT_StringIndex: {1946printf("StringIndex: %s", WARN_MSG);1947break;1948}1949}1950printf(";\n");1951bytes += ent_size;1952size += ent_size;1953}1954printf("Cpool size: %d\n", size);1955fflush(0);1956return;1957} /* end print_cpool_bytes */195819591960// Returns size of constant pool entry.1961jint ConstantPool::cpool_entry_size(jint idx) {1962switch(tag_at(idx).value()) {1963case JVM_CONSTANT_Invalid:1964case JVM_CONSTANT_Unicode:1965return 1;19661967case JVM_CONSTANT_Utf8:1968return 3 + symbol_at(idx)->utf8_length();19691970case JVM_CONSTANT_Class:1971case JVM_CONSTANT_String:1972case JVM_CONSTANT_ClassIndex:1973case JVM_CONSTANT_UnresolvedClass:1974case JVM_CONSTANT_UnresolvedClassInError:1975case JVM_CONSTANT_StringIndex:1976case JVM_CONSTANT_MethodType:1977case JVM_CONSTANT_MethodTypeInError:1978return 3;19791980case JVM_CONSTANT_MethodHandle:1981case JVM_CONSTANT_MethodHandleInError:1982return 4; //tag, ref_kind, ref_index19831984case JVM_CONSTANT_Integer:1985case JVM_CONSTANT_Float:1986case JVM_CONSTANT_Fieldref:1987case JVM_CONSTANT_Methodref:1988case JVM_CONSTANT_InterfaceMethodref:1989case JVM_CONSTANT_NameAndType:1990return 5;19911992case JVM_CONSTANT_Dynamic:1993case JVM_CONSTANT_DynamicInError:1994case JVM_CONSTANT_InvokeDynamic:1995// u1 tag, u2 bsm, u2 nt1996return 5;19971998case JVM_CONSTANT_Long:1999case JVM_CONSTANT_Double:2000return 9;2001}2002assert(false, "cpool_entry_size: Invalid constant pool entry tag");2003return 1;2004} /* end cpool_entry_size */200520062007// SymbolHashMap is used to find a constant pool index from a string.2008// This function fills in SymbolHashMaps, one for utf8s and one for2009// class names, returns size of the cpool raw bytes.2010jint ConstantPool::hash_entries_to(SymbolHashMap *symmap,2011SymbolHashMap *classmap) {2012jint size = 0;20132014for (u2 idx = 1; idx < length(); idx++) {2015u2 tag = tag_at(idx).value();2016size += cpool_entry_size(idx);20172018switch(tag) {2019case JVM_CONSTANT_Utf8: {2020Symbol* sym = symbol_at(idx);2021symmap->add_entry(sym, idx);2022DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));2023break;2024}2025case JVM_CONSTANT_Class:2026case JVM_CONSTANT_UnresolvedClass:2027case JVM_CONSTANT_UnresolvedClassInError: {2028Symbol* sym = klass_name_at(idx);2029classmap->add_entry(sym, idx);2030DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));2031break;2032}2033case JVM_CONSTANT_Long:2034case JVM_CONSTANT_Double: {2035idx++; // Both Long and Double take two cpool slots2036break;2037}2038}2039}2040return size;2041} /* end hash_utf8_entries_to */204220432044// Copy cpool bytes.2045// Returns:2046// 0, in case of OutOfMemoryError2047// -1, in case of internal error2048// > 0, count of the raw cpool bytes that have been copied2049int ConstantPool::copy_cpool_bytes(int cpool_size,2050SymbolHashMap* tbl,2051unsigned char *bytes) {2052u2 idx1, idx2;2053jint size = 0;2054jint cnt = length();2055unsigned char *start_bytes = bytes;20562057for (jint idx = 1; idx < cnt; idx++) {2058u1 tag = tag_at(idx).value();2059jint ent_size = cpool_entry_size(idx);20602061assert(size + ent_size <= cpool_size, "Size mismatch");20622063*bytes = tag;2064DBG(printf("#%03hd tag=%03hd, ", (short)idx, (short)tag));2065switch(tag) {2066case JVM_CONSTANT_Invalid: {2067DBG(printf("JVM_CONSTANT_Invalid"));2068break;2069}2070case JVM_CONSTANT_Unicode: {2071assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");2072DBG(printf("JVM_CONSTANT_Unicode"));2073break;2074}2075case JVM_CONSTANT_Utf8: {2076Symbol* sym = symbol_at(idx);2077char* str = sym->as_utf8();2078// Warning! It's crashing on x86 with len = sym->utf8_length()2079int len = (int) strlen(str);2080Bytes::put_Java_u2((address) (bytes+1), (u2) len);2081for (int i = 0; i < len; i++) {2082bytes[3+i] = (u1) str[i];2083}2084DBG(printf("JVM_CONSTANT_Utf8: %s ", str));2085break;2086}2087case JVM_CONSTANT_Integer: {2088jint val = int_at(idx);2089Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);2090break;2091}2092case JVM_CONSTANT_Float: {2093jfloat val = float_at(idx);2094Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);2095break;2096}2097case JVM_CONSTANT_Long: {2098jlong val = long_at(idx);2099Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);2100idx++; // Long takes two cpool slots2101break;2102}2103case JVM_CONSTANT_Double: {2104jdouble val = double_at(idx);2105Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);2106idx++; // Double takes two cpool slots2107break;2108}2109case JVM_CONSTANT_Class:2110case JVM_CONSTANT_UnresolvedClass:2111case JVM_CONSTANT_UnresolvedClassInError: {2112*bytes = JVM_CONSTANT_Class;2113Symbol* sym = klass_name_at(idx);2114idx1 = tbl->symbol_to_value(sym);2115assert(idx1 != 0, "Have not found a hashtable entry");2116Bytes::put_Java_u2((address) (bytes+1), idx1);2117DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));2118break;2119}2120case JVM_CONSTANT_String: {2121*bytes = JVM_CONSTANT_String;2122Symbol* sym = unresolved_string_at(idx);2123idx1 = tbl->symbol_to_value(sym);2124assert(idx1 != 0, "Have not found a hashtable entry");2125Bytes::put_Java_u2((address) (bytes+1), idx1);2126DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));2127break;2128}2129case JVM_CONSTANT_Fieldref:2130case JVM_CONSTANT_Methodref:2131case JVM_CONSTANT_InterfaceMethodref: {2132idx1 = uncached_klass_ref_index_at(idx);2133idx2 = uncached_name_and_type_ref_index_at(idx);2134Bytes::put_Java_u2((address) (bytes+1), idx1);2135Bytes::put_Java_u2((address) (bytes+3), idx2);2136DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));2137break;2138}2139case JVM_CONSTANT_NameAndType: {2140idx1 = name_ref_index_at(idx);2141idx2 = signature_ref_index_at(idx);2142Bytes::put_Java_u2((address) (bytes+1), idx1);2143Bytes::put_Java_u2((address) (bytes+3), idx2);2144DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));2145break;2146}2147case JVM_CONSTANT_ClassIndex: {2148*bytes = JVM_CONSTANT_Class;2149idx1 = klass_index_at(idx);2150Bytes::put_Java_u2((address) (bytes+1), idx1);2151DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));2152break;2153}2154case JVM_CONSTANT_StringIndex: {2155*bytes = JVM_CONSTANT_String;2156idx1 = string_index_at(idx);2157Bytes::put_Java_u2((address) (bytes+1), idx1);2158DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));2159break;2160}2161case JVM_CONSTANT_MethodHandle:2162case JVM_CONSTANT_MethodHandleInError: {2163*bytes = JVM_CONSTANT_MethodHandle;2164int kind = method_handle_ref_kind_at(idx);2165idx1 = method_handle_index_at(idx);2166*(bytes+1) = (unsigned char) kind;2167Bytes::put_Java_u2((address) (bytes+2), idx1);2168DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));2169break;2170}2171case JVM_CONSTANT_MethodType:2172case JVM_CONSTANT_MethodTypeInError: {2173*bytes = JVM_CONSTANT_MethodType;2174idx1 = method_type_index_at(idx);2175Bytes::put_Java_u2((address) (bytes+1), idx1);2176DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));2177break;2178}2179case JVM_CONSTANT_Dynamic:2180case JVM_CONSTANT_DynamicInError: {2181*bytes = tag;2182idx1 = extract_low_short_from_int(*int_at_addr(idx));2183idx2 = extract_high_short_from_int(*int_at_addr(idx));2184assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");2185Bytes::put_Java_u2((address) (bytes+1), idx1);2186Bytes::put_Java_u2((address) (bytes+3), idx2);2187DBG(printf("JVM_CONSTANT_Dynamic: %hd %hd", idx1, idx2));2188break;2189}2190case JVM_CONSTANT_InvokeDynamic: {2191*bytes = tag;2192idx1 = extract_low_short_from_int(*int_at_addr(idx));2193idx2 = extract_high_short_from_int(*int_at_addr(idx));2194assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");2195Bytes::put_Java_u2((address) (bytes+1), idx1);2196Bytes::put_Java_u2((address) (bytes+3), idx2);2197DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));2198break;2199}2200}2201DBG(printf("\n"));2202bytes += ent_size;2203size += ent_size;2204}2205assert(size == cpool_size, "Size mismatch");22062207// Keep temorarily for debugging until it's stable.2208DBG(print_cpool_bytes(cnt, start_bytes));2209return (int)(bytes - start_bytes);2210} /* end copy_cpool_bytes */22112212#undef DBG221322142215void ConstantPool::set_on_stack(const bool value) {2216if (value) {2217// Only record if it's not already set.2218if (!on_stack()) {2219assert(!is_shared(), "should always be set for shared constant pools");2220_flags |= _on_stack;2221MetadataOnStackMark::record(this);2222}2223} else {2224// Clearing is done single-threadedly.2225if (!is_shared()) {2226_flags &= ~_on_stack;2227}2228}2229}22302231// Printing22322233void ConstantPool::print_on(outputStream* st) const {2234assert(is_constantPool(), "must be constantPool");2235st->print_cr("%s", internal_name());2236if (flags() != 0) {2237st->print(" - flags: 0x%x", flags());2238if (has_preresolution()) st->print(" has_preresolution");2239if (on_stack()) st->print(" on_stack");2240st->cr();2241}2242if (pool_holder() != NULL) {2243st->print_cr(" - holder: " INTPTR_FORMAT, p2i(pool_holder()));2244}2245st->print_cr(" - cache: " INTPTR_FORMAT, p2i(cache()));2246st->print_cr(" - resolved_references: " INTPTR_FORMAT, p2i(resolved_references()));2247st->print_cr(" - reference_map: " INTPTR_FORMAT, p2i(reference_map()));2248st->print_cr(" - resolved_klasses: " INTPTR_FORMAT, p2i(resolved_klasses()));22492250for (int index = 1; index < length(); index++) { // Index 0 is unused2251((ConstantPool*)this)->print_entry_on(index, st);2252switch (tag_at(index).value()) {2253case JVM_CONSTANT_Long :2254case JVM_CONSTANT_Double :2255index++; // Skip entry following eigth-byte constant2256}22572258}2259st->cr();2260}22612262// Print one constant pool entry2263void ConstantPool::print_entry_on(const int index, outputStream* st) {2264EXCEPTION_MARK;2265st->print(" - %3d : ", index);2266tag_at(index).print_on(st);2267st->print(" : ");2268switch (tag_at(index).value()) {2269case JVM_CONSTANT_Class :2270{ Klass* k = klass_at(index, CATCH);2271guarantee(k != NULL, "need klass");2272k->print_value_on(st);2273st->print(" {" PTR_FORMAT "}", p2i(k));2274}2275break;2276case JVM_CONSTANT_Fieldref :2277case JVM_CONSTANT_Methodref :2278case JVM_CONSTANT_InterfaceMethodref :2279st->print("klass_index=%d", uncached_klass_ref_index_at(index));2280st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));2281break;2282case JVM_CONSTANT_String :2283unresolved_string_at(index)->print_value_on(st);2284break;2285case JVM_CONSTANT_Integer :2286st->print("%d", int_at(index));2287break;2288case JVM_CONSTANT_Float :2289st->print("%f", float_at(index));2290break;2291case JVM_CONSTANT_Long :2292st->print_jlong(long_at(index));2293break;2294case JVM_CONSTANT_Double :2295st->print("%lf", double_at(index));2296break;2297case JVM_CONSTANT_NameAndType :2298st->print("name_index=%d", name_ref_index_at(index));2299st->print(" signature_index=%d", signature_ref_index_at(index));2300break;2301case JVM_CONSTANT_Utf8 :2302symbol_at(index)->print_value_on(st);2303break;2304case JVM_CONSTANT_ClassIndex: {2305int name_index = *int_at_addr(index);2306st->print("klass_index=%d ", name_index);2307symbol_at(name_index)->print_value_on(st);2308}2309break;2310case JVM_CONSTANT_UnresolvedClass : // fall-through2311case JVM_CONSTANT_UnresolvedClassInError: {2312CPKlassSlot kslot = klass_slot_at(index);2313int resolved_klass_index = kslot.resolved_klass_index();2314int name_index = kslot.name_index();2315assert(tag_at(name_index).is_symbol(), "sanity");2316symbol_at(name_index)->print_value_on(st);2317}2318break;2319case JVM_CONSTANT_MethodHandle :2320case JVM_CONSTANT_MethodHandleInError :2321st->print("ref_kind=%d", method_handle_ref_kind_at(index));2322st->print(" ref_index=%d", method_handle_index_at(index));2323break;2324case JVM_CONSTANT_MethodType :2325case JVM_CONSTANT_MethodTypeInError :2326st->print("signature_index=%d", method_type_index_at(index));2327break;2328case JVM_CONSTANT_Dynamic :2329case JVM_CONSTANT_DynamicInError :2330{2331st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));2332st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(index));2333int argc = bootstrap_argument_count_at(index);2334if (argc > 0) {2335for (int arg_i = 0; arg_i < argc; arg_i++) {2336int arg = bootstrap_argument_index_at(index, arg_i);2337st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);2338}2339st->print("}");2340}2341}2342break;2343case JVM_CONSTANT_InvokeDynamic :2344{2345st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));2346st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(index));2347int argc = bootstrap_argument_count_at(index);2348if (argc > 0) {2349for (int arg_i = 0; arg_i < argc; arg_i++) {2350int arg = bootstrap_argument_index_at(index, arg_i);2351st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);2352}2353st->print("}");2354}2355}2356break;2357default:2358ShouldNotReachHere();2359break;2360}2361st->cr();2362}23632364void ConstantPool::print_value_on(outputStream* st) const {2365assert(is_constantPool(), "must be constantPool");2366st->print("constant pool [%d]", length());2367if (has_preresolution()) st->print("/preresolution");2368if (operands() != NULL) st->print("/operands[%d]", operands()->length());2369print_address_on(st);2370if (pool_holder() != NULL) {2371st->print(" for ");2372pool_holder()->print_value_on(st);2373bool extra = (pool_holder()->constants() != this);2374if (extra) st->print(" (extra)");2375}2376if (cache() != NULL) {2377st->print(" cache=" PTR_FORMAT, p2i(cache()));2378}2379}23802381// Verification23822383void ConstantPool::verify_on(outputStream* st) {2384guarantee(is_constantPool(), "object must be constant pool");2385for (int i = 0; i< length(); i++) {2386constantTag tag = tag_at(i);2387if (tag.is_klass() || tag.is_unresolved_klass()) {2388guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");2389} else if (tag.is_symbol()) {2390CPSlot entry = slot_at(i);2391guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");2392} else if (tag.is_string()) {2393CPSlot entry = slot_at(i);2394guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");2395}2396}2397if (pool_holder() != NULL) {2398// Note: pool_holder() can be NULL in temporary constant pools2399// used during constant pool merging2400guarantee(pool_holder()->is_klass(), "should be klass");2401}2402}240324042405SymbolHashMap::~SymbolHashMap() {2406SymbolHashMapEntry* next;2407for (int i = 0; i < _table_size; i++) {2408for (SymbolHashMapEntry* cur = bucket(i); cur != NULL; cur = next) {2409next = cur->next();2410delete(cur);2411}2412}2413FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets);2414}24152416void SymbolHashMap::add_entry(Symbol* sym, u2 value) {2417char *str = sym->as_utf8();2418unsigned int hash = compute_hash(str, sym->utf8_length());2419unsigned int index = hash % table_size();24202421// check if already in map2422// we prefer the first entry since it is more likely to be what was used in2423// the class file2424for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {2425assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");2426if (en->hash() == hash && en->symbol() == sym) {2427return; // already there2428}2429}24302431SymbolHashMapEntry* entry = new SymbolHashMapEntry(hash, sym, value);2432entry->set_next(bucket(index));2433_buckets[index].set_entry(entry);2434assert(entry->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");2435}24362437SymbolHashMapEntry* SymbolHashMap::find_entry(Symbol* sym) {2438assert(sym != NULL, "SymbolHashMap::find_entry - symbol is NULL");2439char *str = sym->as_utf8();2440int len = sym->utf8_length();2441unsigned int hash = SymbolHashMap::compute_hash(str, len);2442unsigned int index = hash % table_size();2443for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {2444assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");2445if (en->hash() == hash && en->symbol() == sym) {2446return en;2447}2448}2449return NULL;2450}24512452void SymbolHashMap::initialize_table(int table_size) {2453_table_size = table_size;2454_buckets = NEW_C_HEAP_ARRAY(SymbolHashMapBucket, table_size, mtSymbol);2455for (int index = 0; index < table_size; index++) {2456_buckets[index].clear();2457}2458}245924602461