41 #include "oops/fieldStreams.hpp"
42 #include "oops/klassVtable.hpp"
43 #include "oops/oop.inline.hpp"
44 #include "prims/jvmtiImpl.hpp"
45 #include "prims/jvmtiRedefineClasses.hpp"
46 #include "prims/methodComparator.hpp"
47 #include "runtime/deoptimization.hpp"
48 #include "runtime/relocator.hpp"
49 #include "utilities/bitMap.inline.hpp"
50 #include "utilities/events.hpp"
51
52 Array<Method*>* VM_RedefineClasses::_old_methods = NULL;
53 Array<Method*>* VM_RedefineClasses::_new_methods = NULL;
54 Method** VM_RedefineClasses::_matching_old_methods = NULL;
55 Method** VM_RedefineClasses::_matching_new_methods = NULL;
56 Method** VM_RedefineClasses::_deleted_methods = NULL;
57 Method** VM_RedefineClasses::_added_methods = NULL;
58 int VM_RedefineClasses::_matching_methods_length = 0;
59 int VM_RedefineClasses::_deleted_methods_length = 0;
60 int VM_RedefineClasses::_added_methods_length = 0;
61 Klass* VM_RedefineClasses::_the_class_oop = NULL;
62
63
64 VM_RedefineClasses::VM_RedefineClasses(jint class_count,
65 const jvmtiClassDefinition *class_defs,
66 JvmtiClassLoadKind class_load_kind) {
67 _class_count = class_count;
68 _class_defs = class_defs;
69 _class_load_kind = class_load_kind;
70 _res = JVMTI_ERROR_NONE;
71 }
72
73 static inline InstanceKlass* get_ik(jclass def) {
74 oop mirror = JNIHandles::resolve_non_null(def);
75 return InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
76 }
77
78 // If any of the classes are being redefined, wait
79 // Parallel constant pool merging leads to indeterminate constant pools.
80 void VM_RedefineClasses::lock_classes() {
81 MutexLocker ml(RedefineClasses_lock);
210
211 // check_class() is optionally called for product bits, but is
212 // always called for non-product bits.
213 #ifdef PRODUCT
214 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
215 #endif
216 log_trace(redefine, class, obsolete, metadata)("calling check_class");
217 CheckClass check_class(thread);
218 ClassLoaderDataGraph::classes_do(&check_class);
219 #ifdef PRODUCT
220 }
221 #endif
222 }
223
224 void VM_RedefineClasses::doit_epilogue() {
225 unlock_classes();
226
227 // Free os::malloc allocated memory.
228 os::free(_scratch_classes);
229
230 // Reset the_class_oop to null for error printing.
231 _the_class_oop = NULL;
232
233 if (log_is_enabled(Info, redefine, class, timer)) {
234 // Used to have separate timers for "doit" and "all", but the timer
235 // overhead skewed the measurements.
236 jlong doit_time = _timer_rsc_phase1.milliseconds() +
237 _timer_rsc_phase2.milliseconds();
238 jlong all_time = _timer_vm_op_prologue.milliseconds() + doit_time;
239
240 log_info(redefine, class, timer)
241 ("vm_op: all=" UINT64_FORMAT " prologue=" UINT64_FORMAT " doit=" UINT64_FORMAT,
242 all_time, _timer_vm_op_prologue.milliseconds(), doit_time);
243 log_info(redefine, class, timer)
244 ("redefine_single_class: phase1=" UINT64_FORMAT " phase2=" UINT64_FORMAT,
245 _timer_rsc_phase1.milliseconds(), _timer_rsc_phase2.milliseconds());
246 }
247 }
248
249 bool VM_RedefineClasses::is_modifiable_class(oop klass_mirror) {
250 // classes for primitives cannot be redefined
251 if (java_lang_Class::is_primitive(klass_mirror)) {
640
641 if (log_is_enabled(Trace, redefine, class, constantpool)) {
642 // don't want to loop unless we are tracing
643 int count = 0;
644 for (int i = 1; i < _operands_index_map_p->length(); i++) {
645 int value = _operands_index_map_p->at(i);
646 if (value != -1) {
647 log_trace(redefine, class, constantpool)("operands_index_map[%d]: old=%d new=%d", count, i, value);
648 count++;
649 }
650 }
651 }
652 // Clean-up
653 _operands_index_map_p = NULL;
654 _operands_cur_length = 0;
655 _operands_index_map_count = 0;
656 } // end finalize_operands_merge()
657
658
659 jvmtiError VM_RedefineClasses::compare_and_normalize_class_versions(
660 instanceKlassHandle the_class,
661 instanceKlassHandle scratch_class) {
662 int i;
663
664 // Check superclasses, or rather their names, since superclasses themselves can be
665 // requested to replace.
666 // Check for NULL superclass first since this might be java.lang.Object
667 if (the_class->super() != scratch_class->super() &&
668 (the_class->super() == NULL || scratch_class->super() == NULL ||
669 the_class->super()->name() !=
670 scratch_class->super()->name())) {
671 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
672 }
673
674 // 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 implemented
676 // interfaces are the same, i.e. the order of declaration (which, however, if changed in the
677 // .java file, also changes in .class file) should not matter. However, comparing sets is
678 // technically a bit more difficult, and, more importantly, I am not sure at present that the
679 // order of interfaces does not matter on the implementation level, i.e. that the VM does not
680 // rely on it somewhere.
681 Array<Klass*>* k_interfaces = the_class->local_interfaces();
976 return false; // wrong entry type; not our special case
977 }
978
979 if (t1 == t2) {
980 return false; // not a mismatch; not our special case
981 }
982
983 char *s1 = cp1->klass_name_at(index1)->as_C_string();
984 char *s2 = cp2->klass_name_at(index2)->as_C_string();
985 if (strcmp(s1, s2) != 0) {
986 return false; // strings don't match; not our special case
987 }
988
989 return true; // made it through the gauntlet; this is our special case
990 } // end is_unresolved_class_mismatch()
991
992
993 jvmtiError VM_RedefineClasses::load_new_class_versions(TRAPS) {
994
995 // For consistency allocate memory using os::malloc wrapper.
996 _scratch_classes = (Klass**)
997 os::malloc(sizeof(Klass*) * _class_count, mtClass);
998 if (_scratch_classes == NULL) {
999 return JVMTI_ERROR_OUT_OF_MEMORY;
1000 }
1001 // Zero initialize the _scratch_classes array.
1002 for (int i = 0; i < _class_count; i++) {
1003 _scratch_classes[i] = NULL;
1004 }
1005
1006 ResourceMark rm(THREAD);
1007
1008 JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
1009 // state can only be NULL if the current thread is exiting which
1010 // should not happen since we're trying to do a RedefineClasses
1011 guarantee(state != NULL, "exiting thread calling load_new_class_versions");
1012 for (int i = 0; i < _class_count; i++) {
1013 // Create HandleMark so that any handles created while loading new class
1014 // versions are deleted. Constant pools are deallocated while merging
1015 // constant pools
1016 HandleMark hm(THREAD);
1017 instanceKlassHandle the_class(THREAD, get_ik(_class_defs[i].klass));
1018 Symbol* the_class_sym = the_class->name();
1019
1020 log_debug(redefine, class, load)
1021 ("loading name=%s kind=%d (avail_mem=" UINT64_FORMAT "K)",
1022 the_class->external_name(), _class_load_kind, os::available_memory() >> 10);
1023
1024 ClassFileStream st((u1*)_class_defs[i].class_bytes,
1025 _class_defs[i].class_byte_count,
1026 "__VM_RedefineClasses__",
1027 ClassFileStream::verify);
1028
1029 // Parse the stream.
1030 Handle the_class_loader(THREAD, the_class->class_loader());
1031 Handle 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 file
1034 // load hook event.
1035 state->set_class_being_redefined(&the_class, _class_load_kind);
1036
1037 Klass* k = SystemDictionary::parse_stream(the_class_sym,
1038 the_class_loader,
1039 protection_domain,
1040 &st,
1041 THREAD);
1042 // Clear class_being_redefined just to be sure.
1043 state->clear_class_being_redefined();
1044
1045 // TODO: if this is retransform, and nothing changed we can skip it
1046
1047 instanceKlassHandle scratch_class (THREAD, k);
1048
1049 // Need to clean up allocated InstanceKlass if there's an error so assign
1050 // the result here. Caller deallocates all the scratch classes in case of
1051 // an error.
1052 _scratch_classes[i] = k;
1053
1054 if (HAS_PENDING_EXCEPTION) {
1055 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1056 log_info(redefine, class, load, exceptions)("parse_stream exception: '%s'", ex_name->as_C_string());
1057 CLEAR_PENDING_EXCEPTION;
1058
1059 if (ex_name == vmSymbols::java_lang_UnsupportedClassVersionError()) {
1060 return JVMTI_ERROR_UNSUPPORTED_VERSION;
1061 } else if (ex_name == vmSymbols::java_lang_ClassFormatError()) {
1062 return JVMTI_ERROR_INVALID_CLASS_FORMAT;
1063 } else if (ex_name == vmSymbols::java_lang_ClassCircularityError()) {
1064 return JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION;
1065 } else if (ex_name == vmSymbols::java_lang_NoClassDefFoundError()) {
1066 // The message will be "XXX (wrong name: YYY)"
1067 return JVMTI_ERROR_NAMES_DONT_MATCH;
1068 } else if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1069 return JVMTI_ERROR_OUT_OF_MEMORY;
1070 } else { // Just in case more exceptions can be thrown..
1071 return JVMTI_ERROR_FAILS_VERIFICATION;
1072 }
1089
1090 // Do the validity checks in compare_and_normalize_class_versions()
1091 // before verifying the byte codes. By doing these checks first, we
1092 // limit the number of functions that require redirection from
1093 // the_class to scratch_class. In particular, we don't have to
1094 // modify JNI GetSuperclass() and thus won't change its performance.
1095 jvmtiError res = compare_and_normalize_class_versions(the_class,
1096 scratch_class);
1097 if (res != JVMTI_ERROR_NONE) {
1098 return res;
1099 }
1100
1101 // verify what the caller passed us
1102 {
1103 // The bug 6214132 caused the verification to fail.
1104 // Information about the_class and scratch_class is temporarily
1105 // recorded into jvmtiThreadState. This data is used to redirect
1106 // the_class to scratch_class in the JVM_* functions called by the
1107 // verifier. Please, refer to jvmtiThreadState.hpp for the detailed
1108 // description.
1109 RedefineVerifyMark rvm(&the_class, &scratch_class, state);
1110 Verifier::verify(
1111 scratch_class, Verifier::ThrowException, true, THREAD);
1112 }
1113
1114 if (HAS_PENDING_EXCEPTION) {
1115 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1116 log_info(redefine, class, load, exceptions)("verify_byte_codes exception: '%s'", ex_name->as_C_string());
1117 CLEAR_PENDING_EXCEPTION;
1118 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1119 return JVMTI_ERROR_OUT_OF_MEMORY;
1120 } else {
1121 // tell the caller the bytecodes are bad
1122 return JVMTI_ERROR_FAILS_VERIFICATION;
1123 }
1124 }
1125
1126 res = merge_cp_and_rewrite(the_class, scratch_class, THREAD);
1127 if (HAS_PENDING_EXCEPTION) {
1128 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1129 log_info(redefine, class, load, exceptions)("merge_cp_and_rewrite exception: '%s'", ex_name->as_C_string());
1130 CLEAR_PENDING_EXCEPTION;
1131 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1132 return JVMTI_ERROR_OUT_OF_MEMORY;
1133 } else {
1134 return JVMTI_ERROR_INTERNAL;
1135 }
1136 }
1137
1138 if (VerifyMergedCPBytecodes) {
1139 // verify what we have done during constant pool merging
1140 {
1141 RedefineVerifyMark rvm(&the_class, &scratch_class, state);
1142 Verifier::verify(scratch_class, Verifier::ThrowException, true, THREAD);
1143 }
1144
1145 if (HAS_PENDING_EXCEPTION) {
1146 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1147 log_info(redefine, class, load, exceptions)
1148 ("verify_byte_codes post merge-CP exception: '%s'", ex_name->as_C_string());
1149 CLEAR_PENDING_EXCEPTION;
1150 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1151 return JVMTI_ERROR_OUT_OF_MEMORY;
1152 } else {
1153 // tell the caller that constant pool merging screwed up
1154 return JVMTI_ERROR_INTERNAL;
1155 }
1156 }
1157 }
1158
1159 Rewriter::rewrite(scratch_class, THREAD);
1160 if (!HAS_PENDING_EXCEPTION) {
1161 scratch_class->link_methods(THREAD);
1417 class MergeCPCleaner {
1418 ClassLoaderData* _loader_data;
1419 ConstantPool* _cp;
1420 ConstantPool* _scratch_cp;
1421 public:
1422 MergeCPCleaner(ClassLoaderData* loader_data, ConstantPool* merge_cp) :
1423 _loader_data(loader_data), _cp(merge_cp), _scratch_cp(NULL) {}
1424 ~MergeCPCleaner() {
1425 _loader_data->add_to_deallocate_list(_cp);
1426 if (_scratch_cp != NULL) {
1427 _loader_data->add_to_deallocate_list(_scratch_cp);
1428 }
1429 }
1430 void add_scratch_cp(ConstantPool* scratch_cp) { _scratch_cp = scratch_cp; }
1431 };
1432
1433 // Merge constant pools between the_class and scratch_class and
1434 // potentially rewrite bytecodes in scratch_class to use the merged
1435 // constant pool.
1436 jvmtiError VM_RedefineClasses::merge_cp_and_rewrite(
1437 instanceKlassHandle the_class, instanceKlassHandle scratch_class,
1438 TRAPS) {
1439 // worst case merged constant pool length is old and new combined
1440 int merge_cp_length = the_class->constants()->length()
1441 + scratch_class->constants()->length();
1442
1443 // Constant pools are not easily reused so we allocate a new one
1444 // each time.
1445 // merge_cp is created unsafe for concurrent GC processing. It
1446 // should be marked safe before discarding it. Even though
1447 // garbage, if it crosses a card boundary, it may be scanned
1448 // in order to find the start of the first complete object on the card.
1449 ClassLoaderData* loader_data = the_class->class_loader_data();
1450 ConstantPool* merge_cp_oop =
1451 ConstantPool::allocate(loader_data,
1452 merge_cp_length,
1453 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1454 MergeCPCleaner cp_cleaner(loader_data, merge_cp_oop);
1455
1456 HandleMark hm(THREAD); // make sure handles are cleared before
1457 // MergeCPCleaner clears out merge_cp_oop
1466 // an error.
1467 if (merge_cp_length != the_class->constants()->length()
1468 + scratch_class->constants()->length()) {
1469 return JVMTI_ERROR_INTERNAL;
1470 }
1471
1472 // Update the version number of the constant pools (may keep scratch_cp)
1473 merge_cp->increment_and_save_version(old_cp->version());
1474 scratch_cp->increment_and_save_version(old_cp->version());
1475
1476 ResourceMark rm(THREAD);
1477 _index_map_count = 0;
1478 _index_map_p = new intArray(scratch_cp->length(), scratch_cp->length(), -1);
1479
1480 _operands_cur_length = ConstantPool::operand_array_length(old_cp->operands());
1481 _operands_index_map_count = 0;
1482 int operands_index_map_len = ConstantPool::operand_array_length(scratch_cp->operands());
1483 _operands_index_map_p = new intArray(operands_index_map_len, operands_index_map_len, -1);
1484
1485 // reference to the cp holder is needed for copy_operands()
1486 merge_cp->set_pool_holder(scratch_class());
1487 bool result = merge_constant_pools(old_cp, scratch_cp, &merge_cp,
1488 &merge_cp_length, THREAD);
1489 merge_cp->set_pool_holder(NULL);
1490
1491 if (!result) {
1492 // The merge can fail due to memory allocation failure or due
1493 // to robustness checks.
1494 return JVMTI_ERROR_INTERNAL;
1495 }
1496
1497 log_info(redefine, class, constantpool)("merge_cp_len=%d, index_map_len=%d", merge_cp_length, _index_map_count);
1498
1499 if (_index_map_count == 0) {
1500 // there is nothing to map between the new and merged constant pools
1501
1502 if (old_cp->length() == scratch_cp->length()) {
1503 // The old and new constant pools are the same length and the
1504 // index map is empty. This means that the three constant pools
1505 // are equivalent (but not the same). Unfortunately, the new
1506 // constant pool has not gone through link resolution nor have
1551 if (!rewrite_cp_refs(scratch_class, THREAD)) {
1552 return JVMTI_ERROR_INTERNAL;
1553 }
1554
1555 // Replace the new constant pool with a shrunken copy of the
1556 // merged constant pool so now the rewritten bytecodes have
1557 // valid references; the previous new constant pool will get
1558 // GCed.
1559 set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,
1560 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1561 // The new constant pool replaces scratch_cp so have cleaner clean it up.
1562 // It can't be cleaned up while there are handles to it.
1563 cp_cleaner.add_scratch_cp(scratch_cp());
1564 }
1565
1566 return JVMTI_ERROR_NONE;
1567 } // end merge_cp_and_rewrite()
1568
1569
1570 // Rewrite constant pool references in klass scratch_class.
1571 bool VM_RedefineClasses::rewrite_cp_refs(instanceKlassHandle scratch_class,
1572 TRAPS) {
1573
1574 // rewrite constant pool references in the methods:
1575 if (!rewrite_cp_refs_in_methods(scratch_class, THREAD)) {
1576 // propagate failure back to caller
1577 return false;
1578 }
1579
1580 // rewrite constant pool references in the class_annotations:
1581 if (!rewrite_cp_refs_in_class_annotations(scratch_class, THREAD)) {
1582 // propagate failure back to caller
1583 return false;
1584 }
1585
1586 // rewrite constant pool references in the fields_annotations:
1587 if (!rewrite_cp_refs_in_fields_annotations(scratch_class, THREAD)) {
1588 // propagate failure back to caller
1589 return false;
1590 }
1591
1638 u2 new_source_file_name_idx = find_new_index(source_file_name_idx);
1639 if (new_source_file_name_idx != 0) {
1640 scratch_class->set_source_file_name_index(new_source_file_name_idx);
1641 }
1642 }
1643
1644 // rewrite class generic signature index:
1645 u2 generic_signature_index = scratch_class->generic_signature_index();
1646 if (generic_signature_index != 0) {
1647 u2 new_generic_signature_index = find_new_index(generic_signature_index);
1648 if (new_generic_signature_index != 0) {
1649 scratch_class->set_generic_signature_index(new_generic_signature_index);
1650 }
1651 }
1652
1653 return true;
1654 } // end rewrite_cp_refs()
1655
1656 // Rewrite constant pool references in the methods.
1657 bool VM_RedefineClasses::rewrite_cp_refs_in_methods(
1658 instanceKlassHandle scratch_class, TRAPS) {
1659
1660 Array<Method*>* methods = scratch_class->methods();
1661
1662 if (methods == NULL || methods->length() == 0) {
1663 // no methods so nothing to do
1664 return true;
1665 }
1666
1667 // rewrite constant pool references in the methods:
1668 for (int i = methods->length() - 1; i >= 0; i--) {
1669 methodHandle method(THREAD, methods->at(i));
1670 methodHandle new_method;
1671 rewrite_cp_refs_in_method(method, &new_method, THREAD);
1672 if (!new_method.is_null()) {
1673 // the method has been replaced so save the new method version
1674 // even in the case of an exception. original method is on the
1675 // deallocation list.
1676 methods->at_put(i, new_method());
1677 }
1678 if (HAS_PENDING_EXCEPTION) {
1817
1818 // We also need to rewrite the parameter name indexes, if there is
1819 // method parameter data present
1820 if(method->has_method_parameters()) {
1821 const int len = method->method_parameters_length();
1822 MethodParametersElement* elem = method->method_parameters_start();
1823
1824 for (int i = 0; i < len; i++) {
1825 const u2 cp_index = elem[i].name_cp_index;
1826 const u2 new_cp_index = find_new_index(cp_index);
1827 if (new_cp_index != 0) {
1828 elem[i].name_cp_index = new_cp_index;
1829 }
1830 }
1831 }
1832 } // end rewrite_cp_refs_in_method()
1833
1834
1835 // Rewrite constant pool references in the class_annotations field.
1836 bool VM_RedefineClasses::rewrite_cp_refs_in_class_annotations(
1837 instanceKlassHandle scratch_class, TRAPS) {
1838
1839 AnnotationArray* class_annotations = scratch_class->class_annotations();
1840 if (class_annotations == NULL || class_annotations->length() == 0) {
1841 // no class_annotations so nothing to do
1842 return true;
1843 }
1844
1845 log_debug(redefine, class, annotation)("class_annotations length=%d", class_annotations->length());
1846
1847 int byte_i = 0; // byte index into class_annotations
1848 return rewrite_cp_refs_in_annotations_typeArray(class_annotations, byte_i,
1849 THREAD);
1850 }
1851
1852
1853 // Rewrite constant pool references in an annotations typeArray. This
1854 // "structure" is adapted from the RuntimeVisibleAnnotations_attribute
1855 // that is described in section 4.8.15 of the 2nd-edition of the VM spec:
1856 //
1857 // annotations_typeArray {
2107 annotations_typeArray, byte_i_ref, THREAD)) {
2108 log_debug(redefine, class, annotation)("bad nested element_value at %d", calc_num_values);
2109 // propagate failure back to caller
2110 return false;
2111 }
2112 }
2113 assert(num_values == calc_num_values, "sanity check");
2114 } break;
2115
2116 default:
2117 log_debug(redefine, class, annotation)("bad tag=0x%x", tag);
2118 return false;
2119 } // end decode tag field
2120
2121 return true;
2122 } // end rewrite_cp_refs_in_element_value()
2123
2124
2125 // Rewrite constant pool references in a fields_annotations field.
2126 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations(
2127 instanceKlassHandle scratch_class, TRAPS) {
2128
2129 Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations();
2130
2131 if (fields_annotations == NULL || fields_annotations->length() == 0) {
2132 // no fields_annotations so nothing to do
2133 return true;
2134 }
2135
2136 log_debug(redefine, class, annotation)("fields_annotations length=%d", fields_annotations->length());
2137
2138 for (int i = 0; i < fields_annotations->length(); i++) {
2139 AnnotationArray* field_annotations = fields_annotations->at(i);
2140 if (field_annotations == NULL || field_annotations->length() == 0) {
2141 // this field does not have any annotations so skip it
2142 continue;
2143 }
2144
2145 int byte_i = 0; // byte index into field_annotations
2146 if (!rewrite_cp_refs_in_annotations_typeArray(field_annotations, byte_i,
2147 THREAD)) {
2148 log_debug(redefine, class, annotation)("bad field_annotations at %d", i);
2149 // propagate failure back to caller
2150 return false;
2151 }
2152 }
2153
2154 return true;
2155 } // end rewrite_cp_refs_in_fields_annotations()
2156
2157
2158 // Rewrite constant pool references in a methods_annotations field.
2159 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations(
2160 instanceKlassHandle scratch_class, TRAPS) {
2161
2162 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2163 Method* m = scratch_class->methods()->at(i);
2164 AnnotationArray* method_annotations = m->constMethod()->method_annotations();
2165
2166 if (method_annotations == NULL || method_annotations->length() == 0) {
2167 // this method does not have any annotations so skip it
2168 continue;
2169 }
2170
2171 int byte_i = 0; // byte index into method_annotations
2172 if (!rewrite_cp_refs_in_annotations_typeArray(method_annotations, byte_i,
2173 THREAD)) {
2174 log_debug(redefine, class, annotation)("bad method_annotations at %d", i);
2175 // propagate failure back to caller
2176 return false;
2177 }
2178 }
2179
2180 return true;
2181 } // end rewrite_cp_refs_in_methods_annotations()
2182
2183
2184 // Rewrite constant pool references in a methods_parameter_annotations
2185 // field. This "structure" is adapted from the
2186 // RuntimeVisibleParameterAnnotations_attribute described in section
2187 // 4.8.17 of the 2nd-edition of the VM spec:
2188 //
2189 // methods_parameter_annotations_typeArray {
2190 // u1 num_parameters;
2191 // {
2192 // u2 num_annotations;
2193 // annotation annotations[num_annotations];
2194 // } parameter_annotations[num_parameters];
2195 // }
2196 //
2197 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations(
2198 instanceKlassHandle scratch_class, TRAPS) {
2199
2200 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2201 Method* m = scratch_class->methods()->at(i);
2202 AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations();
2203 if (method_parameter_annotations == NULL
2204 || method_parameter_annotations->length() == 0) {
2205 // this method does not have any parameter annotations so skip it
2206 continue;
2207 }
2208
2209 if (method_parameter_annotations->length() < 1) {
2210 // not enough room for a num_parameters field
2211 log_debug(redefine, class, annotation)("length() is too small for a num_parameters field at %d", i);
2212 return false;
2213 }
2214
2215 int byte_i = 0; // byte index into method_parameter_annotations
2216
2217 u1 num_parameters = method_parameter_annotations->at(byte_i);
2218 byte_i++;
2227 // propagate failure back to caller
2228 return false;
2229 }
2230 }
2231 assert(num_parameters == calc_num_parameters, "sanity check");
2232 }
2233
2234 return true;
2235 } // end rewrite_cp_refs_in_methods_parameter_annotations()
2236
2237
2238 // Rewrite constant pool references in a methods_default_annotations
2239 // field. This "structure" is adapted from the AnnotationDefault_attribute
2240 // that is described in section 4.8.19 of the 2nd-edition of the VM spec:
2241 //
2242 // methods_default_annotations_typeArray {
2243 // element_value default_value;
2244 // }
2245 //
2246 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations(
2247 instanceKlassHandle scratch_class, TRAPS) {
2248
2249 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2250 Method* m = scratch_class->methods()->at(i);
2251 AnnotationArray* method_default_annotations = m->constMethod()->default_annotations();
2252 if (method_default_annotations == NULL
2253 || method_default_annotations->length() == 0) {
2254 // this method does not have any default annotations so skip it
2255 continue;
2256 }
2257
2258 int byte_i = 0; // byte index into method_default_annotations
2259
2260 if (!rewrite_cp_refs_in_element_value(
2261 method_default_annotations, byte_i, THREAD)) {
2262 log_debug(redefine, class, annotation)("bad default element_value at %d", i);
2263 // propagate failure back to caller
2264 return false;
2265 }
2266 }
2267
2268 return true;
2269 } // end rewrite_cp_refs_in_methods_default_annotations()
2270
2271
2272 // Rewrite constant pool references in a class_type_annotations field.
2273 bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations(
2274 instanceKlassHandle scratch_class, TRAPS) {
2275
2276 AnnotationArray* class_type_annotations = scratch_class->class_type_annotations();
2277 if (class_type_annotations == NULL || class_type_annotations->length() == 0) {
2278 // no class_type_annotations so nothing to do
2279 return true;
2280 }
2281
2282 log_debug(redefine, class, annotation)("class_type_annotations length=%d", class_type_annotations->length());
2283
2284 int byte_i = 0; // byte index into class_type_annotations
2285 return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations,
2286 byte_i, "ClassFile", THREAD);
2287 } // end rewrite_cp_refs_in_class_type_annotations()
2288
2289
2290 // Rewrite constant pool references in a fields_type_annotations field.
2291 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations(
2292 instanceKlassHandle scratch_class, TRAPS) {
2293
2294 Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations();
2295 if (fields_type_annotations == NULL || fields_type_annotations->length() == 0) {
2296 // no fields_type_annotations so nothing to do
2297 return true;
2298 }
2299
2300 log_debug(redefine, class, annotation)("fields_type_annotations length=%d", fields_type_annotations->length());
2301
2302 for (int i = 0; i < fields_type_annotations->length(); i++) {
2303 AnnotationArray* field_type_annotations = fields_type_annotations->at(i);
2304 if (field_type_annotations == NULL || field_type_annotations->length() == 0) {
2305 // this field does not have any annotations so skip it
2306 continue;
2307 }
2308
2309 int byte_i = 0; // byte index into field_type_annotations
2310 if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations,
2311 byte_i, "field_info", THREAD)) {
2312 log_debug(redefine, class, annotation)("bad field_type_annotations at %d", i);
2313 // propagate failure back to caller
2314 return false;
2315 }
2316 }
2317
2318 return true;
2319 } // end rewrite_cp_refs_in_fields_type_annotations()
2320
2321
2322 // Rewrite constant pool references in a methods_type_annotations field.
2323 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations(
2324 instanceKlassHandle scratch_class, TRAPS) {
2325
2326 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2327 Method* m = scratch_class->methods()->at(i);
2328 AnnotationArray* method_type_annotations = m->constMethod()->type_annotations();
2329
2330 if (method_type_annotations == NULL || method_type_annotations->length() == 0) {
2331 // this method does not have any annotations so skip it
2332 continue;
2333 }
2334
2335 log_debug(redefine, class, annotation)("methods type_annotations length=%d", method_type_annotations->length());
2336
2337 int byte_i = 0; // byte index into method_type_annotations
2338 if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations,
2339 byte_i, "method_info", THREAD)) {
2340 log_debug(redefine, class, annotation)("bad method_type_annotations at %d", i);
2341 // propagate failure back to caller
2342 return false;
2343 }
2344 }
3057 // }
3058 case ITEM_Uninitialized:
3059 assert(stackmap_p_ref + 2 <= stackmap_end, "no room for offset");
3060 stackmap_p_ref += 2;
3061 break;
3062
3063 default:
3064 log_debug(redefine, class, stackmap)("frame_i=%u, frame_type=%u, bad tag=0x%x", frame_i, frame_type, tag);
3065 ShouldNotReachHere();
3066 break;
3067 } // end switch (tag)
3068 } // end rewrite_cp_refs_in_verification_type_info()
3069
3070
3071 // Change the constant pool associated with klass scratch_class to
3072 // scratch_cp. If shrink is true, then scratch_cp_length elements
3073 // are copied from scratch_cp to a smaller constant pool and the
3074 // smaller constant pool is associated with scratch_class.
3075 void VM_RedefineClasses::set_new_constant_pool(
3076 ClassLoaderData* loader_data,
3077 instanceKlassHandle scratch_class, constantPoolHandle scratch_cp,
3078 int scratch_cp_length, TRAPS) {
3079 assert(scratch_cp->length() >= scratch_cp_length, "sanity check");
3080
3081 // scratch_cp is a merged constant pool and has enough space for a
3082 // worst case merge situation. We want to associate the minimum
3083 // sized constant pool with the klass to save space.
3084 ConstantPool* cp = ConstantPool::allocate(loader_data, scratch_cp_length, CHECK);
3085 constantPoolHandle smaller_cp(THREAD, cp);
3086
3087 // preserve version() value in the smaller copy
3088 int version = scratch_cp->version();
3089 assert(version != 0, "sanity check");
3090 smaller_cp->set_version(version);
3091
3092 // attach klass to new constant pool
3093 // reference to the cp holder is needed for copy_operands()
3094 smaller_cp->set_pool_holder(scratch_class());
3095
3096 scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
3097 if (HAS_PENDING_EXCEPTION) {
3098 // Exception is handled in the caller
3099 loader_data->add_to_deallocate_list(smaller_cp());
3100 return;
3101 }
3102 scratch_cp = smaller_cp;
3103
3104 // attach new constant pool to klass
3105 scratch_class->set_constants(scratch_cp());
3106
3107 int i; // for portability
3108
3109 // update each field in klass to use new constant pool indices as needed
3110 for (JavaFieldStream fs(scratch_class); !fs.done(); fs.next()) {
3111 jshort cur_index = fs.name_index();
3112 jshort new_index = find_new_index(cur_index);
3113 if (new_index != 0) {
3114 log_trace(redefine, class, constantpool)("field-name_index change: %d to %d", cur_index, new_index);
3251 }
3252 } // end for each local variable table entry
3253 } // end if there are local variable table entries
3254
3255 rewrite_cp_refs_in_stack_map_table(method, THREAD);
3256 } // end for each method
3257 } // end set_new_constant_pool()
3258
3259
3260 // Unevolving classes may point to methods of the_class directly
3261 // from their constant pool caches, itables, and/or vtables. We
3262 // use the ClassLoaderDataGraph::classes_do() facility and this helper
3263 // to fix up these pointers.
3264
3265 // Adjust cpools and vtables closure
3266 void VM_RedefineClasses::AdjustCpoolCacheAndVtable::do_klass(Klass* k) {
3267
3268 // This is a very busy routine. We don't want too much tracing
3269 // printed out.
3270 bool trace_name_printed = false;
3271 InstanceKlass *the_class = InstanceKlass::cast(_the_class_oop);
3272
3273 // If the class being redefined is java.lang.Object, we need to fix all
3274 // array class vtables also
3275 if (k->is_array_klass() && _the_class_oop == SystemDictionary::Object_klass()) {
3276 k->vtable()->adjust_method_entries(the_class, &trace_name_printed);
3277
3278 } else if (k->is_instance_klass()) {
3279 HandleMark hm(_thread);
3280 InstanceKlass *ik = InstanceKlass::cast(k);
3281
3282 // HotSpot specific optimization! HotSpot does not currently
3283 // support delegation from the bootstrap class loader to a
3284 // user-defined class loader. This means that if the bootstrap
3285 // class loader is the initiating class loader, then it will also
3286 // be the defining class loader. This also means that classes
3287 // loaded by the bootstrap class loader cannot refer to classes
3288 // loaded by a user-defined class loader. Note: a user-defined
3289 // class loader can delegate to the bootstrap class loader.
3290 //
3291 // If the current class being redefined has a user-defined class
3292 // loader as its defining class loader, then we can skip all
3293 // classes loaded by the bootstrap class loader.
3294 bool is_user_defined =
3295 InstanceKlass::cast(_the_class_oop)->class_loader() != NULL;
3296 if (is_user_defined && ik->class_loader() == NULL) {
3297 return;
3298 }
3299
3300 // Fix the vtable embedded in the_class and subclasses of the_class,
3301 // if one exists. We discard scratch_class and we don't keep an
3302 // InstanceKlass around to hold obsolete methods so we don't have
3303 // any other InstanceKlass embedded vtables to update. The vtable
3304 // holds the Method*s for virtual (but not final) methods.
3305 // Default methods, or concrete methods in interfaces are stored
3306 // in the vtable, so if an interface changes we need to check
3307 // adjust_method_entries() for every InstanceKlass, which will also
3308 // adjust the default method vtable indices.
3309 // We also need to adjust any default method entries that are
3310 // not yet in the vtable, because the vtable setup is in progress.
3311 // This must be done after we adjust the default_methods and
3312 // default_vtable_indices for methods already in the vtable.
3313 // If redefining Unsafe, walk all the vtables looking for entries.
3314 if (ik->vtable_length() > 0 && (_the_class_oop->is_interface()
3315 || _the_class_oop == SystemDictionary::internal_Unsafe_klass()
3316 || ik->is_subtype_of(_the_class_oop))) {
3317 // ik->vtable() creates a wrapper object; rm cleans it up
3318 ResourceMark rm(_thread);
3319
3320 ik->vtable()->adjust_method_entries(the_class, &trace_name_printed);
3321 ik->adjust_default_methods(the_class, &trace_name_printed);
3322 }
3323
3324 // If the current class has an itable and we are either redefining an
3325 // interface or if the current class is a subclass of the_class, then
3326 // we potentially have to fix the itable. If we are redefining an
3327 // interface, then we have to call adjust_method_entries() for
3328 // every InstanceKlass that has an itable since there isn't a
3329 // subclass relationship between an interface and an InstanceKlass.
3330 // If redefining Unsafe, walk all the itables looking for entries.
3331 if (ik->itable_length() > 0 && (_the_class_oop->is_interface()
3332 || _the_class_oop == SystemDictionary::internal_Unsafe_klass()
3333 || ik->is_subclass_of(_the_class_oop))) {
3334 // ik->itable() creates a wrapper object; rm cleans it up
3335 ResourceMark rm(_thread);
3336
3337 ik->itable()->adjust_method_entries(the_class, &trace_name_printed);
3338 }
3339
3340 // The constant pools in other classes (other_cp) can refer to
3341 // methods in the_class. We have to update method information in
3342 // other_cp's cache. If other_cp has a previous version, then we
3343 // have to repeat the process for each previous version. The
3344 // constant pool cache holds the Method*s for non-virtual
3345 // methods and for virtual, final methods.
3346 //
3347 // Special case: if the current class is the_class, then new_cp
3348 // has already been attached to the_class and old_cp has already
3349 // been added as a previous version. The new_cp doesn't have any
3350 // cached references to old methods so it doesn't need to be
3351 // updated. We can simply start with the previous version(s) in
3352 // that case.
3353 constantPoolHandle other_cp;
3354 ConstantPoolCache* cp_cache;
3355
3356 if (ik != _the_class_oop) {
3357 // this klass' constant pool cache may need adjustment
3358 other_cp = constantPoolHandle(ik->constants());
3359 cp_cache = other_cp->cache();
3360 if (cp_cache != NULL) {
3361 cp_cache->adjust_method_entries(the_class, &trace_name_printed);
3362 }
3363 }
3364
3365 // the previous versions' constant pool caches may need adjustment
3366 for (InstanceKlass* pv_node = ik->previous_versions();
3367 pv_node != NULL;
3368 pv_node = pv_node->previous_versions()) {
3369 cp_cache = pv_node->constants()->cache();
3370 if (cp_cache != NULL) {
3371 cp_cache->adjust_method_entries(pv_node, &trace_name_printed);
3372 }
3373 }
3374 }
3375 }
3376
3482 // Count number of methods that are EMCP. The method will be marked
3483 // old but not obsolete if it is EMCP.
3484 emcp_method_count++;
3485
3486 // An EMCP method is _not_ obsolete. An obsolete method has a
3487 // different jmethodID than the current method. An EMCP method
3488 // has the same jmethodID as the current method. Having the
3489 // same jmethodID for all EMCP versions of a method allows for
3490 // a consistent view of the EMCP methods regardless of which
3491 // EMCP method you happen to have in hand. For example, a
3492 // breakpoint set in one EMCP method will work for all EMCP
3493 // versions of the method including the current one.
3494 } else {
3495 // mark obsolete methods as such
3496 old_method->set_is_obsolete();
3497 obsolete_count++;
3498
3499 // obsolete methods need a unique idnum so they become new entries in
3500 // the jmethodID cache in InstanceKlass
3501 assert(old_method->method_idnum() == new_method->method_idnum(), "must match");
3502 u2 num = InstanceKlass::cast(_the_class_oop)->next_method_idnum();
3503 if (num != ConstMethod::UNSET_IDNUM) {
3504 old_method->set_method_idnum(num);
3505 }
3506
3507 // With tracing we try not to "yack" too much. The position of
3508 // this trace assumes there are fewer obsolete methods than
3509 // EMCP methods.
3510 if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3511 ResourceMark rm;
3512 log_trace(redefine, class, obsolete, mark)
3513 ("mark %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3514 }
3515 }
3516 old_method->set_is_old();
3517 }
3518 for (int i = 0; i < _deleted_methods_length; ++i) {
3519 Method* old_method = _deleted_methods[i];
3520
3521 assert(!old_method->has_vtable_index(),
3522 "cannot delete methods with vtable entries");;
3546 // native methods and the complex cases of native method prefixes being added and/or
3547 // removed.
3548 // It expects only to be used during the VM_RedefineClasses op (a safepoint).
3549 //
3550 // This class is used after the new methods have been installed in "the_class".
3551 //
3552 // So, for example, the following must be handled. Where 'm' is a method and
3553 // a number followed by an underscore is a prefix.
3554 //
3555 // Old Name New Name
3556 // Simple transfer to new method m -> m
3557 // Add prefix m -> 1_m
3558 // Remove prefix 1_m -> m
3559 // Simultaneous add of prefixes m -> 3_2_1_m
3560 // Simultaneous removal of prefixes 3_2_1_m -> m
3561 // Simultaneous add and remove 1_m -> 2_m
3562 // Same, caused by prefix removal only 3_2_1_m -> 3_2_m
3563 //
3564 class TransferNativeFunctionRegistration {
3565 private:
3566 instanceKlassHandle the_class;
3567 int prefix_count;
3568 char** prefixes;
3569
3570 // Recursively search the binary tree of possibly prefixed method names.
3571 // Iteration could be used if all agents were well behaved. Full tree walk is
3572 // more resilent to agents not cleaning up intermediate methods.
3573 // Branch at each depth in the binary tree is:
3574 // (1) without the prefix.
3575 // (2) with the prefix.
3576 // where 'prefix' is the prefix at that 'depth' (first prefix, second prefix,...)
3577 Method* search_prefix_name_space(int depth, char* name_str, size_t name_len,
3578 Symbol* signature) {
3579 TempNewSymbol name_symbol = SymbolTable::probe(name_str, (int)name_len);
3580 if (name_symbol != NULL) {
3581 Method* method = the_class()->lookup_method(name_symbol, signature);
3582 if (method != NULL) {
3583 // Even if prefixed, intermediate methods must exist.
3584 if (method->is_native()) {
3585 // Wahoo, we found a (possibly prefixed) version of the method, return it.
3586 return method;
3587 }
3588 if (depth < prefix_count) {
3589 // Try applying further prefixes (other than this one).
3590 method = search_prefix_name_space(depth+1, name_str, name_len, signature);
3591 if (method != NULL) {
3592 return method; // found
3593 }
3594
3595 // Try adding this prefix to the method name and see if it matches
3596 // another method name.
3597 char* prefix = prefixes[depth];
3598 size_t prefix_len = strlen(prefix);
3599 size_t trial_len = name_len + prefix_len;
3600 char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
3601 strcpy(trial_name_str, prefix);
3624 size_t prefix_len = strlen(prefix);
3625 if (strncmp(prefix, name_str, prefix_len) == 0) {
3626 name_str += prefix_len;
3627 }
3628 }
3629 return name_str;
3630 }
3631
3632 // Strip any prefixes off the old native method, then try to find a
3633 // (possibly prefixed) new native that matches it.
3634 Method* strip_and_search_for_new_native(Method* method) {
3635 ResourceMark rm;
3636 char* name_str = method_name_without_prefixes(method);
3637 return search_prefix_name_space(0, name_str, strlen(name_str),
3638 method->signature());
3639 }
3640
3641 public:
3642
3643 // Construct a native method transfer processor for this class.
3644 TransferNativeFunctionRegistration(instanceKlassHandle _the_class) {
3645 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
3646
3647 the_class = _the_class;
3648 prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
3649 }
3650
3651 // Attempt to transfer any of the old or deleted methods that are native
3652 void transfer_registrations(Method** old_methods, int methods_length) {
3653 for (int j = 0; j < methods_length; j++) {
3654 Method* old_method = old_methods[j];
3655
3656 if (old_method->is_native() && old_method->has_native_function()) {
3657 Method* new_method = strip_and_search_for_new_native(old_method);
3658 if (new_method != NULL) {
3659 // Actually set the native function in the new method.
3660 // Redefine does not send events (except CFLH), certainly not this
3661 // behind the scenes re-registration.
3662 new_method->set_native_function(old_method->native_function(),
3663 !Method::native_bind_event_is_interesting);
3664 }
3665 }
3666 }
3667 }
3668 };
3669
3670 // Don't lose the association between a native method and its JNI function.
3671 void VM_RedefineClasses::transfer_old_native_function_registrations(instanceKlassHandle the_class) {
3672 TransferNativeFunctionRegistration transfer(the_class);
3673 transfer.transfer_registrations(_deleted_methods, _deleted_methods_length);
3674 transfer.transfer_registrations(_matching_old_methods, _matching_methods_length);
3675 }
3676
3677 // Deoptimize all compiled code that depends on this class.
3678 //
3679 // If the can_redefine_classes capability is obtained in the onload
3680 // phase then the compiler has recorded all dependencies from startup.
3681 // In that case we need only deoptimize and throw away all compiled code
3682 // that depends on the class.
3683 //
3684 // If can_redefine_classes is obtained sometime after the onload
3685 // phase then the dependency information may be incomplete. In that case
3686 // the first call to RedefineClasses causes all compiled code to be
3687 // thrown away. As can_redefine_classes has been obtained then
3688 // all future compilations will record dependencies so second and
3689 // subsequent calls to RedefineClasses need only throw away code
3690 // that depends on the class.
3691 //
3692 void VM_RedefineClasses::flush_dependent_code(instanceKlassHandle k_h, TRAPS) {
3693 assert_locked_or_safepoint(Compile_lock);
3694
3695 // All dependencies have been recorded from startup or this is a second or
3696 // subsequent use of RedefineClasses
3697 if (JvmtiExport::all_dependencies_are_recorded()) {
3698 CodeCache::flush_evol_dependents_on(k_h);
3699 } else {
3700 CodeCache::mark_all_nmethods_for_deoptimization();
3701
3702 ResourceMark rm(THREAD);
3703 DeoptimizationMarker dm;
3704
3705 // Deoptimize all activations depending on marked nmethods
3706 Deoptimization::deoptimize_dependents();
3707
3708 // Make the dependent methods not entrant
3709 CodeCache::make_marked_nmethods_not_entrant();
3710
3711 // From now on we know that the dependency information is complete
3712 JvmtiExport::set_all_dependencies_are_recorded(true);
3713 }
3714 }
3715
3716 void VM_RedefineClasses::compute_added_deleted_matching_methods() {
3717 Method* old_method;
3718 Method* new_method;
3758 ++oj;
3759 }
3760 } else { // names don't match
3761 if (old_method->name()->fast_compare(new_method->name()) > 0) {
3762 // new method
3763 _added_methods[_added_methods_length++] = new_method;
3764 ++nj;
3765 } else {
3766 // deleted method
3767 _deleted_methods[_deleted_methods_length++] = old_method;
3768 ++oj;
3769 }
3770 }
3771 }
3772 }
3773 assert(_matching_methods_length + _deleted_methods_length == _old_methods->length(), "sanity");
3774 assert(_matching_methods_length + _added_methods_length == _new_methods->length(), "sanity");
3775 }
3776
3777
3778 void VM_RedefineClasses::swap_annotations(instanceKlassHandle the_class,
3779 instanceKlassHandle scratch_class) {
3780 // Swap annotation fields values
3781 Annotations* old_annotations = the_class->annotations();
3782 the_class->set_annotations(scratch_class->annotations());
3783 scratch_class->set_annotations(old_annotations);
3784 }
3785
3786
3787 // Install the redefinition of a class:
3788 // - house keeping (flushing breakpoints and caches, deoptimizing
3789 // dependent compiled code)
3790 // - replacing parts in the_class with parts from scratch_class
3791 // - adding a weak reference to track the obsolete but interesting
3792 // parts of the_class
3793 // - adjusting constant pool caches and vtables in other classes
3794 // that refer to methods in the_class. These adjustments use the
3795 // ClassLoaderDataGraph::classes_do() facility which only allows
3796 // a helper method to be specified. The interesting parameters
3797 // that we would like to pass to the helper method are saved in
3798 // static global fields in the VM operation.
3799 void VM_RedefineClasses::redefine_single_class(jclass the_jclass,
3800 Klass* scratch_class_oop, TRAPS) {
3801
3802 HandleMark hm(THREAD); // make sure handles from this call are freed
3803
3804 if (log_is_enabled(Info, redefine, class, timer)) {
3805 _timer_rsc_phase1.start();
3806 }
3807
3808 instanceKlassHandle scratch_class(THREAD, scratch_class_oop);
3809 instanceKlassHandle the_class(THREAD, get_ik(the_jclass));
3810
3811 // Remove all breakpoints in methods of this class
3812 JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
3813 jvmti_breakpoints.clearall_in_class_at_safepoint(the_class());
3814
3815 // Deoptimize all compiled code that depends on this class
3816 flush_dependent_code(the_class, THREAD);
3817
3818 _old_methods = the_class->methods();
3819 _new_methods = scratch_class->methods();
3820 _the_class_oop = the_class();
3821 compute_added_deleted_matching_methods();
3822 update_jmethod_ids();
3823
3824 // Attach new constant pool to the original klass. The original
3825 // klass still refers to the old constant pool (for now).
3826 scratch_class->constants()->set_pool_holder(the_class());
3827
3828 #if 0
3829 // In theory, with constant pool merging in place we should be able
3830 // to save space by using the new, merged constant pool in place of
3831 // the old constant pool(s). By "pool(s)" I mean the constant pool in
3832 // the klass version we are replacing now and any constant pool(s) in
3833 // previous versions of klass. Nice theory, doesn't work in practice.
3834 // When this code is enabled, even simple programs throw NullPointer
3835 // exceptions. I'm guessing that this is caused by some constant pool
3836 // cache difference between the new, merged constant pool and the
3837 // constant pool that was just being used by the klass. I'm keeping
3838 // this code around to archive the idea, but the code has to remain
3839 // disabled for now.
3840
3841 // Attach each old method to the new constant pool. This can be
3842 // done here since we are past the bytecode verification and
3843 // constant pool optimization phases.
3844 for (int i = _old_methods->length() - 1; i >= 0; i--) {
3845 Method* method = _old_methods->at(i);
3846 method->set_constants(scratch_class->constants());
3847 }
3848
3849 // NOTE: this doesn't work because you can redefine the same class in two
3850 // threads, each getting their own constant pool data appended to the
3851 // original constant pool. In order for the new methods to work when they
3852 // become old methods, they need to keep their updated copy of the constant pool.
3853
3854 {
3855 // walk all previous versions of the klass
3856 InstanceKlass *ik = (InstanceKlass *)the_class();
3857 PreviousVersionWalker pvw(ik);
3858 instanceKlassHandle ikh;
3859 do {
3860 ikh = pvw.next_previous_version();
3861 if (!ikh.is_null()) {
3862 ik = ikh();
3863
3864 // attach previous version of klass to the new constant pool
3865 ik->set_constants(scratch_class->constants());
3866
3867 // Attach each method in the previous version of klass to the
3868 // new constant pool
3869 Array<Method*>* prev_methods = ik->methods();
3870 for (int i = prev_methods->length() - 1; i >= 0; i--) {
3871 Method* method = prev_methods->at(i);
3872 method->set_constants(scratch_class->constants());
3873 }
3874 }
3875 } while (!ikh.is_null());
3876 }
3877 #endif
3878
3879 // Replace methods and constantpool
3880 the_class->set_methods(_new_methods);
3881 scratch_class->set_methods(_old_methods); // To prevent potential GCing of the old methods,
3882 // and to be able to undo operation easily.
3883
3884 Array<int>* old_ordering = the_class->method_ordering();
3885 the_class->set_method_ordering(scratch_class->method_ordering());
3886 scratch_class->set_method_ordering(old_ordering);
3887
3888 ConstantPool* old_constants = the_class->constants();
3889 the_class->set_constants(scratch_class->constants());
3890 scratch_class->set_constants(old_constants); // See the previous comment.
3891 #if 0
3892 // We are swapping the guts of "the new class" with the guts of "the
3893 // class". Since the old constant pool has just been attached to "the
3894 // new class", it seems logical to set the pool holder in the old
3895 // constant pool also. However, doing this will change the observable
4024 AOTLoader::load_for_klass(the_class, THREAD);
4025 }
4026
4027 // keep track of previous versions of this class
4028 the_class->add_previous_version(scratch_class, emcp_method_count);
4029
4030 _timer_rsc_phase1.stop();
4031 if (log_is_enabled(Info, redefine, class, timer)) {
4032 _timer_rsc_phase2.start();
4033 }
4034
4035 // Adjust constantpool caches and vtables for all classes
4036 // that reference methods of the evolved class.
4037 AdjustCpoolCacheAndVtable adjust_cpool_cache_and_vtable(THREAD);
4038 ClassLoaderDataGraph::classes_do(&adjust_cpool_cache_and_vtable);
4039
4040 // JSR-292 support
4041 MemberNameTable* mnt = the_class->member_names();
4042 if (mnt != NULL) {
4043 bool trace_name_printed = false;
4044 mnt->adjust_method_entries(the_class(), &trace_name_printed);
4045 }
4046
4047 if (the_class->oop_map_cache() != NULL) {
4048 // Flush references to any obsolete methods from the oop map cache
4049 // so that obsolete methods are not pinned.
4050 the_class->oop_map_cache()->flush_obsolete_entries();
4051 }
4052
4053 {
4054 ResourceMark rm(THREAD);
4055 // increment the classRedefinedCount field in the_class and in any
4056 // direct and indirect subclasses of the_class
4057 increment_class_counter((InstanceKlass *)the_class(), THREAD);
4058 log_info(redefine, class, load)
4059 ("redefined name=%s, count=%d (avail_mem=" UINT64_FORMAT "K)",
4060 the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror()), os::available_memory() >> 10);
4061 Events::log_redefinition(THREAD, "redefined class name=%s, count=%d",
4062 the_class->external_name(),
4063 java_lang_Class::classRedefinedCount(the_class->java_mirror()));
4064
4065 }
4066 _timer_rsc_phase2.stop();
4067 } // end redefine_single_class()
4068
4069
4070 // Increment the classRedefinedCount field in the specific InstanceKlass
4071 // and in all direct and indirect subclasses.
4072 void VM_RedefineClasses::increment_class_counter(InstanceKlass *ik, TRAPS) {
4073 oop class_mirror = ik->java_mirror();
4074 Klass* class_oop = java_lang_Class::as_Klass(class_mirror);
4075 int new_count = java_lang_Class::classRedefinedCount(class_mirror) + 1;
4076 java_lang_Class::set_classRedefinedCount(class_mirror, new_count);
4077
4078 if (class_oop != _the_class_oop) {
4079 // _the_class_oop count is printed at end of redefine_single_class()
4080 log_debug(redefine, class, subclass)("updated count in subclass=%s to %d", ik->external_name(), new_count);
4081 }
4082
4083 for (Klass *subk = ik->subklass(); subk != NULL;
4084 subk = subk->next_sibling()) {
4085 if (subk->is_instance_klass()) {
4086 // Only update instanceKlasses
4087 InstanceKlass *subik = InstanceKlass::cast(subk);
4088 // recursively do subclasses of the current subclass
4089 increment_class_counter(subik, THREAD);
4090 }
4091 }
4092 }
4093
4094 void VM_RedefineClasses::CheckClass::do_klass(Klass* k) {
4095 bool no_old_methods = true; // be optimistic
4096
4097 // Both array and instance classes have vtables.
4098 // a vtable should never contain old or obsolete methods
4099 ResourceMark rm(_thread);
4195 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4196 m->access_flags().print_on(&log_stream);
4197 log_stream.print(" -- ");
4198 m->print_name(&log_stream);
4199 log_stream.cr();
4200 }
4201 log_trace(redefine, class, dump)("_added_methods --");
4202 for (j = 0; j < _added_methods_length; ++j) {
4203 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4204 Method* m = _added_methods[j];
4205 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4206 m->access_flags().print_on(&log_stream);
4207 log_stream.print(" -- ");
4208 m->print_name(&log_stream);
4209 log_stream.cr();
4210 }
4211 }
4212
4213 void VM_RedefineClasses::print_on_error(outputStream* st) const {
4214 VM_Operation::print_on_error(st);
4215 if (_the_class_oop != NULL) {
4216 ResourceMark rm;
4217 st->print_cr(", redefining class %s", _the_class_oop->external_name());
4218 }
4219 }
|
41 #include "oops/fieldStreams.hpp"
42 #include "oops/klassVtable.hpp"
43 #include "oops/oop.inline.hpp"
44 #include "prims/jvmtiImpl.hpp"
45 #include "prims/jvmtiRedefineClasses.hpp"
46 #include "prims/methodComparator.hpp"
47 #include "runtime/deoptimization.hpp"
48 #include "runtime/relocator.hpp"
49 #include "utilities/bitMap.inline.hpp"
50 #include "utilities/events.hpp"
51
52 Array<Method*>* VM_RedefineClasses::_old_methods = NULL;
53 Array<Method*>* VM_RedefineClasses::_new_methods = NULL;
54 Method** VM_RedefineClasses::_matching_old_methods = NULL;
55 Method** VM_RedefineClasses::_matching_new_methods = NULL;
56 Method** VM_RedefineClasses::_deleted_methods = NULL;
57 Method** VM_RedefineClasses::_added_methods = NULL;
58 int VM_RedefineClasses::_matching_methods_length = 0;
59 int VM_RedefineClasses::_deleted_methods_length = 0;
60 int VM_RedefineClasses::_added_methods_length = 0;
61 Klass* VM_RedefineClasses::_the_class = NULL;
62
63
64 VM_RedefineClasses::VM_RedefineClasses(jint class_count,
65 const jvmtiClassDefinition *class_defs,
66 JvmtiClassLoadKind class_load_kind) {
67 _class_count = class_count;
68 _class_defs = class_defs;
69 _class_load_kind = class_load_kind;
70 _res = JVMTI_ERROR_NONE;
71 }
72
73 static inline InstanceKlass* get_ik(jclass def) {
74 oop mirror = JNIHandles::resolve_non_null(def);
75 return InstanceKlass::cast(java_lang_Class::as_Klass(mirror));
76 }
77
78 // If any of the classes are being redefined, wait
79 // Parallel constant pool merging leads to indeterminate constant pools.
80 void VM_RedefineClasses::lock_classes() {
81 MutexLocker ml(RedefineClasses_lock);
210
211 // check_class() is optionally called for product bits, but is
212 // always called for non-product bits.
213 #ifdef PRODUCT
214 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
215 #endif
216 log_trace(redefine, class, obsolete, metadata)("calling check_class");
217 CheckClass check_class(thread);
218 ClassLoaderDataGraph::classes_do(&check_class);
219 #ifdef PRODUCT
220 }
221 #endif
222 }
223
224 void VM_RedefineClasses::doit_epilogue() {
225 unlock_classes();
226
227 // Free os::malloc allocated memory.
228 os::free(_scratch_classes);
229
230 // Reset the_class to null for error printing.
231 _the_class = NULL;
232
233 if (log_is_enabled(Info, redefine, class, timer)) {
234 // Used to have separate timers for "doit" and "all", but the timer
235 // overhead skewed the measurements.
236 jlong doit_time = _timer_rsc_phase1.milliseconds() +
237 _timer_rsc_phase2.milliseconds();
238 jlong all_time = _timer_vm_op_prologue.milliseconds() + doit_time;
239
240 log_info(redefine, class, timer)
241 ("vm_op: all=" UINT64_FORMAT " prologue=" UINT64_FORMAT " doit=" UINT64_FORMAT,
242 all_time, _timer_vm_op_prologue.milliseconds(), doit_time);
243 log_info(redefine, class, timer)
244 ("redefine_single_class: phase1=" UINT64_FORMAT " phase2=" UINT64_FORMAT,
245 _timer_rsc_phase1.milliseconds(), _timer_rsc_phase2.milliseconds());
246 }
247 }
248
249 bool VM_RedefineClasses::is_modifiable_class(oop klass_mirror) {
250 // classes for primitives cannot be redefined
251 if (java_lang_Class::is_primitive(klass_mirror)) {
640
641 if (log_is_enabled(Trace, redefine, class, constantpool)) {
642 // don't want to loop unless we are tracing
643 int count = 0;
644 for (int i = 1; i < _operands_index_map_p->length(); i++) {
645 int value = _operands_index_map_p->at(i);
646 if (value != -1) {
647 log_trace(redefine, class, constantpool)("operands_index_map[%d]: old=%d new=%d", count, i, value);
648 count++;
649 }
650 }
651 }
652 // Clean-up
653 _operands_index_map_p = NULL;
654 _operands_cur_length = 0;
655 _operands_index_map_count = 0;
656 } // end finalize_operands_merge()
657
658
659 jvmtiError VM_RedefineClasses::compare_and_normalize_class_versions(
660 InstanceKlass* the_class,
661 InstanceKlass* scratch_class) {
662 int i;
663
664 // Check superclasses, or rather their names, since superclasses themselves can be
665 // requested to replace.
666 // Check for NULL superclass first since this might be java.lang.Object
667 if (the_class->super() != scratch_class->super() &&
668 (the_class->super() == NULL || scratch_class->super() == NULL ||
669 the_class->super()->name() !=
670 scratch_class->super()->name())) {
671 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
672 }
673
674 // 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 implemented
676 // interfaces are the same, i.e. the order of declaration (which, however, if changed in the
677 // .java file, also changes in .class file) should not matter. However, comparing sets is
678 // technically a bit more difficult, and, more importantly, I am not sure at present that the
679 // order of interfaces does not matter on the implementation level, i.e. that the VM does not
680 // rely on it somewhere.
681 Array<Klass*>* k_interfaces = the_class->local_interfaces();
976 return false; // wrong entry type; not our special case
977 }
978
979 if (t1 == t2) {
980 return false; // not a mismatch; not our special case
981 }
982
983 char *s1 = cp1->klass_name_at(index1)->as_C_string();
984 char *s2 = cp2->klass_name_at(index2)->as_C_string();
985 if (strcmp(s1, s2) != 0) {
986 return false; // strings don't match; not our special case
987 }
988
989 return true; // made it through the gauntlet; this is our special case
990 } // end is_unresolved_class_mismatch()
991
992
993 jvmtiError VM_RedefineClasses::load_new_class_versions(TRAPS) {
994
995 // For consistency allocate memory using os::malloc wrapper.
996 _scratch_classes = (InstanceKlass**)
997 os::malloc(sizeof(InstanceKlass*) * _class_count, mtClass);
998 if (_scratch_classes == NULL) {
999 return JVMTI_ERROR_OUT_OF_MEMORY;
1000 }
1001 // Zero initialize the _scratch_classes array.
1002 for (int i = 0; i < _class_count; i++) {
1003 _scratch_classes[i] = NULL;
1004 }
1005
1006 ResourceMark rm(THREAD);
1007
1008 JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
1009 // state can only be NULL if the current thread is exiting which
1010 // should not happen since we're trying to do a RedefineClasses
1011 guarantee(state != NULL, "exiting thread calling load_new_class_versions");
1012 for (int i = 0; i < _class_count; i++) {
1013 // Create HandleMark so that any handles created while loading new class
1014 // versions are deleted. Constant pools are deallocated while merging
1015 // constant pools
1016 HandleMark hm(THREAD);
1017 InstanceKlass* the_class = get_ik(_class_defs[i].klass);
1018 Symbol* the_class_sym = the_class->name();
1019
1020 log_debug(redefine, class, load)
1021 ("loading name=%s kind=%d (avail_mem=" UINT64_FORMAT "K)",
1022 the_class->external_name(), _class_load_kind, os::available_memory() >> 10);
1023
1024 ClassFileStream st((u1*)_class_defs[i].class_bytes,
1025 _class_defs[i].class_byte_count,
1026 "__VM_RedefineClasses__",
1027 ClassFileStream::verify);
1028
1029 // Parse the stream.
1030 Handle the_class_loader(THREAD, the_class->class_loader());
1031 Handle 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 file
1034 // load hook event.
1035 state->set_class_being_redefined(the_class, _class_load_kind);
1036
1037 InstanceKlass* scratch_class = SystemDictionary::parse_stream(
1038 the_class_sym,
1039 the_class_loader,
1040 protection_domain,
1041 &st,
1042 THREAD);
1043 // Clear class_being_redefined just to be sure.
1044 state->clear_class_being_redefined();
1045
1046 // TODO: if this is retransform, and nothing changed we can skip it
1047
1048 // Need to clean up allocated InstanceKlass if there's an error so assign
1049 // the result here. Caller deallocates all the scratch classes in case of
1050 // an error.
1051 _scratch_classes[i] = scratch_class;
1052
1053 if (HAS_PENDING_EXCEPTION) {
1054 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1055 log_info(redefine, class, load, exceptions)("parse_stream exception: '%s'", ex_name->as_C_string());
1056 CLEAR_PENDING_EXCEPTION;
1057
1058 if (ex_name == vmSymbols::java_lang_UnsupportedClassVersionError()) {
1059 return JVMTI_ERROR_UNSUPPORTED_VERSION;
1060 } else if (ex_name == vmSymbols::java_lang_ClassFormatError()) {
1061 return JVMTI_ERROR_INVALID_CLASS_FORMAT;
1062 } else if (ex_name == vmSymbols::java_lang_ClassCircularityError()) {
1063 return JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION;
1064 } else if (ex_name == vmSymbols::java_lang_NoClassDefFoundError()) {
1065 // The message will be "XXX (wrong name: YYY)"
1066 return JVMTI_ERROR_NAMES_DONT_MATCH;
1067 } else if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1068 return JVMTI_ERROR_OUT_OF_MEMORY;
1069 } else { // Just in case more exceptions can be thrown..
1070 return JVMTI_ERROR_FAILS_VERIFICATION;
1071 }
1088
1089 // Do the validity checks in compare_and_normalize_class_versions()
1090 // before verifying the byte codes. By doing these checks first, we
1091 // limit the number of functions that require redirection from
1092 // the_class to scratch_class. In particular, we don't have to
1093 // modify JNI GetSuperclass() and thus won't change its performance.
1094 jvmtiError res = compare_and_normalize_class_versions(the_class,
1095 scratch_class);
1096 if (res != JVMTI_ERROR_NONE) {
1097 return res;
1098 }
1099
1100 // verify what the caller passed us
1101 {
1102 // The bug 6214132 caused the verification to fail.
1103 // Information about the_class and scratch_class is temporarily
1104 // recorded into jvmtiThreadState. This data is used to redirect
1105 // the_class to scratch_class in the JVM_* functions called by the
1106 // verifier. Please, refer to jvmtiThreadState.hpp for the detailed
1107 // description.
1108 RedefineVerifyMark rvm(the_class, scratch_class, state);
1109 Verifier::verify(
1110 scratch_class, Verifier::ThrowException, true, THREAD);
1111 }
1112
1113 if (HAS_PENDING_EXCEPTION) {
1114 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1115 log_info(redefine, class, load, exceptions)("verify_byte_codes exception: '%s'", ex_name->as_C_string());
1116 CLEAR_PENDING_EXCEPTION;
1117 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1118 return JVMTI_ERROR_OUT_OF_MEMORY;
1119 } else {
1120 // tell the caller the bytecodes are bad
1121 return JVMTI_ERROR_FAILS_VERIFICATION;
1122 }
1123 }
1124
1125 res = merge_cp_and_rewrite(the_class, scratch_class, THREAD);
1126 if (HAS_PENDING_EXCEPTION) {
1127 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1128 log_info(redefine, class, load, exceptions)("merge_cp_and_rewrite exception: '%s'", ex_name->as_C_string());
1129 CLEAR_PENDING_EXCEPTION;
1130 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1131 return JVMTI_ERROR_OUT_OF_MEMORY;
1132 } else {
1133 return JVMTI_ERROR_INTERNAL;
1134 }
1135 }
1136
1137 if (VerifyMergedCPBytecodes) {
1138 // verify what we have done during constant pool merging
1139 {
1140 RedefineVerifyMark rvm(the_class, scratch_class, state);
1141 Verifier::verify(scratch_class, Verifier::ThrowException, true, THREAD);
1142 }
1143
1144 if (HAS_PENDING_EXCEPTION) {
1145 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1146 log_info(redefine, class, load, exceptions)
1147 ("verify_byte_codes post merge-CP exception: '%s'", ex_name->as_C_string());
1148 CLEAR_PENDING_EXCEPTION;
1149 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1150 return JVMTI_ERROR_OUT_OF_MEMORY;
1151 } else {
1152 // tell the caller that constant pool merging screwed up
1153 return JVMTI_ERROR_INTERNAL;
1154 }
1155 }
1156 }
1157
1158 Rewriter::rewrite(scratch_class, THREAD);
1159 if (!HAS_PENDING_EXCEPTION) {
1160 scratch_class->link_methods(THREAD);
1416 class MergeCPCleaner {
1417 ClassLoaderData* _loader_data;
1418 ConstantPool* _cp;
1419 ConstantPool* _scratch_cp;
1420 public:
1421 MergeCPCleaner(ClassLoaderData* loader_data, ConstantPool* merge_cp) :
1422 _loader_data(loader_data), _cp(merge_cp), _scratch_cp(NULL) {}
1423 ~MergeCPCleaner() {
1424 _loader_data->add_to_deallocate_list(_cp);
1425 if (_scratch_cp != NULL) {
1426 _loader_data->add_to_deallocate_list(_scratch_cp);
1427 }
1428 }
1429 void add_scratch_cp(ConstantPool* scratch_cp) { _scratch_cp = scratch_cp; }
1430 };
1431
1432 // Merge constant pools between the_class and scratch_class and
1433 // potentially rewrite bytecodes in scratch_class to use the merged
1434 // constant pool.
1435 jvmtiError VM_RedefineClasses::merge_cp_and_rewrite(
1436 InstanceKlass* the_class, InstanceKlass* scratch_class,
1437 TRAPS) {
1438 // worst case merged constant pool length is old and new combined
1439 int merge_cp_length = the_class->constants()->length()
1440 + scratch_class->constants()->length();
1441
1442 // Constant pools are not easily reused so we allocate a new one
1443 // each time.
1444 // merge_cp is created unsafe for concurrent GC processing. It
1445 // should be marked safe before discarding it. Even though
1446 // garbage, if it crosses a card boundary, it may be scanned
1447 // in order to find the start of the first complete object on the card.
1448 ClassLoaderData* loader_data = the_class->class_loader_data();
1449 ConstantPool* merge_cp_oop =
1450 ConstantPool::allocate(loader_data,
1451 merge_cp_length,
1452 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1453 MergeCPCleaner cp_cleaner(loader_data, merge_cp_oop);
1454
1455 HandleMark hm(THREAD); // make sure handles are cleared before
1456 // MergeCPCleaner clears out merge_cp_oop
1465 // an error.
1466 if (merge_cp_length != the_class->constants()->length()
1467 + scratch_class->constants()->length()) {
1468 return JVMTI_ERROR_INTERNAL;
1469 }
1470
1471 // Update the version number of the constant pools (may keep scratch_cp)
1472 merge_cp->increment_and_save_version(old_cp->version());
1473 scratch_cp->increment_and_save_version(old_cp->version());
1474
1475 ResourceMark rm(THREAD);
1476 _index_map_count = 0;
1477 _index_map_p = new intArray(scratch_cp->length(), scratch_cp->length(), -1);
1478
1479 _operands_cur_length = ConstantPool::operand_array_length(old_cp->operands());
1480 _operands_index_map_count = 0;
1481 int operands_index_map_len = ConstantPool::operand_array_length(scratch_cp->operands());
1482 _operands_index_map_p = new intArray(operands_index_map_len, operands_index_map_len, -1);
1483
1484 // reference to the cp holder is needed for copy_operands()
1485 merge_cp->set_pool_holder(scratch_class);
1486 bool result = merge_constant_pools(old_cp, scratch_cp, &merge_cp,
1487 &merge_cp_length, THREAD);
1488 merge_cp->set_pool_holder(NULL);
1489
1490 if (!result) {
1491 // The merge can fail due to memory allocation failure or due
1492 // to robustness checks.
1493 return JVMTI_ERROR_INTERNAL;
1494 }
1495
1496 log_info(redefine, class, constantpool)("merge_cp_len=%d, index_map_len=%d", merge_cp_length, _index_map_count);
1497
1498 if (_index_map_count == 0) {
1499 // there is nothing to map between the new and merged constant pools
1500
1501 if (old_cp->length() == scratch_cp->length()) {
1502 // The old and new constant pools are the same length and the
1503 // index map is empty. This means that the three constant pools
1504 // are equivalent (but not the same). Unfortunately, the new
1505 // constant pool has not gone through link resolution nor have
1550 if (!rewrite_cp_refs(scratch_class, THREAD)) {
1551 return JVMTI_ERROR_INTERNAL;
1552 }
1553
1554 // Replace the new constant pool with a shrunken copy of the
1555 // merged constant pool so now the rewritten bytecodes have
1556 // valid references; the previous new constant pool will get
1557 // GCed.
1558 set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,
1559 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1560 // The new constant pool replaces scratch_cp so have cleaner clean it up.
1561 // It can't be cleaned up while there are handles to it.
1562 cp_cleaner.add_scratch_cp(scratch_cp());
1563 }
1564
1565 return JVMTI_ERROR_NONE;
1566 } // end merge_cp_and_rewrite()
1567
1568
1569 // Rewrite constant pool references in klass scratch_class.
1570 bool VM_RedefineClasses::rewrite_cp_refs(InstanceKlass* scratch_class,
1571 TRAPS) {
1572
1573 // rewrite constant pool references in the methods:
1574 if (!rewrite_cp_refs_in_methods(scratch_class, THREAD)) {
1575 // propagate failure back to caller
1576 return false;
1577 }
1578
1579 // rewrite constant pool references in the class_annotations:
1580 if (!rewrite_cp_refs_in_class_annotations(scratch_class, THREAD)) {
1581 // propagate failure back to caller
1582 return false;
1583 }
1584
1585 // rewrite constant pool references in the fields_annotations:
1586 if (!rewrite_cp_refs_in_fields_annotations(scratch_class, THREAD)) {
1587 // propagate failure back to caller
1588 return false;
1589 }
1590
1637 u2 new_source_file_name_idx = find_new_index(source_file_name_idx);
1638 if (new_source_file_name_idx != 0) {
1639 scratch_class->set_source_file_name_index(new_source_file_name_idx);
1640 }
1641 }
1642
1643 // rewrite class generic signature index:
1644 u2 generic_signature_index = scratch_class->generic_signature_index();
1645 if (generic_signature_index != 0) {
1646 u2 new_generic_signature_index = find_new_index(generic_signature_index);
1647 if (new_generic_signature_index != 0) {
1648 scratch_class->set_generic_signature_index(new_generic_signature_index);
1649 }
1650 }
1651
1652 return true;
1653 } // end rewrite_cp_refs()
1654
1655 // Rewrite constant pool references in the methods.
1656 bool VM_RedefineClasses::rewrite_cp_refs_in_methods(
1657 InstanceKlass* scratch_class, TRAPS) {
1658
1659 Array<Method*>* methods = scratch_class->methods();
1660
1661 if (methods == NULL || methods->length() == 0) {
1662 // no methods so nothing to do
1663 return true;
1664 }
1665
1666 // rewrite constant pool references in the methods:
1667 for (int i = methods->length() - 1; i >= 0; i--) {
1668 methodHandle method(THREAD, methods->at(i));
1669 methodHandle new_method;
1670 rewrite_cp_refs_in_method(method, &new_method, THREAD);
1671 if (!new_method.is_null()) {
1672 // the method has been replaced so save the new method version
1673 // even in the case of an exception. original method is on the
1674 // deallocation list.
1675 methods->at_put(i, new_method());
1676 }
1677 if (HAS_PENDING_EXCEPTION) {
1816
1817 // We also need to rewrite the parameter name indexes, if there is
1818 // method parameter data present
1819 if(method->has_method_parameters()) {
1820 const int len = method->method_parameters_length();
1821 MethodParametersElement* elem = method->method_parameters_start();
1822
1823 for (int i = 0; i < len; i++) {
1824 const u2 cp_index = elem[i].name_cp_index;
1825 const u2 new_cp_index = find_new_index(cp_index);
1826 if (new_cp_index != 0) {
1827 elem[i].name_cp_index = new_cp_index;
1828 }
1829 }
1830 }
1831 } // end rewrite_cp_refs_in_method()
1832
1833
1834 // Rewrite constant pool references in the class_annotations field.
1835 bool VM_RedefineClasses::rewrite_cp_refs_in_class_annotations(
1836 InstanceKlass* scratch_class, TRAPS) {
1837
1838 AnnotationArray* class_annotations = scratch_class->class_annotations();
1839 if (class_annotations == NULL || class_annotations->length() == 0) {
1840 // no class_annotations so nothing to do
1841 return true;
1842 }
1843
1844 log_debug(redefine, class, annotation)("class_annotations length=%d", class_annotations->length());
1845
1846 int byte_i = 0; // byte index into class_annotations
1847 return rewrite_cp_refs_in_annotations_typeArray(class_annotations, byte_i,
1848 THREAD);
1849 }
1850
1851
1852 // Rewrite constant pool references in an annotations typeArray. This
1853 // "structure" is adapted from the RuntimeVisibleAnnotations_attribute
1854 // that is described in section 4.8.15 of the 2nd-edition of the VM spec:
1855 //
1856 // annotations_typeArray {
2106 annotations_typeArray, byte_i_ref, THREAD)) {
2107 log_debug(redefine, class, annotation)("bad nested element_value at %d", calc_num_values);
2108 // propagate failure back to caller
2109 return false;
2110 }
2111 }
2112 assert(num_values == calc_num_values, "sanity check");
2113 } break;
2114
2115 default:
2116 log_debug(redefine, class, annotation)("bad tag=0x%x", tag);
2117 return false;
2118 } // end decode tag field
2119
2120 return true;
2121 } // end rewrite_cp_refs_in_element_value()
2122
2123
2124 // Rewrite constant pool references in a fields_annotations field.
2125 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations(
2126 InstanceKlass* scratch_class, TRAPS) {
2127
2128 Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations();
2129
2130 if (fields_annotations == NULL || fields_annotations->length() == 0) {
2131 // no fields_annotations so nothing to do
2132 return true;
2133 }
2134
2135 log_debug(redefine, class, annotation)("fields_annotations length=%d", fields_annotations->length());
2136
2137 for (int i = 0; i < fields_annotations->length(); i++) {
2138 AnnotationArray* field_annotations = fields_annotations->at(i);
2139 if (field_annotations == NULL || field_annotations->length() == 0) {
2140 // this field does not have any annotations so skip it
2141 continue;
2142 }
2143
2144 int byte_i = 0; // byte index into field_annotations
2145 if (!rewrite_cp_refs_in_annotations_typeArray(field_annotations, byte_i,
2146 THREAD)) {
2147 log_debug(redefine, class, annotation)("bad field_annotations at %d", i);
2148 // propagate failure back to caller
2149 return false;
2150 }
2151 }
2152
2153 return true;
2154 } // end rewrite_cp_refs_in_fields_annotations()
2155
2156
2157 // Rewrite constant pool references in a methods_annotations field.
2158 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations(
2159 InstanceKlass* scratch_class, TRAPS) {
2160
2161 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2162 Method* m = scratch_class->methods()->at(i);
2163 AnnotationArray* method_annotations = m->constMethod()->method_annotations();
2164
2165 if (method_annotations == NULL || method_annotations->length() == 0) {
2166 // this method does not have any annotations so skip it
2167 continue;
2168 }
2169
2170 int byte_i = 0; // byte index into method_annotations
2171 if (!rewrite_cp_refs_in_annotations_typeArray(method_annotations, byte_i,
2172 THREAD)) {
2173 log_debug(redefine, class, annotation)("bad method_annotations at %d", i);
2174 // propagate failure back to caller
2175 return false;
2176 }
2177 }
2178
2179 return true;
2180 } // end rewrite_cp_refs_in_methods_annotations()
2181
2182
2183 // Rewrite constant pool references in a methods_parameter_annotations
2184 // field. This "structure" is adapted from the
2185 // RuntimeVisibleParameterAnnotations_attribute described in section
2186 // 4.8.17 of the 2nd-edition of the VM spec:
2187 //
2188 // methods_parameter_annotations_typeArray {
2189 // u1 num_parameters;
2190 // {
2191 // u2 num_annotations;
2192 // annotation annotations[num_annotations];
2193 // } parameter_annotations[num_parameters];
2194 // }
2195 //
2196 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations(
2197 InstanceKlass* scratch_class, TRAPS) {
2198
2199 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2200 Method* m = scratch_class->methods()->at(i);
2201 AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations();
2202 if (method_parameter_annotations == NULL
2203 || method_parameter_annotations->length() == 0) {
2204 // this method does not have any parameter annotations so skip it
2205 continue;
2206 }
2207
2208 if (method_parameter_annotations->length() < 1) {
2209 // not enough room for a num_parameters field
2210 log_debug(redefine, class, annotation)("length() is too small for a num_parameters field at %d", i);
2211 return false;
2212 }
2213
2214 int byte_i = 0; // byte index into method_parameter_annotations
2215
2216 u1 num_parameters = method_parameter_annotations->at(byte_i);
2217 byte_i++;
2226 // propagate failure back to caller
2227 return false;
2228 }
2229 }
2230 assert(num_parameters == calc_num_parameters, "sanity check");
2231 }
2232
2233 return true;
2234 } // end rewrite_cp_refs_in_methods_parameter_annotations()
2235
2236
2237 // Rewrite constant pool references in a methods_default_annotations
2238 // field. This "structure" is adapted from the AnnotationDefault_attribute
2239 // that is described in section 4.8.19 of the 2nd-edition of the VM spec:
2240 //
2241 // methods_default_annotations_typeArray {
2242 // element_value default_value;
2243 // }
2244 //
2245 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations(
2246 InstanceKlass* scratch_class, TRAPS) {
2247
2248 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2249 Method* m = scratch_class->methods()->at(i);
2250 AnnotationArray* method_default_annotations = m->constMethod()->default_annotations();
2251 if (method_default_annotations == NULL
2252 || method_default_annotations->length() == 0) {
2253 // this method does not have any default annotations so skip it
2254 continue;
2255 }
2256
2257 int byte_i = 0; // byte index into method_default_annotations
2258
2259 if (!rewrite_cp_refs_in_element_value(
2260 method_default_annotations, byte_i, THREAD)) {
2261 log_debug(redefine, class, annotation)("bad default element_value at %d", i);
2262 // propagate failure back to caller
2263 return false;
2264 }
2265 }
2266
2267 return true;
2268 } // end rewrite_cp_refs_in_methods_default_annotations()
2269
2270
2271 // Rewrite constant pool references in a class_type_annotations field.
2272 bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations(
2273 InstanceKlass* scratch_class, TRAPS) {
2274
2275 AnnotationArray* class_type_annotations = scratch_class->class_type_annotations();
2276 if (class_type_annotations == NULL || class_type_annotations->length() == 0) {
2277 // no class_type_annotations so nothing to do
2278 return true;
2279 }
2280
2281 log_debug(redefine, class, annotation)("class_type_annotations length=%d", class_type_annotations->length());
2282
2283 int byte_i = 0; // byte index into class_type_annotations
2284 return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations,
2285 byte_i, "ClassFile", THREAD);
2286 } // end rewrite_cp_refs_in_class_type_annotations()
2287
2288
2289 // Rewrite constant pool references in a fields_type_annotations field.
2290 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations(
2291 InstanceKlass* scratch_class, TRAPS) {
2292
2293 Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations();
2294 if (fields_type_annotations == NULL || fields_type_annotations->length() == 0) {
2295 // no fields_type_annotations so nothing to do
2296 return true;
2297 }
2298
2299 log_debug(redefine, class, annotation)("fields_type_annotations length=%d", fields_type_annotations->length());
2300
2301 for (int i = 0; i < fields_type_annotations->length(); i++) {
2302 AnnotationArray* field_type_annotations = fields_type_annotations->at(i);
2303 if (field_type_annotations == NULL || field_type_annotations->length() == 0) {
2304 // this field does not have any annotations so skip it
2305 continue;
2306 }
2307
2308 int byte_i = 0; // byte index into field_type_annotations
2309 if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations,
2310 byte_i, "field_info", THREAD)) {
2311 log_debug(redefine, class, annotation)("bad field_type_annotations at %d", i);
2312 // propagate failure back to caller
2313 return false;
2314 }
2315 }
2316
2317 return true;
2318 } // end rewrite_cp_refs_in_fields_type_annotations()
2319
2320
2321 // Rewrite constant pool references in a methods_type_annotations field.
2322 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations(
2323 InstanceKlass* scratch_class, TRAPS) {
2324
2325 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2326 Method* m = scratch_class->methods()->at(i);
2327 AnnotationArray* method_type_annotations = m->constMethod()->type_annotations();
2328
2329 if (method_type_annotations == NULL || method_type_annotations->length() == 0) {
2330 // this method does not have any annotations so skip it
2331 continue;
2332 }
2333
2334 log_debug(redefine, class, annotation)("methods type_annotations length=%d", method_type_annotations->length());
2335
2336 int byte_i = 0; // byte index into method_type_annotations
2337 if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations,
2338 byte_i, "method_info", THREAD)) {
2339 log_debug(redefine, class, annotation)("bad method_type_annotations at %d", i);
2340 // propagate failure back to caller
2341 return false;
2342 }
2343 }
3056 // }
3057 case ITEM_Uninitialized:
3058 assert(stackmap_p_ref + 2 <= stackmap_end, "no room for offset");
3059 stackmap_p_ref += 2;
3060 break;
3061
3062 default:
3063 log_debug(redefine, class, stackmap)("frame_i=%u, frame_type=%u, bad tag=0x%x", frame_i, frame_type, tag);
3064 ShouldNotReachHere();
3065 break;
3066 } // end switch (tag)
3067 } // end rewrite_cp_refs_in_verification_type_info()
3068
3069
3070 // Change the constant pool associated with klass scratch_class to
3071 // scratch_cp. If shrink is true, then scratch_cp_length elements
3072 // are copied from scratch_cp to a smaller constant pool and the
3073 // smaller constant pool is associated with scratch_class.
3074 void VM_RedefineClasses::set_new_constant_pool(
3075 ClassLoaderData* loader_data,
3076 InstanceKlass* scratch_class, constantPoolHandle scratch_cp,
3077 int scratch_cp_length, TRAPS) {
3078 assert(scratch_cp->length() >= scratch_cp_length, "sanity check");
3079
3080 // scratch_cp is a merged constant pool and has enough space for a
3081 // worst case merge situation. We want to associate the minimum
3082 // sized constant pool with the klass to save space.
3083 ConstantPool* cp = ConstantPool::allocate(loader_data, scratch_cp_length, CHECK);
3084 constantPoolHandle smaller_cp(THREAD, cp);
3085
3086 // preserve version() value in the smaller copy
3087 int version = scratch_cp->version();
3088 assert(version != 0, "sanity check");
3089 smaller_cp->set_version(version);
3090
3091 // attach klass to new constant pool
3092 // reference to the cp holder is needed for copy_operands()
3093 smaller_cp->set_pool_holder(scratch_class);
3094
3095 scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
3096 if (HAS_PENDING_EXCEPTION) {
3097 // Exception is handled in the caller
3098 loader_data->add_to_deallocate_list(smaller_cp());
3099 return;
3100 }
3101 scratch_cp = smaller_cp;
3102
3103 // attach new constant pool to klass
3104 scratch_class->set_constants(scratch_cp());
3105
3106 int i; // for portability
3107
3108 // update each field in klass to use new constant pool indices as needed
3109 for (JavaFieldStream fs(scratch_class); !fs.done(); fs.next()) {
3110 jshort cur_index = fs.name_index();
3111 jshort new_index = find_new_index(cur_index);
3112 if (new_index != 0) {
3113 log_trace(redefine, class, constantpool)("field-name_index change: %d to %d", cur_index, new_index);
3250 }
3251 } // end for each local variable table entry
3252 } // end if there are local variable table entries
3253
3254 rewrite_cp_refs_in_stack_map_table(method, THREAD);
3255 } // end for each method
3256 } // end set_new_constant_pool()
3257
3258
3259 // Unevolving classes may point to methods of the_class directly
3260 // from their constant pool caches, itables, and/or vtables. We
3261 // use the ClassLoaderDataGraph::classes_do() facility and this helper
3262 // to fix up these pointers.
3263
3264 // Adjust cpools and vtables closure
3265 void VM_RedefineClasses::AdjustCpoolCacheAndVtable::do_klass(Klass* k) {
3266
3267 // This is a very busy routine. We don't want too much tracing
3268 // printed out.
3269 bool trace_name_printed = false;
3270 InstanceKlass *the_class = InstanceKlass::cast(_the_class);
3271
3272 // If the class being redefined is java.lang.Object, we need to fix all
3273 // array class vtables also
3274 if (k->is_array_klass() && _the_class == SystemDictionary::Object_klass()) {
3275 k->vtable()->adjust_method_entries(the_class, &trace_name_printed);
3276
3277 } else if (k->is_instance_klass()) {
3278 HandleMark hm(_thread);
3279 InstanceKlass *ik = InstanceKlass::cast(k);
3280
3281 // HotSpot specific optimization! HotSpot does not currently
3282 // support delegation from the bootstrap class loader to a
3283 // user-defined class loader. This means that if the bootstrap
3284 // class loader is the initiating class loader, then it will also
3285 // be the defining class loader. This also means that classes
3286 // loaded by the bootstrap class loader cannot refer to classes
3287 // loaded by a user-defined class loader. Note: a user-defined
3288 // class loader can delegate to the bootstrap class loader.
3289 //
3290 // If the current class being redefined has a user-defined class
3291 // loader as its defining class loader, then we can skip all
3292 // classes loaded by the bootstrap class loader.
3293 bool is_user_defined = (_the_class->class_loader() != NULL);
3294 if (is_user_defined && ik->class_loader() == NULL) {
3295 return;
3296 }
3297
3298 // Fix the vtable embedded in the_class and subclasses of the_class,
3299 // if one exists. We discard scratch_class and we don't keep an
3300 // InstanceKlass around to hold obsolete methods so we don't have
3301 // any other InstanceKlass embedded vtables to update. The vtable
3302 // holds the Method*s for virtual (but not final) methods.
3303 // Default methods, or concrete methods in interfaces are stored
3304 // in the vtable, so if an interface changes we need to check
3305 // adjust_method_entries() for every InstanceKlass, which will also
3306 // adjust the default method vtable indices.
3307 // We also need to adjust any default method entries that are
3308 // not yet in the vtable, because the vtable setup is in progress.
3309 // This must be done after we adjust the default_methods and
3310 // default_vtable_indices for methods already in the vtable.
3311 // If redefining Unsafe, walk all the vtables looking for entries.
3312 if (ik->vtable_length() > 0 && (_the_class->is_interface()
3313 || _the_class == SystemDictionary::internal_Unsafe_klass()
3314 || ik->is_subtype_of(_the_class))) {
3315 // ik->vtable() creates a wrapper object; rm cleans it up
3316 ResourceMark rm(_thread);
3317
3318 ik->vtable()->adjust_method_entries(the_class, &trace_name_printed);
3319 ik->adjust_default_methods(the_class, &trace_name_printed);
3320 }
3321
3322 // If the current class has an itable and we are either redefining an
3323 // interface or if the current class is a subclass of the_class, then
3324 // we potentially have to fix the itable. If we are redefining an
3325 // interface, then we have to call adjust_method_entries() for
3326 // every InstanceKlass that has an itable since there isn't a
3327 // subclass relationship between an interface and an InstanceKlass.
3328 // If redefining Unsafe, walk all the itables looking for entries.
3329 if (ik->itable_length() > 0 && (_the_class->is_interface()
3330 || _the_class == SystemDictionary::internal_Unsafe_klass()
3331 || ik->is_subclass_of(_the_class))) {
3332 // ik->itable() creates a wrapper object; rm cleans it up
3333 ResourceMark rm(_thread);
3334
3335 ik->itable()->adjust_method_entries(the_class, &trace_name_printed);
3336 }
3337
3338 // The constant pools in other classes (other_cp) can refer to
3339 // methods in the_class. We have to update method information in
3340 // other_cp's cache. If other_cp has a previous version, then we
3341 // have to repeat the process for each previous version. The
3342 // constant pool cache holds the Method*s for non-virtual
3343 // methods and for virtual, final methods.
3344 //
3345 // Special case: if the current class is the_class, then new_cp
3346 // has already been attached to the_class and old_cp has already
3347 // been added as a previous version. The new_cp doesn't have any
3348 // cached references to old methods so it doesn't need to be
3349 // updated. We can simply start with the previous version(s) in
3350 // that case.
3351 constantPoolHandle other_cp;
3352 ConstantPoolCache* cp_cache;
3353
3354 if (ik != _the_class) {
3355 // this klass' constant pool cache may need adjustment
3356 other_cp = constantPoolHandle(ik->constants());
3357 cp_cache = other_cp->cache();
3358 if (cp_cache != NULL) {
3359 cp_cache->adjust_method_entries(the_class, &trace_name_printed);
3360 }
3361 }
3362
3363 // the previous versions' constant pool caches may need adjustment
3364 for (InstanceKlass* pv_node = ik->previous_versions();
3365 pv_node != NULL;
3366 pv_node = pv_node->previous_versions()) {
3367 cp_cache = pv_node->constants()->cache();
3368 if (cp_cache != NULL) {
3369 cp_cache->adjust_method_entries(pv_node, &trace_name_printed);
3370 }
3371 }
3372 }
3373 }
3374
3480 // Count number of methods that are EMCP. The method will be marked
3481 // old but not obsolete if it is EMCP.
3482 emcp_method_count++;
3483
3484 // An EMCP method is _not_ obsolete. An obsolete method has a
3485 // different jmethodID than the current method. An EMCP method
3486 // has the same jmethodID as the current method. Having the
3487 // same jmethodID for all EMCP versions of a method allows for
3488 // a consistent view of the EMCP methods regardless of which
3489 // EMCP method you happen to have in hand. For example, a
3490 // breakpoint set in one EMCP method will work for all EMCP
3491 // versions of the method including the current one.
3492 } else {
3493 // mark obsolete methods as such
3494 old_method->set_is_obsolete();
3495 obsolete_count++;
3496
3497 // obsolete methods need a unique idnum so they become new entries in
3498 // the jmethodID cache in InstanceKlass
3499 assert(old_method->method_idnum() == new_method->method_idnum(), "must match");
3500 u2 num = InstanceKlass::cast(_the_class)->next_method_idnum();
3501 if (num != ConstMethod::UNSET_IDNUM) {
3502 old_method->set_method_idnum(num);
3503 }
3504
3505 // With tracing we try not to "yack" too much. The position of
3506 // this trace assumes there are fewer obsolete methods than
3507 // EMCP methods.
3508 if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3509 ResourceMark rm;
3510 log_trace(redefine, class, obsolete, mark)
3511 ("mark %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3512 }
3513 }
3514 old_method->set_is_old();
3515 }
3516 for (int i = 0; i < _deleted_methods_length; ++i) {
3517 Method* old_method = _deleted_methods[i];
3518
3519 assert(!old_method->has_vtable_index(),
3520 "cannot delete methods with vtable entries");;
3544 // native methods and the complex cases of native method prefixes being added and/or
3545 // removed.
3546 // It expects only to be used during the VM_RedefineClasses op (a safepoint).
3547 //
3548 // This class is used after the new methods have been installed in "the_class".
3549 //
3550 // So, for example, the following must be handled. Where 'm' is a method and
3551 // a number followed by an underscore is a prefix.
3552 //
3553 // Old Name New Name
3554 // Simple transfer to new method m -> m
3555 // Add prefix m -> 1_m
3556 // Remove prefix 1_m -> m
3557 // Simultaneous add of prefixes m -> 3_2_1_m
3558 // Simultaneous removal of prefixes 3_2_1_m -> m
3559 // Simultaneous add and remove 1_m -> 2_m
3560 // Same, caused by prefix removal only 3_2_1_m -> 3_2_m
3561 //
3562 class TransferNativeFunctionRegistration {
3563 private:
3564 InstanceKlass* the_class;
3565 int prefix_count;
3566 char** prefixes;
3567
3568 // Recursively search the binary tree of possibly prefixed method names.
3569 // Iteration could be used if all agents were well behaved. Full tree walk is
3570 // more resilent to agents not cleaning up intermediate methods.
3571 // Branch at each depth in the binary tree is:
3572 // (1) without the prefix.
3573 // (2) with the prefix.
3574 // where 'prefix' is the prefix at that 'depth' (first prefix, second prefix,...)
3575 Method* search_prefix_name_space(int depth, char* name_str, size_t name_len,
3576 Symbol* signature) {
3577 TempNewSymbol name_symbol = SymbolTable::probe(name_str, (int)name_len);
3578 if (name_symbol != NULL) {
3579 Method* method = the_class->lookup_method(name_symbol, signature);
3580 if (method != NULL) {
3581 // Even if prefixed, intermediate methods must exist.
3582 if (method->is_native()) {
3583 // Wahoo, we found a (possibly prefixed) version of the method, return it.
3584 return method;
3585 }
3586 if (depth < prefix_count) {
3587 // Try applying further prefixes (other than this one).
3588 method = search_prefix_name_space(depth+1, name_str, name_len, signature);
3589 if (method != NULL) {
3590 return method; // found
3591 }
3592
3593 // Try adding this prefix to the method name and see if it matches
3594 // another method name.
3595 char* prefix = prefixes[depth];
3596 size_t prefix_len = strlen(prefix);
3597 size_t trial_len = name_len + prefix_len;
3598 char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
3599 strcpy(trial_name_str, prefix);
3622 size_t prefix_len = strlen(prefix);
3623 if (strncmp(prefix, name_str, prefix_len) == 0) {
3624 name_str += prefix_len;
3625 }
3626 }
3627 return name_str;
3628 }
3629
3630 // Strip any prefixes off the old native method, then try to find a
3631 // (possibly prefixed) new native that matches it.
3632 Method* strip_and_search_for_new_native(Method* method) {
3633 ResourceMark rm;
3634 char* name_str = method_name_without_prefixes(method);
3635 return search_prefix_name_space(0, name_str, strlen(name_str),
3636 method->signature());
3637 }
3638
3639 public:
3640
3641 // Construct a native method transfer processor for this class.
3642 TransferNativeFunctionRegistration(InstanceKlass* _the_class) {
3643 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
3644
3645 the_class = _the_class;
3646 prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
3647 }
3648
3649 // Attempt to transfer any of the old or deleted methods that are native
3650 void transfer_registrations(Method** old_methods, int methods_length) {
3651 for (int j = 0; j < methods_length; j++) {
3652 Method* old_method = old_methods[j];
3653
3654 if (old_method->is_native() && old_method->has_native_function()) {
3655 Method* new_method = strip_and_search_for_new_native(old_method);
3656 if (new_method != NULL) {
3657 // Actually set the native function in the new method.
3658 // Redefine does not send events (except CFLH), certainly not this
3659 // behind the scenes re-registration.
3660 new_method->set_native_function(old_method->native_function(),
3661 !Method::native_bind_event_is_interesting);
3662 }
3663 }
3664 }
3665 }
3666 };
3667
3668 // Don't lose the association between a native method and its JNI function.
3669 void VM_RedefineClasses::transfer_old_native_function_registrations(InstanceKlass* the_class) {
3670 TransferNativeFunctionRegistration transfer(the_class);
3671 transfer.transfer_registrations(_deleted_methods, _deleted_methods_length);
3672 transfer.transfer_registrations(_matching_old_methods, _matching_methods_length);
3673 }
3674
3675 // Deoptimize all compiled code that depends on this class.
3676 //
3677 // If the can_redefine_classes capability is obtained in the onload
3678 // phase then the compiler has recorded all dependencies from startup.
3679 // In that case we need only deoptimize and throw away all compiled code
3680 // that depends on the class.
3681 //
3682 // If can_redefine_classes is obtained sometime after the onload
3683 // phase then the dependency information may be incomplete. In that case
3684 // the first call to RedefineClasses causes all compiled code to be
3685 // thrown away. As can_redefine_classes has been obtained then
3686 // all future compilations will record dependencies so second and
3687 // subsequent calls to RedefineClasses need only throw away code
3688 // that depends on the class.
3689 //
3690 void VM_RedefineClasses::flush_dependent_code(InstanceKlass* ik, TRAPS) {
3691 assert_locked_or_safepoint(Compile_lock);
3692
3693 // All dependencies have been recorded from startup or this is a second or
3694 // subsequent use of RedefineClasses
3695 if (JvmtiExport::all_dependencies_are_recorded()) {
3696 CodeCache::flush_evol_dependents_on(ik);
3697 } else {
3698 CodeCache::mark_all_nmethods_for_deoptimization();
3699
3700 ResourceMark rm(THREAD);
3701 DeoptimizationMarker dm;
3702
3703 // Deoptimize all activations depending on marked nmethods
3704 Deoptimization::deoptimize_dependents();
3705
3706 // Make the dependent methods not entrant
3707 CodeCache::make_marked_nmethods_not_entrant();
3708
3709 // From now on we know that the dependency information is complete
3710 JvmtiExport::set_all_dependencies_are_recorded(true);
3711 }
3712 }
3713
3714 void VM_RedefineClasses::compute_added_deleted_matching_methods() {
3715 Method* old_method;
3716 Method* new_method;
3756 ++oj;
3757 }
3758 } else { // names don't match
3759 if (old_method->name()->fast_compare(new_method->name()) > 0) {
3760 // new method
3761 _added_methods[_added_methods_length++] = new_method;
3762 ++nj;
3763 } else {
3764 // deleted method
3765 _deleted_methods[_deleted_methods_length++] = old_method;
3766 ++oj;
3767 }
3768 }
3769 }
3770 }
3771 assert(_matching_methods_length + _deleted_methods_length == _old_methods->length(), "sanity");
3772 assert(_matching_methods_length + _added_methods_length == _new_methods->length(), "sanity");
3773 }
3774
3775
3776 void VM_RedefineClasses::swap_annotations(InstanceKlass* the_class,
3777 InstanceKlass* scratch_class) {
3778 // Swap annotation fields values
3779 Annotations* old_annotations = the_class->annotations();
3780 the_class->set_annotations(scratch_class->annotations());
3781 scratch_class->set_annotations(old_annotations);
3782 }
3783
3784
3785 // Install the redefinition of a class:
3786 // - house keeping (flushing breakpoints and caches, deoptimizing
3787 // dependent compiled code)
3788 // - replacing parts in the_class with parts from scratch_class
3789 // - adding a weak reference to track the obsolete but interesting
3790 // parts of the_class
3791 // - adjusting constant pool caches and vtables in other classes
3792 // that refer to methods in the_class. These adjustments use the
3793 // ClassLoaderDataGraph::classes_do() facility which only allows
3794 // a helper method to be specified. The interesting parameters
3795 // that we would like to pass to the helper method are saved in
3796 // static global fields in the VM operation.
3797 void VM_RedefineClasses::redefine_single_class(jclass the_jclass,
3798 InstanceKlass* scratch_class, TRAPS) {
3799
3800 HandleMark hm(THREAD); // make sure handles from this call are freed
3801
3802 if (log_is_enabled(Info, redefine, class, timer)) {
3803 _timer_rsc_phase1.start();
3804 }
3805
3806 InstanceKlass* the_class = get_ik(the_jclass);
3807
3808 // Remove all breakpoints in methods of this class
3809 JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
3810 jvmti_breakpoints.clearall_in_class_at_safepoint(the_class);
3811
3812 // Deoptimize all compiled code that depends on this class
3813 flush_dependent_code(the_class, THREAD);
3814
3815 _old_methods = the_class->methods();
3816 _new_methods = scratch_class->methods();
3817 _the_class = the_class;
3818 compute_added_deleted_matching_methods();
3819 update_jmethod_ids();
3820
3821 // Attach new constant pool to the original klass. The original
3822 // klass still refers to the old constant pool (for now).
3823 scratch_class->constants()->set_pool_holder(the_class);
3824
3825 #if 0
3826 // In theory, with constant pool merging in place we should be able
3827 // to save space by using the new, merged constant pool in place of
3828 // the old constant pool(s). By "pool(s)" I mean the constant pool in
3829 // the klass version we are replacing now and any constant pool(s) in
3830 // previous versions of klass. Nice theory, doesn't work in practice.
3831 // When this code is enabled, even simple programs throw NullPointer
3832 // exceptions. I'm guessing that this is caused by some constant pool
3833 // cache difference between the new, merged constant pool and the
3834 // constant pool that was just being used by the klass. I'm keeping
3835 // this code around to archive the idea, but the code has to remain
3836 // disabled for now.
3837
3838 // Attach each old method to the new constant pool. This can be
3839 // done here since we are past the bytecode verification and
3840 // constant pool optimization phases.
3841 for (int i = _old_methods->length() - 1; i >= 0; i--) {
3842 Method* method = _old_methods->at(i);
3843 method->set_constants(scratch_class->constants());
3844 }
3845
3846 // NOTE: this doesn't work because you can redefine the same class in two
3847 // threads, each getting their own constant pool data appended to the
3848 // original constant pool. In order for the new methods to work when they
3849 // become old methods, they need to keep their updated copy of the constant pool.
3850
3851 {
3852 // walk all previous versions of the klass
3853 InstanceKlass *ik = (InstanceKlass *)the_class;
3854 PreviousVersionWalker pvw(ik);
3855 InstanceKlass* ik;
3856 do {
3857 ik = pvw.next_previous_version();
3858 if (ik != NULL) {
3859
3860 // attach previous version of klass to the new constant pool
3861 ik->set_constants(scratch_class->constants());
3862
3863 // Attach each method in the previous version of klass to the
3864 // new constant pool
3865 Array<Method*>* prev_methods = ik->methods();
3866 for (int i = prev_methods->length() - 1; i >= 0; i--) {
3867 Method* method = prev_methods->at(i);
3868 method->set_constants(scratch_class->constants());
3869 }
3870 }
3871 } while (ik != NULL);
3872 }
3873 #endif
3874
3875 // Replace methods and constantpool
3876 the_class->set_methods(_new_methods);
3877 scratch_class->set_methods(_old_methods); // To prevent potential GCing of the old methods,
3878 // and to be able to undo operation easily.
3879
3880 Array<int>* old_ordering = the_class->method_ordering();
3881 the_class->set_method_ordering(scratch_class->method_ordering());
3882 scratch_class->set_method_ordering(old_ordering);
3883
3884 ConstantPool* old_constants = the_class->constants();
3885 the_class->set_constants(scratch_class->constants());
3886 scratch_class->set_constants(old_constants); // See the previous comment.
3887 #if 0
3888 // We are swapping the guts of "the new class" with the guts of "the
3889 // class". Since the old constant pool has just been attached to "the
3890 // new class", it seems logical to set the pool holder in the old
3891 // constant pool also. However, doing this will change the observable
4020 AOTLoader::load_for_klass(the_class, THREAD);
4021 }
4022
4023 // keep track of previous versions of this class
4024 the_class->add_previous_version(scratch_class, emcp_method_count);
4025
4026 _timer_rsc_phase1.stop();
4027 if (log_is_enabled(Info, redefine, class, timer)) {
4028 _timer_rsc_phase2.start();
4029 }
4030
4031 // Adjust constantpool caches and vtables for all classes
4032 // that reference methods of the evolved class.
4033 AdjustCpoolCacheAndVtable adjust_cpool_cache_and_vtable(THREAD);
4034 ClassLoaderDataGraph::classes_do(&adjust_cpool_cache_and_vtable);
4035
4036 // JSR-292 support
4037 MemberNameTable* mnt = the_class->member_names();
4038 if (mnt != NULL) {
4039 bool trace_name_printed = false;
4040 mnt->adjust_method_entries(the_class, &trace_name_printed);
4041 }
4042
4043 if (the_class->oop_map_cache() != NULL) {
4044 // Flush references to any obsolete methods from the oop map cache
4045 // so that obsolete methods are not pinned.
4046 the_class->oop_map_cache()->flush_obsolete_entries();
4047 }
4048
4049 increment_class_counter((InstanceKlass *)the_class, THREAD);
4050 {
4051 ResourceMark rm(THREAD);
4052 // increment the classRedefinedCount field in the_class and in any
4053 // direct and indirect subclasses of the_class
4054 log_info(redefine, class, load)
4055 ("redefined name=%s, count=%d (avail_mem=" UINT64_FORMAT "K)",
4056 the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror()), os::available_memory() >> 10);
4057 Events::log_redefinition(THREAD, "redefined class name=%s, count=%d",
4058 the_class->external_name(),
4059 java_lang_Class::classRedefinedCount(the_class->java_mirror()));
4060
4061 }
4062 _timer_rsc_phase2.stop();
4063 } // end redefine_single_class()
4064
4065
4066 // Increment the classRedefinedCount field in the specific InstanceKlass
4067 // and in all direct and indirect subclasses.
4068 void VM_RedefineClasses::increment_class_counter(InstanceKlass *ik, TRAPS) {
4069 oop class_mirror = ik->java_mirror();
4070 Klass* class_oop = java_lang_Class::as_Klass(class_mirror);
4071 int new_count = java_lang_Class::classRedefinedCount(class_mirror) + 1;
4072 java_lang_Class::set_classRedefinedCount(class_mirror, new_count);
4073
4074 if (class_oop != _the_class) {
4075 // _the_class count is printed at end of redefine_single_class()
4076 log_debug(redefine, class, subclass)("updated count in subclass=%s to %d", ik->external_name(), new_count);
4077 }
4078
4079 for (Klass *subk = ik->subklass(); subk != NULL;
4080 subk = subk->next_sibling()) {
4081 if (subk->is_instance_klass()) {
4082 // Only update instanceKlasses
4083 InstanceKlass *subik = InstanceKlass::cast(subk);
4084 // recursively do subclasses of the current subclass
4085 increment_class_counter(subik, THREAD);
4086 }
4087 }
4088 }
4089
4090 void VM_RedefineClasses::CheckClass::do_klass(Klass* k) {
4091 bool no_old_methods = true; // be optimistic
4092
4093 // Both array and instance classes have vtables.
4094 // a vtable should never contain old or obsolete methods
4095 ResourceMark rm(_thread);
4191 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4192 m->access_flags().print_on(&log_stream);
4193 log_stream.print(" -- ");
4194 m->print_name(&log_stream);
4195 log_stream.cr();
4196 }
4197 log_trace(redefine, class, dump)("_added_methods --");
4198 for (j = 0; j < _added_methods_length; ++j) {
4199 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4200 Method* m = _added_methods[j];
4201 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4202 m->access_flags().print_on(&log_stream);
4203 log_stream.print(" -- ");
4204 m->print_name(&log_stream);
4205 log_stream.cr();
4206 }
4207 }
4208
4209 void VM_RedefineClasses::print_on_error(outputStream* st) const {
4210 VM_Operation::print_on_error(st);
4211 if (_the_class != NULL) {
4212 ResourceMark rm;
4213 st->print_cr(", redefining class %s", _the_class->external_name());
4214 }
4215 }
|