Path: blob/master/src/hotspot/share/oops/constantPool.cpp
40951 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->is_shared_old_klass()) {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() ||887tag.is_dynamic_constant_in_error()) {888BasicType bt = basic_type_for_constant_at(which);889// dynamic constant could return an array, treat as object890return constantTag::ofBasicType(is_reference_type(bt) ? T_OBJECT : bt);891}892return tag;893}894895BasicType ConstantPool::basic_type_for_constant_at(int which) {896constantTag tag = tag_at(which);897if (tag.is_dynamic_constant() ||898tag.is_dynamic_constant_in_error()) {899// have to look at the signature for this one900Symbol* constant_type = uncached_signature_ref_at(which);901return Signature::basic_type(constant_type);902}903return tag.basic_type();904}905906// Called to resolve constants in the constant pool and return an oop.907// Some constant pool entries cache their resolved oop. This is also908// called to create oops from constants to use in arguments for invokedynamic909oop ConstantPool::resolve_constant_at_impl(const constantPoolHandle& this_cp,910int index, int cache_index,911bool* status_return, TRAPS) {912oop result_oop = NULL;913Handle throw_exception;914915if (cache_index == _possible_index_sentinel) {916// It is possible that this constant is one which is cached in the objects.917// We'll do a linear search. This should be OK because this usage is rare.918// FIXME: If bootstrap specifiers stress this code, consider putting in919// a reverse index. Binary search over a short array should do it.920assert(index > 0, "valid index");921cache_index = this_cp->cp_to_object_index(index);922}923assert(cache_index == _no_index_sentinel || cache_index >= 0, "");924assert(index == _no_index_sentinel || index >= 0, "");925926if (cache_index >= 0) {927result_oop = this_cp->resolved_references()->obj_at(cache_index);928if (result_oop != NULL) {929if (result_oop == Universe::the_null_sentinel()) {930DEBUG_ONLY(int temp_index = (index >= 0 ? index : this_cp->object_to_cp_index(cache_index)));931assert(this_cp->tag_at(temp_index).is_dynamic_constant(), "only condy uses the null sentinel");932result_oop = NULL;933}934if (status_return != NULL) (*status_return) = true;935return result_oop;936// That was easy...937}938index = this_cp->object_to_cp_index(cache_index);939}940941jvalue prim_value; // temp used only in a few cases below942943constantTag tag = this_cp->tag_at(index);944945if (status_return != NULL) {946// don't trigger resolution if the constant might need it947switch (tag.value()) {948case JVM_CONSTANT_Class:949{950CPKlassSlot kslot = this_cp->klass_slot_at(index);951int resolved_klass_index = kslot.resolved_klass_index();952if (this_cp->resolved_klasses()->at(resolved_klass_index) == NULL) {953(*status_return) = false;954return NULL;955}956// the klass is waiting in the CP; go get it957break;958}959case JVM_CONSTANT_String:960case JVM_CONSTANT_Integer:961case JVM_CONSTANT_Float:962case JVM_CONSTANT_Long:963case JVM_CONSTANT_Double:964// these guys trigger OOM at worst965break;966default:967(*status_return) = false;968return NULL;969}970// from now on there is either success or an OOME971(*status_return) = true;972}973974switch (tag.value()) {975976case JVM_CONSTANT_UnresolvedClass:977case JVM_CONSTANT_UnresolvedClassInError:978case JVM_CONSTANT_Class:979{980assert(cache_index == _no_index_sentinel, "should not have been set");981Klass* resolved = klass_at_impl(this_cp, index, CHECK_NULL);982// ldc wants the java mirror.983result_oop = resolved->java_mirror();984break;985}986987case JVM_CONSTANT_Dynamic:988{989// Resolve the Dynamically-Computed constant to invoke the BSM in order to obtain the resulting oop.990BootstrapInfo bootstrap_specifier(this_cp, index);991992// The initial step in resolving an unresolved symbolic reference to a993// dynamically-computed constant is to resolve the symbolic reference to a994// method handle which will be the bootstrap method for the dynamically-computed995// constant. If resolution of the java.lang.invoke.MethodHandle for the bootstrap996// method fails, then a MethodHandleInError is stored at the corresponding997// bootstrap method's CP index for the CONSTANT_MethodHandle_info. No need to998// set a DynamicConstantInError here since any subsequent use of this999// bootstrap method will encounter the resolution of MethodHandleInError.1000// Both the first, (resolution of the BSM and its static arguments), and the second tasks,1001// (invocation of the BSM), of JVMS Section 5.4.3.6 occur within invoke_bootstrap_method()1002// for the bootstrap_specifier created above.1003SystemDictionary::invoke_bootstrap_method(bootstrap_specifier, THREAD);1004Exceptions::wrap_dynamic_exception(/* is_indy */ false, THREAD);1005if (HAS_PENDING_EXCEPTION) {1006// Resolution failure of the dynamically-computed constant, save_and_throw_exception1007// will check for a LinkageError and store a DynamicConstantInError.1008save_and_throw_exception(this_cp, index, tag, CHECK_NULL);1009}1010result_oop = bootstrap_specifier.resolved_value()();1011BasicType type = Signature::basic_type(bootstrap_specifier.signature());1012if (!is_reference_type(type)) {1013// Make sure the primitive value is properly boxed.1014// This is a JDK responsibility.1015const char* fail = NULL;1016if (result_oop == NULL) {1017fail = "null result instead of box";1018} else if (!is_java_primitive(type)) {1019// FIXME: support value types via unboxing1020fail = "can only handle references and primitives";1021} else if (!java_lang_boxing_object::is_instance(result_oop, type)) {1022fail = "primitive is not properly boxed";1023}1024if (fail != NULL) {1025// Since this exception is not a LinkageError, throw exception1026// but do not save a DynamicInError resolution result.1027// See section 5.4.3 of the VM spec.1028THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), fail);1029}1030}10311032LogTarget(Debug, methodhandles, condy) lt_condy;1033if (lt_condy.is_enabled()) {1034LogStream ls(lt_condy);1035bootstrap_specifier.print_msg_on(&ls, "resolve_constant_at_impl");1036}1037break;1038}10391040case JVM_CONSTANT_String:1041assert(cache_index != _no_index_sentinel, "should have been set");1042result_oop = string_at_impl(this_cp, index, cache_index, CHECK_NULL);1043break;10441045case JVM_CONSTANT_DynamicInError:1046case JVM_CONSTANT_MethodHandleInError:1047case JVM_CONSTANT_MethodTypeInError:1048{1049throw_resolution_error(this_cp, index, CHECK_NULL);1050break;1051}10521053case JVM_CONSTANT_MethodHandle:1054{1055int ref_kind = this_cp->method_handle_ref_kind_at(index);1056int callee_index = this_cp->method_handle_klass_index_at(index);1057Symbol* name = this_cp->method_handle_name_ref_at(index);1058Symbol* signature = this_cp->method_handle_signature_ref_at(index);1059constantTag m_tag = this_cp->tag_at(this_cp->method_handle_index_at(index));1060{ ResourceMark rm(THREAD);1061log_debug(class, resolve)("resolve JVM_CONSTANT_MethodHandle:%d [%d/%d/%d] %s.%s",1062ref_kind, index, this_cp->method_handle_index_at(index),1063callee_index, name->as_C_string(), signature->as_C_string());1064}10651066Klass* callee = klass_at_impl(this_cp, callee_index, CHECK_NULL);10671068// Check constant pool method consistency1069if ((callee->is_interface() && m_tag.is_method()) ||1070((!callee->is_interface() && m_tag.is_interface_method()))) {1071ResourceMark rm(THREAD);1072stringStream ss;1073ss.print("Inconsistent constant pool data in classfile for class %s. "1074"Method '", callee->name()->as_C_string());1075signature->print_as_signature_external_return_type(&ss);1076ss.print(" %s(", name->as_C_string());1077signature->print_as_signature_external_parameters(&ss);1078ss.print(")' at index %d is %s and should be %s",1079index,1080callee->is_interface() ? "CONSTANT_MethodRef" : "CONSTANT_InterfaceMethodRef",1081callee->is_interface() ? "CONSTANT_InterfaceMethodRef" : "CONSTANT_MethodRef");1082THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());1083}10841085Klass* klass = this_cp->pool_holder();1086Handle value = SystemDictionary::link_method_handle_constant(klass, ref_kind,1087callee, name, signature,1088THREAD);1089result_oop = value();1090if (HAS_PENDING_EXCEPTION) {1091save_and_throw_exception(this_cp, index, tag, CHECK_NULL);1092}1093break;1094}10951096case JVM_CONSTANT_MethodType:1097{1098Symbol* signature = this_cp->method_type_signature_at(index);1099{ ResourceMark rm(THREAD);1100log_debug(class, resolve)("resolve JVM_CONSTANT_MethodType [%d/%d] %s",1101index, this_cp->method_type_index_at(index),1102signature->as_C_string());1103}1104Klass* klass = this_cp->pool_holder();1105Handle value = SystemDictionary::find_method_handle_type(signature, klass, THREAD);1106result_oop = value();1107if (HAS_PENDING_EXCEPTION) {1108save_and_throw_exception(this_cp, index, tag, CHECK_NULL);1109}1110break;1111}11121113case JVM_CONSTANT_Integer:1114assert(cache_index == _no_index_sentinel, "should not have been set");1115prim_value.i = this_cp->int_at(index);1116result_oop = java_lang_boxing_object::create(T_INT, &prim_value, CHECK_NULL);1117break;11181119case JVM_CONSTANT_Float:1120assert(cache_index == _no_index_sentinel, "should not have been set");1121prim_value.f = this_cp->float_at(index);1122result_oop = java_lang_boxing_object::create(T_FLOAT, &prim_value, CHECK_NULL);1123break;11241125case JVM_CONSTANT_Long:1126assert(cache_index == _no_index_sentinel, "should not have been set");1127prim_value.j = this_cp->long_at(index);1128result_oop = java_lang_boxing_object::create(T_LONG, &prim_value, CHECK_NULL);1129break;11301131case JVM_CONSTANT_Double:1132assert(cache_index == _no_index_sentinel, "should not have been set");1133prim_value.d = this_cp->double_at(index);1134result_oop = java_lang_boxing_object::create(T_DOUBLE, &prim_value, CHECK_NULL);1135break;11361137default:1138DEBUG_ONLY( tty->print_cr("*** %p: tag at CP[%d/%d] = %d",1139this_cp(), index, cache_index, tag.value()));1140assert(false, "unexpected constant tag");1141break;1142}11431144if (cache_index >= 0) {1145// Benign race condition: resolved_references may already be filled in.1146// The important thing here is that all threads pick up the same result.1147// It doesn't matter which racing thread wins, as long as only one1148// result is used by all threads, and all future queries.1149oop new_result = (result_oop == NULL ? Universe::the_null_sentinel() : result_oop);1150oop old_result = this_cp->resolved_references()1151->atomic_compare_exchange_oop(cache_index, new_result, NULL);1152if (old_result == NULL) {1153return result_oop; // was installed1154} else {1155// Return the winning thread's result. This can be different than1156// the result here for MethodHandles.1157if (old_result == Universe::the_null_sentinel())1158old_result = NULL;1159return old_result;1160}1161} else {1162assert(result_oop != Universe::the_null_sentinel(), "");1163return result_oop;1164}1165}11661167oop ConstantPool::uncached_string_at(int which, TRAPS) {1168Symbol* sym = unresolved_string_at(which);1169oop str = StringTable::intern(sym, CHECK_(NULL));1170assert(java_lang_String::is_instance(str), "must be string");1171return str;1172}11731174void ConstantPool::copy_bootstrap_arguments_at_impl(const constantPoolHandle& this_cp, int index,1175int start_arg, int end_arg,1176objArrayHandle info, int pos,1177bool must_resolve, Handle if_not_available,1178TRAPS) {1179int argc;1180int limit = pos + end_arg - start_arg;1181// checks: index in range [0..this_cp->length),1182// tag at index, start..end in range [0..argc],1183// info array non-null, pos..limit in [0..info.length]1184if ((0 >= index || index >= this_cp->length()) ||1185!(this_cp->tag_at(index).is_invoke_dynamic() ||1186this_cp->tag_at(index).is_dynamic_constant()) ||1187(0 > start_arg || start_arg > end_arg) ||1188(end_arg > (argc = this_cp->bootstrap_argument_count_at(index))) ||1189(0 > pos || pos > limit) ||1190(info.is_null() || limit > info->length())) {1191// An index or something else went wrong; throw an error.1192// Since this is an internal API, we don't expect this,1193// so we don't bother to craft a nice message.1194THROW_MSG(vmSymbols::java_lang_LinkageError(), "bad BSM argument access");1195}1196// now we can loop safely1197int info_i = pos;1198for (int i = start_arg; i < end_arg; i++) {1199int arg_index = this_cp->bootstrap_argument_index_at(index, i);1200oop arg_oop;1201if (must_resolve) {1202arg_oop = this_cp->resolve_possibly_cached_constant_at(arg_index, CHECK);1203} else {1204bool found_it = false;1205arg_oop = this_cp->find_cached_constant_at(arg_index, found_it, CHECK);1206if (!found_it) arg_oop = if_not_available();1207}1208info->obj_at_put(info_i++, arg_oop);1209}1210}12111212oop ConstantPool::string_at_impl(const constantPoolHandle& this_cp, int which, int obj_index, TRAPS) {1213// If the string has already been interned, this entry will be non-null1214oop str = this_cp->resolved_references()->obj_at(obj_index);1215assert(str != Universe::the_null_sentinel(), "");1216if (str != NULL) return str;1217Symbol* sym = this_cp->unresolved_string_at(which);1218str = StringTable::intern(sym, CHECK_(NULL));1219this_cp->string_at_put(which, obj_index, str);1220assert(java_lang_String::is_instance(str), "must be string");1221return str;1222}122312241225bool ConstantPool::klass_name_at_matches(const InstanceKlass* k, int which) {1226// Names are interned, so we can compare Symbol*s directly1227Symbol* cp_name = klass_name_at(which);1228return (cp_name == k->name());1229}123012311232// Iterate over symbols and decrement ones which are Symbol*s1233// This is done during GC.1234// Only decrement the UTF8 symbols. Strings point to1235// these symbols but didn't increment the reference count.1236void ConstantPool::unreference_symbols() {1237for (int index = 1; index < length(); index++) { // Index 0 is unused1238constantTag tag = tag_at(index);1239if (tag.is_symbol()) {1240symbol_at(index)->decrement_refcount();1241}1242}1243}124412451246// Compare this constant pool's entry at index1 to the constant pool1247// cp2's entry at index2.1248bool ConstantPool::compare_entry_to(int index1, const constantPoolHandle& cp2,1249int index2) {12501251// The error tags are equivalent to non-error tags when comparing1252jbyte t1 = tag_at(index1).non_error_value();1253jbyte t2 = cp2->tag_at(index2).non_error_value();12541255if (t1 != t2) {1256// Not the same entry type so there is nothing else to check. Note1257// that this style of checking will consider resolved/unresolved1258// class pairs as different.1259// From the ConstantPool* API point of view, this is correct1260// behavior. See VM_RedefineClasses::merge_constant_pools() to see how this1261// plays out in the context of ConstantPool* merging.1262return false;1263}12641265switch (t1) {1266case JVM_CONSTANT_Class:1267{1268Klass* k1 = resolved_klass_at(index1);1269Klass* k2 = cp2->resolved_klass_at(index2);1270if (k1 == k2) {1271return true;1272}1273} break;12741275case JVM_CONSTANT_ClassIndex:1276{1277int recur1 = klass_index_at(index1);1278int recur2 = cp2->klass_index_at(index2);1279if (compare_entry_to(recur1, cp2, recur2)) {1280return true;1281}1282} break;12831284case JVM_CONSTANT_Double:1285{1286jdouble d1 = double_at(index1);1287jdouble d2 = cp2->double_at(index2);1288if (d1 == d2) {1289return true;1290}1291} break;12921293case JVM_CONSTANT_Fieldref:1294case JVM_CONSTANT_InterfaceMethodref:1295case JVM_CONSTANT_Methodref:1296{1297int recur1 = uncached_klass_ref_index_at(index1);1298int recur2 = cp2->uncached_klass_ref_index_at(index2);1299bool match = compare_entry_to(recur1, cp2, recur2);1300if (match) {1301recur1 = uncached_name_and_type_ref_index_at(index1);1302recur2 = cp2->uncached_name_and_type_ref_index_at(index2);1303if (compare_entry_to(recur1, cp2, recur2)) {1304return true;1305}1306}1307} break;13081309case JVM_CONSTANT_Float:1310{1311jfloat f1 = float_at(index1);1312jfloat f2 = cp2->float_at(index2);1313if (f1 == f2) {1314return true;1315}1316} break;13171318case JVM_CONSTANT_Integer:1319{1320jint i1 = int_at(index1);1321jint i2 = cp2->int_at(index2);1322if (i1 == i2) {1323return true;1324}1325} break;13261327case JVM_CONSTANT_Long:1328{1329jlong l1 = long_at(index1);1330jlong l2 = cp2->long_at(index2);1331if (l1 == l2) {1332return true;1333}1334} break;13351336case JVM_CONSTANT_NameAndType:1337{1338int recur1 = name_ref_index_at(index1);1339int recur2 = cp2->name_ref_index_at(index2);1340if (compare_entry_to(recur1, cp2, recur2)) {1341recur1 = signature_ref_index_at(index1);1342recur2 = cp2->signature_ref_index_at(index2);1343if (compare_entry_to(recur1, cp2, recur2)) {1344return true;1345}1346}1347} break;13481349case JVM_CONSTANT_StringIndex:1350{1351int recur1 = string_index_at(index1);1352int recur2 = cp2->string_index_at(index2);1353if (compare_entry_to(recur1, cp2, recur2)) {1354return true;1355}1356} break;13571358case JVM_CONSTANT_UnresolvedClass:1359{1360Symbol* k1 = klass_name_at(index1);1361Symbol* k2 = cp2->klass_name_at(index2);1362if (k1 == k2) {1363return true;1364}1365} break;13661367case JVM_CONSTANT_MethodType:1368{1369int k1 = method_type_index_at(index1);1370int k2 = cp2->method_type_index_at(index2);1371if (compare_entry_to(k1, cp2, k2)) {1372return true;1373}1374} break;13751376case JVM_CONSTANT_MethodHandle:1377{1378int k1 = method_handle_ref_kind_at(index1);1379int k2 = cp2->method_handle_ref_kind_at(index2);1380if (k1 == k2) {1381int i1 = method_handle_index_at(index1);1382int i2 = cp2->method_handle_index_at(index2);1383if (compare_entry_to(i1, cp2, i2)) {1384return true;1385}1386}1387} break;13881389case JVM_CONSTANT_Dynamic:1390{1391int k1 = bootstrap_name_and_type_ref_index_at(index1);1392int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);1393int i1 = bootstrap_methods_attribute_index(index1);1394int i2 = cp2->bootstrap_methods_attribute_index(index2);1395bool match_entry = compare_entry_to(k1, cp2, k2);1396bool match_operand = compare_operand_to(i1, cp2, i2);1397return (match_entry && match_operand);1398} break;13991400case JVM_CONSTANT_InvokeDynamic:1401{1402int k1 = bootstrap_name_and_type_ref_index_at(index1);1403int k2 = cp2->bootstrap_name_and_type_ref_index_at(index2);1404int i1 = bootstrap_methods_attribute_index(index1);1405int i2 = cp2->bootstrap_methods_attribute_index(index2);1406bool match_entry = compare_entry_to(k1, cp2, k2);1407bool match_operand = compare_operand_to(i1, cp2, i2);1408return (match_entry && match_operand);1409} break;14101411case JVM_CONSTANT_String:1412{1413Symbol* s1 = unresolved_string_at(index1);1414Symbol* s2 = cp2->unresolved_string_at(index2);1415if (s1 == s2) {1416return true;1417}1418} break;14191420case JVM_CONSTANT_Utf8:1421{1422Symbol* s1 = symbol_at(index1);1423Symbol* s2 = cp2->symbol_at(index2);1424if (s1 == s2) {1425return true;1426}1427} break;14281429// Invalid is used as the tag for the second constant pool entry1430// occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should1431// not be seen by itself.1432case JVM_CONSTANT_Invalid: // fall through14331434default:1435ShouldNotReachHere();1436break;1437}14381439return false;1440} // end compare_entry_to()144114421443// Resize the operands array with delta_len and delta_size.1444// Used in RedefineClasses for CP merge.1445void ConstantPool::resize_operands(int delta_len, int delta_size, TRAPS) {1446int old_len = operand_array_length(operands());1447int new_len = old_len + delta_len;1448int min_len = (delta_len > 0) ? old_len : new_len;14491450int old_size = operands()->length();1451int new_size = old_size + delta_size;1452int min_size = (delta_size > 0) ? old_size : new_size;14531454ClassLoaderData* loader_data = pool_holder()->class_loader_data();1455Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, new_size, CHECK);14561457// Set index in the resized array for existing elements only1458for (int idx = 0; idx < min_len; idx++) {1459int offset = operand_offset_at(idx); // offset in original array1460operand_offset_at_put(new_ops, idx, offset + 2*delta_len); // offset in resized array1461}1462// Copy the bootstrap specifiers only1463Copy::conjoint_memory_atomic(operands()->adr_at(2*old_len),1464new_ops->adr_at(2*new_len),1465(min_size - 2*min_len) * sizeof(u2));1466// Explicitly deallocate old operands array.1467// Note, it is not needed for 7u backport.1468if ( operands() != NULL) { // the safety check1469MetadataFactory::free_array<u2>(loader_data, operands());1470}1471set_operands(new_ops);1472} // end resize_operands()147314741475// Extend the operands array with the length and size of the ext_cp operands.1476// Used in RedefineClasses for CP merge.1477void ConstantPool::extend_operands(const constantPoolHandle& ext_cp, TRAPS) {1478int delta_len = operand_array_length(ext_cp->operands());1479if (delta_len == 0) {1480return; // nothing to do1481}1482int delta_size = ext_cp->operands()->length();14831484assert(delta_len > 0 && delta_size > 0, "extended operands array must be bigger");14851486if (operand_array_length(operands()) == 0) {1487ClassLoaderData* loader_data = pool_holder()->class_loader_data();1488Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, delta_size, CHECK);1489// The first element index defines the offset of second part1490operand_offset_at_put(new_ops, 0, 2*delta_len); // offset in new array1491set_operands(new_ops);1492} else {1493resize_operands(delta_len, delta_size, CHECK);1494}14951496} // end extend_operands()149714981499// Shrink the operands array to a smaller array with new_len length.1500// Used in RedefineClasses for CP merge.1501void ConstantPool::shrink_operands(int new_len, TRAPS) {1502int old_len = operand_array_length(operands());1503if (new_len == old_len) {1504return; // nothing to do1505}1506assert(new_len < old_len, "shrunken operands array must be smaller");15071508int free_base = operand_next_offset_at(new_len - 1);1509int delta_len = new_len - old_len;1510int delta_size = 2*delta_len + free_base - operands()->length();15111512resize_operands(delta_len, delta_size, CHECK);15131514} // end shrink_operands()151515161517void ConstantPool::copy_operands(const constantPoolHandle& from_cp,1518const constantPoolHandle& to_cp,1519TRAPS) {15201521int from_oplen = operand_array_length(from_cp->operands());1522int old_oplen = operand_array_length(to_cp->operands());1523if (from_oplen != 0) {1524ClassLoaderData* loader_data = to_cp->pool_holder()->class_loader_data();1525// append my operands to the target's operands array1526if (old_oplen == 0) {1527// Can't just reuse from_cp's operand list because of deallocation issues1528int len = from_cp->operands()->length();1529Array<u2>* new_ops = MetadataFactory::new_array<u2>(loader_data, len, CHECK);1530Copy::conjoint_memory_atomic(1531from_cp->operands()->adr_at(0), new_ops->adr_at(0), len * sizeof(u2));1532to_cp->set_operands(new_ops);1533} else {1534int old_len = to_cp->operands()->length();1535int from_len = from_cp->operands()->length();1536int old_off = old_oplen * sizeof(u2);1537int from_off = from_oplen * sizeof(u2);1538// Use the metaspace for the destination constant pool1539Array<u2>* new_operands = MetadataFactory::new_array<u2>(loader_data, old_len + from_len, CHECK);1540int fillp = 0, len = 0;1541// first part of dest1542Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),1543new_operands->adr_at(fillp),1544(len = old_off) * sizeof(u2));1545fillp += len;1546// first part of src1547Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),1548new_operands->adr_at(fillp),1549(len = from_off) * sizeof(u2));1550fillp += len;1551// second part of dest1552Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(old_off),1553new_operands->adr_at(fillp),1554(len = old_len - old_off) * sizeof(u2));1555fillp += len;1556// second part of src1557Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),1558new_operands->adr_at(fillp),1559(len = from_len - from_off) * sizeof(u2));1560fillp += len;1561assert(fillp == new_operands->length(), "");15621563// Adjust indexes in the first part of the copied operands array.1564for (int j = 0; j < from_oplen; j++) {1565int offset = operand_offset_at(new_operands, old_oplen + j);1566assert(offset == operand_offset_at(from_cp->operands(), j), "correct copy");1567offset += old_len; // every new tuple is preceded by old_len extra u2's1568operand_offset_at_put(new_operands, old_oplen + j, offset);1569}15701571// replace target operands array with combined array1572to_cp->set_operands(new_operands);1573}1574}1575} // end copy_operands()157615771578// Copy this constant pool's entries at start_i to end_i (inclusive)1579// to the constant pool to_cp's entries starting at to_i. A total of1580// (end_i - start_i) + 1 entries are copied.1581void ConstantPool::copy_cp_to_impl(const constantPoolHandle& from_cp, int start_i, int end_i,1582const constantPoolHandle& to_cp, int to_i, TRAPS) {158315841585int dest_i = to_i; // leave original alone for debug purposes15861587for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {1588copy_entry_to(from_cp, src_i, to_cp, dest_i);15891590switch (from_cp->tag_at(src_i).value()) {1591case JVM_CONSTANT_Double:1592case JVM_CONSTANT_Long:1593// double and long take two constant pool entries1594src_i += 2;1595dest_i += 2;1596break;15971598default:1599// all others take one constant pool entry1600src_i++;1601dest_i++;1602break;1603}1604}1605copy_operands(from_cp, to_cp, CHECK);16061607} // end copy_cp_to_impl()160816091610// Copy this constant pool's entry at from_i to the constant pool1611// to_cp's entry at to_i.1612void ConstantPool::copy_entry_to(const constantPoolHandle& from_cp, int from_i,1613const constantPoolHandle& to_cp, int to_i) {16141615int tag = from_cp->tag_at(from_i).value();1616switch (tag) {1617case JVM_CONSTANT_ClassIndex:1618{1619jint ki = from_cp->klass_index_at(from_i);1620to_cp->klass_index_at_put(to_i, ki);1621} break;16221623case JVM_CONSTANT_Double:1624{1625jdouble d = from_cp->double_at(from_i);1626to_cp->double_at_put(to_i, d);1627// double takes two constant pool entries so init second entry's tag1628to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);1629} break;16301631case JVM_CONSTANT_Fieldref:1632{1633int class_index = from_cp->uncached_klass_ref_index_at(from_i);1634int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);1635to_cp->field_at_put(to_i, class_index, name_and_type_index);1636} break;16371638case JVM_CONSTANT_Float:1639{1640jfloat f = from_cp->float_at(from_i);1641to_cp->float_at_put(to_i, f);1642} break;16431644case JVM_CONSTANT_Integer:1645{1646jint i = from_cp->int_at(from_i);1647to_cp->int_at_put(to_i, i);1648} break;16491650case JVM_CONSTANT_InterfaceMethodref:1651{1652int class_index = from_cp->uncached_klass_ref_index_at(from_i);1653int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);1654to_cp->interface_method_at_put(to_i, class_index, name_and_type_index);1655} break;16561657case JVM_CONSTANT_Long:1658{1659jlong l = from_cp->long_at(from_i);1660to_cp->long_at_put(to_i, l);1661// long takes two constant pool entries so init second entry's tag1662to_cp->tag_at_put(to_i + 1, JVM_CONSTANT_Invalid);1663} break;16641665case JVM_CONSTANT_Methodref:1666{1667int class_index = from_cp->uncached_klass_ref_index_at(from_i);1668int name_and_type_index = from_cp->uncached_name_and_type_ref_index_at(from_i);1669to_cp->method_at_put(to_i, class_index, name_and_type_index);1670} break;16711672case JVM_CONSTANT_NameAndType:1673{1674int name_ref_index = from_cp->name_ref_index_at(from_i);1675int signature_ref_index = from_cp->signature_ref_index_at(from_i);1676to_cp->name_and_type_at_put(to_i, name_ref_index, signature_ref_index);1677} break;16781679case JVM_CONSTANT_StringIndex:1680{1681jint si = from_cp->string_index_at(from_i);1682to_cp->string_index_at_put(to_i, si);1683} break;16841685case JVM_CONSTANT_Class:1686case JVM_CONSTANT_UnresolvedClass:1687case JVM_CONSTANT_UnresolvedClassInError:1688{1689// Revert to JVM_CONSTANT_ClassIndex1690int name_index = from_cp->klass_slot_at(from_i).name_index();1691assert(from_cp->tag_at(name_index).is_symbol(), "sanity");1692to_cp->klass_index_at_put(to_i, name_index);1693} break;16941695case JVM_CONSTANT_String:1696{1697Symbol* s = from_cp->unresolved_string_at(from_i);1698to_cp->unresolved_string_at_put(to_i, s);1699} break;17001701case JVM_CONSTANT_Utf8:1702{1703Symbol* s = from_cp->symbol_at(from_i);1704// Need to increase refcount, the old one will be thrown away and deferenced1705s->increment_refcount();1706to_cp->symbol_at_put(to_i, s);1707} break;17081709case JVM_CONSTANT_MethodType:1710case JVM_CONSTANT_MethodTypeInError:1711{1712jint k = from_cp->method_type_index_at(from_i);1713to_cp->method_type_index_at_put(to_i, k);1714} break;17151716case JVM_CONSTANT_MethodHandle:1717case JVM_CONSTANT_MethodHandleInError:1718{1719int k1 = from_cp->method_handle_ref_kind_at(from_i);1720int k2 = from_cp->method_handle_index_at(from_i);1721to_cp->method_handle_index_at_put(to_i, k1, k2);1722} break;17231724case JVM_CONSTANT_Dynamic:1725case JVM_CONSTANT_DynamicInError:1726{1727int k1 = from_cp->bootstrap_methods_attribute_index(from_i);1728int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);1729k1 += operand_array_length(to_cp->operands()); // to_cp might already have operands1730to_cp->dynamic_constant_at_put(to_i, k1, k2);1731} break;17321733case JVM_CONSTANT_InvokeDynamic:1734{1735int k1 = from_cp->bootstrap_methods_attribute_index(from_i);1736int k2 = from_cp->bootstrap_name_and_type_ref_index_at(from_i);1737k1 += operand_array_length(to_cp->operands()); // to_cp might already have operands1738to_cp->invoke_dynamic_at_put(to_i, k1, k2);1739} break;17401741// Invalid is used as the tag for the second constant pool entry1742// occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should1743// not be seen by itself.1744case JVM_CONSTANT_Invalid: // fall through17451746default:1747{1748ShouldNotReachHere();1749} break;1750}1751} // end copy_entry_to()17521753// Search constant pool search_cp for an entry that matches this1754// constant pool's entry at pattern_i. Returns the index of a1755// matching entry or zero (0) if there is no matching entry.1756int ConstantPool::find_matching_entry(int pattern_i,1757const constantPoolHandle& search_cp) {17581759// index zero (0) is not used1760for (int i = 1; i < search_cp->length(); i++) {1761bool found = compare_entry_to(pattern_i, search_cp, i);1762if (found) {1763return i;1764}1765}17661767return 0; // entry not found; return unused index zero (0)1768} // end find_matching_entry()176917701771// Compare this constant pool's bootstrap specifier at idx1 to the constant pool1772// cp2's bootstrap specifier at idx2.1773bool ConstantPool::compare_operand_to(int idx1, const constantPoolHandle& cp2, int idx2) {1774int k1 = operand_bootstrap_method_ref_index_at(idx1);1775int k2 = cp2->operand_bootstrap_method_ref_index_at(idx2);1776bool match = compare_entry_to(k1, cp2, k2);17771778if (!match) {1779return false;1780}1781int argc = operand_argument_count_at(idx1);1782if (argc == cp2->operand_argument_count_at(idx2)) {1783for (int j = 0; j < argc; j++) {1784k1 = operand_argument_index_at(idx1, j);1785k2 = cp2->operand_argument_index_at(idx2, j);1786match = compare_entry_to(k1, cp2, k2);1787if (!match) {1788return false;1789}1790}1791return true; // got through loop; all elements equal1792}1793return false;1794} // end compare_operand_to()17951796// Search constant pool search_cp for a bootstrap specifier that matches1797// this constant pool's bootstrap specifier data at pattern_i index.1798// Return the index of a matching bootstrap attribute record or (-1) if there is no match.1799int ConstantPool::find_matching_operand(int pattern_i,1800const constantPoolHandle& search_cp, int search_len) {1801for (int i = 0; i < search_len; i++) {1802bool found = compare_operand_to(pattern_i, search_cp, i);1803if (found) {1804return i;1805}1806}1807return -1; // bootstrap specifier data not found; return unused index (-1)1808} // end find_matching_operand()180918101811#ifndef PRODUCT18121813const char* ConstantPool::printable_name_at(int which) {18141815constantTag tag = tag_at(which);18161817if (tag.is_string()) {1818return string_at_noresolve(which);1819} else if (tag.is_klass() || tag.is_unresolved_klass()) {1820return klass_name_at(which)->as_C_string();1821} else if (tag.is_symbol()) {1822return symbol_at(which)->as_C_string();1823}1824return "";1825}18261827#endif // PRODUCT182818291830// JVMTI GetConstantPool support18311832// For debugging of constant pool1833const bool debug_cpool = false;18341835#define DBG(code) do { if (debug_cpool) { (code); } } while(0)18361837static void print_cpool_bytes(jint cnt, u1 *bytes) {1838const char* WARN_MSG = "Must not be such entry!";1839jint size = 0;1840u2 idx1, idx2;18411842for (jint idx = 1; idx < cnt; idx++) {1843jint ent_size = 0;1844u1 tag = *bytes++;1845size++; // count tag18461847printf("const #%03d, tag: %02d ", idx, tag);1848switch(tag) {1849case JVM_CONSTANT_Invalid: {1850printf("Invalid");1851break;1852}1853case JVM_CONSTANT_Unicode: {1854printf("Unicode %s", WARN_MSG);1855break;1856}1857case JVM_CONSTANT_Utf8: {1858u2 len = Bytes::get_Java_u2(bytes);1859char str[128];1860if (len > 127) {1861len = 127;1862}1863strncpy(str, (char *) (bytes+2), len);1864str[len] = '\0';1865printf("Utf8 \"%s\"", str);1866ent_size = 2 + len;1867break;1868}1869case JVM_CONSTANT_Integer: {1870u4 val = Bytes::get_Java_u4(bytes);1871printf("int %d", *(int *) &val);1872ent_size = 4;1873break;1874}1875case JVM_CONSTANT_Float: {1876u4 val = Bytes::get_Java_u4(bytes);1877printf("float %5.3ff", *(float *) &val);1878ent_size = 4;1879break;1880}1881case JVM_CONSTANT_Long: {1882u8 val = Bytes::get_Java_u8(bytes);1883printf("long " INT64_FORMAT, (int64_t) *(jlong *) &val);1884ent_size = 8;1885idx++; // Long takes two cpool slots1886break;1887}1888case JVM_CONSTANT_Double: {1889u8 val = Bytes::get_Java_u8(bytes);1890printf("double %5.3fd", *(jdouble *)&val);1891ent_size = 8;1892idx++; // Double takes two cpool slots1893break;1894}1895case JVM_CONSTANT_Class: {1896idx1 = Bytes::get_Java_u2(bytes);1897printf("class #%03d", idx1);1898ent_size = 2;1899break;1900}1901case JVM_CONSTANT_String: {1902idx1 = Bytes::get_Java_u2(bytes);1903printf("String #%03d", idx1);1904ent_size = 2;1905break;1906}1907case JVM_CONSTANT_Fieldref: {1908idx1 = Bytes::get_Java_u2(bytes);1909idx2 = Bytes::get_Java_u2(bytes+2);1910printf("Field #%03d, #%03d", (int) idx1, (int) idx2);1911ent_size = 4;1912break;1913}1914case JVM_CONSTANT_Methodref: {1915idx1 = Bytes::get_Java_u2(bytes);1916idx2 = Bytes::get_Java_u2(bytes+2);1917printf("Method #%03d, #%03d", idx1, idx2);1918ent_size = 4;1919break;1920}1921case JVM_CONSTANT_InterfaceMethodref: {1922idx1 = Bytes::get_Java_u2(bytes);1923idx2 = Bytes::get_Java_u2(bytes+2);1924printf("InterfMethod #%03d, #%03d", idx1, idx2);1925ent_size = 4;1926break;1927}1928case JVM_CONSTANT_NameAndType: {1929idx1 = Bytes::get_Java_u2(bytes);1930idx2 = Bytes::get_Java_u2(bytes+2);1931printf("NameAndType #%03d, #%03d", idx1, idx2);1932ent_size = 4;1933break;1934}1935case JVM_CONSTANT_ClassIndex: {1936printf("ClassIndex %s", WARN_MSG);1937break;1938}1939case JVM_CONSTANT_UnresolvedClass: {1940printf("UnresolvedClass: %s", WARN_MSG);1941break;1942}1943case JVM_CONSTANT_UnresolvedClassInError: {1944printf("UnresolvedClassInErr: %s", WARN_MSG);1945break;1946}1947case JVM_CONSTANT_StringIndex: {1948printf("StringIndex: %s", WARN_MSG);1949break;1950}1951}1952printf(";\n");1953bytes += ent_size;1954size += ent_size;1955}1956printf("Cpool size: %d\n", size);1957fflush(0);1958return;1959} /* end print_cpool_bytes */196019611962// Returns size of constant pool entry.1963jint ConstantPool::cpool_entry_size(jint idx) {1964switch(tag_at(idx).value()) {1965case JVM_CONSTANT_Invalid:1966case JVM_CONSTANT_Unicode:1967return 1;19681969case JVM_CONSTANT_Utf8:1970return 3 + symbol_at(idx)->utf8_length();19711972case JVM_CONSTANT_Class:1973case JVM_CONSTANT_String:1974case JVM_CONSTANT_ClassIndex:1975case JVM_CONSTANT_UnresolvedClass:1976case JVM_CONSTANT_UnresolvedClassInError:1977case JVM_CONSTANT_StringIndex:1978case JVM_CONSTANT_MethodType:1979case JVM_CONSTANT_MethodTypeInError:1980return 3;19811982case JVM_CONSTANT_MethodHandle:1983case JVM_CONSTANT_MethodHandleInError:1984return 4; //tag, ref_kind, ref_index19851986case JVM_CONSTANT_Integer:1987case JVM_CONSTANT_Float:1988case JVM_CONSTANT_Fieldref:1989case JVM_CONSTANT_Methodref:1990case JVM_CONSTANT_InterfaceMethodref:1991case JVM_CONSTANT_NameAndType:1992return 5;19931994case JVM_CONSTANT_Dynamic:1995case JVM_CONSTANT_DynamicInError:1996case JVM_CONSTANT_InvokeDynamic:1997// u1 tag, u2 bsm, u2 nt1998return 5;19992000case JVM_CONSTANT_Long:2001case JVM_CONSTANT_Double:2002return 9;2003}2004assert(false, "cpool_entry_size: Invalid constant pool entry tag");2005return 1;2006} /* end cpool_entry_size */200720082009// SymbolHashMap is used to find a constant pool index from a string.2010// This function fills in SymbolHashMaps, one for utf8s and one for2011// class names, returns size of the cpool raw bytes.2012jint ConstantPool::hash_entries_to(SymbolHashMap *symmap,2013SymbolHashMap *classmap) {2014jint size = 0;20152016for (u2 idx = 1; idx < length(); idx++) {2017u2 tag = tag_at(idx).value();2018size += cpool_entry_size(idx);20192020switch(tag) {2021case JVM_CONSTANT_Utf8: {2022Symbol* sym = symbol_at(idx);2023symmap->add_entry(sym, idx);2024DBG(printf("adding symbol entry %s = %d\n", sym->as_utf8(), idx));2025break;2026}2027case JVM_CONSTANT_Class:2028case JVM_CONSTANT_UnresolvedClass:2029case JVM_CONSTANT_UnresolvedClassInError: {2030Symbol* sym = klass_name_at(idx);2031classmap->add_entry(sym, idx);2032DBG(printf("adding class entry %s = %d\n", sym->as_utf8(), idx));2033break;2034}2035case JVM_CONSTANT_Long:2036case JVM_CONSTANT_Double: {2037idx++; // Both Long and Double take two cpool slots2038break;2039}2040}2041}2042return size;2043} /* end hash_utf8_entries_to */204420452046// Copy cpool bytes.2047// Returns:2048// 0, in case of OutOfMemoryError2049// -1, in case of internal error2050// > 0, count of the raw cpool bytes that have been copied2051int ConstantPool::copy_cpool_bytes(int cpool_size,2052SymbolHashMap* tbl,2053unsigned char *bytes) {2054u2 idx1, idx2;2055jint size = 0;2056jint cnt = length();2057unsigned char *start_bytes = bytes;20582059for (jint idx = 1; idx < cnt; idx++) {2060u1 tag = tag_at(idx).value();2061jint ent_size = cpool_entry_size(idx);20622063assert(size + ent_size <= cpool_size, "Size mismatch");20642065*bytes = tag;2066DBG(printf("#%03hd tag=%03hd, ", (short)idx, (short)tag));2067switch(tag) {2068case JVM_CONSTANT_Invalid: {2069DBG(printf("JVM_CONSTANT_Invalid"));2070break;2071}2072case JVM_CONSTANT_Unicode: {2073assert(false, "Wrong constant pool tag: JVM_CONSTANT_Unicode");2074DBG(printf("JVM_CONSTANT_Unicode"));2075break;2076}2077case JVM_CONSTANT_Utf8: {2078Symbol* sym = symbol_at(idx);2079char* str = sym->as_utf8();2080// Warning! It's crashing on x86 with len = sym->utf8_length()2081int len = (int) strlen(str);2082Bytes::put_Java_u2((address) (bytes+1), (u2) len);2083for (int i = 0; i < len; i++) {2084bytes[3+i] = (u1) str[i];2085}2086DBG(printf("JVM_CONSTANT_Utf8: %s ", str));2087break;2088}2089case JVM_CONSTANT_Integer: {2090jint val = int_at(idx);2091Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);2092break;2093}2094case JVM_CONSTANT_Float: {2095jfloat val = float_at(idx);2096Bytes::put_Java_u4((address) (bytes+1), *(u4*)&val);2097break;2098}2099case JVM_CONSTANT_Long: {2100jlong val = long_at(idx);2101Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);2102idx++; // Long takes two cpool slots2103break;2104}2105case JVM_CONSTANT_Double: {2106jdouble val = double_at(idx);2107Bytes::put_Java_u8((address) (bytes+1), *(u8*)&val);2108idx++; // Double takes two cpool slots2109break;2110}2111case JVM_CONSTANT_Class:2112case JVM_CONSTANT_UnresolvedClass:2113case JVM_CONSTANT_UnresolvedClassInError: {2114*bytes = JVM_CONSTANT_Class;2115Symbol* sym = klass_name_at(idx);2116idx1 = tbl->symbol_to_value(sym);2117assert(idx1 != 0, "Have not found a hashtable entry");2118Bytes::put_Java_u2((address) (bytes+1), idx1);2119DBG(printf("JVM_CONSTANT_Class: idx=#%03hd, %s", idx1, sym->as_utf8()));2120break;2121}2122case JVM_CONSTANT_String: {2123*bytes = JVM_CONSTANT_String;2124Symbol* sym = unresolved_string_at(idx);2125idx1 = tbl->symbol_to_value(sym);2126assert(idx1 != 0, "Have not found a hashtable entry");2127Bytes::put_Java_u2((address) (bytes+1), idx1);2128DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));2129break;2130}2131case JVM_CONSTANT_Fieldref:2132case JVM_CONSTANT_Methodref:2133case JVM_CONSTANT_InterfaceMethodref: {2134idx1 = uncached_klass_ref_index_at(idx);2135idx2 = uncached_name_and_type_ref_index_at(idx);2136Bytes::put_Java_u2((address) (bytes+1), idx1);2137Bytes::put_Java_u2((address) (bytes+3), idx2);2138DBG(printf("JVM_CONSTANT_Methodref: %hd %hd", idx1, idx2));2139break;2140}2141case JVM_CONSTANT_NameAndType: {2142idx1 = name_ref_index_at(idx);2143idx2 = signature_ref_index_at(idx);2144Bytes::put_Java_u2((address) (bytes+1), idx1);2145Bytes::put_Java_u2((address) (bytes+3), idx2);2146DBG(printf("JVM_CONSTANT_NameAndType: %hd %hd", idx1, idx2));2147break;2148}2149case JVM_CONSTANT_ClassIndex: {2150*bytes = JVM_CONSTANT_Class;2151idx1 = klass_index_at(idx);2152Bytes::put_Java_u2((address) (bytes+1), idx1);2153DBG(printf("JVM_CONSTANT_ClassIndex: %hd", idx1));2154break;2155}2156case JVM_CONSTANT_StringIndex: {2157*bytes = JVM_CONSTANT_String;2158idx1 = string_index_at(idx);2159Bytes::put_Java_u2((address) (bytes+1), idx1);2160DBG(printf("JVM_CONSTANT_StringIndex: %hd", idx1));2161break;2162}2163case JVM_CONSTANT_MethodHandle:2164case JVM_CONSTANT_MethodHandleInError: {2165*bytes = JVM_CONSTANT_MethodHandle;2166int kind = method_handle_ref_kind_at(idx);2167idx1 = method_handle_index_at(idx);2168*(bytes+1) = (unsigned char) kind;2169Bytes::put_Java_u2((address) (bytes+2), idx1);2170DBG(printf("JVM_CONSTANT_MethodHandle: %d %hd", kind, idx1));2171break;2172}2173case JVM_CONSTANT_MethodType:2174case JVM_CONSTANT_MethodTypeInError: {2175*bytes = JVM_CONSTANT_MethodType;2176idx1 = method_type_index_at(idx);2177Bytes::put_Java_u2((address) (bytes+1), idx1);2178DBG(printf("JVM_CONSTANT_MethodType: %hd", idx1));2179break;2180}2181case JVM_CONSTANT_Dynamic:2182case JVM_CONSTANT_DynamicInError: {2183*bytes = tag;2184idx1 = extract_low_short_from_int(*int_at_addr(idx));2185idx2 = extract_high_short_from_int(*int_at_addr(idx));2186assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");2187Bytes::put_Java_u2((address) (bytes+1), idx1);2188Bytes::put_Java_u2((address) (bytes+3), idx2);2189DBG(printf("JVM_CONSTANT_Dynamic: %hd %hd", idx1, idx2));2190break;2191}2192case JVM_CONSTANT_InvokeDynamic: {2193*bytes = tag;2194idx1 = extract_low_short_from_int(*int_at_addr(idx));2195idx2 = extract_high_short_from_int(*int_at_addr(idx));2196assert(idx2 == bootstrap_name_and_type_ref_index_at(idx), "correct half of u4");2197Bytes::put_Java_u2((address) (bytes+1), idx1);2198Bytes::put_Java_u2((address) (bytes+3), idx2);2199DBG(printf("JVM_CONSTANT_InvokeDynamic: %hd %hd", idx1, idx2));2200break;2201}2202}2203DBG(printf("\n"));2204bytes += ent_size;2205size += ent_size;2206}2207assert(size == cpool_size, "Size mismatch");22082209// Keep temorarily for debugging until it's stable.2210DBG(print_cpool_bytes(cnt, start_bytes));2211return (int)(bytes - start_bytes);2212} /* end copy_cpool_bytes */22132214#undef DBG221522162217void ConstantPool::set_on_stack(const bool value) {2218if (value) {2219// Only record if it's not already set.2220if (!on_stack()) {2221assert(!is_shared(), "should always be set for shared constant pools");2222_flags |= _on_stack;2223MetadataOnStackMark::record(this);2224}2225} else {2226// Clearing is done single-threadedly.2227if (!is_shared()) {2228_flags &= ~_on_stack;2229}2230}2231}22322233// Printing22342235void ConstantPool::print_on(outputStream* st) const {2236assert(is_constantPool(), "must be constantPool");2237st->print_cr("%s", internal_name());2238if (flags() != 0) {2239st->print(" - flags: 0x%x", flags());2240if (has_preresolution()) st->print(" has_preresolution");2241if (on_stack()) st->print(" on_stack");2242st->cr();2243}2244if (pool_holder() != NULL) {2245st->print_cr(" - holder: " INTPTR_FORMAT, p2i(pool_holder()));2246}2247st->print_cr(" - cache: " INTPTR_FORMAT, p2i(cache()));2248st->print_cr(" - resolved_references: " INTPTR_FORMAT, p2i(resolved_references()));2249st->print_cr(" - reference_map: " INTPTR_FORMAT, p2i(reference_map()));2250st->print_cr(" - resolved_klasses: " INTPTR_FORMAT, p2i(resolved_klasses()));22512252for (int index = 1; index < length(); index++) { // Index 0 is unused2253((ConstantPool*)this)->print_entry_on(index, st);2254switch (tag_at(index).value()) {2255case JVM_CONSTANT_Long :2256case JVM_CONSTANT_Double :2257index++; // Skip entry following eigth-byte constant2258}22592260}2261st->cr();2262}22632264// Print one constant pool entry2265void ConstantPool::print_entry_on(const int index, outputStream* st) {2266EXCEPTION_MARK;2267st->print(" - %3d : ", index);2268tag_at(index).print_on(st);2269st->print(" : ");2270switch (tag_at(index).value()) {2271case JVM_CONSTANT_Class :2272{ Klass* k = klass_at(index, CATCH);2273guarantee(k != NULL, "need klass");2274k->print_value_on(st);2275st->print(" {" PTR_FORMAT "}", p2i(k));2276}2277break;2278case JVM_CONSTANT_Fieldref :2279case JVM_CONSTANT_Methodref :2280case JVM_CONSTANT_InterfaceMethodref :2281st->print("klass_index=%d", uncached_klass_ref_index_at(index));2282st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));2283break;2284case JVM_CONSTANT_String :2285unresolved_string_at(index)->print_value_on(st);2286break;2287case JVM_CONSTANT_Integer :2288st->print("%d", int_at(index));2289break;2290case JVM_CONSTANT_Float :2291st->print("%f", float_at(index));2292break;2293case JVM_CONSTANT_Long :2294st->print_jlong(long_at(index));2295break;2296case JVM_CONSTANT_Double :2297st->print("%lf", double_at(index));2298break;2299case JVM_CONSTANT_NameAndType :2300st->print("name_index=%d", name_ref_index_at(index));2301st->print(" signature_index=%d", signature_ref_index_at(index));2302break;2303case JVM_CONSTANT_Utf8 :2304symbol_at(index)->print_value_on(st);2305break;2306case JVM_CONSTANT_ClassIndex: {2307int name_index = *int_at_addr(index);2308st->print("klass_index=%d ", name_index);2309symbol_at(name_index)->print_value_on(st);2310}2311break;2312case JVM_CONSTANT_UnresolvedClass : // fall-through2313case JVM_CONSTANT_UnresolvedClassInError: {2314CPKlassSlot kslot = klass_slot_at(index);2315int resolved_klass_index = kslot.resolved_klass_index();2316int name_index = kslot.name_index();2317assert(tag_at(name_index).is_symbol(), "sanity");2318symbol_at(name_index)->print_value_on(st);2319}2320break;2321case JVM_CONSTANT_MethodHandle :2322case JVM_CONSTANT_MethodHandleInError :2323st->print("ref_kind=%d", method_handle_ref_kind_at(index));2324st->print(" ref_index=%d", method_handle_index_at(index));2325break;2326case JVM_CONSTANT_MethodType :2327case JVM_CONSTANT_MethodTypeInError :2328st->print("signature_index=%d", method_type_index_at(index));2329break;2330case JVM_CONSTANT_Dynamic :2331case JVM_CONSTANT_DynamicInError :2332{2333st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));2334st->print(" type_index=%d", bootstrap_name_and_type_ref_index_at(index));2335int argc = bootstrap_argument_count_at(index);2336if (argc > 0) {2337for (int arg_i = 0; arg_i < argc; arg_i++) {2338int arg = bootstrap_argument_index_at(index, arg_i);2339st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);2340}2341st->print("}");2342}2343}2344break;2345case JVM_CONSTANT_InvokeDynamic :2346{2347st->print("bootstrap_method_index=%d", bootstrap_method_ref_index_at(index));2348st->print(" name_and_type_index=%d", bootstrap_name_and_type_ref_index_at(index));2349int argc = bootstrap_argument_count_at(index);2350if (argc > 0) {2351for (int arg_i = 0; arg_i < argc; arg_i++) {2352int arg = bootstrap_argument_index_at(index, arg_i);2353st->print((arg_i == 0 ? " arguments={%d" : ", %d"), arg);2354}2355st->print("}");2356}2357}2358break;2359default:2360ShouldNotReachHere();2361break;2362}2363st->cr();2364}23652366void ConstantPool::print_value_on(outputStream* st) const {2367assert(is_constantPool(), "must be constantPool");2368st->print("constant pool [%d]", length());2369if (has_preresolution()) st->print("/preresolution");2370if (operands() != NULL) st->print("/operands[%d]", operands()->length());2371print_address_on(st);2372if (pool_holder() != NULL) {2373st->print(" for ");2374pool_holder()->print_value_on(st);2375bool extra = (pool_holder()->constants() != this);2376if (extra) st->print(" (extra)");2377}2378if (cache() != NULL) {2379st->print(" cache=" PTR_FORMAT, p2i(cache()));2380}2381}23822383// Verification23842385void ConstantPool::verify_on(outputStream* st) {2386guarantee(is_constantPool(), "object must be constant pool");2387for (int i = 0; i< length(); i++) {2388constantTag tag = tag_at(i);2389if (tag.is_klass() || tag.is_unresolved_klass()) {2390guarantee(klass_name_at(i)->refcount() != 0, "should have nonzero reference count");2391} else if (tag.is_symbol()) {2392CPSlot entry = slot_at(i);2393guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");2394} else if (tag.is_string()) {2395CPSlot entry = slot_at(i);2396guarantee(entry.get_symbol()->refcount() != 0, "should have nonzero reference count");2397}2398}2399if (pool_holder() != NULL) {2400// Note: pool_holder() can be NULL in temporary constant pools2401// used during constant pool merging2402guarantee(pool_holder()->is_klass(), "should be klass");2403}2404}240524062407SymbolHashMap::~SymbolHashMap() {2408SymbolHashMapEntry* next;2409for (int i = 0; i < _table_size; i++) {2410for (SymbolHashMapEntry* cur = bucket(i); cur != NULL; cur = next) {2411next = cur->next();2412delete(cur);2413}2414}2415FREE_C_HEAP_ARRAY(SymbolHashMapBucket, _buckets);2416}24172418void SymbolHashMap::add_entry(Symbol* sym, u2 value) {2419char *str = sym->as_utf8();2420unsigned int hash = compute_hash(str, sym->utf8_length());2421unsigned int index = hash % table_size();24222423// check if already in map2424// we prefer the first entry since it is more likely to be what was used in2425// the class file2426for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {2427assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");2428if (en->hash() == hash && en->symbol() == sym) {2429return; // already there2430}2431}24322433SymbolHashMapEntry* entry = new SymbolHashMapEntry(hash, sym, value);2434entry->set_next(bucket(index));2435_buckets[index].set_entry(entry);2436assert(entry->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");2437}24382439SymbolHashMapEntry* SymbolHashMap::find_entry(Symbol* sym) {2440assert(sym != NULL, "SymbolHashMap::find_entry - symbol is NULL");2441char *str = sym->as_utf8();2442int len = sym->utf8_length();2443unsigned int hash = SymbolHashMap::compute_hash(str, len);2444unsigned int index = hash % table_size();2445for (SymbolHashMapEntry *en = bucket(index); en != NULL; en = en->next()) {2446assert(en->symbol() != NULL, "SymbolHashMapEntry symbol is NULL");2447if (en->hash() == hash && en->symbol() == sym) {2448return en;2449}2450}2451return NULL;2452}24532454void SymbolHashMap::initialize_table(int table_size) {2455_table_size = table_size;2456_buckets = NEW_C_HEAP_ARRAY(SymbolHashMapBucket, table_size, mtSymbol);2457for (int index = 0; index < table_size; index++) {2458_buckets[index].clear();2459}2460}246124622463