Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp
32285 views
/*1* Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/metadataOnStackMark.hpp"26#include "classfile/systemDictionary.hpp"27#include "classfile/verifier.hpp"28#include "code/codeCache.hpp"29#include "compiler/compileBroker.hpp"30#include "interpreter/oopMapCache.hpp"31#include "interpreter/rewriter.hpp"32#include "memory/gcLocker.hpp"33#include "memory/metadataFactory.hpp"34#include "memory/metaspaceShared.hpp"35#include "memory/universe.inline.hpp"36#include "oops/fieldStreams.hpp"37#include "oops/klassVtable.hpp"38#include "prims/jvmtiImpl.hpp"39#include "prims/jvmtiRedefineClasses.hpp"40#include "prims/methodComparator.hpp"41#include "runtime/deoptimization.hpp"42#include "runtime/relocator.hpp"43#include "utilities/bitMap.inline.hpp"44#include "utilities/events.hpp"4546PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC4748Array<Method*>* VM_RedefineClasses::_old_methods = NULL;49Array<Method*>* VM_RedefineClasses::_new_methods = NULL;50Method** VM_RedefineClasses::_matching_old_methods = NULL;51Method** VM_RedefineClasses::_matching_new_methods = NULL;52Method** VM_RedefineClasses::_deleted_methods = NULL;53Method** VM_RedefineClasses::_added_methods = NULL;54int VM_RedefineClasses::_matching_methods_length = 0;55int VM_RedefineClasses::_deleted_methods_length = 0;56int VM_RedefineClasses::_added_methods_length = 0;57Klass* VM_RedefineClasses::_the_class_oop = NULL;585960VM_RedefineClasses::VM_RedefineClasses(jint class_count,61const jvmtiClassDefinition *class_defs,62JvmtiClassLoadKind class_load_kind) {63_class_count = class_count;64_class_defs = class_defs;65_class_load_kind = class_load_kind;66_res = JVMTI_ERROR_NONE;67}6869static inline InstanceKlass* get_ik(jclass def) {70oop mirror = JNIHandles::resolve_non_null(def);71return InstanceKlass::cast(java_lang_Class::as_Klass(mirror));72}7374// If any of the classes are being redefined, wait75// Parallel constant pool merging leads to indeterminate constant pools.76void VM_RedefineClasses::lock_classes() {77MutexLocker ml(RedefineClasses_lock);78bool has_redefined;79do {80has_redefined = false;81// Go through classes each time until none are being redefined.82for (int i = 0; i < _class_count; i++) {83if (get_ik(_class_defs[i].klass)->is_being_redefined()) {84RedefineClasses_lock->wait();85has_redefined = true;86break; // for loop87}88}89} while (has_redefined);90for (int i = 0; i < _class_count; i++) {91get_ik(_class_defs[i].klass)->set_is_being_redefined(true);92}93RedefineClasses_lock->notify_all();94}9596void VM_RedefineClasses::unlock_classes() {97MutexLocker ml(RedefineClasses_lock);98for (int i = 0; i < _class_count; i++) {99assert(get_ik(_class_defs[i].klass)->is_being_redefined(),100"should be being redefined to get here");101get_ik(_class_defs[i].klass)->set_is_being_redefined(false);102}103RedefineClasses_lock->notify_all();104}105106bool VM_RedefineClasses::doit_prologue() {107if (_class_count == 0) {108_res = JVMTI_ERROR_NONE;109return false;110}111if (_class_defs == NULL) {112_res = JVMTI_ERROR_NULL_POINTER;113return false;114}115for (int i = 0; i < _class_count; i++) {116if (_class_defs[i].klass == NULL) {117_res = JVMTI_ERROR_INVALID_CLASS;118return false;119}120if (_class_defs[i].class_byte_count == 0) {121_res = JVMTI_ERROR_INVALID_CLASS_FORMAT;122return false;123}124if (_class_defs[i].class_bytes == NULL) {125_res = JVMTI_ERROR_NULL_POINTER;126return false;127}128129oop mirror = JNIHandles::resolve_non_null(_class_defs[i].klass);130// classes for primitives and arrays cannot be redefined131// check here so following code can assume these classes are InstanceKlass132if (!is_modifiable_class(mirror)) {133_res = JVMTI_ERROR_UNMODIFIABLE_CLASS;134return false;135}136}137138// Start timer after all the sanity checks; not quite accurate, but139// better than adding a bunch of stop() calls.140RC_TIMER_START(_timer_vm_op_prologue);141142lock_classes();143// We first load new class versions in the prologue, because somewhere down the144// call chain it is required that the current thread is a Java thread.145_res = load_new_class_versions(Thread::current());146if (_res != JVMTI_ERROR_NONE) {147// free any successfully created classes, since none are redefined148for (int i = 0; i < _class_count; i++) {149if (_scratch_classes[i] != NULL) {150ClassLoaderData* cld = _scratch_classes[i]->class_loader_data();151// Free the memory for this class at class unloading time. Not before152// because CMS might think this is still live.153InstanceKlass* ik = get_ik(_class_defs[i].klass);154if (ik->get_cached_class_file() == ((InstanceKlass*)_scratch_classes[i])->get_cached_class_file()) {155// Don't double-free cached_class_file copied from the original class if error.156((InstanceKlass*)_scratch_classes[i])->set_cached_class_file(NULL);157}158cld->add_to_deallocate_list((InstanceKlass*)_scratch_classes[i]);159}160}161// Free os::malloc allocated memory in load_new_class_version.162os::free(_scratch_classes);163RC_TIMER_STOP(_timer_vm_op_prologue);164unlock_classes();165return false;166}167168RC_TIMER_STOP(_timer_vm_op_prologue);169return true;170}171172void VM_RedefineClasses::doit() {173Thread *thread = Thread::current();174175if (UseSharedSpaces) {176// Sharing is enabled so we remap the shared readonly space to177// shared readwrite, private just in case we need to redefine178// a shared class. We do the remap during the doit() phase of179// the safepoint to be safer.180if (!MetaspaceShared::remap_shared_readonly_as_readwrite()) {181RC_TRACE_WITH_THREAD(0x00000001, thread,182("failed to remap shared readonly space to readwrite, private"));183_res = JVMTI_ERROR_INTERNAL;184return;185}186}187188// Mark methods seen on stack and everywhere else so old methods are not189// cleaned up if they're on the stack.190MetadataOnStackMark md_on_stack(true);191HandleMark hm(thread); // make sure any handles created are deleted192// before the stack walk again.193194for (int i = 0; i < _class_count; i++) {195redefine_single_class(_class_defs[i].klass, _scratch_classes[i], thread);196ClassLoaderData* cld = _scratch_classes[i]->class_loader_data();197// Free the memory for this class at class unloading time. Not before198// because CMS might think this is still live.199cld->add_to_deallocate_list((InstanceKlass*)_scratch_classes[i]);200_scratch_classes[i] = NULL;201}202203// Disable any dependent concurrent compilations204SystemDictionary::notice_modification();205206// Set flag indicating that some invariants are no longer true.207// See jvmtiExport.hpp for detailed explanation.208JvmtiExport::set_has_redefined_a_class();209210// check_class() is optionally called for product bits, but is211// always called for non-product bits.212#ifdef PRODUCT213if (RC_TRACE_ENABLED(0x00004000)) {214#endif215RC_TRACE_WITH_THREAD(0x00004000, thread, ("calling check_class"));216CheckClass check_class(thread);217ClassLoaderDataGraph::classes_do(&check_class);218#ifdef PRODUCT219}220#endif221}222223void VM_RedefineClasses::doit_epilogue() {224unlock_classes();225226// Free os::malloc allocated memory.227os::free(_scratch_classes);228229// Reset the_class_oop to null for error printing.230_the_class_oop = NULL;231232if (RC_TRACE_ENABLED(0x00000004)) {233// Used to have separate timers for "doit" and "all", but the timer234// overhead skewed the measurements.235jlong doit_time = _timer_rsc_phase1.milliseconds() +236_timer_rsc_phase2.milliseconds();237jlong all_time = _timer_vm_op_prologue.milliseconds() + doit_time;238239RC_TRACE(0x00000004, ("vm_op: all=" UINT64_FORMAT240" prologue=" UINT64_FORMAT " doit=" UINT64_FORMAT, all_time,241_timer_vm_op_prologue.milliseconds(), doit_time));242RC_TRACE(0x00000004,243("redefine_single_class: phase1=" UINT64_FORMAT " phase2=" UINT64_FORMAT,244_timer_rsc_phase1.milliseconds(), _timer_rsc_phase2.milliseconds()));245}246}247248bool VM_RedefineClasses::is_modifiable_class(oop klass_mirror) {249// classes for primitives cannot be redefined250if (java_lang_Class::is_primitive(klass_mirror)) {251return false;252}253Klass* the_class_oop = java_lang_Class::as_Klass(klass_mirror);254// classes for arrays cannot be redefined255if (the_class_oop == NULL || !the_class_oop->oop_is_instance()) {256return false;257}258return true;259}260261// Append the current entry at scratch_i in scratch_cp to *merge_cp_p262// where the end of *merge_cp_p is specified by *merge_cp_length_p. For263// direct CP entries, there is just the current entry to append. For264// indirect and double-indirect CP entries, there are zero or more265// referenced CP entries along with the current entry to append.266// Indirect and double-indirect CP entries are handled by recursive267// calls to append_entry() as needed. The referenced CP entries are268// always appended to *merge_cp_p before the referee CP entry. These269// referenced CP entries may already exist in *merge_cp_p in which case270// there is nothing extra to append and only the current entry is271// appended.272void VM_RedefineClasses::append_entry(constantPoolHandle scratch_cp,273int scratch_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p,274TRAPS) {275276// append is different depending on entry tag type277switch (scratch_cp->tag_at(scratch_i).value()) {278279// The old verifier is implemented outside the VM. It loads classes,280// but does not resolve constant pool entries directly so we never281// see Class entries here with the old verifier. Similarly the old282// verifier does not like Class entries in the input constant pool.283// The split-verifier is implemented in the VM so it can optionally284// and directly resolve constant pool entries to load classes. The285// split-verifier can accept either Class entries or UnresolvedClass286// entries in the input constant pool. We revert the appended copy287// back to UnresolvedClass so that either verifier will be happy288// with the constant pool entry.289case JVM_CONSTANT_Class:290{291// revert the copy to JVM_CONSTANT_UnresolvedClass292(*merge_cp_p)->unresolved_klass_at_put(*merge_cp_length_p,293scratch_cp->klass_name_at(scratch_i));294295if (scratch_i != *merge_cp_length_p) {296// The new entry in *merge_cp_p is at a different index than297// the new entry in scratch_cp so we need to map the index values.298map_index(scratch_cp, scratch_i, *merge_cp_length_p);299}300(*merge_cp_length_p)++;301} break;302303// these are direct CP entries so they can be directly appended,304// but double and long take two constant pool entries305case JVM_CONSTANT_Double: // fall through306case JVM_CONSTANT_Long:307{308ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p,309THREAD);310311if (scratch_i != *merge_cp_length_p) {312// The new entry in *merge_cp_p is at a different index than313// the new entry in scratch_cp so we need to map the index values.314map_index(scratch_cp, scratch_i, *merge_cp_length_p);315}316(*merge_cp_length_p) += 2;317} break;318319// these are direct CP entries so they can be directly appended320case JVM_CONSTANT_Float: // fall through321case JVM_CONSTANT_Integer: // fall through322case JVM_CONSTANT_Utf8: // fall through323324// This was an indirect CP entry, but it has been changed into325// Symbol*s so this entry can be directly appended.326case JVM_CONSTANT_String: // fall through327328// These were indirect CP entries, but they have been changed into329// Symbol*s so these entries can be directly appended.330case JVM_CONSTANT_UnresolvedClass: // fall through331{332ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p,333THREAD);334335if (scratch_i != *merge_cp_length_p) {336// The new entry in *merge_cp_p is at a different index than337// the new entry in scratch_cp so we need to map the index values.338map_index(scratch_cp, scratch_i, *merge_cp_length_p);339}340(*merge_cp_length_p)++;341} break;342343// this is an indirect CP entry so it needs special handling344case JVM_CONSTANT_NameAndType:345{346int name_ref_i = scratch_cp->name_ref_index_at(scratch_i);347int new_name_ref_i = find_or_append_indirect_entry(scratch_cp, name_ref_i, merge_cp_p,348merge_cp_length_p, THREAD);349350int signature_ref_i = scratch_cp->signature_ref_index_at(scratch_i);351int new_signature_ref_i = find_or_append_indirect_entry(scratch_cp, signature_ref_i,352merge_cp_p, merge_cp_length_p,353THREAD);354355// If the referenced entries already exist in *merge_cp_p, then356// both new_name_ref_i and new_signature_ref_i will both be 0.357// In that case, all we are appending is the current entry.358if (new_name_ref_i != name_ref_i) {359RC_TRACE(0x00080000,360("NameAndType entry@%d name_ref_index change: %d to %d",361*merge_cp_length_p, name_ref_i, new_name_ref_i));362}363if (new_signature_ref_i != signature_ref_i) {364RC_TRACE(0x00080000,365("NameAndType entry@%d signature_ref_index change: %d to %d",366*merge_cp_length_p, signature_ref_i, new_signature_ref_i));367}368369(*merge_cp_p)->name_and_type_at_put(*merge_cp_length_p,370new_name_ref_i, new_signature_ref_i);371if (scratch_i != *merge_cp_length_p) {372// The new entry in *merge_cp_p is at a different index than373// the new entry in scratch_cp so we need to map the index values.374map_index(scratch_cp, scratch_i, *merge_cp_length_p);375}376(*merge_cp_length_p)++;377} break;378379// this is a double-indirect CP entry so it needs special handling380case JVM_CONSTANT_Fieldref: // fall through381case JVM_CONSTANT_InterfaceMethodref: // fall through382case JVM_CONSTANT_Methodref:383{384int klass_ref_i = scratch_cp->uncached_klass_ref_index_at(scratch_i);385int new_klass_ref_i = find_or_append_indirect_entry(scratch_cp, klass_ref_i,386merge_cp_p, merge_cp_length_p, THREAD);387388int name_and_type_ref_i = scratch_cp->uncached_name_and_type_ref_index_at(scratch_i);389int new_name_and_type_ref_i = find_or_append_indirect_entry(scratch_cp, name_and_type_ref_i,390merge_cp_p, merge_cp_length_p, THREAD);391392const char *entry_name = NULL;393switch (scratch_cp->tag_at(scratch_i).value()) {394case JVM_CONSTANT_Fieldref:395entry_name = "Fieldref";396(*merge_cp_p)->field_at_put(*merge_cp_length_p, new_klass_ref_i,397new_name_and_type_ref_i);398break;399case JVM_CONSTANT_InterfaceMethodref:400entry_name = "IFMethodref";401(*merge_cp_p)->interface_method_at_put(*merge_cp_length_p,402new_klass_ref_i, new_name_and_type_ref_i);403break;404case JVM_CONSTANT_Methodref:405entry_name = "Methodref";406(*merge_cp_p)->method_at_put(*merge_cp_length_p, new_klass_ref_i,407new_name_and_type_ref_i);408break;409default:410guarantee(false, "bad switch");411break;412}413414if (klass_ref_i != new_klass_ref_i) {415RC_TRACE(0x00080000, ("%s entry@%d class_index changed: %d to %d",416entry_name, *merge_cp_length_p, klass_ref_i, new_klass_ref_i));417}418if (name_and_type_ref_i != new_name_and_type_ref_i) {419RC_TRACE(0x00080000,420("%s entry@%d name_and_type_index changed: %d to %d",421entry_name, *merge_cp_length_p, name_and_type_ref_i,422new_name_and_type_ref_i));423}424425if (scratch_i != *merge_cp_length_p) {426// The new entry in *merge_cp_p is at a different index than427// the new entry in scratch_cp so we need to map the index values.428map_index(scratch_cp, scratch_i, *merge_cp_length_p);429}430(*merge_cp_length_p)++;431} break;432433// this is an indirect CP entry so it needs special handling434case JVM_CONSTANT_MethodType:435{436int ref_i = scratch_cp->method_type_index_at(scratch_i);437int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,438merge_cp_length_p, THREAD);439if (new_ref_i != ref_i) {440RC_TRACE(0x00080000,441("MethodType entry@%d ref_index change: %d to %d",442*merge_cp_length_p, ref_i, new_ref_i));443}444(*merge_cp_p)->method_type_index_at_put(*merge_cp_length_p, new_ref_i);445if (scratch_i != *merge_cp_length_p) {446// The new entry in *merge_cp_p is at a different index than447// the new entry in scratch_cp so we need to map the index values.448map_index(scratch_cp, scratch_i, *merge_cp_length_p);449}450(*merge_cp_length_p)++;451} break;452453// this is an indirect CP entry so it needs special handling454case JVM_CONSTANT_MethodHandle:455{456int ref_kind = scratch_cp->method_handle_ref_kind_at(scratch_i);457int ref_i = scratch_cp->method_handle_index_at(scratch_i);458int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,459merge_cp_length_p, THREAD);460if (new_ref_i != ref_i) {461RC_TRACE(0x00080000,462("MethodHandle entry@%d ref_index change: %d to %d",463*merge_cp_length_p, ref_i, new_ref_i));464}465(*merge_cp_p)->method_handle_index_at_put(*merge_cp_length_p, ref_kind, new_ref_i);466if (scratch_i != *merge_cp_length_p) {467// The new entry in *merge_cp_p is at a different index than468// the new entry in scratch_cp so we need to map the index values.469map_index(scratch_cp, scratch_i, *merge_cp_length_p);470}471(*merge_cp_length_p)++;472} break;473474// this is an indirect CP entry so it needs special handling475case JVM_CONSTANT_InvokeDynamic:476{477// Index of the bootstrap specifier in the operands array478int old_bs_i = scratch_cp->invoke_dynamic_bootstrap_specifier_index(scratch_i);479int new_bs_i = find_or_append_operand(scratch_cp, old_bs_i, merge_cp_p,480merge_cp_length_p, THREAD);481// The bootstrap method NameAndType_info index482int old_ref_i = scratch_cp->invoke_dynamic_name_and_type_ref_index_at(scratch_i);483int new_ref_i = find_or_append_indirect_entry(scratch_cp, old_ref_i, merge_cp_p,484merge_cp_length_p, THREAD);485if (new_bs_i != old_bs_i) {486RC_TRACE(0x00080000,487("InvokeDynamic entry@%d bootstrap_method_attr_index change: %d to %d",488*merge_cp_length_p, old_bs_i, new_bs_i));489}490if (new_ref_i != old_ref_i) {491RC_TRACE(0x00080000,492("InvokeDynamic entry@%d name_and_type_index change: %d to %d",493*merge_cp_length_p, old_ref_i, new_ref_i));494}495496(*merge_cp_p)->invoke_dynamic_at_put(*merge_cp_length_p, new_bs_i, new_ref_i);497if (scratch_i != *merge_cp_length_p) {498// The new entry in *merge_cp_p is at a different index than499// the new entry in scratch_cp so we need to map the index values.500map_index(scratch_cp, scratch_i, *merge_cp_length_p);501}502(*merge_cp_length_p)++;503} break;504505// At this stage, Class or UnresolvedClass could be here, but not506// ClassIndex507case JVM_CONSTANT_ClassIndex: // fall through508509// Invalid is used as the tag for the second constant pool entry510// occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should511// not be seen by itself.512case JVM_CONSTANT_Invalid: // fall through513514// At this stage, String could be here, but not StringIndex515case JVM_CONSTANT_StringIndex: // fall through516517// At this stage JVM_CONSTANT_UnresolvedClassInError should not be518// here519case JVM_CONSTANT_UnresolvedClassInError: // fall through520521default:522{523// leave a breadcrumb524jbyte bad_value = scratch_cp->tag_at(scratch_i).value();525ShouldNotReachHere();526} break;527} // end switch tag value528} // end append_entry()529530531int VM_RedefineClasses::find_or_append_indirect_entry(constantPoolHandle scratch_cp,532int ref_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS) {533534int new_ref_i = ref_i;535bool match = (ref_i < *merge_cp_length_p) &&536scratch_cp->compare_entry_to(ref_i, *merge_cp_p, ref_i, THREAD);537538if (!match) {539// forward reference in *merge_cp_p or not a direct match540int found_i = scratch_cp->find_matching_entry(ref_i, *merge_cp_p, THREAD);541if (found_i != 0) {542guarantee(found_i != ref_i, "compare_entry_to() and find_matching_entry() do not agree");543// Found a matching entry somewhere else in *merge_cp_p so just need a mapping entry.544new_ref_i = found_i;545map_index(scratch_cp, ref_i, found_i);546} else {547// no match found so we have to append this entry to *merge_cp_p548append_entry(scratch_cp, ref_i, merge_cp_p, merge_cp_length_p, THREAD);549// The above call to append_entry() can only append one entry550// so the post call query of *merge_cp_length_p is only for551// the sake of consistency.552new_ref_i = *merge_cp_length_p - 1;553}554}555556return new_ref_i;557} // end find_or_append_indirect_entry()558559560// Append a bootstrap specifier into the merge_cp operands that is semantically equal561// to the scratch_cp operands bootstrap specifier passed by the old_bs_i index.562// Recursively append new merge_cp entries referenced by the new bootstrap specifier.563void VM_RedefineClasses::append_operand(constantPoolHandle scratch_cp, int old_bs_i,564constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS) {565566int old_ref_i = scratch_cp->operand_bootstrap_method_ref_index_at(old_bs_i);567int new_ref_i = find_or_append_indirect_entry(scratch_cp, old_ref_i, merge_cp_p,568merge_cp_length_p, THREAD);569if (new_ref_i != old_ref_i) {570RC_TRACE(0x00080000,571("operands entry@%d bootstrap method ref_index change: %d to %d",572_operands_cur_length, old_ref_i, new_ref_i));573}574575Array<u2>* merge_ops = (*merge_cp_p)->operands();576int new_bs_i = _operands_cur_length;577// We have _operands_cur_length == 0 when the merge_cp operands is empty yet.578// However, the operand_offset_at(0) was set in the extend_operands() call.579int new_base = (new_bs_i == 0) ? (*merge_cp_p)->operand_offset_at(0)580: (*merge_cp_p)->operand_next_offset_at(new_bs_i - 1);581int argc = scratch_cp->operand_argument_count_at(old_bs_i);582583ConstantPool::operand_offset_at_put(merge_ops, _operands_cur_length, new_base);584merge_ops->at_put(new_base++, new_ref_i);585merge_ops->at_put(new_base++, argc);586587for (int i = 0; i < argc; i++) {588int old_arg_ref_i = scratch_cp->operand_argument_index_at(old_bs_i, i);589int new_arg_ref_i = find_or_append_indirect_entry(scratch_cp, old_arg_ref_i, merge_cp_p,590merge_cp_length_p, THREAD);591merge_ops->at_put(new_base++, new_arg_ref_i);592if (new_arg_ref_i != old_arg_ref_i) {593RC_TRACE(0x00080000,594("operands entry@%d bootstrap method argument ref_index change: %d to %d",595_operands_cur_length, old_arg_ref_i, new_arg_ref_i));596}597}598if (old_bs_i != _operands_cur_length) {599// The bootstrap specifier in *merge_cp_p is at a different index than600// that in scratch_cp so we need to map the index values.601map_operand_index(old_bs_i, new_bs_i);602}603_operands_cur_length++;604} // end append_operand()605606607int VM_RedefineClasses::find_or_append_operand(constantPoolHandle scratch_cp,608int old_bs_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS) {609610int new_bs_i = old_bs_i; // bootstrap specifier index611bool match = (old_bs_i < _operands_cur_length) &&612scratch_cp->compare_operand_to(old_bs_i, *merge_cp_p, old_bs_i, THREAD);613614if (!match) {615// forward reference in *merge_cp_p or not a direct match616int found_i = scratch_cp->find_matching_operand(old_bs_i, *merge_cp_p,617_operands_cur_length, THREAD);618if (found_i != -1) {619guarantee(found_i != old_bs_i, "compare_operand_to() and find_matching_operand() disagree");620// found a matching operand somewhere else in *merge_cp_p so just need a mapping621new_bs_i = found_i;622map_operand_index(old_bs_i, found_i);623} else {624// no match found so we have to append this bootstrap specifier to *merge_cp_p625append_operand(scratch_cp, old_bs_i, merge_cp_p, merge_cp_length_p, THREAD);626new_bs_i = _operands_cur_length - 1;627}628}629return new_bs_i;630} // end find_or_append_operand()631632633void VM_RedefineClasses::finalize_operands_merge(constantPoolHandle merge_cp, TRAPS) {634if (merge_cp->operands() == NULL) {635return;636}637// Shrink the merge_cp operands638merge_cp->shrink_operands(_operands_cur_length, CHECK);639640if (RC_TRACE_ENABLED(0x00040000)) {641// don't want to loop unless we are tracing642int count = 0;643for (int i = 1; i < _operands_index_map_p->length(); i++) {644int value = _operands_index_map_p->at(i);645if (value != -1) {646RC_TRACE_WITH_THREAD(0x00040000, THREAD,647("operands_index_map[%d]: old=%d new=%d", count, i, value));648count++;649}650}651}652// Clean-up653_operands_index_map_p = NULL;654_operands_cur_length = 0;655_operands_index_map_count = 0;656} // end finalize_operands_merge()657658659jvmtiError VM_RedefineClasses::compare_and_normalize_class_versions(660instanceKlassHandle the_class,661instanceKlassHandle scratch_class) {662int i;663664// Check superclasses, or rather their names, since superclasses themselves can be665// requested to replace.666// Check for NULL superclass first since this might be java.lang.Object667if (the_class->super() != scratch_class->super() &&668(the_class->super() == NULL || scratch_class->super() == NULL ||669the_class->super()->name() !=670scratch_class->super()->name())) {671return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;672}673674// Check if the number, names and order of directly implemented interfaces are the same.675// I think in principle we should just check if the sets of names of directly implemented676// interfaces are the same, i.e. the order of declaration (which, however, if changed in the677// .java file, also changes in .class file) should not matter. However, comparing sets is678// technically a bit more difficult, and, more importantly, I am not sure at present that the679// order of interfaces does not matter on the implementation level, i.e. that the VM does not680// rely on it somewhere.681Array<Klass*>* k_interfaces = the_class->local_interfaces();682Array<Klass*>* k_new_interfaces = scratch_class->local_interfaces();683int n_intfs = k_interfaces->length();684if (n_intfs != k_new_interfaces->length()) {685return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;686}687for (i = 0; i < n_intfs; i++) {688if (k_interfaces->at(i)->name() !=689k_new_interfaces->at(i)->name()) {690return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;691}692}693694// Check whether class is in the error init state.695if (the_class->is_in_error_state()) {696// TBD #5057930: special error code is needed in 1.6697return JVMTI_ERROR_INVALID_CLASS;698}699700// Check whether class modifiers are the same.701jushort old_flags = (jushort) the_class->access_flags().get_flags();702jushort new_flags = (jushort) scratch_class->access_flags().get_flags();703if (old_flags != new_flags) {704return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED;705}706707// Check if the number, names, types and order of fields declared in these classes708// are the same.709JavaFieldStream old_fs(the_class);710JavaFieldStream new_fs(scratch_class);711for (; !old_fs.done() && !new_fs.done(); old_fs.next(), new_fs.next()) {712// access713old_flags = old_fs.access_flags().as_short();714new_flags = new_fs.access_flags().as_short();715if ((old_flags ^ new_flags) & JVM_RECOGNIZED_FIELD_MODIFIERS) {716return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;717}718// offset719if (old_fs.offset() != new_fs.offset()) {720return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;721}722// name and signature723Symbol* name_sym1 = the_class->constants()->symbol_at(old_fs.name_index());724Symbol* sig_sym1 = the_class->constants()->symbol_at(old_fs.signature_index());725Symbol* name_sym2 = scratch_class->constants()->symbol_at(new_fs.name_index());726Symbol* sig_sym2 = scratch_class->constants()->symbol_at(new_fs.signature_index());727if (name_sym1 != name_sym2 || sig_sym1 != sig_sym2) {728return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;729}730}731732// If both streams aren't done then we have a differing number of733// fields.734if (!old_fs.done() || !new_fs.done()) {735return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;736}737738// Do a parallel walk through the old and new methods. Detect739// cases where they match (exist in both), have been added in740// the new methods, or have been deleted (exist only in the741// old methods). The class file parser places methods in order742// by method name, but does not order overloaded methods by743// signature. In order to determine what fate befell the methods,744// this code places the overloaded new methods that have matching745// old methods in the same order as the old methods and places746// new overloaded methods at the end of overloaded methods of747// that name. The code for this order normalization is adapted748// from the algorithm used in InstanceKlass::find_method().749// Since we are swapping out of order entries as we find them,750// we only have to search forward through the overloaded methods.751// Methods which are added and have the same name as an existing752// method (but different signature) will be put at the end of753// the methods with that name, and the name mismatch code will754// handle them.755Array<Method*>* k_old_methods(the_class->methods());756Array<Method*>* k_new_methods(scratch_class->methods());757int n_old_methods = k_old_methods->length();758int n_new_methods = k_new_methods->length();759Thread* thread = Thread::current();760761int ni = 0;762int oi = 0;763while (true) {764Method* k_old_method;765Method* k_new_method;766enum { matched, added, deleted, undetermined } method_was = undetermined;767768if (oi >= n_old_methods) {769if (ni >= n_new_methods) {770break; // we've looked at everything, done771}772// New method at the end773k_new_method = k_new_methods->at(ni);774method_was = added;775} else if (ni >= n_new_methods) {776// Old method, at the end, is deleted777k_old_method = k_old_methods->at(oi);778method_was = deleted;779} else {780// There are more methods in both the old and new lists781k_old_method = k_old_methods->at(oi);782k_new_method = k_new_methods->at(ni);783if (k_old_method->name() != k_new_method->name()) {784// Methods are sorted by method name, so a mismatch means added785// or deleted786if (k_old_method->name()->fast_compare(k_new_method->name()) > 0) {787method_was = added;788} else {789method_was = deleted;790}791} else if (k_old_method->signature() == k_new_method->signature()) {792// Both the name and signature match793method_was = matched;794} else {795// The name matches, but the signature doesn't, which means we have to796// search forward through the new overloaded methods.797int nj; // outside the loop for post-loop check798for (nj = ni + 1; nj < n_new_methods; nj++) {799Method* m = k_new_methods->at(nj);800if (k_old_method->name() != m->name()) {801// reached another method name so no more overloaded methods802method_was = deleted;803break;804}805if (k_old_method->signature() == m->signature()) {806// found a match so swap the methods807k_new_methods->at_put(ni, m);808k_new_methods->at_put(nj, k_new_method);809k_new_method = m;810method_was = matched;811break;812}813}814815if (nj >= n_new_methods) {816// reached the end without a match; so method was deleted817method_was = deleted;818}819}820}821822switch (method_was) {823case matched:824// methods match, be sure modifiers do too825old_flags = (jushort) k_old_method->access_flags().get_flags();826new_flags = (jushort) k_new_method->access_flags().get_flags();827if ((old_flags ^ new_flags) & ~(JVM_ACC_NATIVE)) {828return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED;829}830{831u2 new_num = k_new_method->method_idnum();832u2 old_num = k_old_method->method_idnum();833if (new_num != old_num) {834Method* idnum_owner = scratch_class->method_with_idnum(old_num);835if (idnum_owner != NULL) {836// There is already a method assigned this idnum -- switch them837// Take current and original idnum from the new_method838idnum_owner->set_method_idnum(new_num);839idnum_owner->set_orig_method_idnum(k_new_method->orig_method_idnum());840}841// Take current and original idnum from the old_method842k_new_method->set_method_idnum(old_num);843k_new_method->set_orig_method_idnum(k_old_method->orig_method_idnum());844if (thread->has_pending_exception()) {845return JVMTI_ERROR_OUT_OF_MEMORY;846}847}848}849RC_TRACE(0x00008000, ("Method matched: new: %s [%d] == old: %s [%d]",850k_new_method->name_and_sig_as_C_string(), ni,851k_old_method->name_and_sig_as_C_string(), oi));852// advance to next pair of methods853++oi;854++ni;855break;856case added:857// method added, see if it is OK858new_flags = (jushort) k_new_method->access_flags().get_flags();859if ((new_flags & JVM_ACC_PRIVATE) == 0860// hack: private should be treated as final, but alas861|| (new_flags & (JVM_ACC_FINAL|JVM_ACC_STATIC)) == 0862) {863// new methods must be private864return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED;865}866{867u2 num = the_class->next_method_idnum();868if (num == ConstMethod::UNSET_IDNUM) {869// cannot add any more methods870return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED;871}872u2 new_num = k_new_method->method_idnum();873Method* idnum_owner = scratch_class->method_with_idnum(num);874if (idnum_owner != NULL) {875// There is already a method assigned this idnum -- switch them876// Take current and original idnum from the new_method877idnum_owner->set_method_idnum(new_num);878idnum_owner->set_orig_method_idnum(k_new_method->orig_method_idnum());879}880k_new_method->set_method_idnum(num);881k_new_method->set_orig_method_idnum(num);882if (thread->has_pending_exception()) {883return JVMTI_ERROR_OUT_OF_MEMORY;884}885}886RC_TRACE(0x00008000, ("Method added: new: %s [%d]",887k_new_method->name_and_sig_as_C_string(), ni));888++ni; // advance to next new method889break;890case deleted:891// method deleted, see if it is OK892old_flags = (jushort) k_old_method->access_flags().get_flags();893if ((old_flags & JVM_ACC_PRIVATE) == 0894// hack: private should be treated as final, but alas895|| (old_flags & (JVM_ACC_FINAL|JVM_ACC_STATIC)) == 0896) {897// deleted methods must be private898return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED;899}900RC_TRACE(0x00008000, ("Method deleted: old: %s [%d]",901k_old_method->name_and_sig_as_C_string(), oi));902++oi; // advance to next old method903break;904default:905ShouldNotReachHere();906}907}908909return JVMTI_ERROR_NONE;910}911912913// Find new constant pool index value for old constant pool index value914// by seaching the index map. Returns zero (0) if there is no mapped915// value for the old constant pool index.916int VM_RedefineClasses::find_new_index(int old_index) {917if (_index_map_count == 0) {918// map is empty so nothing can be found919return 0;920}921922if (old_index < 1 || old_index >= _index_map_p->length()) {923// The old_index is out of range so it is not mapped. This should924// not happen in regular constant pool merging use, but it can925// happen if a corrupt annotation is processed.926return 0;927}928929int value = _index_map_p->at(old_index);930if (value == -1) {931// the old_index is not mapped932return 0;933}934935return value;936} // end find_new_index()937938939// Find new bootstrap specifier index value for old bootstrap specifier index940// value by seaching the index map. Returns unused index (-1) if there is941// no mapped value for the old bootstrap specifier index.942int VM_RedefineClasses::find_new_operand_index(int old_index) {943if (_operands_index_map_count == 0) {944// map is empty so nothing can be found945return -1;946}947948if (old_index == -1 || old_index >= _operands_index_map_p->length()) {949// The old_index is out of range so it is not mapped.950// This should not happen in regular constant pool merging use.951return -1;952}953954int value = _operands_index_map_p->at(old_index);955if (value == -1) {956// the old_index is not mapped957return -1;958}959960return value;961} // end find_new_operand_index()962963964// Returns true if the current mismatch is due to a resolved/unresolved965// class pair. Otherwise, returns false.966bool VM_RedefineClasses::is_unresolved_class_mismatch(constantPoolHandle cp1,967int index1, constantPoolHandle cp2, int index2) {968969jbyte t1 = cp1->tag_at(index1).value();970if (t1 != JVM_CONSTANT_Class && t1 != JVM_CONSTANT_UnresolvedClass) {971return false; // wrong entry type; not our special case972}973974jbyte t2 = cp2->tag_at(index2).value();975if (t2 != JVM_CONSTANT_Class && t2 != JVM_CONSTANT_UnresolvedClass) {976return false; // wrong entry type; not our special case977}978979if (t1 == t2) {980return false; // not a mismatch; not our special case981}982983char *s1 = cp1->klass_name_at(index1)->as_C_string();984char *s2 = cp2->klass_name_at(index2)->as_C_string();985if (strcmp(s1, s2) != 0) {986return false; // strings don't match; not our special case987}988989return true; // made it through the gauntlet; this is our special case990} // end is_unresolved_class_mismatch()991992993jvmtiError VM_RedefineClasses::load_new_class_versions(TRAPS) {994995// For consistency allocate memory using os::malloc wrapper.996_scratch_classes = (Klass**)997os::malloc(sizeof(Klass*) * _class_count, mtClass);998if (_scratch_classes == NULL) {999return JVMTI_ERROR_OUT_OF_MEMORY;1000}1001// Zero initialize the _scratch_classes array.1002for (int i = 0; i < _class_count; i++) {1003_scratch_classes[i] = NULL;1004}10051006ResourceMark rm(THREAD);10071008JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());1009// state can only be NULL if the current thread is exiting which1010// should not happen since we're trying to do a RedefineClasses1011guarantee(state != NULL, "exiting thread calling load_new_class_versions");1012for (int i = 0; i < _class_count; i++) {1013// Create HandleMark so that any handles created while loading new class1014// versions are deleted. Constant pools are deallocated while merging1015// constant pools1016HandleMark hm(THREAD);1017instanceKlassHandle the_class(THREAD, get_ik(_class_defs[i].klass));1018Symbol* the_class_sym = the_class->name();10191020// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1021RC_TRACE_WITH_THREAD(0x00000001, THREAD,1022("loading name=%s kind=%d (avail_mem=" UINT64_FORMAT "K)",1023the_class->external_name(), _class_load_kind,1024os::available_memory() >> 10));10251026ClassFileStream st((u1*) _class_defs[i].class_bytes,1027_class_defs[i].class_byte_count, (char *)"__VM_RedefineClasses__");10281029// Parse the stream.1030Handle the_class_loader(THREAD, the_class->class_loader());1031Handle protection_domain(THREAD, the_class->protection_domain());1032// Set redefined class handle in JvmtiThreadState class.1033// This redefined class is sent to agent event handler for class file1034// load hook event.1035state->set_class_being_redefined(&the_class, _class_load_kind);10361037Klass* k = SystemDictionary::parse_stream(the_class_sym,1038the_class_loader,1039protection_domain,1040&st,1041THREAD);1042// Clear class_being_redefined just to be sure.1043state->clear_class_being_redefined();10441045// TODO: if this is retransform, and nothing changed we can skip it10461047instanceKlassHandle scratch_class (THREAD, k);10481049// Need to clean up allocated InstanceKlass if there's an error so assign1050// the result here. Caller deallocates all the scratch classes in case of1051// an error.1052_scratch_classes[i] = k;10531054if (HAS_PENDING_EXCEPTION) {1055Symbol* ex_name = PENDING_EXCEPTION->klass()->name();1056// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1057RC_TRACE_WITH_THREAD(0x00000002, THREAD, ("parse_stream exception: '%s'",1058ex_name->as_C_string()));1059CLEAR_PENDING_EXCEPTION;10601061if (ex_name == vmSymbols::java_lang_UnsupportedClassVersionError()) {1062return JVMTI_ERROR_UNSUPPORTED_VERSION;1063} else if (ex_name == vmSymbols::java_lang_ClassFormatError()) {1064return JVMTI_ERROR_INVALID_CLASS_FORMAT;1065} else if (ex_name == vmSymbols::java_lang_ClassCircularityError()) {1066return JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION;1067} else if (ex_name == vmSymbols::java_lang_NoClassDefFoundError()) {1068// The message will be "XXX (wrong name: YYY)"1069return JVMTI_ERROR_NAMES_DONT_MATCH;1070} else if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {1071return JVMTI_ERROR_OUT_OF_MEMORY;1072} else { // Just in case more exceptions can be thrown..1073return JVMTI_ERROR_FAILS_VERIFICATION;1074}1075}10761077// Ensure class is linked before redefine1078if (!the_class->is_linked()) {1079the_class->link_class(THREAD);1080if (HAS_PENDING_EXCEPTION) {1081Symbol* ex_name = PENDING_EXCEPTION->klass()->name();1082// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1083RC_TRACE_WITH_THREAD(0x00000002, THREAD, ("link_class exception: '%s'",1084ex_name->as_C_string()));1085CLEAR_PENDING_EXCEPTION;1086if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {1087return JVMTI_ERROR_OUT_OF_MEMORY;1088} else {1089return JVMTI_ERROR_INTERNAL;1090}1091}1092}10931094// Do the validity checks in compare_and_normalize_class_versions()1095// before verifying the byte codes. By doing these checks first, we1096// limit the number of functions that require redirection from1097// the_class to scratch_class. In particular, we don't have to1098// modify JNI GetSuperclass() and thus won't change its performance.1099jvmtiError res = compare_and_normalize_class_versions(the_class,1100scratch_class);1101if (res != JVMTI_ERROR_NONE) {1102return res;1103}11041105// verify what the caller passed us1106{1107// The bug 6214132 caused the verification to fail.1108// Information about the_class and scratch_class is temporarily1109// recorded into jvmtiThreadState. This data is used to redirect1110// the_class to scratch_class in the JVM_* functions called by the1111// verifier. Please, refer to jvmtiThreadState.hpp for the detailed1112// description.1113RedefineVerifyMark rvm(&the_class, &scratch_class, state);1114Verifier::verify(1115scratch_class, Verifier::ThrowException, true, THREAD);1116}11171118if (HAS_PENDING_EXCEPTION) {1119Symbol* ex_name = PENDING_EXCEPTION->klass()->name();1120// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1121RC_TRACE_WITH_THREAD(0x00000002, THREAD,1122("verify_byte_codes exception: '%s'", ex_name->as_C_string()));1123CLEAR_PENDING_EXCEPTION;1124if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {1125return JVMTI_ERROR_OUT_OF_MEMORY;1126} else {1127// tell the caller the bytecodes are bad1128return JVMTI_ERROR_FAILS_VERIFICATION;1129}1130}11311132res = merge_cp_and_rewrite(the_class, scratch_class, THREAD);1133if (HAS_PENDING_EXCEPTION) {1134Symbol* ex_name = PENDING_EXCEPTION->klass()->name();1135// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1136RC_TRACE_WITH_THREAD(0x00000002, THREAD,1137("merge_cp_and_rewrite exception: '%s'", ex_name->as_C_string()));1138CLEAR_PENDING_EXCEPTION;1139if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {1140return JVMTI_ERROR_OUT_OF_MEMORY;1141} else {1142return JVMTI_ERROR_INTERNAL;1143}1144}11451146if (VerifyMergedCPBytecodes) {1147// verify what we have done during constant pool merging1148{1149RedefineVerifyMark rvm(&the_class, &scratch_class, state);1150Verifier::verify(scratch_class, Verifier::ThrowException, true, THREAD);1151}11521153if (HAS_PENDING_EXCEPTION) {1154Symbol* ex_name = PENDING_EXCEPTION->klass()->name();1155// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1156RC_TRACE_WITH_THREAD(0x00000002, THREAD,1157("verify_byte_codes post merge-CP exception: '%s'",1158ex_name->as_C_string()));1159CLEAR_PENDING_EXCEPTION;1160if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {1161return JVMTI_ERROR_OUT_OF_MEMORY;1162} else {1163// tell the caller that constant pool merging screwed up1164return JVMTI_ERROR_INTERNAL;1165}1166}1167}11681169Rewriter::rewrite(scratch_class, THREAD);1170if (!HAS_PENDING_EXCEPTION) {1171scratch_class->link_methods(THREAD);1172}1173if (HAS_PENDING_EXCEPTION) {1174Symbol* ex_name = PENDING_EXCEPTION->klass()->name();1175// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1176RC_TRACE_WITH_THREAD(0x00000002, THREAD,1177("Rewriter::rewrite or link_methods exception: '%s'", ex_name->as_C_string()));1178CLEAR_PENDING_EXCEPTION;1179if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {1180return JVMTI_ERROR_OUT_OF_MEMORY;1181} else {1182return JVMTI_ERROR_INTERNAL;1183}1184}11851186// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1187RC_TRACE_WITH_THREAD(0x00000001, THREAD,1188("loaded name=%s (avail_mem=" UINT64_FORMAT "K)",1189the_class->external_name(), os::available_memory() >> 10));1190}11911192return JVMTI_ERROR_NONE;1193}119411951196// Map old_index to new_index as needed. scratch_cp is only needed1197// for RC_TRACE() calls.1198void VM_RedefineClasses::map_index(constantPoolHandle scratch_cp,1199int old_index, int new_index) {1200if (find_new_index(old_index) != 0) {1201// old_index is already mapped1202return;1203}12041205if (old_index == new_index) {1206// no mapping is needed1207return;1208}12091210_index_map_p->at_put(old_index, new_index);1211_index_map_count++;12121213RC_TRACE(0x00040000, ("mapped tag %d at index %d to %d",1214scratch_cp->tag_at(old_index).value(), old_index, new_index));1215} // end map_index()121612171218// Map old_index to new_index as needed.1219void VM_RedefineClasses::map_operand_index(int old_index, int new_index) {1220if (find_new_operand_index(old_index) != -1) {1221// old_index is already mapped1222return;1223}12241225if (old_index == new_index) {1226// no mapping is needed1227return;1228}12291230_operands_index_map_p->at_put(old_index, new_index);1231_operands_index_map_count++;12321233RC_TRACE(0x00040000, ("mapped bootstrap specifier at index %d to %d", old_index, new_index));1234} // end map_index()123512361237// Merge old_cp and scratch_cp and return the results of the merge via1238// merge_cp_p. The number of entries in *merge_cp_p is returned via1239// merge_cp_length_p. The entries in old_cp occupy the same locations1240// in *merge_cp_p. Also creates a map of indices from entries in1241// scratch_cp to the corresponding entry in *merge_cp_p. Index map1242// entries are only created for entries in scratch_cp that occupy a1243// different location in *merged_cp_p.1244bool VM_RedefineClasses::merge_constant_pools(constantPoolHandle old_cp,1245constantPoolHandle scratch_cp, constantPoolHandle *merge_cp_p,1246int *merge_cp_length_p, TRAPS) {12471248if (merge_cp_p == NULL) {1249assert(false, "caller must provide scratch constantPool");1250return false; // robustness1251}1252if (merge_cp_length_p == NULL) {1253assert(false, "caller must provide scratch CP length");1254return false; // robustness1255}1256// Worst case we need old_cp->length() + scratch_cp()->length(),1257// but the caller might be smart so make sure we have at least1258// the minimum.1259if ((*merge_cp_p)->length() < old_cp->length()) {1260assert(false, "merge area too small");1261return false; // robustness1262}12631264RC_TRACE_WITH_THREAD(0x00010000, THREAD,1265("old_cp_len=%d, scratch_cp_len=%d", old_cp->length(),1266scratch_cp->length()));12671268{1269// Pass 0:1270// The old_cp is copied to *merge_cp_p; this means that any code1271// using old_cp does not have to change. This work looks like a1272// perfect fit for ConstantPool*::copy_cp_to(), but we need to1273// handle one special case:1274// - revert JVM_CONSTANT_Class to JVM_CONSTANT_UnresolvedClass1275// This will make verification happy.12761277int old_i; // index into old_cp12781279// index zero (0) is not used in constantPools1280for (old_i = 1; old_i < old_cp->length(); old_i++) {1281// leave debugging crumb1282jbyte old_tag = old_cp->tag_at(old_i).value();1283switch (old_tag) {1284case JVM_CONSTANT_Class:1285case JVM_CONSTANT_UnresolvedClass:1286// revert the copy to JVM_CONSTANT_UnresolvedClass1287// May be resolving while calling this so do the same for1288// JVM_CONSTANT_UnresolvedClass (klass_name_at() deals with transition)1289(*merge_cp_p)->unresolved_klass_at_put(old_i,1290old_cp->klass_name_at(old_i));1291break;12921293case JVM_CONSTANT_Double:1294case JVM_CONSTANT_Long:1295// just copy the entry to *merge_cp_p, but double and long take1296// two constant pool entries1297ConstantPool::copy_entry_to(old_cp, old_i, *merge_cp_p, old_i, CHECK_0);1298old_i++;1299break;13001301default:1302// just copy the entry to *merge_cp_p1303ConstantPool::copy_entry_to(old_cp, old_i, *merge_cp_p, old_i, CHECK_0);1304break;1305}1306} // end for each old_cp entry13071308ConstantPool::copy_operands(old_cp, *merge_cp_p, CHECK_0);1309(*merge_cp_p)->extend_operands(scratch_cp, CHECK_0);13101311// We don't need to sanity check that *merge_cp_length_p is within1312// *merge_cp_p bounds since we have the minimum on-entry check above.1313(*merge_cp_length_p) = old_i;1314}13151316// merge_cp_len should be the same as old_cp->length() at this point1317// so this trace message is really a "warm-and-breathing" message.1318RC_TRACE_WITH_THREAD(0x00020000, THREAD,1319("after pass 0: merge_cp_len=%d", *merge_cp_length_p));13201321int scratch_i; // index into scratch_cp1322{1323// Pass 1a:1324// Compare scratch_cp entries to the old_cp entries that we have1325// already copied to *merge_cp_p. In this pass, we are eliminating1326// exact duplicates (matching entry at same index) so we only1327// compare entries in the common indice range.1328int increment = 1;1329int pass1a_length = MIN2(old_cp->length(), scratch_cp->length());1330for (scratch_i = 1; scratch_i < pass1a_length; scratch_i += increment) {1331switch (scratch_cp->tag_at(scratch_i).value()) {1332case JVM_CONSTANT_Double:1333case JVM_CONSTANT_Long:1334// double and long take two constant pool entries1335increment = 2;1336break;13371338default:1339increment = 1;1340break;1341}13421343bool match = scratch_cp->compare_entry_to(scratch_i, *merge_cp_p,1344scratch_i, CHECK_0);1345if (match) {1346// found a match at the same index so nothing more to do1347continue;1348} else if (is_unresolved_class_mismatch(scratch_cp, scratch_i,1349*merge_cp_p, scratch_i)) {1350// The mismatch in compare_entry_to() above is because of a1351// resolved versus unresolved class entry at the same index1352// with the same string value. Since Pass 0 reverted any1353// class entries to unresolved class entries in *merge_cp_p,1354// we go with the unresolved class entry.1355continue;1356}13571358int found_i = scratch_cp->find_matching_entry(scratch_i, *merge_cp_p,1359CHECK_0);1360if (found_i != 0) {1361guarantee(found_i != scratch_i,1362"compare_entry_to() and find_matching_entry() do not agree");13631364// Found a matching entry somewhere else in *merge_cp_p so1365// just need a mapping entry.1366map_index(scratch_cp, scratch_i, found_i);1367continue;1368}13691370// The find_matching_entry() call above could fail to find a match1371// due to a resolved versus unresolved class or string entry situation1372// like we solved above with the is_unresolved_*_mismatch() calls.1373// However, we would have to call is_unresolved_*_mismatch() over1374// all of *merge_cp_p (potentially) and that doesn't seem to be1375// worth the time.13761377// No match found so we have to append this entry and any unique1378// referenced entries to *merge_cp_p.1379append_entry(scratch_cp, scratch_i, merge_cp_p, merge_cp_length_p,1380CHECK_0);1381}1382}13831384RC_TRACE_WITH_THREAD(0x00020000, THREAD,1385("after pass 1a: merge_cp_len=%d, scratch_i=%d, index_map_len=%d",1386*merge_cp_length_p, scratch_i, _index_map_count));13871388if (scratch_i < scratch_cp->length()) {1389// Pass 1b:1390// old_cp is smaller than scratch_cp so there are entries in1391// scratch_cp that we have not yet processed. We take care of1392// those now.1393int increment = 1;1394for (; scratch_i < scratch_cp->length(); scratch_i += increment) {1395switch (scratch_cp->tag_at(scratch_i).value()) {1396case JVM_CONSTANT_Double:1397case JVM_CONSTANT_Long:1398// double and long take two constant pool entries1399increment = 2;1400break;14011402default:1403increment = 1;1404break;1405}14061407int found_i =1408scratch_cp->find_matching_entry(scratch_i, *merge_cp_p, CHECK_0);1409if (found_i != 0) {1410// Found a matching entry somewhere else in *merge_cp_p so1411// just need a mapping entry.1412map_index(scratch_cp, scratch_i, found_i);1413continue;1414}14151416// No match found so we have to append this entry and any unique1417// referenced entries to *merge_cp_p.1418append_entry(scratch_cp, scratch_i, merge_cp_p, merge_cp_length_p,1419CHECK_0);1420}14211422RC_TRACE_WITH_THREAD(0x00020000, THREAD,1423("after pass 1b: merge_cp_len=%d, scratch_i=%d, index_map_len=%d",1424*merge_cp_length_p, scratch_i, _index_map_count));1425}1426finalize_operands_merge(*merge_cp_p, THREAD);14271428return true;1429} // end merge_constant_pools()143014311432// Scoped object to clean up the constant pool(s) created for merging1433class MergeCPCleaner {1434ClassLoaderData* _loader_data;1435ConstantPool* _cp;1436ConstantPool* _scratch_cp;1437public:1438MergeCPCleaner(ClassLoaderData* loader_data, ConstantPool* merge_cp) :1439_loader_data(loader_data), _cp(merge_cp), _scratch_cp(NULL) {}1440~MergeCPCleaner() {1441_loader_data->add_to_deallocate_list(_cp);1442if (_scratch_cp != NULL) {1443_loader_data->add_to_deallocate_list(_scratch_cp);1444}1445}1446void add_scratch_cp(ConstantPool* scratch_cp) { _scratch_cp = scratch_cp; }1447};14481449// Merge constant pools between the_class and scratch_class and1450// potentially rewrite bytecodes in scratch_class to use the merged1451// constant pool.1452jvmtiError VM_RedefineClasses::merge_cp_and_rewrite(1453instanceKlassHandle the_class, instanceKlassHandle scratch_class,1454TRAPS) {1455// worst case merged constant pool length is old and new combined1456int merge_cp_length = the_class->constants()->length()1457+ scratch_class->constants()->length();14581459// Constant pools are not easily reused so we allocate a new one1460// each time.1461// merge_cp is created unsafe for concurrent GC processing. It1462// should be marked safe before discarding it. Even though1463// garbage, if it crosses a card boundary, it may be scanned1464// in order to find the start of the first complete object on the card.1465ClassLoaderData* loader_data = the_class->class_loader_data();1466ConstantPool* merge_cp_oop =1467ConstantPool::allocate(loader_data,1468merge_cp_length,1469CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));1470MergeCPCleaner cp_cleaner(loader_data, merge_cp_oop);14711472HandleMark hm(THREAD); // make sure handles are cleared before1473// MergeCPCleaner clears out merge_cp_oop1474constantPoolHandle merge_cp(THREAD, merge_cp_oop);14751476// Get constants() from the old class because it could have been rewritten1477// while we were at a safepoint allocating a new constant pool.1478constantPoolHandle old_cp(THREAD, the_class->constants());1479constantPoolHandle scratch_cp(THREAD, scratch_class->constants());14801481// If the length changed, the class was redefined out from under us. Return1482// an error.1483if (merge_cp_length != the_class->constants()->length()1484+ scratch_class->constants()->length()) {1485return JVMTI_ERROR_INTERNAL;1486}14871488// Update the version number of the constant pool1489merge_cp->increment_and_save_version(old_cp->version());14901491ResourceMark rm(THREAD);1492_index_map_count = 0;1493_index_map_p = new intArray(scratch_cp->length(), -1);14941495_operands_cur_length = ConstantPool::operand_array_length(old_cp->operands());1496_operands_index_map_count = 0;1497_operands_index_map_p = new intArray(1498ConstantPool::operand_array_length(scratch_cp->operands()), -1);14991500// reference to the cp holder is needed for copy_operands()1501merge_cp->set_pool_holder(scratch_class());1502bool result = merge_constant_pools(old_cp, scratch_cp, &merge_cp,1503&merge_cp_length, THREAD);1504merge_cp->set_pool_holder(NULL);15051506if (!result) {1507// The merge can fail due to memory allocation failure or due1508// to robustness checks.1509return JVMTI_ERROR_INTERNAL;1510}15111512RC_TRACE_WITH_THREAD(0x00010000, THREAD,1513("merge_cp_len=%d, index_map_len=%d", merge_cp_length, _index_map_count));15141515if (_index_map_count == 0) {1516// there is nothing to map between the new and merged constant pools15171518if (old_cp->length() == scratch_cp->length()) {1519// The old and new constant pools are the same length and the1520// index map is empty. This means that the three constant pools1521// are equivalent (but not the same). Unfortunately, the new1522// constant pool has not gone through link resolution nor have1523// the new class bytecodes gone through constant pool cache1524// rewriting so we can't use the old constant pool with the new1525// class.15261527// toss the merged constant pool at return1528} else if (old_cp->length() < scratch_cp->length()) {1529// The old constant pool has fewer entries than the new constant1530// pool and the index map is empty. This means the new constant1531// pool is a superset of the old constant pool. However, the old1532// class bytecodes have already gone through constant pool cache1533// rewriting so we can't use the new constant pool with the old1534// class.15351536// toss the merged constant pool at return1537} else {1538// The old constant pool has more entries than the new constant1539// pool and the index map is empty. This means that both the old1540// and merged constant pools are supersets of the new constant1541// pool.15421543// Replace the new constant pool with a shrunken copy of the1544// merged constant pool1545set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,1546CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));1547// The new constant pool replaces scratch_cp so have cleaner clean it up.1548// It can't be cleaned up while there are handles to it.1549cp_cleaner.add_scratch_cp(scratch_cp());1550}1551} else {1552if (RC_TRACE_ENABLED(0x00040000)) {1553// don't want to loop unless we are tracing1554int count = 0;1555for (int i = 1; i < _index_map_p->length(); i++) {1556int value = _index_map_p->at(i);15571558if (value != -1) {1559RC_TRACE_WITH_THREAD(0x00040000, THREAD,1560("index_map[%d]: old=%d new=%d", count, i, value));1561count++;1562}1563}1564}15651566// We have entries mapped between the new and merged constant pools1567// so we have to rewrite some constant pool references.1568if (!rewrite_cp_refs(scratch_class, THREAD)) {1569return JVMTI_ERROR_INTERNAL;1570}15711572// Replace the new constant pool with a shrunken copy of the1573// merged constant pool so now the rewritten bytecodes have1574// valid references; the previous new constant pool will get1575// GCed.1576set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,1577CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));1578// The new constant pool replaces scratch_cp so have cleaner clean it up.1579// It can't be cleaned up while there are handles to it.1580cp_cleaner.add_scratch_cp(scratch_cp());1581}15821583return JVMTI_ERROR_NONE;1584} // end merge_cp_and_rewrite()158515861587// Rewrite constant pool references in klass scratch_class.1588bool VM_RedefineClasses::rewrite_cp_refs(instanceKlassHandle scratch_class,1589TRAPS) {15901591// rewrite constant pool references in the methods:1592if (!rewrite_cp_refs_in_methods(scratch_class, THREAD)) {1593// propagate failure back to caller1594return false;1595}15961597// rewrite constant pool references in the class_annotations:1598if (!rewrite_cp_refs_in_class_annotations(scratch_class, THREAD)) {1599// propagate failure back to caller1600return false;1601}16021603// rewrite constant pool references in the fields_annotations:1604if (!rewrite_cp_refs_in_fields_annotations(scratch_class, THREAD)) {1605// propagate failure back to caller1606return false;1607}16081609// rewrite constant pool references in the methods_annotations:1610if (!rewrite_cp_refs_in_methods_annotations(scratch_class, THREAD)) {1611// propagate failure back to caller1612return false;1613}16141615// rewrite constant pool references in the methods_parameter_annotations:1616if (!rewrite_cp_refs_in_methods_parameter_annotations(scratch_class,1617THREAD)) {1618// propagate failure back to caller1619return false;1620}16211622// rewrite constant pool references in the methods_default_annotations:1623if (!rewrite_cp_refs_in_methods_default_annotations(scratch_class,1624THREAD)) {1625// propagate failure back to caller1626return false;1627}16281629// rewrite constant pool references in the class_type_annotations:1630if (!rewrite_cp_refs_in_class_type_annotations(scratch_class, THREAD)) {1631// propagate failure back to caller1632return false;1633}16341635// rewrite constant pool references in the fields_type_annotations:1636if (!rewrite_cp_refs_in_fields_type_annotations(scratch_class, THREAD)) {1637// propagate failure back to caller1638return false;1639}16401641// rewrite constant pool references in the methods_type_annotations:1642if (!rewrite_cp_refs_in_methods_type_annotations(scratch_class, THREAD)) {1643// propagate failure back to caller1644return false;1645}16461647// There can be type annotations in the Code part of a method_info attribute.1648// These annotations are not accessible, even by reflection.1649// Currently they are not even parsed by the ClassFileParser.1650// If runtime access is added they will also need to be rewritten.16511652// rewrite source file name index:1653u2 source_file_name_idx = scratch_class->source_file_name_index();1654if (source_file_name_idx != 0) {1655u2 new_source_file_name_idx = find_new_index(source_file_name_idx);1656if (new_source_file_name_idx != 0) {1657scratch_class->set_source_file_name_index(new_source_file_name_idx);1658}1659}16601661// rewrite class generic signature index:1662u2 generic_signature_index = scratch_class->generic_signature_index();1663if (generic_signature_index != 0) {1664u2 new_generic_signature_index = find_new_index(generic_signature_index);1665if (new_generic_signature_index != 0) {1666scratch_class->set_generic_signature_index(new_generic_signature_index);1667}1668}16691670return true;1671} // end rewrite_cp_refs()16721673// Rewrite constant pool references in the methods.1674bool VM_RedefineClasses::rewrite_cp_refs_in_methods(1675instanceKlassHandle scratch_class, TRAPS) {16761677Array<Method*>* methods = scratch_class->methods();16781679if (methods == NULL || methods->length() == 0) {1680// no methods so nothing to do1681return true;1682}16831684// rewrite constant pool references in the methods:1685for (int i = methods->length() - 1; i >= 0; i--) {1686methodHandle method(THREAD, methods->at(i));1687methodHandle new_method;1688rewrite_cp_refs_in_method(method, &new_method, THREAD);1689if (!new_method.is_null()) {1690// the method has been replaced so save the new method version1691// even in the case of an exception. original method is on the1692// deallocation list.1693methods->at_put(i, new_method());1694}1695if (HAS_PENDING_EXCEPTION) {1696Symbol* ex_name = PENDING_EXCEPTION->klass()->name();1697// RC_TRACE_WITH_THREAD macro has an embedded ResourceMark1698RC_TRACE_WITH_THREAD(0x00000002, THREAD,1699("rewrite_cp_refs_in_method exception: '%s'", ex_name->as_C_string()));1700// Need to clear pending exception here as the super caller sets1701// the JVMTI_ERROR_INTERNAL if the returned value is false.1702CLEAR_PENDING_EXCEPTION;1703return false;1704}1705}17061707return true;1708}170917101711// Rewrite constant pool references in the specific method. This code1712// was adapted from Rewriter::rewrite_method().1713void VM_RedefineClasses::rewrite_cp_refs_in_method(methodHandle method,1714methodHandle *new_method_p, TRAPS) {17151716*new_method_p = methodHandle(); // default is no new method17171718// We cache a pointer to the bytecodes here in code_base. If GC1719// moves the Method*, then the bytecodes will also move which1720// will likely cause a crash. We create a No_Safepoint_Verifier1721// object to detect whether we pass a possible safepoint in this1722// code block.1723No_Safepoint_Verifier nsv;17241725// Bytecodes and their length1726address code_base = method->code_base();1727int code_length = method->code_size();17281729int bc_length;1730for (int bci = 0; bci < code_length; bci += bc_length) {1731address bcp = code_base + bci;1732Bytecodes::Code c = (Bytecodes::Code)(*bcp);17331734bc_length = Bytecodes::length_for(c);1735if (bc_length == 0) {1736// More complicated bytecodes report a length of zero so1737// we have to try again a slightly different way.1738bc_length = Bytecodes::length_at(method(), bcp);1739}17401741assert(bc_length != 0, "impossible bytecode length");17421743switch (c) {1744case Bytecodes::_ldc:1745{1746int cp_index = *(bcp + 1);1747int new_index = find_new_index(cp_index);17481749if (StressLdcRewrite && new_index == 0) {1750// If we are stressing ldc -> ldc_w rewriting, then we1751// always need a new_index value.1752new_index = cp_index;1753}1754if (new_index != 0) {1755// the original index is mapped so we have more work to do1756if (!StressLdcRewrite && new_index <= max_jubyte) {1757// The new value can still use ldc instead of ldc_w1758// unless we are trying to stress ldc -> ldc_w rewriting1759RC_TRACE_WITH_THREAD(0x00080000, THREAD,1760("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c),1761bcp, cp_index, new_index));1762*(bcp + 1) = new_index;1763} else {1764RC_TRACE_WITH_THREAD(0x00080000, THREAD,1765("%s->ldc_w@" INTPTR_FORMAT " old=%d, new=%d",1766Bytecodes::name(c), bcp, cp_index, new_index));1767// the new value needs ldc_w instead of ldc1768u_char inst_buffer[4]; // max instruction size is 4 bytes1769bcp = (address)inst_buffer;1770// construct new instruction sequence1771*bcp = Bytecodes::_ldc_w;1772bcp++;1773// Rewriter::rewrite_method() does not rewrite ldc -> ldc_w.1774// See comment below for difference between put_Java_u2()1775// and put_native_u2().1776Bytes::put_Java_u2(bcp, new_index);17771778Relocator rc(method, NULL /* no RelocatorListener needed */);1779methodHandle m;1780{1781Pause_No_Safepoint_Verifier pnsv(&nsv);17821783// ldc is 2 bytes and ldc_w is 3 bytes1784m = rc.insert_space_at(bci, 3, inst_buffer, CHECK);1785}17861787// return the new method so that the caller can update1788// the containing class1789*new_method_p = method = m;1790// switch our bytecode processing loop from the old method1791// to the new method1792code_base = method->code_base();1793code_length = method->code_size();1794bcp = code_base + bci;1795c = (Bytecodes::Code)(*bcp);1796bc_length = Bytecodes::length_for(c);1797assert(bc_length != 0, "sanity check");1798} // end we need ldc_w instead of ldc1799} // end if there is a mapped index1800} break;18011802// these bytecodes have a two-byte constant pool index1803case Bytecodes::_anewarray : // fall through1804case Bytecodes::_checkcast : // fall through1805case Bytecodes::_getfield : // fall through1806case Bytecodes::_getstatic : // fall through1807case Bytecodes::_instanceof : // fall through1808case Bytecodes::_invokedynamic : // fall through1809case Bytecodes::_invokeinterface: // fall through1810case Bytecodes::_invokespecial : // fall through1811case Bytecodes::_invokestatic : // fall through1812case Bytecodes::_invokevirtual : // fall through1813case Bytecodes::_ldc_w : // fall through1814case Bytecodes::_ldc2_w : // fall through1815case Bytecodes::_multianewarray : // fall through1816case Bytecodes::_new : // fall through1817case Bytecodes::_putfield : // fall through1818case Bytecodes::_putstatic :1819{1820address p = bcp + 1;1821int cp_index = Bytes::get_Java_u2(p);1822int new_index = find_new_index(cp_index);1823if (new_index != 0) {1824// the original index is mapped so update w/ new value1825RC_TRACE_WITH_THREAD(0x00080000, THREAD,1826("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c),1827bcp, cp_index, new_index));1828// Rewriter::rewrite_method() uses put_native_u2() in this1829// situation because it is reusing the constant pool index1830// location for a native index into the ConstantPoolCache.1831// Since we are updating the constant pool index prior to1832// verification and ConstantPoolCache initialization, we1833// need to keep the new index in Java byte order.1834Bytes::put_Java_u2(p, new_index);1835}1836} break;1837}1838} // end for each bytecode18391840// We also need to rewrite the parameter name indexes, if there is1841// method parameter data present1842if(method->has_method_parameters()) {1843const int len = method->method_parameters_length();1844MethodParametersElement* elem = method->method_parameters_start();18451846for (int i = 0; i < len; i++) {1847const u2 cp_index = elem[i].name_cp_index;1848const u2 new_cp_index = find_new_index(cp_index);1849if (new_cp_index != 0) {1850elem[i].name_cp_index = new_cp_index;1851}1852}1853}1854} // end rewrite_cp_refs_in_method()185518561857// Rewrite constant pool references in the class_annotations field.1858bool VM_RedefineClasses::rewrite_cp_refs_in_class_annotations(1859instanceKlassHandle scratch_class, TRAPS) {18601861AnnotationArray* class_annotations = scratch_class->class_annotations();1862if (class_annotations == NULL || class_annotations->length() == 0) {1863// no class_annotations so nothing to do1864return true;1865}18661867RC_TRACE_WITH_THREAD(0x02000000, THREAD,1868("class_annotations length=%d", class_annotations->length()));18691870int byte_i = 0; // byte index into class_annotations1871return rewrite_cp_refs_in_annotations_typeArray(class_annotations, byte_i,1872THREAD);1873}187418751876// Rewrite constant pool references in an annotations typeArray. This1877// "structure" is adapted from the RuntimeVisibleAnnotations_attribute1878// that is described in section 4.8.15 of the 2nd-edition of the VM spec:1879//1880// annotations_typeArray {1881// u2 num_annotations;1882// annotation annotations[num_annotations];1883// }1884//1885bool VM_RedefineClasses::rewrite_cp_refs_in_annotations_typeArray(1886AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {18871888if ((byte_i_ref + 2) > annotations_typeArray->length()) {1889// not enough room for num_annotations field1890RC_TRACE_WITH_THREAD(0x02000000, THREAD,1891("length() is too small for num_annotations field"));1892return false;1893}18941895u2 num_annotations = Bytes::get_Java_u2((address)1896annotations_typeArray->adr_at(byte_i_ref));1897byte_i_ref += 2;18981899RC_TRACE_WITH_THREAD(0x02000000, THREAD,1900("num_annotations=%d", num_annotations));19011902int calc_num_annotations = 0;1903for (; calc_num_annotations < num_annotations; calc_num_annotations++) {1904if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray,1905byte_i_ref, THREAD)) {1906RC_TRACE_WITH_THREAD(0x02000000, THREAD,1907("bad annotation_struct at %d", calc_num_annotations));1908// propagate failure back to caller1909return false;1910}1911}1912assert(num_annotations == calc_num_annotations, "sanity check");19131914return true;1915} // end rewrite_cp_refs_in_annotations_typeArray()191619171918// Rewrite constant pool references in the annotation struct portion of1919// an annotations_typeArray. This "structure" is from section 4.8.15 of1920// the 2nd-edition of the VM spec:1921//1922// struct annotation {1923// u2 type_index;1924// u2 num_element_value_pairs;1925// {1926// u2 element_name_index;1927// element_value value;1928// } element_value_pairs[num_element_value_pairs];1929// }1930//1931bool VM_RedefineClasses::rewrite_cp_refs_in_annotation_struct(1932AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {1933if ((byte_i_ref + 2 + 2) > annotations_typeArray->length()) {1934// not enough room for smallest annotation_struct1935RC_TRACE_WITH_THREAD(0x02000000, THREAD,1936("length() is too small for annotation_struct"));1937return false;1938}19391940u2 type_index = rewrite_cp_ref_in_annotation_data(annotations_typeArray,1941byte_i_ref, "mapped old type_index=%d", THREAD);19421943u2 num_element_value_pairs = Bytes::get_Java_u2((address)1944annotations_typeArray->adr_at(byte_i_ref));1945byte_i_ref += 2;19461947RC_TRACE_WITH_THREAD(0x02000000, THREAD,1948("type_index=%d num_element_value_pairs=%d", type_index,1949num_element_value_pairs));19501951int calc_num_element_value_pairs = 0;1952for (; calc_num_element_value_pairs < num_element_value_pairs;1953calc_num_element_value_pairs++) {1954if ((byte_i_ref + 2) > annotations_typeArray->length()) {1955// not enough room for another element_name_index, let alone1956// the rest of another component1957RC_TRACE_WITH_THREAD(0x02000000, THREAD,1958("length() is too small for element_name_index"));1959return false;1960}19611962u2 element_name_index = rewrite_cp_ref_in_annotation_data(1963annotations_typeArray, byte_i_ref,1964"mapped old element_name_index=%d", THREAD);19651966RC_TRACE_WITH_THREAD(0x02000000, THREAD,1967("element_name_index=%d", element_name_index));19681969if (!rewrite_cp_refs_in_element_value(annotations_typeArray,1970byte_i_ref, THREAD)) {1971RC_TRACE_WITH_THREAD(0x02000000, THREAD,1972("bad element_value at %d", calc_num_element_value_pairs));1973// propagate failure back to caller1974return false;1975}1976} // end for each component1977assert(num_element_value_pairs == calc_num_element_value_pairs,1978"sanity check");19791980return true;1981} // end rewrite_cp_refs_in_annotation_struct()198219831984// Rewrite a constant pool reference at the current position in1985// annotations_typeArray if needed. Returns the original constant1986// pool reference if a rewrite was not needed or the new constant1987// pool reference if a rewrite was needed.1988PRAGMA_DIAG_PUSH1989PRAGMA_FORMAT_NONLITERAL_IGNORED1990u2 VM_RedefineClasses::rewrite_cp_ref_in_annotation_data(1991AnnotationArray* annotations_typeArray, int &byte_i_ref,1992const char * trace_mesg, TRAPS) {19931994address cp_index_addr = (address)1995annotations_typeArray->adr_at(byte_i_ref);1996u2 old_cp_index = Bytes::get_Java_u2(cp_index_addr);1997u2 new_cp_index = find_new_index(old_cp_index);1998if (new_cp_index != 0) {1999RC_TRACE_WITH_THREAD(0x02000000, THREAD, (trace_mesg, old_cp_index));2000Bytes::put_Java_u2(cp_index_addr, new_cp_index);2001old_cp_index = new_cp_index;2002}2003byte_i_ref += 2;2004return old_cp_index;2005}2006PRAGMA_DIAG_POP200720082009// Rewrite constant pool references in the element_value portion of an2010// annotations_typeArray. This "structure" is from section 4.8.15.1 of2011// the 2nd-edition of the VM spec:2012//2013// struct element_value {2014// u1 tag;2015// union {2016// u2 const_value_index;2017// {2018// u2 type_name_index;2019// u2 const_name_index;2020// } enum_const_value;2021// u2 class_info_index;2022// annotation annotation_value;2023// struct {2024// u2 num_values;2025// element_value values[num_values];2026// } array_value;2027// } value;2028// }2029//2030bool VM_RedefineClasses::rewrite_cp_refs_in_element_value(2031AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {20322033if ((byte_i_ref + 1) > annotations_typeArray->length()) {2034// not enough room for a tag let alone the rest of an element_value2035RC_TRACE_WITH_THREAD(0x02000000, THREAD,2036("length() is too small for a tag"));2037return false;2038}20392040u1 tag = annotations_typeArray->at(byte_i_ref);2041byte_i_ref++;2042RC_TRACE_WITH_THREAD(0x02000000, THREAD, ("tag='%c'", tag));20432044switch (tag) {2045// These BaseType tag values are from Table 4.2 in VM spec:2046case 'B': // byte2047case 'C': // char2048case 'D': // double2049case 'F': // float2050case 'I': // int2051case 'J': // long2052case 'S': // short2053case 'Z': // boolean20542055// The remaining tag values are from Table 4.8 in the 2nd-edition of2056// the VM spec:2057case 's':2058{2059// For the above tag values (including the BaseType values),2060// value.const_value_index is right union field.20612062if ((byte_i_ref + 2) > annotations_typeArray->length()) {2063// not enough room for a const_value_index2064RC_TRACE_WITH_THREAD(0x02000000, THREAD,2065("length() is too small for a const_value_index"));2066return false;2067}20682069u2 const_value_index = rewrite_cp_ref_in_annotation_data(2070annotations_typeArray, byte_i_ref,2071"mapped old const_value_index=%d", THREAD);20722073RC_TRACE_WITH_THREAD(0x02000000, THREAD,2074("const_value_index=%d", const_value_index));2075} break;20762077case 'e':2078{2079// for the above tag value, value.enum_const_value is right union field20802081if ((byte_i_ref + 4) > annotations_typeArray->length()) {2082// not enough room for a enum_const_value2083RC_TRACE_WITH_THREAD(0x02000000, THREAD,2084("length() is too small for a enum_const_value"));2085return false;2086}20872088u2 type_name_index = rewrite_cp_ref_in_annotation_data(2089annotations_typeArray, byte_i_ref,2090"mapped old type_name_index=%d", THREAD);20912092u2 const_name_index = rewrite_cp_ref_in_annotation_data(2093annotations_typeArray, byte_i_ref,2094"mapped old const_name_index=%d", THREAD);20952096RC_TRACE_WITH_THREAD(0x02000000, THREAD,2097("type_name_index=%d const_name_index=%d", type_name_index,2098const_name_index));2099} break;21002101case 'c':2102{2103// for the above tag value, value.class_info_index is right union field21042105if ((byte_i_ref + 2) > annotations_typeArray->length()) {2106// not enough room for a class_info_index2107RC_TRACE_WITH_THREAD(0x02000000, THREAD,2108("length() is too small for a class_info_index"));2109return false;2110}21112112u2 class_info_index = rewrite_cp_ref_in_annotation_data(2113annotations_typeArray, byte_i_ref,2114"mapped old class_info_index=%d", THREAD);21152116RC_TRACE_WITH_THREAD(0x02000000, THREAD,2117("class_info_index=%d", class_info_index));2118} break;21192120case '@':2121// For the above tag value, value.attr_value is the right union2122// field. This is a nested annotation.2123if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray,2124byte_i_ref, THREAD)) {2125// propagate failure back to caller2126return false;2127}2128break;21292130case '[':2131{2132if ((byte_i_ref + 2) > annotations_typeArray->length()) {2133// not enough room for a num_values field2134RC_TRACE_WITH_THREAD(0x02000000, THREAD,2135("length() is too small for a num_values field"));2136return false;2137}21382139// For the above tag value, value.array_value is the right union2140// field. This is an array of nested element_value.2141u2 num_values = Bytes::get_Java_u2((address)2142annotations_typeArray->adr_at(byte_i_ref));2143byte_i_ref += 2;2144RC_TRACE_WITH_THREAD(0x02000000, THREAD, ("num_values=%d", num_values));21452146int calc_num_values = 0;2147for (; calc_num_values < num_values; calc_num_values++) {2148if (!rewrite_cp_refs_in_element_value(2149annotations_typeArray, byte_i_ref, THREAD)) {2150RC_TRACE_WITH_THREAD(0x02000000, THREAD,2151("bad nested element_value at %d", calc_num_values));2152// propagate failure back to caller2153return false;2154}2155}2156assert(num_values == calc_num_values, "sanity check");2157} break;21582159default:2160RC_TRACE_WITH_THREAD(0x02000000, THREAD, ("bad tag=0x%x", tag));2161return false;2162} // end decode tag field21632164return true;2165} // end rewrite_cp_refs_in_element_value()216621672168// Rewrite constant pool references in a fields_annotations field.2169bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations(2170instanceKlassHandle scratch_class, TRAPS) {21712172Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations();21732174if (fields_annotations == NULL || fields_annotations->length() == 0) {2175// no fields_annotations so nothing to do2176return true;2177}21782179RC_TRACE_WITH_THREAD(0x02000000, THREAD,2180("fields_annotations length=%d", fields_annotations->length()));21812182for (int i = 0; i < fields_annotations->length(); i++) {2183AnnotationArray* field_annotations = fields_annotations->at(i);2184if (field_annotations == NULL || field_annotations->length() == 0) {2185// this field does not have any annotations so skip it2186continue;2187}21882189int byte_i = 0; // byte index into field_annotations2190if (!rewrite_cp_refs_in_annotations_typeArray(field_annotations, byte_i,2191THREAD)) {2192RC_TRACE_WITH_THREAD(0x02000000, THREAD,2193("bad field_annotations at %d", i));2194// propagate failure back to caller2195return false;2196}2197}21982199return true;2200} // end rewrite_cp_refs_in_fields_annotations()220122022203// Rewrite constant pool references in a methods_annotations field.2204bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations(2205instanceKlassHandle scratch_class, TRAPS) {22062207for (int i = 0; i < scratch_class->methods()->length(); i++) {2208Method* m = scratch_class->methods()->at(i);2209AnnotationArray* method_annotations = m->constMethod()->method_annotations();22102211if (method_annotations == NULL || method_annotations->length() == 0) {2212// this method does not have any annotations so skip it2213continue;2214}22152216int byte_i = 0; // byte index into method_annotations2217if (!rewrite_cp_refs_in_annotations_typeArray(method_annotations, byte_i,2218THREAD)) {2219RC_TRACE_WITH_THREAD(0x02000000, THREAD,2220("bad method_annotations at %d", i));2221// propagate failure back to caller2222return false;2223}2224}22252226return true;2227} // end rewrite_cp_refs_in_methods_annotations()222822292230// Rewrite constant pool references in a methods_parameter_annotations2231// field. This "structure" is adapted from the2232// RuntimeVisibleParameterAnnotations_attribute described in section2233// 4.8.17 of the 2nd-edition of the VM spec:2234//2235// methods_parameter_annotations_typeArray {2236// u1 num_parameters;2237// {2238// u2 num_annotations;2239// annotation annotations[num_annotations];2240// } parameter_annotations[num_parameters];2241// }2242//2243bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations(2244instanceKlassHandle scratch_class, TRAPS) {22452246for (int i = 0; i < scratch_class->methods()->length(); i++) {2247Method* m = scratch_class->methods()->at(i);2248AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations();2249if (method_parameter_annotations == NULL2250|| method_parameter_annotations->length() == 0) {2251// this method does not have any parameter annotations so skip it2252continue;2253}22542255if (method_parameter_annotations->length() < 1) {2256// not enough room for a num_parameters field2257RC_TRACE_WITH_THREAD(0x02000000, THREAD,2258("length() is too small for a num_parameters field at %d", i));2259return false;2260}22612262int byte_i = 0; // byte index into method_parameter_annotations22632264u1 num_parameters = method_parameter_annotations->at(byte_i);2265byte_i++;22662267RC_TRACE_WITH_THREAD(0x02000000, THREAD,2268("num_parameters=%d", num_parameters));22692270int calc_num_parameters = 0;2271for (; calc_num_parameters < num_parameters; calc_num_parameters++) {2272if (!rewrite_cp_refs_in_annotations_typeArray(2273method_parameter_annotations, byte_i, THREAD)) {2274RC_TRACE_WITH_THREAD(0x02000000, THREAD,2275("bad method_parameter_annotations at %d", calc_num_parameters));2276// propagate failure back to caller2277return false;2278}2279}2280assert(num_parameters == calc_num_parameters, "sanity check");2281}22822283return true;2284} // end rewrite_cp_refs_in_methods_parameter_annotations()228522862287// Rewrite constant pool references in a methods_default_annotations2288// field. This "structure" is adapted from the AnnotationDefault_attribute2289// that is described in section 4.8.19 of the 2nd-edition of the VM spec:2290//2291// methods_default_annotations_typeArray {2292// element_value default_value;2293// }2294//2295bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations(2296instanceKlassHandle scratch_class, TRAPS) {22972298for (int i = 0; i < scratch_class->methods()->length(); i++) {2299Method* m = scratch_class->methods()->at(i);2300AnnotationArray* method_default_annotations = m->constMethod()->default_annotations();2301if (method_default_annotations == NULL2302|| method_default_annotations->length() == 0) {2303// this method does not have any default annotations so skip it2304continue;2305}23062307int byte_i = 0; // byte index into method_default_annotations23082309if (!rewrite_cp_refs_in_element_value(2310method_default_annotations, byte_i, THREAD)) {2311RC_TRACE_WITH_THREAD(0x02000000, THREAD,2312("bad default element_value at %d", i));2313// propagate failure back to caller2314return false;2315}2316}23172318return true;2319} // end rewrite_cp_refs_in_methods_default_annotations()232023212322// Rewrite constant pool references in a class_type_annotations field.2323bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations(2324instanceKlassHandle scratch_class, TRAPS) {23252326AnnotationArray* class_type_annotations = scratch_class->class_type_annotations();2327if (class_type_annotations == NULL || class_type_annotations->length() == 0) {2328// no class_type_annotations so nothing to do2329return true;2330}23312332RC_TRACE_WITH_THREAD(0x02000000, THREAD,2333("class_type_annotations length=%d", class_type_annotations->length()));23342335int byte_i = 0; // byte index into class_type_annotations2336return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations,2337byte_i, "ClassFile", THREAD);2338} // end rewrite_cp_refs_in_class_type_annotations()233923402341// Rewrite constant pool references in a fields_type_annotations field.2342bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations(2343instanceKlassHandle scratch_class, TRAPS) {23442345Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations();2346if (fields_type_annotations == NULL || fields_type_annotations->length() == 0) {2347// no fields_type_annotations so nothing to do2348return true;2349}23502351RC_TRACE_WITH_THREAD(0x02000000, THREAD,2352("fields_type_annotations length=%d", fields_type_annotations->length()));23532354for (int i = 0; i < fields_type_annotations->length(); i++) {2355AnnotationArray* field_type_annotations = fields_type_annotations->at(i);2356if (field_type_annotations == NULL || field_type_annotations->length() == 0) {2357// this field does not have any annotations so skip it2358continue;2359}23602361int byte_i = 0; // byte index into field_type_annotations2362if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations,2363byte_i, "field_info", THREAD)) {2364RC_TRACE_WITH_THREAD(0x02000000, THREAD,2365("bad field_type_annotations at %d", i));2366// propagate failure back to caller2367return false;2368}2369}23702371return true;2372} // end rewrite_cp_refs_in_fields_type_annotations()237323742375// Rewrite constant pool references in a methods_type_annotations field.2376bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations(2377instanceKlassHandle scratch_class, TRAPS) {23782379for (int i = 0; i < scratch_class->methods()->length(); i++) {2380Method* m = scratch_class->methods()->at(i);2381AnnotationArray* method_type_annotations = m->constMethod()->type_annotations();23822383if (method_type_annotations == NULL || method_type_annotations->length() == 0) {2384// this method does not have any annotations so skip it2385continue;2386}23872388RC_TRACE_WITH_THREAD(0x02000000, THREAD,2389("methods type_annotations length=%d", method_type_annotations->length()));23902391int byte_i = 0; // byte index into method_type_annotations2392if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations,2393byte_i, "method_info", THREAD)) {2394RC_TRACE_WITH_THREAD(0x02000000, THREAD,2395("bad method_type_annotations at %d", i));2396// propagate failure back to caller2397return false;2398}2399}24002401return true;2402} // end rewrite_cp_refs_in_methods_type_annotations()240324042405// Rewrite constant pool references in a type_annotations2406// field. This "structure" is adapted from the2407// RuntimeVisibleTypeAnnotations_attribute described in2408// section 4.7.20 of the Java SE 8 Edition of the VM spec:2409//2410// type_annotations_typeArray {2411// u2 num_annotations;2412// type_annotation annotations[num_annotations];2413// }2414//2415bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotations_typeArray(2416AnnotationArray* type_annotations_typeArray, int &byte_i_ref,2417const char * location_mesg, TRAPS) {24182419if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {2420// not enough room for num_annotations field2421RC_TRACE_WITH_THREAD(0x02000000, THREAD,2422("length() is too small for num_annotations field"));2423return false;2424}24252426u2 num_annotations = Bytes::get_Java_u2((address)2427type_annotations_typeArray->adr_at(byte_i_ref));2428byte_i_ref += 2;24292430RC_TRACE_WITH_THREAD(0x02000000, THREAD,2431("num_type_annotations=%d", num_annotations));24322433int calc_num_annotations = 0;2434for (; calc_num_annotations < num_annotations; calc_num_annotations++) {2435if (!rewrite_cp_refs_in_type_annotation_struct(type_annotations_typeArray,2436byte_i_ref, location_mesg, THREAD)) {2437RC_TRACE_WITH_THREAD(0x02000000, THREAD,2438("bad type_annotation_struct at %d", calc_num_annotations));2439// propagate failure back to caller2440return false;2441}2442}2443assert(num_annotations == calc_num_annotations, "sanity check");24442445if (byte_i_ref != type_annotations_typeArray->length()) {2446RC_TRACE_WITH_THREAD(0x02000000, THREAD,2447("read wrong amount of bytes at end of processing "2448"type_annotations_typeArray (%d of %d bytes were read)",2449byte_i_ref, type_annotations_typeArray->length()));2450return false;2451}24522453return true;2454} // end rewrite_cp_refs_in_type_annotations_typeArray()245524562457// Rewrite constant pool references in a type_annotation2458// field. This "structure" is adapted from the2459// RuntimeVisibleTypeAnnotations_attribute described in2460// section 4.7.20 of the Java SE 8 Edition of the VM spec:2461//2462// type_annotation {2463// u1 target_type;2464// union {2465// type_parameter_target;2466// supertype_target;2467// type_parameter_bound_target;2468// empty_target;2469// method_formal_parameter_target;2470// throws_target;2471// localvar_target;2472// catch_target;2473// offset_target;2474// type_argument_target;2475// } target_info;2476// type_path target_path;2477// annotation anno;2478// }2479//2480bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotation_struct(2481AnnotationArray* type_annotations_typeArray, int &byte_i_ref,2482const char * location_mesg, TRAPS) {24832484if (!skip_type_annotation_target(type_annotations_typeArray,2485byte_i_ref, location_mesg, THREAD)) {2486return false;2487}24882489if (!skip_type_annotation_type_path(type_annotations_typeArray,2490byte_i_ref, THREAD)) {2491return false;2492}24932494if (!rewrite_cp_refs_in_annotation_struct(type_annotations_typeArray,2495byte_i_ref, THREAD)) {2496return false;2497}24982499return true;2500} // end rewrite_cp_refs_in_type_annotation_struct()250125022503// Read, verify and skip over the target_type and target_info part2504// so that rewriting can continue in the later parts of the struct.2505//2506// u1 target_type;2507// union {2508// type_parameter_target;2509// supertype_target;2510// type_parameter_bound_target;2511// empty_target;2512// method_formal_parameter_target;2513// throws_target;2514// localvar_target;2515// catch_target;2516// offset_target;2517// type_argument_target;2518// } target_info;2519//2520bool VM_RedefineClasses::skip_type_annotation_target(2521AnnotationArray* type_annotations_typeArray, int &byte_i_ref,2522const char * location_mesg, TRAPS) {25232524if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {2525// not enough room for a target_type let alone the rest of a type_annotation2526RC_TRACE_WITH_THREAD(0x02000000, THREAD,2527("length() is too small for a target_type"));2528return false;2529}25302531u1 target_type = type_annotations_typeArray->at(byte_i_ref);2532byte_i_ref += 1;2533RC_TRACE_WITH_THREAD(0x02000000, THREAD, ("target_type=0x%.2x", target_type));2534RC_TRACE_WITH_THREAD(0x02000000, THREAD, ("location=%s", location_mesg));25352536// Skip over target_info2537switch (target_type) {2538case 0x00:2539// kind: type parameter declaration of generic class or interface2540// location: ClassFile2541case 0x01:2542// kind: type parameter declaration of generic method or constructor2543// location: method_info25442545{2546// struct:2547// type_parameter_target {2548// u1 type_parameter_index;2549// }2550//2551if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {2552RC_TRACE_WITH_THREAD(0x02000000, THREAD,2553("length() is too small for a type_parameter_target"));2554return false;2555}25562557u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);2558byte_i_ref += 1;25592560RC_TRACE_WITH_THREAD(0x02000000, THREAD,2561("type_parameter_target: type_parameter_index=%d",2562type_parameter_index));2563} break;25642565case 0x10:2566// kind: type in extends clause of class or interface declaration2567// (including the direct superclass of an anonymous class declaration),2568// or in implements clause of interface declaration2569// location: ClassFile25702571{2572// struct:2573// supertype_target {2574// u2 supertype_index;2575// }2576//2577if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {2578RC_TRACE_WITH_THREAD(0x02000000, THREAD,2579("length() is too small for a supertype_target"));2580return false;2581}25822583u2 supertype_index = Bytes::get_Java_u2((address)2584type_annotations_typeArray->adr_at(byte_i_ref));2585byte_i_ref += 2;25862587RC_TRACE_WITH_THREAD(0x02000000, THREAD,2588("supertype_target: supertype_index=%d", supertype_index));2589} break;25902591case 0x11:2592// kind: type in bound of type parameter declaration of generic class or interface2593// location: ClassFile2594case 0x12:2595// kind: type in bound of type parameter declaration of generic method or constructor2596// location: method_info25972598{2599// struct:2600// type_parameter_bound_target {2601// u1 type_parameter_index;2602// u1 bound_index;2603// }2604//2605if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {2606RC_TRACE_WITH_THREAD(0x02000000, THREAD,2607("length() is too small for a type_parameter_bound_target"));2608return false;2609}26102611u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);2612byte_i_ref += 1;2613u1 bound_index = type_annotations_typeArray->at(byte_i_ref);2614byte_i_ref += 1;26152616RC_TRACE_WITH_THREAD(0x02000000, THREAD,2617("type_parameter_bound_target: type_parameter_index=%d, bound_index=%d",2618type_parameter_index, bound_index));2619} break;26202621case 0x13:2622// kind: type in field declaration2623// location: field_info2624case 0x14:2625// kind: return type of method, or type of newly constructed object2626// location: method_info2627case 0x15:2628// kind: receiver type of method or constructor2629// location: method_info26302631{2632// struct:2633// empty_target {2634// }2635//2636RC_TRACE_WITH_THREAD(0x02000000, THREAD,2637("empty_target"));2638} break;26392640case 0x16:2641// kind: type in formal parameter declaration of method, constructor, or lambda expression2642// location: method_info26432644{2645// struct:2646// formal_parameter_target {2647// u1 formal_parameter_index;2648// }2649//2650if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {2651RC_TRACE_WITH_THREAD(0x02000000, THREAD,2652("length() is too small for a formal_parameter_target"));2653return false;2654}26552656u1 formal_parameter_index = type_annotations_typeArray->at(byte_i_ref);2657byte_i_ref += 1;26582659RC_TRACE_WITH_THREAD(0x02000000, THREAD,2660("formal_parameter_target: formal_parameter_index=%d",2661formal_parameter_index));2662} break;26632664case 0x17:2665// kind: type in throws clause of method or constructor2666// location: method_info26672668{2669// struct:2670// throws_target {2671// u2 throws_type_index2672// }2673//2674if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {2675RC_TRACE_WITH_THREAD(0x02000000, THREAD,2676("length() is too small for a throws_target"));2677return false;2678}26792680u2 throws_type_index = Bytes::get_Java_u2((address)2681type_annotations_typeArray->adr_at(byte_i_ref));2682byte_i_ref += 2;26832684RC_TRACE_WITH_THREAD(0x02000000, THREAD,2685("throws_target: throws_type_index=%d", throws_type_index));2686} break;26872688case 0x40:2689// kind: type in local variable declaration2690// location: Code2691case 0x41:2692// kind: type in resource variable declaration2693// location: Code26942695{2696// struct:2697// localvar_target {2698// u2 table_length;2699// struct {2700// u2 start_pc;2701// u2 length;2702// u2 index;2703// } table[table_length];2704// }2705//2706if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {2707// not enough room for a table_length let alone the rest of a localvar_target2708RC_TRACE_WITH_THREAD(0x02000000, THREAD,2709("length() is too small for a localvar_target table_length"));2710return false;2711}27122713u2 table_length = Bytes::get_Java_u2((address)2714type_annotations_typeArray->adr_at(byte_i_ref));2715byte_i_ref += 2;27162717RC_TRACE_WITH_THREAD(0x02000000, THREAD,2718("localvar_target: table_length=%d", table_length));27192720int table_struct_size = 2 + 2 + 2; // 3 u2 variables per table entry2721int table_size = table_length * table_struct_size;27222723if ((byte_i_ref + table_size) > type_annotations_typeArray->length()) {2724// not enough room for a table2725RC_TRACE_WITH_THREAD(0x02000000, THREAD,2726("length() is too small for a table array of length %d", table_length));2727return false;2728}27292730// Skip over table2731byte_i_ref += table_size;2732} break;27332734case 0x42:2735// kind: type in exception parameter declaration2736// location: Code27372738{2739// struct:2740// catch_target {2741// u2 exception_table_index;2742// }2743//2744if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {2745RC_TRACE_WITH_THREAD(0x02000000, THREAD,2746("length() is too small for a catch_target"));2747return false;2748}27492750u2 exception_table_index = Bytes::get_Java_u2((address)2751type_annotations_typeArray->adr_at(byte_i_ref));2752byte_i_ref += 2;27532754RC_TRACE_WITH_THREAD(0x02000000, THREAD,2755("catch_target: exception_table_index=%d", exception_table_index));2756} break;27572758case 0x43:2759// kind: type in instanceof expression2760// location: Code2761case 0x44:2762// kind: type in new expression2763// location: Code2764case 0x45:2765// kind: type in method reference expression using ::new2766// location: Code2767case 0x46:2768// kind: type in method reference expression using ::Identifier2769// location: Code27702771{2772// struct:2773// offset_target {2774// u2 offset;2775// }2776//2777if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {2778RC_TRACE_WITH_THREAD(0x02000000, THREAD,2779("length() is too small for a offset_target"));2780return false;2781}27822783u2 offset = Bytes::get_Java_u2((address)2784type_annotations_typeArray->adr_at(byte_i_ref));2785byte_i_ref += 2;27862787RC_TRACE_WITH_THREAD(0x02000000, THREAD,2788("offset_target: offset=%d", offset));2789} break;27902791case 0x47:2792// kind: type in cast expression2793// location: Code2794case 0x48:2795// kind: type argument for generic constructor in new expression or2796// explicit constructor invocation statement2797// location: Code2798case 0x49:2799// kind: type argument for generic method in method invocation expression2800// location: Code2801case 0x4A:2802// kind: type argument for generic constructor in method reference expression using ::new2803// location: Code2804case 0x4B:2805// kind: type argument for generic method in method reference expression using ::Identifier2806// location: Code28072808{2809// struct:2810// type_argument_target {2811// u2 offset;2812// u1 type_argument_index;2813// }2814//2815if ((byte_i_ref + 3) > type_annotations_typeArray->length()) {2816RC_TRACE_WITH_THREAD(0x02000000, THREAD,2817("length() is too small for a type_argument_target"));2818return false;2819}28202821u2 offset = Bytes::get_Java_u2((address)2822type_annotations_typeArray->adr_at(byte_i_ref));2823byte_i_ref += 2;2824u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);2825byte_i_ref += 1;28262827RC_TRACE_WITH_THREAD(0x02000000, THREAD,2828("type_argument_target: offset=%d, type_argument_index=%d",2829offset, type_argument_index));2830} break;28312832default:2833RC_TRACE_WITH_THREAD(0x02000000, THREAD,2834("unknown target_type"));2835#ifdef ASSERT2836ShouldNotReachHere();2837#endif2838return false;2839}28402841return true;2842} // end skip_type_annotation_target()284328442845// Read, verify and skip over the type_path part so that rewriting2846// can continue in the later parts of the struct.2847//2848// type_path {2849// u1 path_length;2850// {2851// u1 type_path_kind;2852// u1 type_argument_index;2853// } path[path_length];2854// }2855//2856bool VM_RedefineClasses::skip_type_annotation_type_path(2857AnnotationArray* type_annotations_typeArray, int &byte_i_ref, TRAPS) {28582859if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {2860// not enough room for a path_length let alone the rest of the type_path2861RC_TRACE_WITH_THREAD(0x02000000, THREAD,2862("length() is too small for a type_path"));2863return false;2864}28652866u1 path_length = type_annotations_typeArray->at(byte_i_ref);2867byte_i_ref += 1;28682869RC_TRACE_WITH_THREAD(0x02000000, THREAD,2870("type_path: path_length=%d", path_length));28712872int calc_path_length = 0;2873for (; calc_path_length < path_length; calc_path_length++) {2874if ((byte_i_ref + 1 + 1) > type_annotations_typeArray->length()) {2875// not enough room for a path2876RC_TRACE_WITH_THREAD(0x02000000, THREAD,2877("length() is too small for path entry %d of %d",2878calc_path_length, path_length));2879return false;2880}28812882u1 type_path_kind = type_annotations_typeArray->at(byte_i_ref);2883byte_i_ref += 1;2884u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);2885byte_i_ref += 1;28862887RC_TRACE_WITH_THREAD(0x02000000, THREAD,2888("type_path: path[%d]: type_path_kind=%d, type_argument_index=%d",2889calc_path_length, type_path_kind, type_argument_index));28902891if (type_path_kind > 3 || (type_path_kind != 3 && type_argument_index != 0)) {2892// not enough room for a path2893RC_TRACE_WITH_THREAD(0x02000000, THREAD,2894("inconsistent type_path values"));2895return false;2896}2897}2898assert(path_length == calc_path_length, "sanity check");28992900return true;2901} // end skip_type_annotation_type_path()290229032904// Rewrite constant pool references in the method's stackmap table.2905// These "structures" are adapted from the StackMapTable_attribute that2906// is described in section 4.8.4 of the 6.0 version of the VM spec2907// (dated 2005.10.26):2908// file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf2909//2910// stack_map {2911// u2 number_of_entries;2912// stack_map_frame entries[number_of_entries];2913// }2914//2915void VM_RedefineClasses::rewrite_cp_refs_in_stack_map_table(2916methodHandle method, TRAPS) {29172918if (!method->has_stackmap_table()) {2919return;2920}29212922AnnotationArray* stackmap_data = method->stackmap_data();2923address stackmap_p = (address)stackmap_data->adr_at(0);2924address stackmap_end = stackmap_p + stackmap_data->length();29252926assert(stackmap_p + 2 <= stackmap_end, "no room for number_of_entries");2927u2 number_of_entries = Bytes::get_Java_u2(stackmap_p);2928stackmap_p += 2;29292930RC_TRACE_WITH_THREAD(0x04000000, THREAD,2931("number_of_entries=%u", number_of_entries));29322933// walk through each stack_map_frame2934u2 calc_number_of_entries = 0;2935for (; calc_number_of_entries < number_of_entries; calc_number_of_entries++) {2936// The stack_map_frame structure is a u1 frame_type followed by2937// 0 or more bytes of data:2938//2939// union stack_map_frame {2940// same_frame;2941// same_locals_1_stack_item_frame;2942// same_locals_1_stack_item_frame_extended;2943// chop_frame;2944// same_frame_extended;2945// append_frame;2946// full_frame;2947// }29482949assert(stackmap_p + 1 <= stackmap_end, "no room for frame_type");2950// The Linux compiler does not like frame_type to be u1 or u2. It2951// issues the following warning for the first if-statement below:2952//2953// "warning: comparison is always true due to limited range of data type"2954//2955u4 frame_type = *stackmap_p;2956stackmap_p++;29572958// same_frame {2959// u1 frame_type = SAME; /* 0-63 */2960// }2961if (frame_type >= 0 && frame_type <= 63) {2962// nothing more to do for same_frame2963}29642965// same_locals_1_stack_item_frame {2966// u1 frame_type = SAME_LOCALS_1_STACK_ITEM; /* 64-127 */2967// verification_type_info stack[1];2968// }2969else if (frame_type >= 64 && frame_type <= 127) {2970rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,2971calc_number_of_entries, frame_type, THREAD);2972}29732974// reserved for future use2975else if (frame_type >= 128 && frame_type <= 246) {2976// nothing more to do for reserved frame_types2977}29782979// same_locals_1_stack_item_frame_extended {2980// u1 frame_type = SAME_LOCALS_1_STACK_ITEM_EXTENDED; /* 247 */2981// u2 offset_delta;2982// verification_type_info stack[1];2983// }2984else if (frame_type == 247) {2985stackmap_p += 2;2986rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,2987calc_number_of_entries, frame_type, THREAD);2988}29892990// chop_frame {2991// u1 frame_type = CHOP; /* 248-250 */2992// u2 offset_delta;2993// }2994else if (frame_type >= 248 && frame_type <= 250) {2995stackmap_p += 2;2996}29972998// same_frame_extended {2999// u1 frame_type = SAME_FRAME_EXTENDED; /* 251*/3000// u2 offset_delta;3001// }3002else if (frame_type == 251) {3003stackmap_p += 2;3004}30053006// append_frame {3007// u1 frame_type = APPEND; /* 252-254 */3008// u2 offset_delta;3009// verification_type_info locals[frame_type - 251];3010// }3011else if (frame_type >= 252 && frame_type <= 254) {3012assert(stackmap_p + 2 <= stackmap_end,3013"no room for offset_delta");3014stackmap_p += 2;3015u1 len = frame_type - 251;3016for (u1 i = 0; i < len; i++) {3017rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,3018calc_number_of_entries, frame_type, THREAD);3019}3020}30213022// full_frame {3023// u1 frame_type = FULL_FRAME; /* 255 */3024// u2 offset_delta;3025// u2 number_of_locals;3026// verification_type_info locals[number_of_locals];3027// u2 number_of_stack_items;3028// verification_type_info stack[number_of_stack_items];3029// }3030else if (frame_type == 255) {3031assert(stackmap_p + 2 + 2 <= stackmap_end,3032"no room for smallest full_frame");3033stackmap_p += 2;30343035u2 number_of_locals = Bytes::get_Java_u2(stackmap_p);3036stackmap_p += 2;30373038for (u2 locals_i = 0; locals_i < number_of_locals; locals_i++) {3039rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,3040calc_number_of_entries, frame_type, THREAD);3041}30423043// Use the largest size for the number_of_stack_items, but only get3044// the right number of bytes.3045u2 number_of_stack_items = Bytes::get_Java_u2(stackmap_p);3046stackmap_p += 2;30473048for (u2 stack_i = 0; stack_i < number_of_stack_items; stack_i++) {3049rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,3050calc_number_of_entries, frame_type, THREAD);3051}3052}3053} // end while there is a stack_map_frame3054assert(number_of_entries == calc_number_of_entries, "sanity check");3055} // end rewrite_cp_refs_in_stack_map_table()305630573058// Rewrite constant pool references in the verification type info3059// portion of the method's stackmap table. These "structures" are3060// adapted from the StackMapTable_attribute that is described in3061// section 4.8.4 of the 6.0 version of the VM spec (dated 2005.10.26):3062// file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf3063//3064// The verification_type_info structure is a u1 tag followed by 0 or3065// more bytes of data:3066//3067// union verification_type_info {3068// Top_variable_info;3069// Integer_variable_info;3070// Float_variable_info;3071// Long_variable_info;3072// Double_variable_info;3073// Null_variable_info;3074// UninitializedThis_variable_info;3075// Object_variable_info;3076// Uninitialized_variable_info;3077// }3078//3079void VM_RedefineClasses::rewrite_cp_refs_in_verification_type_info(3080address& stackmap_p_ref, address stackmap_end, u2 frame_i,3081u1 frame_type, TRAPS) {30823083assert(stackmap_p_ref + 1 <= stackmap_end, "no room for tag");3084u1 tag = *stackmap_p_ref;3085stackmap_p_ref++;30863087switch (tag) {3088// Top_variable_info {3089// u1 tag = ITEM_Top; /* 0 */3090// }3091// verificationType.hpp has zero as ITEM_Bogus instead of ITEM_Top3092case 0: // fall through30933094// Integer_variable_info {3095// u1 tag = ITEM_Integer; /* 1 */3096// }3097case ITEM_Integer: // fall through30983099// Float_variable_info {3100// u1 tag = ITEM_Float; /* 2 */3101// }3102case ITEM_Float: // fall through31033104// Double_variable_info {3105// u1 tag = ITEM_Double; /* 3 */3106// }3107case ITEM_Double: // fall through31083109// Long_variable_info {3110// u1 tag = ITEM_Long; /* 4 */3111// }3112case ITEM_Long: // fall through31133114// Null_variable_info {3115// u1 tag = ITEM_Null; /* 5 */3116// }3117case ITEM_Null: // fall through31183119// UninitializedThis_variable_info {3120// u1 tag = ITEM_UninitializedThis; /* 6 */3121// }3122case ITEM_UninitializedThis:3123// nothing more to do for the above tag types3124break;31253126// Object_variable_info {3127// u1 tag = ITEM_Object; /* 7 */3128// u2 cpool_index;3129// }3130case ITEM_Object:3131{3132assert(stackmap_p_ref + 2 <= stackmap_end, "no room for cpool_index");3133u2 cpool_index = Bytes::get_Java_u2(stackmap_p_ref);3134u2 new_cp_index = find_new_index(cpool_index);3135if (new_cp_index != 0) {3136RC_TRACE_WITH_THREAD(0x04000000, THREAD,3137("mapped old cpool_index=%d", cpool_index));3138Bytes::put_Java_u2(stackmap_p_ref, new_cp_index);3139cpool_index = new_cp_index;3140}3141stackmap_p_ref += 2;31423143RC_TRACE_WITH_THREAD(0x04000000, THREAD,3144("frame_i=%u, frame_type=%u, cpool_index=%d", frame_i,3145frame_type, cpool_index));3146} break;31473148// Uninitialized_variable_info {3149// u1 tag = ITEM_Uninitialized; /* 8 */3150// u2 offset;3151// }3152case ITEM_Uninitialized:3153assert(stackmap_p_ref + 2 <= stackmap_end, "no room for offset");3154stackmap_p_ref += 2;3155break;31563157default:3158RC_TRACE_WITH_THREAD(0x04000000, THREAD,3159("frame_i=%u, frame_type=%u, bad tag=0x%x", frame_i, frame_type, tag));3160ShouldNotReachHere();3161break;3162} // end switch (tag)3163} // end rewrite_cp_refs_in_verification_type_info()316431653166// Change the constant pool associated with klass scratch_class to3167// scratch_cp. If shrink is true, then scratch_cp_length elements3168// are copied from scratch_cp to a smaller constant pool and the3169// smaller constant pool is associated with scratch_class.3170void VM_RedefineClasses::set_new_constant_pool(3171ClassLoaderData* loader_data,3172instanceKlassHandle scratch_class, constantPoolHandle scratch_cp,3173int scratch_cp_length, TRAPS) {3174assert(scratch_cp->length() >= scratch_cp_length, "sanity check");31753176// scratch_cp is a merged constant pool and has enough space for a3177// worst case merge situation. We want to associate the minimum3178// sized constant pool with the klass to save space.3179ConstantPool* cp = ConstantPool::allocate(loader_data, scratch_cp_length, CHECK);3180constantPoolHandle smaller_cp(THREAD, cp);31813182// preserve version() value in the smaller copy3183int version = scratch_cp->version();3184assert(version != 0, "sanity check");3185smaller_cp->set_version(version);31863187// attach klass to new constant pool3188// reference to the cp holder is needed for copy_operands()3189smaller_cp->set_pool_holder(scratch_class());31903191scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);3192if (HAS_PENDING_EXCEPTION) {3193// Exception is handled in the caller3194loader_data->add_to_deallocate_list(smaller_cp());3195return;3196}3197scratch_cp = smaller_cp;31983199// attach new constant pool to klass3200scratch_class->set_constants(scratch_cp());32013202int i; // for portability32033204// update each field in klass to use new constant pool indices as needed3205for (JavaFieldStream fs(scratch_class); !fs.done(); fs.next()) {3206jshort cur_index = fs.name_index();3207jshort new_index = find_new_index(cur_index);3208if (new_index != 0) {3209RC_TRACE_WITH_THREAD(0x00080000, THREAD,3210("field-name_index change: %d to %d", cur_index, new_index));3211fs.set_name_index(new_index);3212}3213cur_index = fs.signature_index();3214new_index = find_new_index(cur_index);3215if (new_index != 0) {3216RC_TRACE_WITH_THREAD(0x00080000, THREAD,3217("field-signature_index change: %d to %d", cur_index, new_index));3218fs.set_signature_index(new_index);3219}3220cur_index = fs.initval_index();3221new_index = find_new_index(cur_index);3222if (new_index != 0) {3223RC_TRACE_WITH_THREAD(0x00080000, THREAD,3224("field-initval_index change: %d to %d", cur_index, new_index));3225fs.set_initval_index(new_index);3226}3227cur_index = fs.generic_signature_index();3228new_index = find_new_index(cur_index);3229if (new_index != 0) {3230RC_TRACE_WITH_THREAD(0x00080000, THREAD,3231("field-generic_signature change: %d to %d", cur_index, new_index));3232fs.set_generic_signature_index(new_index);3233}3234} // end for each field32353236// Update constant pool indices in the inner classes info to use3237// new constant indices as needed. The inner classes info is a3238// quadruple:3239// (inner_class_info, outer_class_info, inner_name, inner_access_flags)3240InnerClassesIterator iter(scratch_class);3241for (; !iter.done(); iter.next()) {3242int cur_index = iter.inner_class_info_index();3243if (cur_index == 0) {3244continue; // JVM spec. allows null inner class refs so skip it3245}3246int new_index = find_new_index(cur_index);3247if (new_index != 0) {3248RC_TRACE_WITH_THREAD(0x00080000, THREAD,3249("inner_class_info change: %d to %d", cur_index, new_index));3250iter.set_inner_class_info_index(new_index);3251}3252cur_index = iter.outer_class_info_index();3253new_index = find_new_index(cur_index);3254if (new_index != 0) {3255RC_TRACE_WITH_THREAD(0x00080000, THREAD,3256("outer_class_info change: %d to %d", cur_index, new_index));3257iter.set_outer_class_info_index(new_index);3258}3259cur_index = iter.inner_name_index();3260new_index = find_new_index(cur_index);3261if (new_index != 0) {3262RC_TRACE_WITH_THREAD(0x00080000, THREAD,3263("inner_name change: %d to %d", cur_index, new_index));3264iter.set_inner_name_index(new_index);3265}3266} // end for each inner class32673268// Attach each method in klass to the new constant pool and update3269// to use new constant pool indices as needed:3270Array<Method*>* methods = scratch_class->methods();3271for (i = methods->length() - 1; i >= 0; i--) {3272methodHandle method(THREAD, methods->at(i));3273method->set_constants(scratch_cp());32743275int new_index = find_new_index(method->name_index());3276if (new_index != 0) {3277RC_TRACE_WITH_THREAD(0x00080000, THREAD,3278("method-name_index change: %d to %d", method->name_index(),3279new_index));3280method->set_name_index(new_index);3281}3282new_index = find_new_index(method->signature_index());3283if (new_index != 0) {3284RC_TRACE_WITH_THREAD(0x00080000, THREAD,3285("method-signature_index change: %d to %d",3286method->signature_index(), new_index));3287method->set_signature_index(new_index);3288}3289new_index = find_new_index(method->generic_signature_index());3290if (new_index != 0) {3291RC_TRACE_WITH_THREAD(0x00080000, THREAD,3292("method-generic_signature_index change: %d to %d",3293method->generic_signature_index(), new_index));3294method->set_generic_signature_index(new_index);3295}32963297// Update constant pool indices in the method's checked exception3298// table to use new constant indices as needed.3299int cext_length = method->checked_exceptions_length();3300if (cext_length > 0) {3301CheckedExceptionElement * cext_table =3302method->checked_exceptions_start();3303for (int j = 0; j < cext_length; j++) {3304int cur_index = cext_table[j].class_cp_index;3305int new_index = find_new_index(cur_index);3306if (new_index != 0) {3307RC_TRACE_WITH_THREAD(0x00080000, THREAD,3308("cext-class_cp_index change: %d to %d", cur_index, new_index));3309cext_table[j].class_cp_index = (u2)new_index;3310}3311} // end for each checked exception table entry3312} // end if there are checked exception table entries33133314// Update each catch type index in the method's exception table3315// to use new constant pool indices as needed. The exception table3316// holds quadruple entries of the form:3317// (beg_bci, end_bci, handler_bci, klass_index)33183319ExceptionTable ex_table(method());3320int ext_length = ex_table.length();33213322for (int j = 0; j < ext_length; j ++) {3323int cur_index = ex_table.catch_type_index(j);3324int new_index = find_new_index(cur_index);3325if (new_index != 0) {3326RC_TRACE_WITH_THREAD(0x00080000, THREAD,3327("ext-klass_index change: %d to %d", cur_index, new_index));3328ex_table.set_catch_type_index(j, new_index);3329}3330} // end for each exception table entry33313332// Update constant pool indices in the method's local variable3333// table to use new constant indices as needed. The local variable3334// table hold sextuple entries of the form:3335// (start_pc, length, name_index, descriptor_index, signature_index, slot)3336int lvt_length = method->localvariable_table_length();3337if (lvt_length > 0) {3338LocalVariableTableElement * lv_table =3339method->localvariable_table_start();3340for (int j = 0; j < lvt_length; j++) {3341int cur_index = lv_table[j].name_cp_index;3342int new_index = find_new_index(cur_index);3343if (new_index != 0) {3344RC_TRACE_WITH_THREAD(0x00080000, THREAD,3345("lvt-name_cp_index change: %d to %d", cur_index, new_index));3346lv_table[j].name_cp_index = (u2)new_index;3347}3348cur_index = lv_table[j].descriptor_cp_index;3349new_index = find_new_index(cur_index);3350if (new_index != 0) {3351RC_TRACE_WITH_THREAD(0x00080000, THREAD,3352("lvt-descriptor_cp_index change: %d to %d", cur_index,3353new_index));3354lv_table[j].descriptor_cp_index = (u2)new_index;3355}3356cur_index = lv_table[j].signature_cp_index;3357new_index = find_new_index(cur_index);3358if (new_index != 0) {3359RC_TRACE_WITH_THREAD(0x00080000, THREAD,3360("lvt-signature_cp_index change: %d to %d", cur_index, new_index));3361lv_table[j].signature_cp_index = (u2)new_index;3362}3363} // end for each local variable table entry3364} // end if there are local variable table entries33653366rewrite_cp_refs_in_stack_map_table(method, THREAD);3367} // end for each method3368} // end set_new_constant_pool()336933703371// Unevolving classes may point to methods of the_class directly3372// from their constant pool caches, itables, and/or vtables. We3373// use the ClassLoaderDataGraph::classes_do() facility and this helper3374// to fix up these pointers.33753376// Adjust cpools and vtables closure3377void VM_RedefineClasses::AdjustCpoolCacheAndVtable::do_klass(Klass* k) {33783379// This is a very busy routine. We don't want too much tracing3380// printed out.3381bool trace_name_printed = false;3382InstanceKlass *the_class = InstanceKlass::cast(_the_class_oop);33833384// Very noisy: only enable this call if you are trying to determine3385// that a specific class gets found by this routine.3386// RC_TRACE macro has an embedded ResourceMark3387// RC_TRACE_WITH_THREAD(0x00100000, THREAD,3388// ("adjust check: name=%s", k->external_name()));3389// trace_name_printed = true;33903391// If the class being redefined is java.lang.Object, we need to fix all3392// array class vtables also3393if (k->oop_is_array() && _the_class_oop == SystemDictionary::Object_klass()) {3394k->vtable()->adjust_method_entries(the_class, &trace_name_printed);33953396} else if (k->oop_is_instance()) {3397HandleMark hm(_thread);3398InstanceKlass *ik = InstanceKlass::cast(k);33993400// HotSpot specific optimization! HotSpot does not currently3401// support delegation from the bootstrap class loader to a3402// user-defined class loader. This means that if the bootstrap3403// class loader is the initiating class loader, then it will also3404// be the defining class loader. This also means that classes3405// loaded by the bootstrap class loader cannot refer to classes3406// loaded by a user-defined class loader. Note: a user-defined3407// class loader can delegate to the bootstrap class loader.3408//3409// If the current class being redefined has a user-defined class3410// loader as its defining class loader, then we can skip all3411// classes loaded by the bootstrap class loader.3412bool is_user_defined =3413InstanceKlass::cast(_the_class_oop)->class_loader() != NULL;3414if (is_user_defined && ik->class_loader() == NULL) {3415return;3416}34173418// Fix the vtable embedded in the_class and subclasses of the_class,3419// if one exists. We discard scratch_class and we don't keep an3420// InstanceKlass around to hold obsolete methods so we don't have3421// any other InstanceKlass embedded vtables to update. The vtable3422// holds the Method*s for virtual (but not final) methods.3423// Default methods, or concrete methods in interfaces are stored3424// in the vtable, so if an interface changes we need to check3425// adjust_method_entries() for every InstanceKlass, which will also3426// adjust the default method vtable indices.3427// We also need to adjust any default method entries that are3428// not yet in the vtable, because the vtable setup is in progress.3429// This must be done after we adjust the default_methods and3430// default_vtable_indices for methods already in the vtable.3431// If redefining Unsafe, walk all the vtables looking for entries.3432if (ik->vtable_length() > 0 && (_the_class_oop->is_interface()3433|| _the_class_oop == SystemDictionary::misc_Unsafe_klass()3434|| ik->is_subtype_of(_the_class_oop))) {3435// ik->vtable() creates a wrapper object; rm cleans it up3436ResourceMark rm(_thread);34373438ik->vtable()->adjust_method_entries(the_class, &trace_name_printed);3439ik->adjust_default_methods(the_class, &trace_name_printed);3440}34413442// If the current class has an itable and we are either redefining an3443// interface or if the current class is a subclass of the_class, then3444// we potentially have to fix the itable. If we are redefining an3445// interface, then we have to call adjust_method_entries() for3446// every InstanceKlass that has an itable since there isn't a3447// subclass relationship between an interface and an InstanceKlass.3448// If redefining Unsafe, walk all the itables looking for entries.3449if (ik->itable_length() > 0 && (_the_class_oop->is_interface()3450|| _the_class_oop == SystemDictionary::misc_Unsafe_klass()3451|| ik->is_subclass_of(_the_class_oop))) {3452// ik->itable() creates a wrapper object; rm cleans it up3453ResourceMark rm(_thread);34543455ik->itable()->adjust_method_entries(the_class, &trace_name_printed);3456}34573458// The constant pools in other classes (other_cp) can refer to3459// methods in the_class. We have to update method information in3460// other_cp's cache. If other_cp has a previous version, then we3461// have to repeat the process for each previous version. The3462// constant pool cache holds the Method*s for non-virtual3463// methods and for virtual, final methods.3464//3465// Special case: if the current class is the_class, then new_cp3466// has already been attached to the_class and old_cp has already3467// been added as a previous version. The new_cp doesn't have any3468// cached references to old methods so it doesn't need to be3469// updated. We can simply start with the previous version(s) in3470// that case.3471constantPoolHandle other_cp;3472ConstantPoolCache* cp_cache;34733474if (ik != _the_class_oop) {3475// this klass' constant pool cache may need adjustment3476other_cp = constantPoolHandle(ik->constants());3477cp_cache = other_cp->cache();3478if (cp_cache != NULL) {3479cp_cache->adjust_method_entries(the_class, &trace_name_printed);3480}3481}34823483// the previous versions' constant pool caches may need adjustment3484for (InstanceKlass* pv_node = ik->previous_versions();3485pv_node != NULL;3486pv_node = pv_node->previous_versions()) {3487cp_cache = pv_node->constants()->cache();3488if (cp_cache != NULL) {3489cp_cache->adjust_method_entries(pv_node, &trace_name_printed);3490}3491}3492}3493}34943495void VM_RedefineClasses::update_jmethod_ids() {3496for (int j = 0; j < _matching_methods_length; ++j) {3497Method* old_method = _matching_old_methods[j];3498jmethodID jmid = old_method->find_jmethod_id_or_null();3499if (jmid != NULL) {3500// There is a jmethodID, change it to point to the new method3501methodHandle new_method_h(_matching_new_methods[j]);3502Method::change_method_associated_with_jmethod_id(jmid, new_method_h());3503assert(Method::resolve_jmethod_id(jmid) == _matching_new_methods[j],3504"should be replaced");3505}3506}3507}35083509int VM_RedefineClasses::check_methods_and_mark_as_obsolete() {3510int emcp_method_count = 0;3511int obsolete_count = 0;3512int old_index = 0;3513for (int j = 0; j < _matching_methods_length; ++j, ++old_index) {3514Method* old_method = _matching_old_methods[j];3515Method* new_method = _matching_new_methods[j];3516Method* old_array_method;35173518// Maintain an old_index into the _old_methods array by skipping3519// deleted methods3520while ((old_array_method = _old_methods->at(old_index)) != old_method) {3521++old_index;3522}35233524if (MethodComparator::methods_EMCP(old_method, new_method)) {3525// The EMCP definition from JSR-163 requires the bytecodes to be3526// the same with the exception of constant pool indices which may3527// differ. However, the constants referred to by those indices3528// must be the same.3529//3530// We use methods_EMCP() for comparison since constant pool3531// merging can remove duplicate constant pool entries that were3532// present in the old method and removed from the rewritten new3533// method. A faster binary comparison function would consider the3534// old and new methods to be different when they are actually3535// EMCP.3536//3537// The old and new methods are EMCP and you would think that we3538// could get rid of one of them here and now and save some space.3539// However, the concept of EMCP only considers the bytecodes and3540// the constant pool entries in the comparison. Other things,3541// e.g., the line number table (LNT) or the local variable table3542// (LVT) don't count in the comparison. So the new (and EMCP)3543// method can have a new LNT that we need so we can't just3544// overwrite the new method with the old method.3545//3546// When this routine is called, we have already attached the new3547// methods to the_class so the old methods are effectively3548// overwritten. However, if an old method is still executing,3549// then the old method cannot be collected until sometime after3550// the old method call has returned. So the overwriting of old3551// methods by new methods will save us space except for those3552// (hopefully few) old methods that are still executing.3553//3554// A method refers to a ConstMethod* and this presents another3555// possible avenue to space savings. The ConstMethod* in the3556// new method contains possibly new attributes (LNT, LVT, etc).3557// At first glance, it seems possible to save space by replacing3558// the ConstMethod* in the old method with the ConstMethod*3559// from the new method. The old and new methods would share the3560// same ConstMethod* and we would save the space occupied by3561// the old ConstMethod*. However, the ConstMethod* contains3562// a back reference to the containing method. Sharing the3563// ConstMethod* between two methods could lead to confusion in3564// the code that uses the back reference. This would lead to3565// brittle code that could be broken in non-obvious ways now or3566// in the future.3567//3568// Another possibility is to copy the ConstMethod* from the new3569// method to the old method and then overwrite the new method with3570// the old method. Since the ConstMethod* contains the bytecodes3571// for the method embedded in the oop, this option would change3572// the bytecodes out from under any threads executing the old3573// method and make the thread's bcp invalid. Since EMCP requires3574// that the bytecodes be the same modulo constant pool indices, it3575// is straight forward to compute the correct new bcp in the new3576// ConstMethod* from the old bcp in the old ConstMethod*. The3577// time consuming part would be searching all the frames in all3578// of the threads to find all of the calls to the old method.3579//3580// It looks like we will have to live with the limited savings3581// that we get from effectively overwriting the old methods3582// when the new methods are attached to the_class.35833584// Count number of methods that are EMCP. The method will be marked3585// old but not obsolete if it is EMCP.3586emcp_method_count++;35873588// An EMCP method is _not_ obsolete. An obsolete method has a3589// different jmethodID than the current method. An EMCP method3590// has the same jmethodID as the current method. Having the3591// same jmethodID for all EMCP versions of a method allows for3592// a consistent view of the EMCP methods regardless of which3593// EMCP method you happen to have in hand. For example, a3594// breakpoint set in one EMCP method will work for all EMCP3595// versions of the method including the current one.3596} else {3597// mark obsolete methods as such3598old_method->set_is_obsolete();3599obsolete_count++;36003601// obsolete methods need a unique idnum so they become new entries in3602// the jmethodID cache in InstanceKlass3603assert(old_method->method_idnum() == new_method->method_idnum(), "must match");3604u2 num = InstanceKlass::cast(_the_class_oop)->next_method_idnum();3605if (num != ConstMethod::UNSET_IDNUM) {3606old_method->set_method_idnum(num);3607}36083609// With tracing we try not to "yack" too much. The position of3610// this trace assumes there are fewer obsolete methods than3611// EMCP methods.3612RC_TRACE(0x00000100, ("mark %s(%s) as obsolete",3613old_method->name()->as_C_string(),3614old_method->signature()->as_C_string()));3615}3616old_method->set_is_old();3617}3618for (int i = 0; i < _deleted_methods_length; ++i) {3619Method* old_method = _deleted_methods[i];36203621assert(!old_method->has_vtable_index(),3622"cannot delete methods with vtable entries");;36233624// Mark all deleted methods as old, obsolete and deleted3625old_method->set_is_deleted();3626old_method->set_is_old();3627old_method->set_is_obsolete();3628++obsolete_count;3629// With tracing we try not to "yack" too much. The position of3630// this trace assumes there are fewer obsolete methods than3631// EMCP methods.3632RC_TRACE(0x00000100, ("mark deleted %s(%s) as obsolete",3633old_method->name()->as_C_string(),3634old_method->signature()->as_C_string()));3635}3636assert((emcp_method_count + obsolete_count) == _old_methods->length(),3637"sanity check");3638RC_TRACE(0x00000100, ("EMCP_cnt=%d, obsolete_cnt=%d", emcp_method_count,3639obsolete_count));3640return emcp_method_count;3641}36423643// This internal class transfers the native function registration from old methods3644// to new methods. It is designed to handle both the simple case of unchanged3645// native methods and the complex cases of native method prefixes being added and/or3646// removed.3647// It expects only to be used during the VM_RedefineClasses op (a safepoint).3648//3649// This class is used after the new methods have been installed in "the_class".3650//3651// So, for example, the following must be handled. Where 'm' is a method and3652// a number followed by an underscore is a prefix.3653//3654// Old Name New Name3655// Simple transfer to new method m -> m3656// Add prefix m -> 1_m3657// Remove prefix 1_m -> m3658// Simultaneous add of prefixes m -> 3_2_1_m3659// Simultaneous removal of prefixes 3_2_1_m -> m3660// Simultaneous add and remove 1_m -> 2_m3661// Same, caused by prefix removal only 3_2_1_m -> 3_2_m3662//3663class TransferNativeFunctionRegistration {3664private:3665instanceKlassHandle the_class;3666int prefix_count;3667char** prefixes;36683669// Recursively search the binary tree of possibly prefixed method names.3670// Iteration could be used if all agents were well behaved. Full tree walk is3671// more resilent to agents not cleaning up intermediate methods.3672// Branch at each depth in the binary tree is:3673// (1) without the prefix.3674// (2) with the prefix.3675// where 'prefix' is the prefix at that 'depth' (first prefix, second prefix,...)3676Method* search_prefix_name_space(int depth, char* name_str, size_t name_len,3677Symbol* signature) {3678TempNewSymbol name_symbol = SymbolTable::probe(name_str, (int)name_len);3679if (name_symbol != NULL) {3680Method* method = the_class()->lookup_method(name_symbol, signature);3681if (method != NULL) {3682// Even if prefixed, intermediate methods must exist.3683if (method->is_native()) {3684// Wahoo, we found a (possibly prefixed) version of the method, return it.3685return method;3686}3687if (depth < prefix_count) {3688// Try applying further prefixes (other than this one).3689method = search_prefix_name_space(depth+1, name_str, name_len, signature);3690if (method != NULL) {3691return method; // found3692}36933694// Try adding this prefix to the method name and see if it matches3695// another method name.3696char* prefix = prefixes[depth];3697size_t prefix_len = strlen(prefix);3698size_t trial_len = name_len + prefix_len;3699char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);3700strcpy(trial_name_str, prefix);3701strcat(trial_name_str, name_str);3702method = search_prefix_name_space(depth+1, trial_name_str, trial_len,3703signature);3704if (method != NULL) {3705// If found along this branch, it was prefixed, mark as such3706method->set_is_prefixed_native();3707return method; // found3708}3709}3710}3711}3712return NULL; // This whole branch bore nothing3713}37143715// Return the method name with old prefixes stripped away.3716char* method_name_without_prefixes(Method* method) {3717Symbol* name = method->name();3718char* name_str = name->as_utf8();37193720// Old prefixing may be defunct, strip prefixes, if any.3721for (int i = prefix_count-1; i >= 0; i--) {3722char* prefix = prefixes[i];3723size_t prefix_len = strlen(prefix);3724if (strncmp(prefix, name_str, prefix_len) == 0) {3725name_str += prefix_len;3726}3727}3728return name_str;3729}37303731// Strip any prefixes off the old native method, then try to find a3732// (possibly prefixed) new native that matches it.3733Method* strip_and_search_for_new_native(Method* method) {3734ResourceMark rm;3735char* name_str = method_name_without_prefixes(method);3736return search_prefix_name_space(0, name_str, strlen(name_str),3737method->signature());3738}37393740public:37413742// Construct a native method transfer processor for this class.3743TransferNativeFunctionRegistration(instanceKlassHandle _the_class) {3744assert(SafepointSynchronize::is_at_safepoint(), "sanity check");37453746the_class = _the_class;3747prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);3748}37493750// Attempt to transfer any of the old or deleted methods that are native3751void transfer_registrations(Method** old_methods, int methods_length) {3752for (int j = 0; j < methods_length; j++) {3753Method* old_method = old_methods[j];37543755if (old_method->is_native() && old_method->has_native_function()) {3756Method* new_method = strip_and_search_for_new_native(old_method);3757if (new_method != NULL) {3758// Actually set the native function in the new method.3759// Redefine does not send events (except CFLH), certainly not this3760// behind the scenes re-registration.3761new_method->set_native_function(old_method->native_function(),3762!Method::native_bind_event_is_interesting);3763}3764}3765}3766}3767};37683769// Don't lose the association between a native method and its JNI function.3770void VM_RedefineClasses::transfer_old_native_function_registrations(instanceKlassHandle the_class) {3771TransferNativeFunctionRegistration transfer(the_class);3772transfer.transfer_registrations(_deleted_methods, _deleted_methods_length);3773transfer.transfer_registrations(_matching_old_methods, _matching_methods_length);3774}37753776// Deoptimize all compiled code that depends on this class.3777//3778// If the can_redefine_classes capability is obtained in the onload3779// phase then the compiler has recorded all dependencies from startup.3780// In that case we need only deoptimize and throw away all compiled code3781// that depends on the class.3782//3783// If can_redefine_classes is obtained sometime after the onload3784// phase then the dependency information may be incomplete. In that case3785// the first call to RedefineClasses causes all compiled code to be3786// thrown away. As can_redefine_classes has been obtained then3787// all future compilations will record dependencies so second and3788// subsequent calls to RedefineClasses need only throw away code3789// that depends on the class.3790//3791void VM_RedefineClasses::flush_dependent_code(instanceKlassHandle k_h, TRAPS) {3792assert_locked_or_safepoint(Compile_lock);37933794// All dependencies have been recorded from startup or this is a second or3795// subsequent use of RedefineClasses3796if (JvmtiExport::all_dependencies_are_recorded()) {3797Universe::flush_evol_dependents_on(k_h);3798} else {3799CodeCache::mark_all_nmethods_for_deoptimization();38003801ResourceMark rm(THREAD);3802DeoptimizationMarker dm;38033804// Deoptimize all activations depending on marked nmethods3805Deoptimization::deoptimize_dependents();38063807// Make the dependent methods not entrant3808CodeCache::make_marked_nmethods_not_entrant();38093810// From now on we know that the dependency information is complete3811JvmtiExport::set_all_dependencies_are_recorded(true);3812}3813}38143815void VM_RedefineClasses::compute_added_deleted_matching_methods() {3816Method* old_method;3817Method* new_method;38183819_matching_old_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());3820_matching_new_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());3821_added_methods = NEW_RESOURCE_ARRAY(Method*, _new_methods->length());3822_deleted_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());38233824_matching_methods_length = 0;3825_deleted_methods_length = 0;3826_added_methods_length = 0;38273828int nj = 0;3829int oj = 0;3830while (true) {3831if (oj >= _old_methods->length()) {3832if (nj >= _new_methods->length()) {3833break; // we've looked at everything, done3834}3835// New method at the end3836new_method = _new_methods->at(nj);3837_added_methods[_added_methods_length++] = new_method;3838++nj;3839} else if (nj >= _new_methods->length()) {3840// Old method, at the end, is deleted3841old_method = _old_methods->at(oj);3842_deleted_methods[_deleted_methods_length++] = old_method;3843++oj;3844} else {3845old_method = _old_methods->at(oj);3846new_method = _new_methods->at(nj);3847if (old_method->name() == new_method->name()) {3848if (old_method->signature() == new_method->signature()) {3849_matching_old_methods[_matching_methods_length ] = old_method;3850_matching_new_methods[_matching_methods_length++] = new_method;3851++nj;3852++oj;3853} else {3854// added overloaded have already been moved to the end,3855// so this is a deleted overloaded method3856_deleted_methods[_deleted_methods_length++] = old_method;3857++oj;3858}3859} else { // names don't match3860if (old_method->name()->fast_compare(new_method->name()) > 0) {3861// new method3862_added_methods[_added_methods_length++] = new_method;3863++nj;3864} else {3865// deleted method3866_deleted_methods[_deleted_methods_length++] = old_method;3867++oj;3868}3869}3870}3871}3872assert(_matching_methods_length + _deleted_methods_length == _old_methods->length(), "sanity");3873assert(_matching_methods_length + _added_methods_length == _new_methods->length(), "sanity");3874}387538763877void VM_RedefineClasses::swap_annotations(instanceKlassHandle the_class,3878instanceKlassHandle scratch_class) {3879// Swap annotation fields values3880Annotations* old_annotations = the_class->annotations();3881the_class->set_annotations(scratch_class->annotations());3882scratch_class->set_annotations(old_annotations);3883}388438853886// Install the redefinition of a class:3887// - house keeping (flushing breakpoints and caches, deoptimizing3888// dependent compiled code)3889// - replacing parts in the_class with parts from scratch_class3890// - adding a weak reference to track the obsolete but interesting3891// parts of the_class3892// - adjusting constant pool caches and vtables in other classes3893// that refer to methods in the_class. These adjustments use the3894// ClassLoaderDataGraph::classes_do() facility which only allows3895// a helper method to be specified. The interesting parameters3896// that we would like to pass to the helper method are saved in3897// static global fields in the VM operation.3898void VM_RedefineClasses::redefine_single_class(jclass the_jclass,3899Klass* scratch_class_oop, TRAPS) {39003901HandleMark hm(THREAD); // make sure handles from this call are freed3902RC_TIMER_START(_timer_rsc_phase1);39033904instanceKlassHandle scratch_class(THREAD, scratch_class_oop);3905instanceKlassHandle the_class(THREAD, get_ik(the_jclass));39063907// Remove all breakpoints in methods of this class3908JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();3909jvmti_breakpoints.clearall_in_class_at_safepoint(the_class());39103911// Deoptimize all compiled code that depends on this class3912flush_dependent_code(the_class, THREAD);39133914_old_methods = the_class->methods();3915_new_methods = scratch_class->methods();3916_the_class_oop = the_class();3917compute_added_deleted_matching_methods();3918update_jmethod_ids();39193920// Attach new constant pool to the original klass. The original3921// klass still refers to the old constant pool (for now).3922scratch_class->constants()->set_pool_holder(the_class());39233924#if 03925// In theory, with constant pool merging in place we should be able3926// to save space by using the new, merged constant pool in place of3927// the old constant pool(s). By "pool(s)" I mean the constant pool in3928// the klass version we are replacing now and any constant pool(s) in3929// previous versions of klass. Nice theory, doesn't work in practice.3930// When this code is enabled, even simple programs throw NullPointer3931// exceptions. I'm guessing that this is caused by some constant pool3932// cache difference between the new, merged constant pool and the3933// constant pool that was just being used by the klass. I'm keeping3934// this code around to archive the idea, but the code has to remain3935// disabled for now.39363937// Attach each old method to the new constant pool. This can be3938// done here since we are past the bytecode verification and3939// constant pool optimization phases.3940for (int i = _old_methods->length() - 1; i >= 0; i--) {3941Method* method = _old_methods->at(i);3942method->set_constants(scratch_class->constants());3943}39443945{3946// walk all previous versions of the klass3947InstanceKlass *ik = (InstanceKlass *)the_class();3948PreviousVersionWalker pvw(ik);3949instanceKlassHandle ikh;3950do {3951ikh = pvw.next_previous_version();3952if (!ikh.is_null()) {3953ik = ikh();39543955// attach previous version of klass to the new constant pool3956ik->set_constants(scratch_class->constants());39573958// Attach each method in the previous version of klass to the3959// new constant pool3960Array<Method*>* prev_methods = ik->methods();3961for (int i = prev_methods->length() - 1; i >= 0; i--) {3962Method* method = prev_methods->at(i);3963method->set_constants(scratch_class->constants());3964}3965}3966} while (!ikh.is_null());3967}3968#endif39693970// Replace methods and constantpool3971the_class->set_methods(_new_methods);3972scratch_class->set_methods(_old_methods); // To prevent potential GCing of the old methods,3973// and to be able to undo operation easily.39743975Array<int>* old_ordering = the_class->method_ordering();3976the_class->set_method_ordering(scratch_class->method_ordering());3977scratch_class->set_method_ordering(old_ordering);39783979ConstantPool* old_constants = the_class->constants();3980the_class->set_constants(scratch_class->constants());3981scratch_class->set_constants(old_constants); // See the previous comment.3982#if 03983// We are swapping the guts of "the new class" with the guts of "the3984// class". Since the old constant pool has just been attached to "the3985// new class", it seems logical to set the pool holder in the old3986// constant pool also. However, doing this will change the observable3987// class hierarchy for any old methods that are still executing. A3988// method can query the identity of its "holder" and this query uses3989// the method's constant pool link to find the holder. The change in3990// holding class from "the class" to "the new class" can confuse3991// things.3992//3993// Setting the old constant pool's holder will also cause3994// verification done during vtable initialization below to fail.3995// During vtable initialization, the vtable's class is verified to be3996// a subtype of the method's holder. The vtable's class is "the3997// class" and the method's holder is gotten from the constant pool3998// link in the method itself. For "the class"'s directly implemented3999// methods, the method holder is "the class" itself (as gotten from4000// the new constant pool). The check works fine in this case. The4001// check also works fine for methods inherited from super classes.4002//4003// Miranda methods are a little more complicated. A miranda method is4004// provided by an interface when the class implementing the interface4005// does not provide its own method. These interfaces are implemented4006// internally as an InstanceKlass. These special instanceKlasses4007// share the constant pool of the class that "implements" the4008// interface. By sharing the constant pool, the method holder of a4009// miranda method is the class that "implements" the interface. In a4010// non-redefine situation, the subtype check works fine. However, if4011// the old constant pool's pool holder is modified, then the check4012// fails because there is no class hierarchy relationship between the4013// vtable's class and "the new class".40144015old_constants->set_pool_holder(scratch_class());4016#endif40174018// track number of methods that are EMCP for add_previous_version() call below4019int emcp_method_count = check_methods_and_mark_as_obsolete();4020transfer_old_native_function_registrations(the_class);40214022// The class file bytes from before any retransformable agents mucked4023// with them was cached on the scratch class, move to the_class.4024// Note: we still want to do this if nothing needed caching since it4025// should get cleared in the_class too.4026if (the_class->get_cached_class_file() == 0) {4027// the_class doesn't have a cache yet so copy it4028the_class->set_cached_class_file(scratch_class->get_cached_class_file());4029}4030else if (scratch_class->get_cached_class_file() !=4031the_class->get_cached_class_file()) {4032// The same class can be present twice in the scratch classes list or there4033// are multiple concurrent RetransformClasses calls on different threads.4034// In such cases we have to deallocate scratch_class cached_class_file.4035os::free(scratch_class->get_cached_class_file());4036}40374038// NULL out in scratch class to not delete twice. The class to be redefined4039// always owns these bytes.4040scratch_class->set_cached_class_file(NULL);40414042// Replace inner_classes4043Array<u2>* old_inner_classes = the_class->inner_classes();4044the_class->set_inner_classes(scratch_class->inner_classes());4045scratch_class->set_inner_classes(old_inner_classes);40464047// Initialize the vtable and interface table after4048// methods have been rewritten4049{4050ResourceMark rm(THREAD);4051// no exception should happen here since we explicitly4052// do not check loader constraints.4053// compare_and_normalize_class_versions has already checked:4054// - classloaders unchanged, signatures unchanged4055// - all instanceKlasses for redefined classes reused & contents updated4056the_class->vtable()->initialize_vtable(false, THREAD);4057the_class->itable()->initialize_itable(false, THREAD);4058assert(!HAS_PENDING_EXCEPTION || (THREAD->pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())), "redefine exception");4059}40604061// Leave arrays of jmethodIDs and itable index cache unchanged40624063// Copy the "source file name" attribute from new class version4064the_class->set_source_file_name_index(4065scratch_class->source_file_name_index());40664067// Copy the "source debug extension" attribute from new class version4068the_class->set_source_debug_extension(4069scratch_class->source_debug_extension(),4070scratch_class->source_debug_extension() == NULL ? 0 :4071(int)strlen(scratch_class->source_debug_extension()));40724073// Use of javac -g could be different in the old and the new4074if (scratch_class->access_flags().has_localvariable_table() !=4075the_class->access_flags().has_localvariable_table()) {40764077AccessFlags flags = the_class->access_flags();4078if (scratch_class->access_flags().has_localvariable_table()) {4079flags.set_has_localvariable_table();4080} else {4081flags.clear_has_localvariable_table();4082}4083the_class->set_access_flags(flags);4084}40854086swap_annotations(the_class, scratch_class);40874088// Replace minor version number of class file4089u2 old_minor_version = the_class->minor_version();4090the_class->set_minor_version(scratch_class->minor_version());4091scratch_class->set_minor_version(old_minor_version);40924093// Replace major version number of class file4094u2 old_major_version = the_class->major_version();4095the_class->set_major_version(scratch_class->major_version());4096scratch_class->set_major_version(old_major_version);40974098// Replace CP indexes for class and name+type of enclosing method4099u2 old_class_idx = the_class->enclosing_method_class_index();4100u2 old_method_idx = the_class->enclosing_method_method_index();4101the_class->set_enclosing_method_indices(4102scratch_class->enclosing_method_class_index(),4103scratch_class->enclosing_method_method_index());4104scratch_class->set_enclosing_method_indices(old_class_idx, old_method_idx);41054106the_class->set_has_been_redefined();41074108// keep track of previous versions of this class4109the_class->add_previous_version(scratch_class, emcp_method_count);41104111RC_TIMER_STOP(_timer_rsc_phase1);4112RC_TIMER_START(_timer_rsc_phase2);41134114// Adjust constantpool caches and vtables for all classes4115// that reference methods of the evolved class.4116AdjustCpoolCacheAndVtable adjust_cpool_cache_and_vtable(THREAD);4117ClassLoaderDataGraph::classes_do(&adjust_cpool_cache_and_vtable);41184119// JSR-292 support4120MemberNameTable* mnt = the_class->member_names();4121if (mnt != NULL) {4122bool trace_name_printed = false;4123mnt->adjust_method_entries(the_class(), &trace_name_printed);4124}41254126if (the_class->oop_map_cache() != NULL) {4127// Flush references to any obsolete methods from the oop map cache4128// so that obsolete methods are not pinned.4129the_class->oop_map_cache()->flush_obsolete_entries();4130}41314132// increment the classRedefinedCount field in the_class and in any4133// direct and indirect subclasses of the_class4134increment_class_counter((InstanceKlass *)the_class(), THREAD);41354136// RC_TRACE macro has an embedded ResourceMark4137RC_TRACE_WITH_THREAD(0x00000001, THREAD,4138("redefined name=%s, count=%d (avail_mem=" UINT64_FORMAT "K)",4139the_class->external_name(),4140java_lang_Class::classRedefinedCount(the_class->java_mirror()),4141os::available_memory() >> 10));41424143{4144ResourceMark rm(THREAD);4145Events::log_redefinition(THREAD, "redefined class name=%s, count=%d",4146the_class->external_name(),4147java_lang_Class::classRedefinedCount(the_class->java_mirror()));41484149}4150RC_TIMER_STOP(_timer_rsc_phase2);4151} // end redefine_single_class()415241534154// Increment the classRedefinedCount field in the specific InstanceKlass4155// and in all direct and indirect subclasses.4156void VM_RedefineClasses::increment_class_counter(InstanceKlass *ik, TRAPS) {4157oop class_mirror = ik->java_mirror();4158Klass* class_oop = java_lang_Class::as_Klass(class_mirror);4159int new_count = java_lang_Class::classRedefinedCount(class_mirror) + 1;4160java_lang_Class::set_classRedefinedCount(class_mirror, new_count);41614162if (class_oop != _the_class_oop) {4163// _the_class_oop count is printed at end of redefine_single_class()4164RC_TRACE_WITH_THREAD(0x00000008, THREAD,4165("updated count in subclass=%s to %d", ik->external_name(), new_count));4166}41674168for (Klass *subk = ik->subklass(); subk != NULL;4169subk = subk->next_sibling()) {4170if (subk->oop_is_instance()) {4171// Only update instanceKlasses4172InstanceKlass *subik = (InstanceKlass*)subk;4173// recursively do subclasses of the current subclass4174increment_class_counter(subik, THREAD);4175}4176}4177}41784179void VM_RedefineClasses::CheckClass::do_klass(Klass* k) {4180bool no_old_methods = true; // be optimistic41814182// Both array and instance classes have vtables.4183// a vtable should never contain old or obsolete methods4184ResourceMark rm(_thread);4185if (k->vtable_length() > 0 &&4186!k->vtable()->check_no_old_or_obsolete_entries()) {4187if (RC_TRACE_ENABLED(0x00004000)) {4188RC_TRACE_WITH_THREAD(0x00004000, _thread,4189("klassVtable::check_no_old_or_obsolete_entries failure"4190" -- OLD or OBSOLETE method found -- class: %s",4191k->signature_name()));4192k->vtable()->dump_vtable();4193}4194no_old_methods = false;4195}41964197if (k->oop_is_instance()) {4198HandleMark hm(_thread);4199InstanceKlass *ik = InstanceKlass::cast(k);42004201// an itable should never contain old or obsolete methods4202if (ik->itable_length() > 0 &&4203!ik->itable()->check_no_old_or_obsolete_entries()) {4204if (RC_TRACE_ENABLED(0x00004000)) {4205RC_TRACE_WITH_THREAD(0x00004000, _thread,4206("klassItable::check_no_old_or_obsolete_entries failure"4207" -- OLD or OBSOLETE method found -- class: %s",4208ik->signature_name()));4209ik->itable()->dump_itable();4210}4211no_old_methods = false;4212}42134214// the constant pool cache should never contain non-deleted old or obsolete methods4215if (ik->constants() != NULL &&4216ik->constants()->cache() != NULL &&4217!ik->constants()->cache()->check_no_old_or_obsolete_entries()) {4218if (RC_TRACE_ENABLED(0x00004000)) {4219RC_TRACE_WITH_THREAD(0x00004000, _thread,4220("cp-cache::check_no_old_or_obsolete_entries failure"4221" -- OLD or OBSOLETE method found -- class: %s",4222ik->signature_name()));4223ik->constants()->cache()->dump_cache();4224}4225no_old_methods = false;4226}4227}42284229// print and fail guarantee if old methods are found.4230if (!no_old_methods) {4231if (RC_TRACE_ENABLED(0x00004000)) {4232dump_methods();4233} else {4234tty->print_cr("INFO: use the '-XX:TraceRedefineClasses=16384' option "4235"to see more info about the following guarantee() failure.");4236}4237guarantee(false, "OLD and/or OBSOLETE method(s) found");4238}4239}424042414242void VM_RedefineClasses::dump_methods() {4243int j;4244RC_TRACE(0x00004000, ("_old_methods --"));4245for (j = 0; j < _old_methods->length(); ++j) {4246Method* m = _old_methods->at(j);4247RC_TRACE_NO_CR(0x00004000, ("%4d (%5d) ", j, m->vtable_index()));4248m->access_flags().print_on(tty);4249tty->print(" -- ");4250m->print_name(tty);4251tty->cr();4252}4253RC_TRACE(0x00004000, ("_new_methods --"));4254for (j = 0; j < _new_methods->length(); ++j) {4255Method* m = _new_methods->at(j);4256RC_TRACE_NO_CR(0x00004000, ("%4d (%5d) ", j, m->vtable_index()));4257m->access_flags().print_on(tty);4258tty->print(" -- ");4259m->print_name(tty);4260tty->cr();4261}4262RC_TRACE(0x00004000, ("_matching_(old/new)_methods --"));4263for (j = 0; j < _matching_methods_length; ++j) {4264Method* m = _matching_old_methods[j];4265RC_TRACE_NO_CR(0x00004000, ("%4d (%5d) ", j, m->vtable_index()));4266m->access_flags().print_on(tty);4267tty->print(" -- ");4268m->print_name(tty);4269tty->cr();4270m = _matching_new_methods[j];4271RC_TRACE_NO_CR(0x00004000, (" (%5d) ", m->vtable_index()));4272m->access_flags().print_on(tty);4273tty->cr();4274}4275RC_TRACE(0x00004000, ("_deleted_methods --"));4276for (j = 0; j < _deleted_methods_length; ++j) {4277Method* m = _deleted_methods[j];4278RC_TRACE_NO_CR(0x00004000, ("%4d (%5d) ", j, m->vtable_index()));4279m->access_flags().print_on(tty);4280tty->print(" -- ");4281m->print_name(tty);4282tty->cr();4283}4284RC_TRACE(0x00004000, ("_added_methods --"));4285for (j = 0; j < _added_methods_length; ++j) {4286Method* m = _added_methods[j];4287RC_TRACE_NO_CR(0x00004000, ("%4d (%5d) ", j, m->vtable_index()));4288m->access_flags().print_on(tty);4289tty->print(" -- ");4290m->print_name(tty);4291tty->cr();4292}4293}42944295void VM_RedefineClasses::print_on_error(outputStream* st) const {4296VM_Operation::print_on_error(st);4297if (_the_class_oop != NULL) {4298ResourceMark rm;4299st->print_cr(", redefining class %s", _the_class_oop->external_name());4300}4301}430243034304