1 /*
2 * Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "cds/aotMetaspace.hpp"
26 #include "cds/cdsConfig.hpp"
27 #include "classfile/classFileStream.hpp"
28 #include "classfile/classLoaderDataGraph.hpp"
29 #include "classfile/classLoadInfo.hpp"
30 #include "classfile/javaClasses.inline.hpp"
31 #include "classfile/klassFactory.hpp"
32 #include "classfile/metadataOnStackMark.hpp"
33 #include "classfile/stackMapTable.hpp"
34 #include "classfile/symbolTable.hpp"
35 #include "classfile/verifier.hpp"
36 #include "classfile/vmClasses.hpp"
37 #include "classfile/vmSymbols.hpp"
38 #include "code/codeCache.hpp"
39 #include "compiler/compileBroker.hpp"
40 #include "interpreter/oopMapCache.hpp"
41 #include "interpreter/rewriter.hpp"
42 #include "jfr/jfrEvents.hpp"
43 #include "logging/logStream.hpp"
44 #include "memory/metadataFactory.hpp"
45 #include "memory/resourceArea.hpp"
46 #include "memory/universe.hpp"
47 #include "oops/annotations.hpp"
48 #include "oops/constantPool.hpp"
49 #include "oops/fieldStreams.inline.hpp"
50 #include "oops/klass.inline.hpp"
51 #include "oops/klassVtable.hpp"
52 #include "oops/method.hpp"
53 #include "oops/oop.inline.hpp"
54 #include "oops/recordComponent.hpp"
55 #include "prims/jvmtiImpl.hpp"
56 #include "prims/jvmtiRedefineClasses.hpp"
57 #include "prims/jvmtiThreadState.inline.hpp"
58 #include "prims/methodComparator.hpp"
59 #include "prims/resolvedMethodTable.hpp"
60 #include "runtime/atomicAccess.hpp"
61 #include "runtime/deoptimization.hpp"
62 #include "runtime/handles.inline.hpp"
63 #include "runtime/jniHandles.inline.hpp"
64 #include "runtime/relocator.hpp"
65 #include "runtime/safepointVerifiers.hpp"
66 #include "utilities/bitMap.inline.hpp"
67 #include "utilities/checkedCast.hpp"
68 #include "utilities/events.hpp"
69 #include "utilities/macros.hpp"
70 #if INCLUDE_JFR
71 #include "jfr/jfr.hpp"
72 #endif
73
74 Array<Method*>* VM_RedefineClasses::_old_methods = nullptr;
75 Array<Method*>* VM_RedefineClasses::_new_methods = nullptr;
76 Method** VM_RedefineClasses::_matching_old_methods = nullptr;
77 Method** VM_RedefineClasses::_matching_new_methods = nullptr;
78 Method** VM_RedefineClasses::_deleted_methods = nullptr;
79 Method** VM_RedefineClasses::_added_methods = nullptr;
80 int VM_RedefineClasses::_matching_methods_length = 0;
81 int VM_RedefineClasses::_deleted_methods_length = 0;
82 int VM_RedefineClasses::_added_methods_length = 0;
83
84 // This flag is global as the constructor does not reset it:
85 bool VM_RedefineClasses::_has_redefined_Object = false;
86 u8 VM_RedefineClasses::_id_counter = 0;
87
88 VM_RedefineClasses::VM_RedefineClasses(jint class_count,
89 const jvmtiClassDefinition *class_defs,
90 JvmtiClassLoadKind class_load_kind) {
91 _class_count = class_count;
92 _class_defs = class_defs;
93 _class_load_kind = class_load_kind;
94 _any_class_has_resolved_methods = false;
95 _res = JVMTI_ERROR_NONE;
96 _the_class = nullptr;
97 _id = next_id();
98 }
99
100 static inline InstanceKlass* get_ik(jclass def) {
101 oop mirror = JNIHandles::resolve_non_null(def);
102 return java_lang_Class::as_InstanceKlass(mirror);
103 }
104
105 // If any of the classes are being redefined, wait
106 // Parallel constant pool merging leads to indeterminate constant pools.
107 void VM_RedefineClasses::lock_classes() {
108 JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
109 GrowableArray<Klass*>* redef_classes = state->get_classes_being_redefined();
110
111 MonitorLocker ml(RedefineClasses_lock);
112
113 if (redef_classes == nullptr) {
114 redef_classes = new (mtClass) GrowableArray<Klass*>(1, mtClass);
115 state->set_classes_being_redefined(redef_classes);
116 }
117
118 bool has_redefined;
119 do {
120 has_redefined = false;
121 // Go through classes each time until none are being redefined. Skip
122 // the ones that are being redefined by this thread currently. Class file
123 // load hook event may trigger new class redefine when we are redefining
124 // a class (after lock_classes()).
125 for (int i = 0; i < _class_count; i++) {
126 InstanceKlass* ik = get_ik(_class_defs[i].klass);
127 // Check if we are currently redefining the class in this thread already.
128 if (redef_classes->contains(ik)) {
129 assert(ik->is_being_redefined(), "sanity");
130 } else {
131 if (ik->is_being_redefined()) {
132 ml.wait();
133 has_redefined = true;
134 break; // for loop
135 }
136 }
137 }
138 } while (has_redefined);
139
140 for (int i = 0; i < _class_count; i++) {
141 InstanceKlass* ik = get_ik(_class_defs[i].klass);
142 redef_classes->push(ik); // Add to the _classes_being_redefined list
143 ik->set_is_being_redefined(true);
144 }
145 ml.notify_all();
146 }
147
148 void VM_RedefineClasses::unlock_classes() {
149 JvmtiThreadState *state = JvmtiThreadState::state_for(JavaThread::current());
150 GrowableArray<Klass*>* redef_classes = state->get_classes_being_redefined();
151 assert(redef_classes != nullptr, "_classes_being_redefined is not allocated");
152
153 MonitorLocker ml(RedefineClasses_lock);
154
155 for (int i = _class_count - 1; i >= 0; i--) {
156 InstanceKlass* def_ik = get_ik(_class_defs[i].klass);
157 if (redef_classes->length() > 0) {
158 // Remove the class from _classes_being_redefined list
159 Klass* k = redef_classes->pop();
160 assert(def_ik == k, "unlocking wrong class");
161 }
162 assert(def_ik->is_being_redefined(),
163 "should be being redefined to get here");
164
165 // Unlock after we finish all redefines for this class within
166 // the thread. Same class can be pushed to the list multiple
167 // times (not more than once by each recursive redefinition).
168 if (!redef_classes->contains(def_ik)) {
169 def_ik->set_is_being_redefined(false);
170 }
171 }
172 ml.notify_all();
173 }
174
175 bool VM_RedefineClasses::doit_prologue() {
176 if (_class_count == 0) {
177 _res = JVMTI_ERROR_NONE;
178 return false;
179 }
180 if (_class_defs == nullptr) {
181 _res = JVMTI_ERROR_NULL_POINTER;
182 return false;
183 }
184
185 for (int i = 0; i < _class_count; i++) {
186 if (_class_defs[i].klass == nullptr) {
187 _res = JVMTI_ERROR_INVALID_CLASS;
188 return false;
189 }
190 if (_class_defs[i].class_byte_count == 0) {
191 _res = JVMTI_ERROR_INVALID_CLASS_FORMAT;
192 return false;
193 }
194 if (_class_defs[i].class_bytes == nullptr) {
195 _res = JVMTI_ERROR_NULL_POINTER;
196 return false;
197 }
198
199 oop mirror = JNIHandles::resolve_non_null(_class_defs[i].klass);
200 // classes for primitives, arrays, and hidden classes
201 // cannot be redefined.
202 if (!is_modifiable_class(mirror)) {
203 _res = JVMTI_ERROR_UNMODIFIABLE_CLASS;
204 return false;
205 }
206 }
207
208 // Start timer after all the sanity checks; not quite accurate, but
209 // better than adding a bunch of stop() calls.
210 if (log_is_enabled(Info, redefine, class, timer)) {
211 _timer_vm_op_prologue.start();
212 }
213
214 lock_classes();
215 // We first load new class versions in the prologue, because somewhere down the
216 // call chain it is required that the current thread is a Java thread.
217 _res = load_new_class_versions();
218 if (_res != JVMTI_ERROR_NONE) {
219 // free any successfully created classes, since none are redefined
220 for (int i = 0; i < _class_count; i++) {
221 if (_scratch_classes[i] != nullptr) {
222 ClassLoaderData* cld = _scratch_classes[i]->class_loader_data();
223 // Free the memory for this class at class unloading time. Not before
224 // because CMS might think this is still live.
225 InstanceKlass* ik = get_ik(_class_defs[i].klass);
226 if (ik->get_cached_class_file() == _scratch_classes[i]->get_cached_class_file()) {
227 // Don't double-free cached_class_file copied from the original class if error.
228 _scratch_classes[i]->set_cached_class_file(nullptr);
229 }
230 cld->add_to_deallocate_list(InstanceKlass::cast(_scratch_classes[i]));
231 }
232 }
233 // Free os::malloc allocated memory in load_new_class_version.
234 os::free(_scratch_classes);
235 _timer_vm_op_prologue.stop();
236 unlock_classes();
237 return false;
238 }
239
240 _timer_vm_op_prologue.stop();
241 return true;
242 }
243
244 void VM_RedefineClasses::doit() {
245 Thread* current = Thread::current();
246
247 if (log_is_enabled(Info, redefine, class, timer)) {
248 _timer_vm_op_doit.start();
249 }
250
251 #if INCLUDE_CDS
252 if (CDSConfig::is_using_archive()) {
253 // Sharing is enabled so we remap the shared readonly space to
254 // shared readwrite, private just in case we need to redefine
255 // a shared class. We do the remap during the doit() phase of
256 // the safepoint to be safer.
257 if (!AOTMetaspace::remap_shared_readonly_as_readwrite()) {
258 log_info(redefine, class, load)("failed to remap shared readonly space to readwrite, private");
259 _res = JVMTI_ERROR_INTERNAL;
260 _timer_vm_op_doit.stop();
261 return;
262 }
263 }
264 #endif
265
266 // Mark methods seen on stack and everywhere else so old methods are not
267 // cleaned up if they're on the stack.
268 MetadataOnStackMark md_on_stack(/*walk_all_metadata*/true, /*redefinition_walk*/true);
269 HandleMark hm(current); // make sure any handles created are deleted
270 // before the stack walk again.
271
272 for (int i = 0; i < _class_count; i++) {
273 redefine_single_class(current, _class_defs[i].klass, _scratch_classes[i]);
274 }
275
276 // Flush all compiled code that depends on the classes redefined.
277 flush_dependent_code();
278
279 // Adjust constantpool caches and vtables for all classes
280 // that reference methods of the evolved classes.
281 // Have to do this after all classes are redefined and all methods that
282 // are redefined are marked as old.
283 AdjustAndCleanMetadata adjust_and_clean_metadata(current);
284 ClassLoaderDataGraph::classes_do(&adjust_and_clean_metadata);
285
286 // JSR-292 support
287 if (_any_class_has_resolved_methods) {
288 bool trace_name_printed = false;
289 ResolvedMethodTable::adjust_method_entries(&trace_name_printed);
290 }
291
292 // Increment flag indicating that some invariants are no longer true.
293 // See jvmtiExport.hpp for detailed explanation.
294 JvmtiExport::increment_redefinition_count();
295
296 // check_class() is optionally called for product bits, but is
297 // always called for non-product bits.
298 #ifdef PRODUCT
299 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
300 #endif
301 log_trace(redefine, class, obsolete, metadata)("calling check_class");
302 CheckClass check_class(current);
303 ClassLoaderDataGraph::classes_do(&check_class);
304 #ifdef PRODUCT
305 }
306 #endif
307
308 // Clean up any metadata now unreferenced while MetadataOnStackMark is set.
309 ClassLoaderDataGraph::clean_deallocate_lists(false);
310
311 _timer_vm_op_doit.stop();
312 }
313
314 void VM_RedefineClasses::doit_epilogue() {
315 unlock_classes();
316
317 // Free os::malloc allocated memory.
318 os::free(_scratch_classes);
319
320 // Reset the_class to null for error printing.
321 _the_class = nullptr;
322
323 if (log_is_enabled(Info, redefine, class, timer)) {
324 // Used to have separate timers for "doit" and "all", but the timer
325 // overhead skewed the measurements.
326 julong doit_time = _timer_vm_op_doit.milliseconds();
327 julong all_time = _timer_vm_op_prologue.milliseconds() + doit_time;
328
329 log_info(redefine, class, timer)
330 ("vm_op: all=" JULONG_FORMAT " prologue=" JULONG_FORMAT " doit=" JULONG_FORMAT,
331 all_time, (julong)_timer_vm_op_prologue.milliseconds(), doit_time);
332 log_info(redefine, class, timer)
333 ("redefine_single_class: phase1=" JULONG_FORMAT " phase2=" JULONG_FORMAT,
334 (julong)_timer_rsc_phase1.milliseconds(), (julong)_timer_rsc_phase2.milliseconds());
335 }
336 }
337
338 bool VM_RedefineClasses::is_modifiable_class(oop klass_mirror) {
339 // classes for primitives cannot be redefined
340 if (java_lang_Class::is_primitive(klass_mirror)) {
341 return false;
342 }
343 Klass* k = java_lang_Class::as_Klass(klass_mirror);
344 // classes for arrays cannot be redefined
345 if (k == nullptr || !k->is_instance_klass()) {
346 return false;
347 }
348
349 // Cannot redefine or retransform a hidden class.
350 if (InstanceKlass::cast(k)->is_hidden()) {
351 return false;
352 }
353 if (InstanceKlass::cast(k) == vmClasses::Continuation_klass()) {
354 // Don't redefine Continuation class. See 8302779.
355 return false;
356 }
357 return true;
358 }
359
360 // Append the current entry at scratch_i in scratch_cp to *merge_cp_p
361 // where the end of *merge_cp_p is specified by *merge_cp_length_p. For
362 // direct CP entries, there is just the current entry to append. For
363 // indirect and double-indirect CP entries, there are zero or more
364 // referenced CP entries along with the current entry to append.
365 // Indirect and double-indirect CP entries are handled by recursive
366 // calls to append_entry() as needed. The referenced CP entries are
367 // always appended to *merge_cp_p before the referee CP entry. These
368 // referenced CP entries may already exist in *merge_cp_p in which case
369 // there is nothing extra to append and only the current entry is
370 // appended.
371 void VM_RedefineClasses::append_entry(const constantPoolHandle& scratch_cp,
372 int scratch_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p) {
373
374 // append is different depending on entry tag type
375 switch (scratch_cp->tag_at(scratch_i).value()) {
376
377 // The old verifier is implemented outside the VM. It loads classes,
378 // but does not resolve constant pool entries directly so we never
379 // see Class entries here with the old verifier. Similarly the old
380 // verifier does not like Class entries in the input constant pool.
381 // The split-verifier is implemented in the VM so it can optionally
382 // and directly resolve constant pool entries to load classes. The
383 // split-verifier can accept either Class entries or UnresolvedClass
384 // entries in the input constant pool. We revert the appended copy
385 // back to UnresolvedClass so that either verifier will be happy
386 // with the constant pool entry.
387 //
388 // this is an indirect CP entry so it needs special handling
389 case JVM_CONSTANT_Class:
390 case JVM_CONSTANT_UnresolvedClass:
391 {
392 int name_i = scratch_cp->klass_name_index_at(scratch_i);
393 int new_name_i = find_or_append_indirect_entry(scratch_cp, name_i, merge_cp_p,
394 merge_cp_length_p);
395
396 if (new_name_i != name_i) {
397 log_trace(redefine, class, constantpool)
398 ("Class entry@%d name_index change: %d to %d",
399 *merge_cp_length_p, name_i, new_name_i);
400 }
401
402 (*merge_cp_p)->temp_unresolved_klass_at_put(*merge_cp_length_p, new_name_i);
403 if (scratch_i != *merge_cp_length_p) {
404 // The new entry in *merge_cp_p is at a different index than
405 // the new entry in scratch_cp so we need to map the index values.
406 map_index(scratch_cp, scratch_i, *merge_cp_length_p);
407 }
408 (*merge_cp_length_p)++;
409 } break;
410
411 // these are direct CP entries so they can be directly appended,
412 // but double and long take two constant pool entries
413 case JVM_CONSTANT_Double: // fall through
414 case JVM_CONSTANT_Long:
415 {
416 ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p);
417
418 if (scratch_i != *merge_cp_length_p) {
419 // The new entry in *merge_cp_p is at a different index than
420 // the new entry in scratch_cp so we need to map the index values.
421 map_index(scratch_cp, scratch_i, *merge_cp_length_p);
422 }
423 (*merge_cp_length_p) += 2;
424 } break;
425
426 // these are direct CP entries so they can be directly appended
427 case JVM_CONSTANT_Float: // fall through
428 case JVM_CONSTANT_Integer: // fall through
429 case JVM_CONSTANT_Utf8: // fall through
430
431 // This was an indirect CP entry, but it has been changed into
432 // Symbol*s so this entry can be directly appended.
433 case JVM_CONSTANT_String: // fall through
434 {
435 ConstantPool::copy_entry_to(scratch_cp, scratch_i, *merge_cp_p, *merge_cp_length_p);
436
437 if (scratch_i != *merge_cp_length_p) {
438 // The new entry in *merge_cp_p is at a different index than
439 // the new entry in scratch_cp so we need to map the index values.
440 map_index(scratch_cp, scratch_i, *merge_cp_length_p);
441 }
442 (*merge_cp_length_p)++;
443 } break;
444
445 // this is an indirect CP entry so it needs special handling
446 case JVM_CONSTANT_NameAndType:
447 {
448 int name_ref_i = scratch_cp->name_ref_index_at(scratch_i);
449 int new_name_ref_i = find_or_append_indirect_entry(scratch_cp, name_ref_i, merge_cp_p,
450 merge_cp_length_p);
451
452 int signature_ref_i = scratch_cp->signature_ref_index_at(scratch_i);
453 int new_signature_ref_i = find_or_append_indirect_entry(scratch_cp, signature_ref_i,
454 merge_cp_p, merge_cp_length_p);
455
456 // If the referenced entries already exist in *merge_cp_p, then
457 // both new_name_ref_i and new_signature_ref_i will both be 0.
458 // In that case, all we are appending is the current entry.
459 if (new_name_ref_i != name_ref_i) {
460 log_trace(redefine, class, constantpool)
461 ("NameAndType entry@%d name_ref_index change: %d to %d",
462 *merge_cp_length_p, name_ref_i, new_name_ref_i);
463 }
464 if (new_signature_ref_i != signature_ref_i) {
465 log_trace(redefine, class, constantpool)
466 ("NameAndType entry@%d signature_ref_index change: %d to %d",
467 *merge_cp_length_p, signature_ref_i, new_signature_ref_i);
468 }
469
470 (*merge_cp_p)->name_and_type_at_put(*merge_cp_length_p,
471 new_name_ref_i, new_signature_ref_i);
472 if (scratch_i != *merge_cp_length_p) {
473 // The new entry in *merge_cp_p is at a different index than
474 // the new entry in scratch_cp so we need to map the index values.
475 map_index(scratch_cp, scratch_i, *merge_cp_length_p);
476 }
477 (*merge_cp_length_p)++;
478 } break;
479
480 // this is a double-indirect CP entry so it needs special handling
481 case JVM_CONSTANT_Fieldref: // fall through
482 case JVM_CONSTANT_InterfaceMethodref: // fall through
483 case JVM_CONSTANT_Methodref:
484 {
485 int klass_ref_i = scratch_cp->uncached_klass_ref_index_at(scratch_i);
486 int new_klass_ref_i = find_or_append_indirect_entry(scratch_cp, klass_ref_i,
487 merge_cp_p, merge_cp_length_p);
488
489 int name_and_type_ref_i = scratch_cp->uncached_name_and_type_ref_index_at(scratch_i);
490 int new_name_and_type_ref_i = find_or_append_indirect_entry(scratch_cp, name_and_type_ref_i,
491 merge_cp_p, merge_cp_length_p);
492
493 const char *entry_name = nullptr;
494 switch (scratch_cp->tag_at(scratch_i).value()) {
495 case JVM_CONSTANT_Fieldref:
496 entry_name = "Fieldref";
497 (*merge_cp_p)->field_at_put(*merge_cp_length_p, new_klass_ref_i,
498 new_name_and_type_ref_i);
499 break;
500 case JVM_CONSTANT_InterfaceMethodref:
501 entry_name = "IFMethodref";
502 (*merge_cp_p)->interface_method_at_put(*merge_cp_length_p,
503 new_klass_ref_i, new_name_and_type_ref_i);
504 break;
505 case JVM_CONSTANT_Methodref:
506 entry_name = "Methodref";
507 (*merge_cp_p)->method_at_put(*merge_cp_length_p, new_klass_ref_i,
508 new_name_and_type_ref_i);
509 break;
510 default:
511 guarantee(false, "bad switch");
512 break;
513 }
514
515 if (klass_ref_i != new_klass_ref_i) {
516 log_trace(redefine, class, constantpool)
517 ("%s entry@%d class_index changed: %d to %d", entry_name, *merge_cp_length_p, klass_ref_i, new_klass_ref_i);
518 }
519 if (name_and_type_ref_i != new_name_and_type_ref_i) {
520 log_trace(redefine, class, constantpool)
521 ("%s entry@%d name_and_type_index changed: %d to %d",
522 entry_name, *merge_cp_length_p, name_and_type_ref_i, new_name_and_type_ref_i);
523 }
524
525 if (scratch_i != *merge_cp_length_p) {
526 // The new entry in *merge_cp_p is at a different index than
527 // the new entry in scratch_cp so we need to map the index values.
528 map_index(scratch_cp, scratch_i, *merge_cp_length_p);
529 }
530 (*merge_cp_length_p)++;
531 } break;
532
533 // this is an indirect CP entry so it needs special handling
534 case JVM_CONSTANT_MethodType:
535 {
536 int ref_i = scratch_cp->method_type_index_at(scratch_i);
537 int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
538 merge_cp_length_p);
539 if (new_ref_i != ref_i) {
540 log_trace(redefine, class, constantpool)
541 ("MethodType entry@%d ref_index change: %d to %d", *merge_cp_length_p, ref_i, new_ref_i);
542 }
543 (*merge_cp_p)->method_type_index_at_put(*merge_cp_length_p, new_ref_i);
544 if (scratch_i != *merge_cp_length_p) {
545 // The new entry in *merge_cp_p is at a different index than
546 // the new entry in scratch_cp so we need to map the index values.
547 map_index(scratch_cp, scratch_i, *merge_cp_length_p);
548 }
549 (*merge_cp_length_p)++;
550 } break;
551
552 // this is an indirect CP entry so it needs special handling
553 case JVM_CONSTANT_MethodHandle:
554 {
555 int ref_kind = scratch_cp->method_handle_ref_kind_at(scratch_i);
556 int ref_i = scratch_cp->method_handle_index_at(scratch_i);
557 int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
558 merge_cp_length_p);
559 if (new_ref_i != ref_i) {
560 log_trace(redefine, class, constantpool)
561 ("MethodHandle entry@%d ref_index change: %d to %d", *merge_cp_length_p, ref_i, new_ref_i);
562 }
563 (*merge_cp_p)->method_handle_index_at_put(*merge_cp_length_p, ref_kind, new_ref_i);
564 if (scratch_i != *merge_cp_length_p) {
565 // The new entry in *merge_cp_p is at a different index than
566 // the new entry in scratch_cp so we need to map the index values.
567 map_index(scratch_cp, scratch_i, *merge_cp_length_p);
568 }
569 (*merge_cp_length_p)++;
570 } break;
571
572 // this is an indirect CP entry so it needs special handling
573 case JVM_CONSTANT_Dynamic: // fall through
574 case JVM_CONSTANT_InvokeDynamic:
575 {
576 // Index of the bootstrap specifier in the operands array
577 int old_bs_i = scratch_cp->bootstrap_methods_attribute_index(scratch_i);
578 int new_bs_i = find_or_append_operand(scratch_cp, old_bs_i, merge_cp_p,
579 merge_cp_length_p);
580 // The bootstrap method NameAndType_info index
581 int old_ref_i = scratch_cp->bootstrap_name_and_type_ref_index_at(scratch_i);
582 int new_ref_i = find_or_append_indirect_entry(scratch_cp, old_ref_i, merge_cp_p,
583 merge_cp_length_p);
584 if (new_bs_i != old_bs_i) {
585 log_trace(redefine, class, constantpool)
586 ("Dynamic entry@%d bootstrap_method_attr_index change: %d to %d",
587 *merge_cp_length_p, old_bs_i, new_bs_i);
588 }
589 if (new_ref_i != old_ref_i) {
590 log_trace(redefine, class, constantpool)
591 ("Dynamic entry@%d name_and_type_index change: %d to %d", *merge_cp_length_p, old_ref_i, new_ref_i);
592 }
593
594 if (scratch_cp->tag_at(scratch_i).is_dynamic_constant())
595 (*merge_cp_p)->dynamic_constant_at_put(*merge_cp_length_p, new_bs_i, new_ref_i);
596 else
597 (*merge_cp_p)->invoke_dynamic_at_put(*merge_cp_length_p, new_bs_i, new_ref_i);
598 if (scratch_i != *merge_cp_length_p) {
599 // The new entry in *merge_cp_p is at a different index than
600 // the new entry in scratch_cp so we need to map the index values.
601 map_index(scratch_cp, scratch_i, *merge_cp_length_p);
602 }
603 (*merge_cp_length_p)++;
604 } break;
605
606 // At this stage, Class or UnresolvedClass could be in scratch_cp, but not
607 // ClassIndex
608 case JVM_CONSTANT_ClassIndex: // fall through
609
610 // Invalid is used as the tag for the second constant pool entry
611 // occupied by JVM_CONSTANT_Double or JVM_CONSTANT_Long. It should
612 // not be seen by itself.
613 case JVM_CONSTANT_Invalid: // fall through
614
615 // At this stage, String could be here, but not StringIndex
616 case JVM_CONSTANT_StringIndex: // fall through
617
618 // At this stage JVM_CONSTANT_UnresolvedClassInError should not be
619 // here
620 case JVM_CONSTANT_UnresolvedClassInError: // fall through
621
622 default:
623 {
624 // leave a breadcrumb
625 jbyte bad_value = scratch_cp->tag_at(scratch_i).value();
626 ShouldNotReachHere();
627 } break;
628 } // end switch tag value
629 } // end append_entry()
630
631
632 u2 VM_RedefineClasses::find_or_append_indirect_entry(const constantPoolHandle& scratch_cp,
633 int ref_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p) {
634
635 int new_ref_i = ref_i;
636 bool match = (ref_i < *merge_cp_length_p) &&
637 scratch_cp->compare_entry_to(ref_i, *merge_cp_p, ref_i);
638
639 if (!match) {
640 // forward reference in *merge_cp_p or not a direct match
641 int found_i = scratch_cp->find_matching_entry(ref_i, *merge_cp_p);
642 if (found_i != 0) {
643 guarantee(found_i != ref_i, "compare_entry_to() and find_matching_entry() do not agree");
644 // Found a matching entry somewhere else in *merge_cp_p so just need a mapping entry.
645 new_ref_i = found_i;
646 map_index(scratch_cp, ref_i, found_i);
647 } else {
648 // no match found so we have to append this entry to *merge_cp_p
649 append_entry(scratch_cp, ref_i, merge_cp_p, merge_cp_length_p);
650 // The above call to append_entry() can only append one entry
651 // so the post call query of *merge_cp_length_p is only for
652 // the sake of consistency.
653 new_ref_i = *merge_cp_length_p - 1;
654 }
655 }
656
657 // constant pool indices are u2, unless the merged constant pool overflows which
658 // we don't check for.
659 return checked_cast<u2>(new_ref_i);
660 } // end find_or_append_indirect_entry()
661
662
663 // Append a bootstrap specifier into the merge_cp operands that is semantically equal
664 // to the scratch_cp operands bootstrap specifier passed by the old_bs_i index.
665 // Recursively append new merge_cp entries referenced by the new bootstrap specifier.
666 void VM_RedefineClasses::append_operand(const constantPoolHandle& scratch_cp, const int old_bs_i,
667 constantPoolHandle *merge_cp_p, int *merge_cp_length_p) {
668
669 BSMAttributeEntry* old_bsme = scratch_cp->bsm_attribute_entry(old_bs_i);
670 u2 old_ref_i = old_bsme->bootstrap_method_index();
671 u2 new_ref_i = find_or_append_indirect_entry(scratch_cp, old_ref_i, merge_cp_p,
672 merge_cp_length_p);
673 if (new_ref_i != old_ref_i) {
674 log_trace(redefine, class, constantpool)
675 ("operands entry@%d bootstrap method ref_index change: %d to %d", _operands_cur_length, old_ref_i, new_ref_i);
676 }
677
678 Array<u2>* merge_ops = (*merge_cp_p)->operands();
679 int new_bs_i = _operands_cur_length;
680 // We have _operands_cur_length == 0 when the merge_cp operands is empty yet.
681 // However, the operand_offset_at(0) was set in the extend_operands() call.
682 int new_base = (new_bs_i == 0) ? (*merge_cp_p)->operand_offset_at(0)
683 : (*merge_cp_p)->operand_next_offset_at(new_bs_i - 1);
684 u2 argc = old_bsme->argument_count();
685
686 ConstantPool::operand_offset_at_put(merge_ops, _operands_cur_length, new_base);
687 merge_ops->at_put(new_base++, new_ref_i);
688 merge_ops->at_put(new_base++, argc);
689
690 for (int i = 0; i < argc; i++) {
691 u2 old_arg_ref_i = old_bsme->argument_index(i);
692 u2 new_arg_ref_i = find_or_append_indirect_entry(scratch_cp, old_arg_ref_i, merge_cp_p,
693 merge_cp_length_p);
694 merge_ops->at_put(new_base++, new_arg_ref_i);
695 if (new_arg_ref_i != old_arg_ref_i) {
696 log_trace(redefine, class, constantpool)
697 ("operands entry@%d bootstrap method argument ref_index change: %d to %d",
698 _operands_cur_length, old_arg_ref_i, new_arg_ref_i);
699 }
700 }
701 if (old_bs_i != _operands_cur_length) {
702 // The bootstrap specifier in *merge_cp_p is at a different index than
703 // that in scratch_cp so we need to map the index values.
704 map_operand_index(old_bs_i, new_bs_i);
705 }
706 _operands_cur_length++;
707 } // end append_operand()
708
709
710 int VM_RedefineClasses::find_or_append_operand(const constantPoolHandle& scratch_cp,
711 int old_bs_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p) {
712
713 int new_bs_i = old_bs_i; // bootstrap specifier index
714 bool match = (old_bs_i < _operands_cur_length) &&
715 scratch_cp->compare_operand_to(old_bs_i, *merge_cp_p, old_bs_i);
716
717 if (!match) {
718 // forward reference in *merge_cp_p or not a direct match
719 int found_i = scratch_cp->find_matching_operand(old_bs_i, *merge_cp_p,
720 _operands_cur_length);
721 if (found_i != -1) {
722 guarantee(found_i != old_bs_i, "compare_operand_to() and find_matching_operand() disagree");
723 // found a matching operand somewhere else in *merge_cp_p so just need a mapping
724 new_bs_i = found_i;
725 map_operand_index(old_bs_i, found_i);
726 } else {
727 // no match found so we have to append this bootstrap specifier to *merge_cp_p
728 append_operand(scratch_cp, old_bs_i, merge_cp_p, merge_cp_length_p);
729 new_bs_i = _operands_cur_length - 1;
730 }
731 }
732 return new_bs_i;
733 } // end find_or_append_operand()
734
735
736 void VM_RedefineClasses::finalize_operands_merge(const constantPoolHandle& merge_cp, TRAPS) {
737 if (merge_cp->operands() == nullptr) {
738 return;
739 }
740 // Shrink the merge_cp operands
741 merge_cp->shrink_operands(_operands_cur_length, CHECK);
742
743 if (log_is_enabled(Trace, redefine, class, constantpool)) {
744 // don't want to loop unless we are tracing
745 int count = 0;
746 for (int i = 1; i < _operands_index_map_p->length(); i++) {
747 int value = _operands_index_map_p->at(i);
748 if (value != -1) {
749 log_trace(redefine, class, constantpool)("operands_index_map[%d]: old=%d new=%d", count, i, value);
750 count++;
751 }
752 }
753 }
754 // Clean-up
755 _operands_index_map_p = nullptr;
756 _operands_cur_length = 0;
757 _operands_index_map_count = 0;
758 } // end finalize_operands_merge()
759
760 // Symbol* comparator for qsort
761 // The caller must have an active ResourceMark.
762 static int symcmp(const void* a, const void* b) {
763 char* astr = (*(Symbol**)a)->as_C_string();
764 char* bstr = (*(Symbol**)b)->as_C_string();
765 return strcmp(astr, bstr);
766 }
767
768 // The caller must have an active ResourceMark.
769 static jvmtiError check_attribute_arrays(const char* attr_name,
770 InstanceKlass* the_class, InstanceKlass* scratch_class,
771 Array<u2>* the_array, Array<u2>* scr_array) {
772 bool the_array_exists = the_array != Universe::the_empty_short_array();
773 bool scr_array_exists = scr_array != Universe::the_empty_short_array();
774
775 int array_len = the_array->length();
776 if (the_array_exists && scr_array_exists) {
777 if (array_len != scr_array->length()) {
778 log_trace(redefine, class)
779 ("redefined class %s attribute change error: %s len=%d changed to len=%d",
780 the_class->external_name(), attr_name, array_len, scr_array->length());
781 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
782 }
783
784 // The order of entries in the attribute array is not specified so we
785 // have to explicitly check for the same contents. We do this by copying
786 // the referenced symbols into their own arrays, sorting them and then
787 // comparing each element pair.
788
789 Symbol** the_syms = NEW_RESOURCE_ARRAY_RETURN_NULL(Symbol*, array_len);
790 Symbol** scr_syms = NEW_RESOURCE_ARRAY_RETURN_NULL(Symbol*, array_len);
791
792 if (the_syms == nullptr || scr_syms == nullptr) {
793 return JVMTI_ERROR_OUT_OF_MEMORY;
794 }
795
796 for (int i = 0; i < array_len; i++) {
797 int the_cp_index = the_array->at(i);
798 int scr_cp_index = scr_array->at(i);
799 the_syms[i] = the_class->constants()->klass_name_at(the_cp_index);
800 scr_syms[i] = scratch_class->constants()->klass_name_at(scr_cp_index);
801 }
802
803 qsort(the_syms, array_len, sizeof(Symbol*), symcmp);
804 qsort(scr_syms, array_len, sizeof(Symbol*), symcmp);
805
806 for (int i = 0; i < array_len; i++) {
807 if (the_syms[i] != scr_syms[i]) {
808 log_info(redefine, class)
809 ("redefined class %s attribute change error: %s[%d]: %s changed to %s",
810 the_class->external_name(), attr_name, i,
811 the_syms[i]->as_C_string(), scr_syms[i]->as_C_string());
812 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
813 }
814 }
815 } else if (the_array_exists ^ scr_array_exists) {
816 const char* action_str = (the_array_exists) ? "removed" : "added";
817 log_info(redefine, class)
818 ("redefined class %s attribute change error: %s attribute %s",
819 the_class->external_name(), attr_name, action_str);
820 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
821 }
822 return JVMTI_ERROR_NONE;
823 }
824
825 static jvmtiError check_nest_attributes(InstanceKlass* the_class,
826 InstanceKlass* scratch_class) {
827 // Check whether the class NestHost attribute has been changed.
828 Thread* thread = Thread::current();
829 ResourceMark rm(thread);
830 u2 the_nest_host_idx = the_class->nest_host_index();
831 u2 scr_nest_host_idx = scratch_class->nest_host_index();
832
833 if (the_nest_host_idx != 0 && scr_nest_host_idx != 0) {
834 Symbol* the_sym = the_class->constants()->klass_name_at(the_nest_host_idx);
835 Symbol* scr_sym = scratch_class->constants()->klass_name_at(scr_nest_host_idx);
836 if (the_sym != scr_sym) {
837 log_info(redefine, class, nestmates)
838 ("redefined class %s attribute change error: NestHost class: %s replaced with: %s",
839 the_class->external_name(), the_sym->as_C_string(), scr_sym->as_C_string());
840 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
841 }
842 } else if ((the_nest_host_idx == 0) ^ (scr_nest_host_idx == 0)) {
843 const char* action_str = (the_nest_host_idx != 0) ? "removed" : "added";
844 log_info(redefine, class, nestmates)
845 ("redefined class %s attribute change error: NestHost attribute %s",
846 the_class->external_name(), action_str);
847 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
848 }
849
850 // Check whether the class NestMembers attribute has been changed.
851 return check_attribute_arrays("NestMembers",
852 the_class, scratch_class,
853 the_class->nest_members(),
854 scratch_class->nest_members());
855 }
856
857 // Return an error status if the class Record attribute was changed.
858 static jvmtiError check_record_attribute(InstanceKlass* the_class, InstanceKlass* scratch_class) {
859 // Get lists of record components.
860 Array<RecordComponent*>* the_record = the_class->record_components();
861 Array<RecordComponent*>* scr_record = scratch_class->record_components();
862 bool the_record_exists = the_record != nullptr;
863 bool scr_record_exists = scr_record != nullptr;
864
865 if (the_record_exists && scr_record_exists) {
866 int the_num_components = the_record->length();
867 int scr_num_components = scr_record->length();
868 if (the_num_components != scr_num_components) {
869 log_info(redefine, class, record)
870 ("redefined class %s attribute change error: Record num_components=%d changed to num_components=%d",
871 the_class->external_name(), the_num_components, scr_num_components);
872 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
873 }
874
875 // Compare each field in each record component.
876 ConstantPool* the_cp = the_class->constants();
877 ConstantPool* scr_cp = scratch_class->constants();
878 for (int x = 0; x < the_num_components; x++) {
879 RecordComponent* the_component = the_record->at(x);
880 RecordComponent* scr_component = scr_record->at(x);
881 const Symbol* const the_name = the_cp->symbol_at(the_component->name_index());
882 const Symbol* const scr_name = scr_cp->symbol_at(scr_component->name_index());
883 const Symbol* const the_descr = the_cp->symbol_at(the_component->descriptor_index());
884 const Symbol* const scr_descr = scr_cp->symbol_at(scr_component->descriptor_index());
885 if (the_name != scr_name || the_descr != scr_descr) {
886 log_info(redefine, class, record)
887 ("redefined class %s attribute change error: Record name_index, descriptor_index, and/or attributes_count changed",
888 the_class->external_name());
889 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
890 }
891
892 int the_gen_sig = the_component->generic_signature_index();
893 int scr_gen_sig = scr_component->generic_signature_index();
894 const Symbol* const the_gen_sig_sym = (the_gen_sig == 0 ? nullptr :
895 the_cp->symbol_at(the_component->generic_signature_index()));
896 const Symbol* const scr_gen_sig_sym = (scr_gen_sig == 0 ? nullptr :
897 scr_cp->symbol_at(scr_component->generic_signature_index()));
898 if (the_gen_sig_sym != scr_gen_sig_sym) {
899 log_info(redefine, class, record)
900 ("redefined class %s attribute change error: Record generic_signature attribute changed",
901 the_class->external_name());
902 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
903 }
904
905 // It's okay if a record component's annotations were changed.
906 }
907
908 } else if (the_record_exists ^ scr_record_exists) {
909 const char* action_str = (the_record_exists) ? "removed" : "added";
910 log_info(redefine, class, record)
911 ("redefined class %s attribute change error: Record attribute %s",
912 the_class->external_name(), action_str);
913 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_ATTRIBUTE_CHANGED;
914 }
915
916 return JVMTI_ERROR_NONE;
917 }
918
919
920 static jvmtiError check_permitted_subclasses_attribute(InstanceKlass* the_class,
921 InstanceKlass* scratch_class) {
922 Thread* thread = Thread::current();
923 ResourceMark rm(thread);
924
925 // Check whether the class PermittedSubclasses attribute has been changed.
926 return check_attribute_arrays("PermittedSubclasses",
927 the_class, scratch_class,
928 the_class->permitted_subclasses(),
929 scratch_class->permitted_subclasses());
930 }
931
932 static bool can_add_or_delete(Method* m) {
933 // Compatibility mode
934 return (AllowRedefinitionToAddDeleteMethods &&
935 (m->is_private() && (m->is_static() || m->is_final())));
936 }
937
938 jvmtiError VM_RedefineClasses::compare_and_normalize_class_versions(
939 InstanceKlass* the_class,
940 InstanceKlass* scratch_class) {
941 int i;
942
943 // Check superclasses, or rather their names, since superclasses themselves can be
944 // requested to replace.
945 // Check for null superclass first since this might be java.lang.Object
946 if (the_class->super() != scratch_class->super() &&
947 (the_class->super() == nullptr || scratch_class->super() == nullptr ||
948 the_class->super()->name() !=
949 scratch_class->super()->name())) {
950 log_info(redefine, class, normalize)
951 ("redefined class %s superclass change error: superclass changed from %s to %s.",
952 the_class->external_name(),
953 the_class->super() == nullptr ? "null" : the_class->super()->external_name(),
954 scratch_class->super() == nullptr ? "null" : scratch_class->super()->external_name());
955 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
956 }
957
958 // Check if the number, names and order of directly implemented interfaces are the same.
959 // I think in principle we should just check if the sets of names of directly implemented
960 // interfaces are the same, i.e. the order of declaration (which, however, if changed in the
961 // .java file, also changes in .class file) should not matter. However, comparing sets is
962 // technically a bit more difficult, and, more importantly, I am not sure at present that the
963 // order of interfaces does not matter on the implementation level, i.e. that the VM does not
964 // rely on it somewhere.
965 Array<InstanceKlass*>* k_interfaces = the_class->local_interfaces();
966 Array<InstanceKlass*>* k_new_interfaces = scratch_class->local_interfaces();
967 int n_intfs = k_interfaces->length();
968 if (n_intfs != k_new_interfaces->length()) {
969 log_info(redefine, class, normalize)
970 ("redefined class %s interfaces change error: number of implemented interfaces changed from %d to %d.",
971 the_class->external_name(), n_intfs, k_new_interfaces->length());
972 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
973 }
974 for (i = 0; i < n_intfs; i++) {
975 if (k_interfaces->at(i)->name() !=
976 k_new_interfaces->at(i)->name()) {
977 log_info(redefine, class, normalize)
978 ("redefined class %s interfaces change error: interface changed from %s to %s.",
979 the_class->external_name(),
980 k_interfaces->at(i)->external_name(), k_new_interfaces->at(i)->external_name());
981 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED;
982 }
983 }
984
985 // Check whether class is in the error init state.
986 if (the_class->is_in_error_state()) {
987 log_info(redefine, class, normalize)
988 ("redefined class %s is in error init state.", the_class->external_name());
989 // TBD #5057930: special error code is needed in 1.6
990 return JVMTI_ERROR_INVALID_CLASS;
991 }
992
993 // Check whether the nest-related attributes have been changed.
994 jvmtiError err = check_nest_attributes(the_class, scratch_class);
995 if (err != JVMTI_ERROR_NONE) {
996 return err;
997 }
998
999 // Check whether the Record attribute has been changed.
1000 err = check_record_attribute(the_class, scratch_class);
1001 if (err != JVMTI_ERROR_NONE) {
1002 return err;
1003 }
1004
1005 // Check whether the PermittedSubclasses attribute has been changed.
1006 err = check_permitted_subclasses_attribute(the_class, scratch_class);
1007 if (err != JVMTI_ERROR_NONE) {
1008 return err;
1009 }
1010
1011 // Check whether class modifiers are the same.
1012 u2 old_flags = the_class->access_flags().as_class_flags();
1013 u2 new_flags = scratch_class->access_flags().as_class_flags();
1014 if (old_flags != new_flags) {
1015 log_info(redefine, class, normalize)
1016 ("redefined class %s modifiers change error: modifiers changed from %d to %d.",
1017 the_class->external_name(), old_flags, new_flags);
1018 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED;
1019 }
1020
1021 // Check if the number, names, types and order of fields declared in these classes
1022 // are the same.
1023 JavaFieldStream old_fs(the_class);
1024 JavaFieldStream new_fs(scratch_class);
1025 for (; !old_fs.done() && !new_fs.done(); old_fs.next(), new_fs.next()) {
1026 // name and signature
1027 Symbol* name_sym1 = the_class->constants()->symbol_at(old_fs.name_index());
1028 Symbol* sig_sym1 = the_class->constants()->symbol_at(old_fs.signature_index());
1029 Symbol* name_sym2 = scratch_class->constants()->symbol_at(new_fs.name_index());
1030 Symbol* sig_sym2 = scratch_class->constants()->symbol_at(new_fs.signature_index());
1031 if (name_sym1 != name_sym2 || sig_sym1 != sig_sym2) {
1032 log_info(redefine, class, normalize)
1033 ("redefined class %s fields change error: field %s %s changed to %s %s.",
1034 the_class->external_name(),
1035 sig_sym1->as_C_string(), name_sym1->as_C_string(),
1036 sig_sym2->as_C_string(), name_sym2->as_C_string());
1037 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
1038 }
1039 // offset
1040 if (old_fs.offset() != new_fs.offset()) {
1041 log_info(redefine, class, normalize)
1042 ("redefined class %s field %s change error: offset changed from %d to %d.",
1043 the_class->external_name(), name_sym2->as_C_string(), old_fs.offset(), new_fs.offset());
1044 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
1045 }
1046 // access
1047 old_flags = old_fs.access_flags().as_field_flags();
1048 new_flags = new_fs.access_flags().as_field_flags();
1049 if (old_flags != new_flags) {
1050 log_info(redefine, class, normalize)
1051 ("redefined class %s field %s change error: modifiers changed from %d to %d.",
1052 the_class->external_name(), name_sym2->as_C_string(), old_flags, new_flags);
1053 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
1054 }
1055 }
1056
1057 // If both streams aren't done then we have a differing number of
1058 // fields.
1059 if (!old_fs.done() || !new_fs.done()) {
1060 const char* action = old_fs.done() ? "added" : "deleted";
1061 log_info(redefine, class, normalize)
1062 ("redefined class %s fields change error: some fields were %s.",
1063 the_class->external_name(), action);
1064 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED;
1065 }
1066
1067 // Do a parallel walk through the old and new methods. Detect
1068 // cases where they match (exist in both), have been added in
1069 // the new methods, or have been deleted (exist only in the
1070 // old methods). The class file parser places methods in order
1071 // by method name, but does not order overloaded methods by
1072 // signature. In order to determine what fate befell the methods,
1073 // this code places the overloaded new methods that have matching
1074 // old methods in the same order as the old methods and places
1075 // new overloaded methods at the end of overloaded methods of
1076 // that name. The code for this order normalization is adapted
1077 // from the algorithm used in InstanceKlass::find_method().
1078 // Since we are swapping out of order entries as we find them,
1079 // we only have to search forward through the overloaded methods.
1080 // Methods which are added and have the same name as an existing
1081 // method (but different signature) will be put at the end of
1082 // the methods with that name, and the name mismatch code will
1083 // handle them.
1084 Array<Method*>* k_old_methods(the_class->methods());
1085 Array<Method*>* k_new_methods(scratch_class->methods());
1086 int n_old_methods = k_old_methods->length();
1087 int n_new_methods = k_new_methods->length();
1088 Thread* thread = Thread::current();
1089
1090 int ni = 0;
1091 int oi = 0;
1092 while (true) {
1093 Method* k_old_method;
1094 Method* k_new_method;
1095 enum { matched, added, deleted, undetermined } method_was = undetermined;
1096
1097 if (oi >= n_old_methods) {
1098 if (ni >= n_new_methods) {
1099 break; // we've looked at everything, done
1100 }
1101 // New method at the end
1102 k_new_method = k_new_methods->at(ni);
1103 method_was = added;
1104 } else if (ni >= n_new_methods) {
1105 // Old method, at the end, is deleted
1106 k_old_method = k_old_methods->at(oi);
1107 method_was = deleted;
1108 } else {
1109 // There are more methods in both the old and new lists
1110 k_old_method = k_old_methods->at(oi);
1111 k_new_method = k_new_methods->at(ni);
1112 if (k_old_method->name() != k_new_method->name()) {
1113 // Methods are sorted by method name, so a mismatch means added
1114 // or deleted
1115 if (k_old_method->name()->fast_compare(k_new_method->name()) > 0) {
1116 method_was = added;
1117 } else {
1118 method_was = deleted;
1119 }
1120 } else if (k_old_method->signature() == k_new_method->signature()) {
1121 // Both the name and signature match
1122 method_was = matched;
1123 } else {
1124 // The name matches, but the signature doesn't, which means we have to
1125 // search forward through the new overloaded methods.
1126 int nj; // outside the loop for post-loop check
1127 for (nj = ni + 1; nj < n_new_methods; nj++) {
1128 Method* m = k_new_methods->at(nj);
1129 if (k_old_method->name() != m->name()) {
1130 // reached another method name so no more overloaded methods
1131 method_was = deleted;
1132 break;
1133 }
1134 if (k_old_method->signature() == m->signature()) {
1135 // found a match so swap the methods
1136 k_new_methods->at_put(ni, m);
1137 k_new_methods->at_put(nj, k_new_method);
1138 k_new_method = m;
1139 method_was = matched;
1140 break;
1141 }
1142 }
1143
1144 if (nj >= n_new_methods) {
1145 // reached the end without a match; so method was deleted
1146 method_was = deleted;
1147 }
1148 }
1149 }
1150
1151 switch (method_was) {
1152 case matched:
1153 // methods match, be sure modifiers do too
1154 old_flags = k_old_method->access_flags().as_method_flags();
1155 new_flags = k_new_method->access_flags().as_method_flags();
1156 if ((old_flags ^ new_flags) & ~(JVM_ACC_NATIVE)) {
1157 log_info(redefine, class, normalize)
1158 ("redefined class %s method %s modifiers error: modifiers changed from %d to %d",
1159 the_class->external_name(), k_old_method->name_and_sig_as_C_string(), old_flags, new_flags);
1160 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED;
1161 }
1162 {
1163 u2 new_num = k_new_method->method_idnum();
1164 u2 old_num = k_old_method->method_idnum();
1165 if (new_num != old_num) {
1166 Method* idnum_owner = scratch_class->method_with_idnum(old_num);
1167 if (idnum_owner != nullptr) {
1168 // There is already a method assigned this idnum -- switch them
1169 // Take current and original idnum from the new_method
1170 idnum_owner->set_method_idnum(new_num);
1171 idnum_owner->set_orig_method_idnum(k_new_method->orig_method_idnum());
1172 }
1173 // Take current and original idnum from the old_method
1174 k_new_method->set_method_idnum(old_num);
1175 k_new_method->set_orig_method_idnum(k_old_method->orig_method_idnum());
1176 if (thread->has_pending_exception()) {
1177 return JVMTI_ERROR_OUT_OF_MEMORY;
1178 }
1179 }
1180 }
1181 log_trace(redefine, class, normalize)
1182 ("Method matched: new: %s [%d] == old: %s [%d]",
1183 k_new_method->name_and_sig_as_C_string(), ni, k_old_method->name_and_sig_as_C_string(), oi);
1184 // advance to next pair of methods
1185 ++oi;
1186 ++ni;
1187 break;
1188 case added:
1189 // method added, see if it is OK
1190 if (!can_add_or_delete(k_new_method)) {
1191 log_info(redefine, class, normalize)
1192 ("redefined class %s methods error: added method: %s [%d]",
1193 the_class->external_name(), k_new_method->name_and_sig_as_C_string(), ni);
1194 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED;
1195 }
1196 {
1197 u2 num = the_class->next_method_idnum();
1198 if (num == ConstMethod::UNSET_IDNUM) {
1199 // cannot add any more methods
1200 log_info(redefine, class, normalize)
1201 ("redefined class %s methods error: can't create ID for new method %s [%d]",
1202 the_class->external_name(), k_new_method->name_and_sig_as_C_string(), ni);
1203 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED;
1204 }
1205 u2 new_num = k_new_method->method_idnum();
1206 Method* idnum_owner = scratch_class->method_with_idnum(num);
1207 if (idnum_owner != nullptr) {
1208 // There is already a method assigned this idnum -- switch them
1209 // Take current and original idnum from the new_method
1210 idnum_owner->set_method_idnum(new_num);
1211 idnum_owner->set_orig_method_idnum(k_new_method->orig_method_idnum());
1212 }
1213 k_new_method->set_method_idnum(num);
1214 k_new_method->set_orig_method_idnum(num);
1215 if (thread->has_pending_exception()) {
1216 return JVMTI_ERROR_OUT_OF_MEMORY;
1217 }
1218 }
1219 log_trace(redefine, class, normalize)
1220 ("Method added: new: %s [%d]", k_new_method->name_and_sig_as_C_string(), ni);
1221 ++ni; // advance to next new method
1222 break;
1223 case deleted:
1224 // method deleted, see if it is OK
1225 if (!can_add_or_delete(k_old_method)) {
1226 log_info(redefine, class, normalize)
1227 ("redefined class %s methods error: deleted method %s [%d]",
1228 the_class->external_name(), k_old_method->name_and_sig_as_C_string(), oi);
1229 return JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED;
1230 }
1231 log_trace(redefine, class, normalize)
1232 ("Method deleted: old: %s [%d]", k_old_method->name_and_sig_as_C_string(), oi);
1233 ++oi; // advance to next old method
1234 break;
1235 default:
1236 ShouldNotReachHere();
1237 }
1238 }
1239
1240 return JVMTI_ERROR_NONE;
1241 }
1242
1243
1244 // Find new constant pool index value for old constant pool index value
1245 // by searching the index map. Returns zero (0) if there is no mapped
1246 // value for the old constant pool index.
1247 u2 VM_RedefineClasses::find_new_index(int old_index) {
1248 if (_index_map_count == 0) {
1249 // map is empty so nothing can be found
1250 return 0;
1251 }
1252
1253 if (old_index < 1 || old_index >= _index_map_p->length()) {
1254 // The old_index is out of range so it is not mapped. This should
1255 // not happen in regular constant pool merging use, but it can
1256 // happen if a corrupt annotation is processed.
1257 return 0;
1258 }
1259
1260 int value = _index_map_p->at(old_index);
1261 if (value == -1) {
1262 // the old_index is not mapped
1263 return 0;
1264 }
1265
1266 // constant pool indices are u2, unless the merged constant pool overflows which
1267 // we don't check for.
1268 return checked_cast<u2>(value);
1269 } // end find_new_index()
1270
1271
1272 // Find new bootstrap specifier index value for old bootstrap specifier index
1273 // value by searching the index map. Returns unused index (-1) if there is
1274 // no mapped value for the old bootstrap specifier index.
1275 int VM_RedefineClasses::find_new_operand_index(int old_index) {
1276 if (_operands_index_map_count == 0) {
1277 // map is empty so nothing can be found
1278 return -1;
1279 }
1280
1281 if (old_index == -1 || old_index >= _operands_index_map_p->length()) {
1282 // The old_index is out of range so it is not mapped.
1283 // This should not happen in regular constant pool merging use.
1284 return -1;
1285 }
1286
1287 int value = _operands_index_map_p->at(old_index);
1288 if (value == -1) {
1289 // the old_index is not mapped
1290 return -1;
1291 }
1292
1293 return value;
1294 } // end find_new_operand_index()
1295
1296
1297 // The bug 6214132 caused the verification to fail.
1298 // 1. What's done in RedefineClasses() before verification:
1299 // a) A reference to the class being redefined (_the_class) and a
1300 // reference to new version of the class (_scratch_class) are
1301 // saved here for use during the bytecode verification phase of
1302 // RedefineClasses.
1303 // b) The _java_mirror field from _the_class is copied to the
1304 // _java_mirror field in _scratch_class. This means that a jclass
1305 // returned for _the_class or _scratch_class will refer to the
1306 // same Java mirror. The verifier will see the "one true mirror"
1307 // for the class being verified.
1308 // 2. See comments in JvmtiThreadState for what is done during verification.
1309
1310 class RedefineVerifyMark : public StackObj {
1311 private:
1312 JvmtiThreadState* _state;
1313 InstanceKlass* _scratch_class;
1314 OopHandle _scratch_mirror;
1315
1316 public:
1317
1318 RedefineVerifyMark(InstanceKlass* the_class, InstanceKlass* scratch_class,
1319 JvmtiThreadState* state) : _state(state), _scratch_class(scratch_class)
1320 {
1321 _state->set_class_versions_map(the_class, scratch_class);
1322 _scratch_mirror = the_class->java_mirror_handle(); // this is a copy that is swapped
1323 _scratch_class->swap_java_mirror_handle(_scratch_mirror);
1324 }
1325
1326 ~RedefineVerifyMark() {
1327 // Restore the scratch class's mirror, so when scratch_class is removed
1328 // the correct mirror pointing to it can be cleared.
1329 _scratch_class->swap_java_mirror_handle(_scratch_mirror);
1330 _state->clear_class_versions_map();
1331 }
1332 };
1333
1334
1335 jvmtiError VM_RedefineClasses::load_new_class_versions() {
1336
1337 // For consistency allocate memory using os::malloc wrapper.
1338 _scratch_classes = (InstanceKlass**)
1339 os::malloc(sizeof(InstanceKlass*) * _class_count, mtClass);
1340 if (_scratch_classes == nullptr) {
1341 return JVMTI_ERROR_OUT_OF_MEMORY;
1342 }
1343 // Zero initialize the _scratch_classes array.
1344 for (int i = 0; i < _class_count; i++) {
1345 _scratch_classes[i] = nullptr;
1346 }
1347
1348 JavaThread* current = JavaThread::current();
1349 ResourceMark rm(current);
1350
1351 JvmtiThreadState *state = JvmtiThreadState::state_for(current);
1352 // state can only be null if the current thread is exiting which
1353 // should not happen since we're trying to do a RedefineClasses
1354 guarantee(state != nullptr, "exiting thread calling load_new_class_versions");
1355 for (int i = 0; i < _class_count; i++) {
1356 // Create HandleMark so that any handles created while loading new class
1357 // versions are deleted. Constant pools are deallocated while merging
1358 // constant pools
1359 HandleMark hm(current);
1360 InstanceKlass* the_class = get_ik(_class_defs[i].klass);
1361 physical_memory_size_type avail_mem = 0;
1362 // Return value ignored - defaulting to 0 on failure.
1363 (void)os::available_memory(avail_mem);
1364 log_debug(redefine, class, load)
1365 ("loading name=%s kind=%d (avail_mem=" PHYS_MEM_TYPE_FORMAT "K)",
1366 the_class->external_name(), _class_load_kind, avail_mem >> 10);
1367
1368 ClassFileStream st((u1*)_class_defs[i].class_bytes,
1369 _class_defs[i].class_byte_count,
1370 "__VM_RedefineClasses__");
1371
1372 // Set redefined class handle in JvmtiThreadState class.
1373 // This redefined class is sent to agent event handler for class file
1374 // load hook event.
1375 state->set_class_being_redefined(the_class, _class_load_kind);
1376
1377 JavaThread* THREAD = current; // For exception macros.
1378 ExceptionMark em(THREAD);
1379 Handle protection_domain(THREAD, the_class->protection_domain());
1380 ClassLoadInfo cl_info(protection_domain);
1381 // Parse and create a class from the bytes, but this class isn't added
1382 // to the dictionary, so do not call resolve_from_stream.
1383 InstanceKlass* scratch_class = KlassFactory::create_from_stream(&st,
1384 the_class->name(),
1385 the_class->class_loader_data(),
1386 cl_info,
1387 THREAD);
1388
1389 // Clear class_being_redefined just to be sure.
1390 state->clear_class_being_redefined();
1391
1392 // TODO: if this is retransform, and nothing changed we can skip it
1393
1394 // Need to clean up allocated InstanceKlass if there's an error so assign
1395 // the result here. Caller deallocates all the scratch classes in case of
1396 // an error.
1397 _scratch_classes[i] = scratch_class;
1398
1399 if (HAS_PENDING_EXCEPTION) {
1400 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1401 log_info(redefine, class, load, exceptions)("create_from_stream exception: '%s'", ex_name->as_C_string());
1402 CLEAR_PENDING_EXCEPTION;
1403
1404 if (ex_name == vmSymbols::java_lang_UnsupportedClassVersionError()) {
1405 return JVMTI_ERROR_UNSUPPORTED_VERSION;
1406 } else if (ex_name == vmSymbols::java_lang_ClassFormatError()) {
1407 return JVMTI_ERROR_INVALID_CLASS_FORMAT;
1408 } else if (ex_name == vmSymbols::java_lang_ClassCircularityError()) {
1409 return JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION;
1410 } else if (ex_name == vmSymbols::java_lang_NoClassDefFoundError()) {
1411 // The message will be "XXX (wrong name: YYY)"
1412 return JVMTI_ERROR_NAMES_DONT_MATCH;
1413 } else if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1414 return JVMTI_ERROR_OUT_OF_MEMORY;
1415 } else { // Just in case more exceptions can be thrown..
1416 return JVMTI_ERROR_FAILS_VERIFICATION;
1417 }
1418 }
1419
1420 // Ensure class is linked before redefine
1421 if (!the_class->is_linked()) {
1422 the_class->link_class(THREAD);
1423 if (HAS_PENDING_EXCEPTION) {
1424 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1425 oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
1426 if (message != nullptr) {
1427 char* ex_msg = java_lang_String::as_utf8_string(message);
1428 log_info(redefine, class, load, exceptions)("link_class exception: '%s %s'",
1429 ex_name->as_C_string(), ex_msg);
1430 } else {
1431 log_info(redefine, class, load, exceptions)("link_class exception: '%s'",
1432 ex_name->as_C_string());
1433 }
1434 CLEAR_PENDING_EXCEPTION;
1435 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1436 return JVMTI_ERROR_OUT_OF_MEMORY;
1437 } else if (ex_name == vmSymbols::java_lang_NoClassDefFoundError()) {
1438 return JVMTI_ERROR_INVALID_CLASS;
1439 } else {
1440 return JVMTI_ERROR_INTERNAL;
1441 }
1442 }
1443 }
1444
1445 // Do the validity checks in compare_and_normalize_class_versions()
1446 // before verifying the byte codes. By doing these checks first, we
1447 // limit the number of functions that require redirection from
1448 // the_class to scratch_class. In particular, we don't have to
1449 // modify JNI GetSuperclass() and thus won't change its performance.
1450 jvmtiError res = compare_and_normalize_class_versions(the_class,
1451 scratch_class);
1452 if (res != JVMTI_ERROR_NONE) {
1453 return res;
1454 }
1455
1456 // verify what the caller passed us
1457 {
1458 // The bug 6214132 caused the verification to fail.
1459 // Information about the_class and scratch_class is temporarily
1460 // recorded into jvmtiThreadState. This data is used to redirect
1461 // the_class to scratch_class in the JVM_* functions called by the
1462 // verifier. Please, refer to jvmtiThreadState.hpp for the detailed
1463 // description.
1464 RedefineVerifyMark rvm(the_class, scratch_class, state);
1465 Verifier::verify(scratch_class, true, THREAD);
1466 }
1467
1468 if (HAS_PENDING_EXCEPTION) {
1469 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1470 log_info(redefine, class, load, exceptions)("verify_byte_codes exception: '%s'", ex_name->as_C_string());
1471 CLEAR_PENDING_EXCEPTION;
1472 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1473 return JVMTI_ERROR_OUT_OF_MEMORY;
1474 } else {
1475 // tell the caller the bytecodes are bad
1476 return JVMTI_ERROR_FAILS_VERIFICATION;
1477 }
1478 }
1479
1480 res = merge_cp_and_rewrite(the_class, scratch_class, THREAD);
1481 if (HAS_PENDING_EXCEPTION) {
1482 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1483 log_info(redefine, class, load, exceptions)("merge_cp_and_rewrite exception: '%s'", ex_name->as_C_string());
1484 CLEAR_PENDING_EXCEPTION;
1485 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1486 return JVMTI_ERROR_OUT_OF_MEMORY;
1487 } else {
1488 return JVMTI_ERROR_INTERNAL;
1489 }
1490 }
1491
1492 #ifdef ASSERT
1493 {
1494 // verify what we have done during constant pool merging
1495 {
1496 RedefineVerifyMark rvm(the_class, scratch_class, state);
1497 Verifier::verify(scratch_class, true, THREAD);
1498 }
1499
1500 if (HAS_PENDING_EXCEPTION) {
1501 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1502 log_info(redefine, class, load, exceptions)
1503 ("verify_byte_codes post merge-CP exception: '%s'", ex_name->as_C_string());
1504 CLEAR_PENDING_EXCEPTION;
1505 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1506 return JVMTI_ERROR_OUT_OF_MEMORY;
1507 } else {
1508 // tell the caller that constant pool merging screwed up
1509 return JVMTI_ERROR_INTERNAL;
1510 }
1511 }
1512 }
1513 #endif // ASSERT
1514
1515 Rewriter::rewrite(scratch_class, THREAD);
1516 if (!HAS_PENDING_EXCEPTION) {
1517 scratch_class->link_methods(THREAD);
1518 }
1519 if (HAS_PENDING_EXCEPTION) {
1520 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1521 log_info(redefine, class, load, exceptions)
1522 ("Rewriter::rewrite or link_methods exception: '%s'", ex_name->as_C_string());
1523 CLEAR_PENDING_EXCEPTION;
1524 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1525 return JVMTI_ERROR_OUT_OF_MEMORY;
1526 } else {
1527 return JVMTI_ERROR_INTERNAL;
1528 }
1529 }
1530 // Return value ignored - defaulting to 0 on failure.
1531 (void)os::available_memory(avail_mem);
1532 log_debug(redefine, class, load)
1533 ("loaded name=%s (avail_mem=" PHYS_MEM_TYPE_FORMAT "K)", the_class->external_name(), avail_mem >> 10);
1534 }
1535
1536 return JVMTI_ERROR_NONE;
1537 }
1538
1539
1540 // Map old_index to new_index as needed. scratch_cp is only needed
1541 // for log calls.
1542 void VM_RedefineClasses::map_index(const constantPoolHandle& scratch_cp,
1543 int old_index, int new_index) {
1544 if (find_new_index(old_index) != 0) {
1545 // old_index is already mapped
1546 return;
1547 }
1548
1549 if (old_index == new_index) {
1550 // no mapping is needed
1551 return;
1552 }
1553
1554 _index_map_p->at_put(old_index, new_index);
1555 _index_map_count++;
1556
1557 log_trace(redefine, class, constantpool)
1558 ("mapped tag %d at index %d to %d", scratch_cp->tag_at(old_index).value(), old_index, new_index);
1559 } // end map_index()
1560
1561
1562 // Map old_index to new_index as needed.
1563 void VM_RedefineClasses::map_operand_index(int old_index, int new_index) {
1564 if (find_new_operand_index(old_index) != -1) {
1565 // old_index is already mapped
1566 return;
1567 }
1568
1569 if (old_index == new_index) {
1570 // no mapping is needed
1571 return;
1572 }
1573
1574 _operands_index_map_p->at_put(old_index, new_index);
1575 _operands_index_map_count++;
1576
1577 log_trace(redefine, class, constantpool)("mapped bootstrap specifier at index %d to %d", old_index, new_index);
1578 } // end map_index()
1579
1580
1581 // Merge old_cp and scratch_cp and return the results of the merge via
1582 // merge_cp_p. The number of entries in merge_cp_p is returned via
1583 // merge_cp_length_p. The entries in old_cp occupy the same locations
1584 // in merge_cp_p. Also creates a map of indices from entries in
1585 // scratch_cp to the corresponding entry in merge_cp_p. Index map
1586 // entries are only created for entries in scratch_cp that occupy a
1587 // different location in merged_cp_p.
1588 bool VM_RedefineClasses::merge_constant_pools(const constantPoolHandle& old_cp,
1589 const constantPoolHandle& scratch_cp, constantPoolHandle& merge_cp_p,
1590 int& merge_cp_length_p, TRAPS) {
1591
1592 // Worst case we need old_cp->length() + scratch_cp()->length(),
1593 // but the caller might be smart so make sure we have at least
1594 // the minimum.
1595 if (merge_cp_p->length() < old_cp->length()) {
1596 assert(false, "merge area too small");
1597 return false; // robustness
1598 }
1599
1600 log_info(redefine, class, constantpool)("old_cp_len=%d, scratch_cp_len=%d", old_cp->length(), scratch_cp->length());
1601
1602 {
1603 // Pass 0:
1604 // The old_cp is copied to *merge_cp_p; this means that any code
1605 // using old_cp does not have to change. This work looks like a
1606 // perfect fit for ConstantPool*::copy_cp_to(), but we need to
1607 // handle one special case:
1608 // - revert JVM_CONSTANT_Class to JVM_CONSTANT_UnresolvedClass
1609 // This will make verification happy.
1610
1611 int old_i; // index into old_cp
1612
1613 // index zero (0) is not used in constantPools
1614 for (old_i = 1; old_i < old_cp->length(); old_i++) {
1615 // leave debugging crumb
1616 jbyte old_tag = old_cp->tag_at(old_i).value();
1617 switch (old_tag) {
1618 case JVM_CONSTANT_Class:
1619 case JVM_CONSTANT_UnresolvedClass:
1620 // revert the copy to JVM_CONSTANT_UnresolvedClass
1621 // May be resolving while calling this so do the same for
1622 // JVM_CONSTANT_UnresolvedClass (klass_name_at() deals with transition)
1623 merge_cp_p->temp_unresolved_klass_at_put(old_i,
1624 old_cp->klass_name_index_at(old_i));
1625 break;
1626
1627 case JVM_CONSTANT_Double:
1628 case JVM_CONSTANT_Long:
1629 // just copy the entry to merge_cp_p, but double and long take
1630 // two constant pool entries
1631 ConstantPool::copy_entry_to(old_cp, old_i, merge_cp_p, old_i);
1632 old_i++;
1633 break;
1634
1635 default:
1636 // just copy the entry to merge_cp_p
1637 ConstantPool::copy_entry_to(old_cp, old_i, merge_cp_p, old_i);
1638 break;
1639 }
1640 } // end for each old_cp entry
1641
1642 ConstantPool::copy_operands(old_cp, merge_cp_p, CHECK_false);
1643 merge_cp_p->extend_operands(scratch_cp, CHECK_false);
1644
1645 // We don't need to sanity check that *merge_cp_length_p is within
1646 // *merge_cp_p bounds since we have the minimum on-entry check above.
1647 merge_cp_length_p = old_i;
1648 }
1649
1650 // merge_cp_len should be the same as old_cp->length() at this point
1651 // so this trace message is really a "warm-and-breathing" message.
1652 log_debug(redefine, class, constantpool)("after pass 0: merge_cp_len=%d", merge_cp_length_p);
1653
1654 int scratch_i; // index into scratch_cp
1655 {
1656 // Pass 1a:
1657 // Compare scratch_cp entries to the old_cp entries that we have
1658 // already copied to *merge_cp_p. In this pass, we are eliminating
1659 // exact duplicates (matching entry at same index) so we only
1660 // compare entries in the common indice range.
1661 int increment = 1;
1662 int pass1a_length = MIN2(old_cp->length(), scratch_cp->length());
1663 for (scratch_i = 1; scratch_i < pass1a_length; scratch_i += increment) {
1664 switch (scratch_cp->tag_at(scratch_i).value()) {
1665 case JVM_CONSTANT_Double:
1666 case JVM_CONSTANT_Long:
1667 // double and long take two constant pool entries
1668 increment = 2;
1669 break;
1670
1671 default:
1672 increment = 1;
1673 break;
1674 }
1675
1676 bool match = scratch_cp->compare_entry_to(scratch_i, merge_cp_p, scratch_i);
1677 if (match) {
1678 // found a match at the same index so nothing more to do
1679 continue;
1680 }
1681
1682 int found_i = scratch_cp->find_matching_entry(scratch_i, merge_cp_p);
1683 if (found_i != 0) {
1684 guarantee(found_i != scratch_i,
1685 "compare_entry_to() and find_matching_entry() do not agree");
1686
1687 // Found a matching entry somewhere else in *merge_cp_p so
1688 // just need a mapping entry.
1689 map_index(scratch_cp, scratch_i, found_i);
1690 continue;
1691 }
1692
1693 // No match found so we have to append this entry and any unique
1694 // referenced entries to merge_cp_p.
1695 append_entry(scratch_cp, scratch_i, &merge_cp_p, &merge_cp_length_p);
1696 }
1697 }
1698
1699 log_debug(redefine, class, constantpool)
1700 ("after pass 1a: merge_cp_len=%d, scratch_i=%d, index_map_len=%d",
1701 merge_cp_length_p, scratch_i, _index_map_count);
1702
1703 if (scratch_i < scratch_cp->length()) {
1704 // Pass 1b:
1705 // old_cp is smaller than scratch_cp so there are entries in
1706 // scratch_cp that we have not yet processed. We take care of
1707 // those now.
1708 int increment = 1;
1709 for (; scratch_i < scratch_cp->length(); scratch_i += increment) {
1710 switch (scratch_cp->tag_at(scratch_i).value()) {
1711 case JVM_CONSTANT_Double:
1712 case JVM_CONSTANT_Long:
1713 // double and long take two constant pool entries
1714 increment = 2;
1715 break;
1716
1717 default:
1718 increment = 1;
1719 break;
1720 }
1721
1722 int found_i =
1723 scratch_cp->find_matching_entry(scratch_i, merge_cp_p);
1724 if (found_i != 0) {
1725 // Found a matching entry somewhere else in merge_cp_p so
1726 // just need a mapping entry.
1727 map_index(scratch_cp, scratch_i, found_i);
1728 continue;
1729 }
1730
1731 // No match found so we have to append this entry and any unique
1732 // referenced entries to merge_cp_p.
1733 append_entry(scratch_cp, scratch_i, &merge_cp_p, &merge_cp_length_p);
1734 }
1735
1736 log_debug(redefine, class, constantpool)
1737 ("after pass 1b: merge_cp_len=%d, scratch_i=%d, index_map_len=%d",
1738 merge_cp_length_p, scratch_i, _index_map_count);
1739 }
1740 finalize_operands_merge(merge_cp_p, CHECK_false);
1741
1742 return true;
1743 } // end merge_constant_pools()
1744
1745
1746 // Scoped object to clean up the constant pool(s) created for merging
1747 class MergeCPCleaner {
1748 ClassLoaderData* _loader_data;
1749 ConstantPool* _cp;
1750 ConstantPool* _scratch_cp;
1751 public:
1752 MergeCPCleaner(ClassLoaderData* loader_data, ConstantPool* merge_cp) :
1753 _loader_data(loader_data), _cp(merge_cp), _scratch_cp(nullptr) {}
1754 ~MergeCPCleaner() {
1755 _loader_data->add_to_deallocate_list(_cp);
1756 if (_scratch_cp != nullptr) {
1757 _loader_data->add_to_deallocate_list(_scratch_cp);
1758 }
1759 }
1760 void add_scratch_cp(ConstantPool* scratch_cp) { _scratch_cp = scratch_cp; }
1761 };
1762
1763 // Merge constant pools between the_class and scratch_class and
1764 // potentially rewrite bytecodes in scratch_class to use the merged
1765 // constant pool.
1766 jvmtiError VM_RedefineClasses::merge_cp_and_rewrite(
1767 InstanceKlass* the_class, InstanceKlass* scratch_class,
1768 TRAPS) {
1769 // worst case merged constant pool length is old and new combined
1770 int merge_cp_length = the_class->constants()->length()
1771 + scratch_class->constants()->length();
1772
1773 // Constant pools are not easily reused so we allocate a new one
1774 // each time.
1775 // merge_cp is created unsafe for concurrent GC processing. It
1776 // should be marked safe before discarding it. Even though
1777 // garbage, if it crosses a card boundary, it may be scanned
1778 // in order to find the start of the first complete object on the card.
1779 ClassLoaderData* loader_data = the_class->class_loader_data();
1780 ConstantPool* merge_cp_oop =
1781 ConstantPool::allocate(loader_data,
1782 merge_cp_length,
1783 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1784 MergeCPCleaner cp_cleaner(loader_data, merge_cp_oop);
1785
1786 HandleMark hm(THREAD); // make sure handles are cleared before
1787 // MergeCPCleaner clears out merge_cp_oop
1788 constantPoolHandle merge_cp(THREAD, merge_cp_oop);
1789
1790 // Get constants() from the old class because it could have been rewritten
1791 // while we were at a safepoint allocating a new constant pool.
1792 constantPoolHandle old_cp(THREAD, the_class->constants());
1793 constantPoolHandle scratch_cp(THREAD, scratch_class->constants());
1794
1795 // If the length changed, the class was redefined out from under us. Return
1796 // an error.
1797 if (merge_cp_length != the_class->constants()->length()
1798 + scratch_class->constants()->length()) {
1799 return JVMTI_ERROR_INTERNAL;
1800 }
1801
1802 // Update the version number of the constant pools (may keep scratch_cp)
1803 merge_cp->increment_and_save_version(old_cp->version());
1804 scratch_cp->increment_and_save_version(old_cp->version());
1805
1806 ResourceMark rm(THREAD);
1807 _index_map_count = 0;
1808 _index_map_p = new intArray(scratch_cp->length(), scratch_cp->length(), -1);
1809
1810 _operands_cur_length = ConstantPool::operand_array_length(old_cp->operands());
1811 _operands_index_map_count = 0;
1812 int operands_index_map_len = ConstantPool::operand_array_length(scratch_cp->operands());
1813 _operands_index_map_p = new intArray(operands_index_map_len, operands_index_map_len, -1);
1814
1815 // reference to the cp holder is needed for copy_operands()
1816 merge_cp->set_pool_holder(scratch_class);
1817 bool result = merge_constant_pools(old_cp, scratch_cp, merge_cp,
1818 merge_cp_length, THREAD);
1819 merge_cp->set_pool_holder(nullptr);
1820
1821 if (!result) {
1822 // The merge can fail due to memory allocation failure or due
1823 // to robustness checks.
1824 return JVMTI_ERROR_INTERNAL;
1825 }
1826
1827 // ensure merged constant pool size does not overflow u2
1828 if (merge_cp_length > 0xFFFF) {
1829 log_warning(redefine, class, constantpool)("Merged constant pool overflow: %d entries", merge_cp_length);
1830 return JVMTI_ERROR_INTERNAL;
1831 }
1832
1833 // Set dynamic constants attribute from the original CP.
1834 if (old_cp->has_dynamic_constant()) {
1835 scratch_cp->set_has_dynamic_constant();
1836 }
1837
1838 log_info(redefine, class, constantpool)("merge_cp_len=%d, index_map_len=%d", merge_cp_length, _index_map_count);
1839
1840 if (_index_map_count == 0) {
1841 // there is nothing to map between the new and merged constant pools
1842
1843 // Copy attributes from scratch_cp to merge_cp
1844 merge_cp->copy_fields(scratch_cp());
1845
1846 if (old_cp->length() == scratch_cp->length()) {
1847 // The old and new constant pools are the same length and the
1848 // index map is empty. This means that the three constant pools
1849 // are equivalent (but not the same). Unfortunately, the new
1850 // constant pool has not gone through link resolution nor have
1851 // the new class bytecodes gone through constant pool cache
1852 // rewriting so we can't use the old constant pool with the new
1853 // class.
1854
1855 // toss the merged constant pool at return
1856 } else if (old_cp->length() < scratch_cp->length()) {
1857 // The old constant pool has fewer entries than the new constant
1858 // pool and the index map is empty. This means the new constant
1859 // pool is a superset of the old constant pool. However, the old
1860 // class bytecodes have already gone through constant pool cache
1861 // rewriting so we can't use the new constant pool with the old
1862 // class.
1863
1864 // toss the merged constant pool at return
1865 } else {
1866 // The old constant pool has more entries than the new constant
1867 // pool and the index map is empty. This means that both the old
1868 // and merged constant pools are supersets of the new constant
1869 // pool.
1870
1871 // Replace the new constant pool with a shrunken copy of the
1872 // merged constant pool
1873 set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,
1874 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1875 // The new constant pool replaces scratch_cp so have cleaner clean it up.
1876 // It can't be cleaned up while there are handles to it.
1877 cp_cleaner.add_scratch_cp(scratch_cp());
1878 }
1879 } else {
1880 if (log_is_enabled(Trace, redefine, class, constantpool)) {
1881 // don't want to loop unless we are tracing
1882 int count = 0;
1883 for (int i = 1; i < _index_map_p->length(); i++) {
1884 int value = _index_map_p->at(i);
1885
1886 if (value != -1) {
1887 log_trace(redefine, class, constantpool)("index_map[%d]: old=%d new=%d", count, i, value);
1888 count++;
1889 }
1890 }
1891 }
1892
1893 // We have entries mapped between the new and merged constant pools
1894 // so we have to rewrite some constant pool references.
1895 if (!rewrite_cp_refs(scratch_class)) {
1896 return JVMTI_ERROR_INTERNAL;
1897 }
1898
1899 // Copy attributes from scratch_cp to merge_cp (should be done after rewrite_cp_refs())
1900 merge_cp->copy_fields(scratch_cp());
1901
1902 // Replace the new constant pool with a shrunken copy of the
1903 // merged constant pool so now the rewritten bytecodes have
1904 // valid references; the previous new constant pool will get
1905 // GCed.
1906 set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,
1907 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1908 // The new constant pool replaces scratch_cp so have cleaner clean it up.
1909 // It can't be cleaned up while there are handles to it.
1910 cp_cleaner.add_scratch_cp(scratch_cp());
1911 }
1912
1913 return JVMTI_ERROR_NONE;
1914 } // end merge_cp_and_rewrite()
1915
1916
1917 // Rewrite constant pool references in klass scratch_class.
1918 bool VM_RedefineClasses::rewrite_cp_refs(InstanceKlass* scratch_class) {
1919
1920 // rewrite constant pool references in the nest attributes:
1921 if (!rewrite_cp_refs_in_nest_attributes(scratch_class)) {
1922 // propagate failure back to caller
1923 return false;
1924 }
1925
1926 // rewrite constant pool references in the Record attribute:
1927 if (!rewrite_cp_refs_in_record_attribute(scratch_class)) {
1928 // propagate failure back to caller
1929 return false;
1930 }
1931
1932 // rewrite constant pool references in the PermittedSubclasses attribute:
1933 if (!rewrite_cp_refs_in_permitted_subclasses_attribute(scratch_class)) {
1934 // propagate failure back to caller
1935 return false;
1936 }
1937
1938 // rewrite constant pool references in the methods:
1939 if (!rewrite_cp_refs_in_methods(scratch_class)) {
1940 // propagate failure back to caller
1941 return false;
1942 }
1943
1944 // rewrite constant pool references in the class_annotations:
1945 if (!rewrite_cp_refs_in_class_annotations(scratch_class)) {
1946 // propagate failure back to caller
1947 return false;
1948 }
1949
1950 // rewrite constant pool references in the fields_annotations:
1951 if (!rewrite_cp_refs_in_fields_annotations(scratch_class)) {
1952 // propagate failure back to caller
1953 return false;
1954 }
1955
1956 // rewrite constant pool references in the methods_annotations:
1957 if (!rewrite_cp_refs_in_methods_annotations(scratch_class)) {
1958 // propagate failure back to caller
1959 return false;
1960 }
1961
1962 // rewrite constant pool references in the methods_parameter_annotations:
1963 if (!rewrite_cp_refs_in_methods_parameter_annotations(scratch_class)) {
1964 // propagate failure back to caller
1965 return false;
1966 }
1967
1968 // rewrite constant pool references in the methods_default_annotations:
1969 if (!rewrite_cp_refs_in_methods_default_annotations(scratch_class)) {
1970 // propagate failure back to caller
1971 return false;
1972 }
1973
1974 // rewrite constant pool references in the class_type_annotations:
1975 if (!rewrite_cp_refs_in_class_type_annotations(scratch_class)) {
1976 // propagate failure back to caller
1977 return false;
1978 }
1979
1980 // rewrite constant pool references in the fields_type_annotations:
1981 if (!rewrite_cp_refs_in_fields_type_annotations(scratch_class)) {
1982 // propagate failure back to caller
1983 return false;
1984 }
1985
1986 // rewrite constant pool references in the methods_type_annotations:
1987 if (!rewrite_cp_refs_in_methods_type_annotations(scratch_class)) {
1988 // propagate failure back to caller
1989 return false;
1990 }
1991
1992 // There can be type annotations in the Code part of a method_info attribute.
1993 // These annotations are not accessible, even by reflection.
1994 // Currently they are not even parsed by the ClassFileParser.
1995 // If runtime access is added they will also need to be rewritten.
1996
1997 // rewrite source file name index:
1998 u2 source_file_name_idx = scratch_class->source_file_name_index();
1999 if (source_file_name_idx != 0) {
2000 u2 new_source_file_name_idx = find_new_index(source_file_name_idx);
2001 if (new_source_file_name_idx != 0) {
2002 scratch_class->set_source_file_name_index(new_source_file_name_idx);
2003 }
2004 }
2005
2006 // rewrite class generic signature index:
2007 u2 generic_signature_index = scratch_class->generic_signature_index();
2008 if (generic_signature_index != 0) {
2009 u2 new_generic_signature_index = find_new_index(generic_signature_index);
2010 if (new_generic_signature_index != 0) {
2011 scratch_class->set_generic_signature_index(new_generic_signature_index);
2012 }
2013 }
2014
2015 return true;
2016 } // end rewrite_cp_refs()
2017
2018 // Rewrite constant pool references in the NestHost and NestMembers attributes.
2019 bool VM_RedefineClasses::rewrite_cp_refs_in_nest_attributes(
2020 InstanceKlass* scratch_class) {
2021
2022 u2 cp_index = scratch_class->nest_host_index();
2023 if (cp_index != 0) {
2024 scratch_class->set_nest_host_index(find_new_index(cp_index));
2025 }
2026 Array<u2>* nest_members = scratch_class->nest_members();
2027 for (int i = 0; i < nest_members->length(); i++) {
2028 u2 cp_index = nest_members->at(i);
2029 nest_members->at_put(i, find_new_index(cp_index));
2030 }
2031 return true;
2032 }
2033
2034 // Rewrite constant pool references in the Record attribute.
2035 bool VM_RedefineClasses::rewrite_cp_refs_in_record_attribute(InstanceKlass* scratch_class) {
2036 Array<RecordComponent*>* components = scratch_class->record_components();
2037 if (components != nullptr) {
2038 for (int i = 0; i < components->length(); i++) {
2039 RecordComponent* component = components->at(i);
2040 u2 cp_index = component->name_index();
2041 component->set_name_index(find_new_index(cp_index));
2042 cp_index = component->descriptor_index();
2043 component->set_descriptor_index(find_new_index(cp_index));
2044 cp_index = component->generic_signature_index();
2045 if (cp_index != 0) {
2046 component->set_generic_signature_index(find_new_index(cp_index));
2047 }
2048
2049 AnnotationArray* annotations = component->annotations();
2050 if (annotations != nullptr && annotations->length() != 0) {
2051 int byte_i = 0; // byte index into annotations
2052 if (!rewrite_cp_refs_in_annotations_typeArray(annotations, byte_i)) {
2053 log_debug(redefine, class, annotation)("bad record_component_annotations at %d", i);
2054 // propagate failure back to caller
2055 return false;
2056 }
2057 }
2058
2059 AnnotationArray* type_annotations = component->type_annotations();
2060 if (type_annotations != nullptr && type_annotations->length() != 0) {
2061 int byte_i = 0; // byte index into annotations
2062 if (!rewrite_cp_refs_in_annotations_typeArray(type_annotations, byte_i)) {
2063 log_debug(redefine, class, annotation)("bad record_component_type_annotations at %d", i);
2064 // propagate failure back to caller
2065 return false;
2066 }
2067 }
2068 }
2069 }
2070 return true;
2071 }
2072
2073 // Rewrite constant pool references in the PermittedSubclasses attribute.
2074 bool VM_RedefineClasses::rewrite_cp_refs_in_permitted_subclasses_attribute(
2075 InstanceKlass* scratch_class) {
2076
2077 Array<u2>* permitted_subclasses = scratch_class->permitted_subclasses();
2078 assert(permitted_subclasses != nullptr, "unexpected null permitted_subclasses");
2079 for (int i = 0; i < permitted_subclasses->length(); i++) {
2080 u2 cp_index = permitted_subclasses->at(i);
2081 permitted_subclasses->at_put(i, find_new_index(cp_index));
2082 }
2083 return true;
2084 }
2085
2086 // Rewrite constant pool references in the methods.
2087 bool VM_RedefineClasses::rewrite_cp_refs_in_methods(InstanceKlass* scratch_class) {
2088
2089 Array<Method*>* methods = scratch_class->methods();
2090
2091 if (methods == nullptr || methods->length() == 0) {
2092 // no methods so nothing to do
2093 return true;
2094 }
2095
2096 JavaThread* THREAD = JavaThread::current(); // For exception macros.
2097 ExceptionMark em(THREAD);
2098
2099 // rewrite constant pool references in the methods:
2100 for (int i = methods->length() - 1; i >= 0; i--) {
2101 methodHandle method(THREAD, methods->at(i));
2102 methodHandle new_method;
2103 rewrite_cp_refs_in_method(method, &new_method, THREAD);
2104 if (!new_method.is_null()) {
2105 // the method has been replaced so save the new method version
2106 // even in the case of an exception. original method is on the
2107 // deallocation list.
2108 methods->at_put(i, new_method());
2109 }
2110 if (HAS_PENDING_EXCEPTION) {
2111 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
2112 log_info(redefine, class, load, exceptions)("rewrite_cp_refs_in_method exception: '%s'", ex_name->as_C_string());
2113 // Need to clear pending exception here as the super caller sets
2114 // the JVMTI_ERROR_INTERNAL if the returned value is false.
2115 CLEAR_PENDING_EXCEPTION;
2116 return false;
2117 }
2118 }
2119
2120 return true;
2121 }
2122
2123
2124 // Rewrite constant pool references in the specific method. This code
2125 // was adapted from Rewriter::rewrite_method().
2126 void VM_RedefineClasses::rewrite_cp_refs_in_method(methodHandle method,
2127 methodHandle *new_method_p, TRAPS) {
2128
2129 *new_method_p = methodHandle(); // default is no new method
2130
2131 // We cache a pointer to the bytecodes here in code_base. If GC
2132 // moves the Method*, then the bytecodes will also move which
2133 // will likely cause a crash. We create a NoSafepointVerifier
2134 // object to detect whether we pass a possible safepoint in this
2135 // code block.
2136 NoSafepointVerifier nsv;
2137
2138 // Bytecodes and their length
2139 address code_base = method->code_base();
2140 int code_length = method->code_size();
2141
2142 int bc_length;
2143 for (int bci = 0; bci < code_length; bci += bc_length) {
2144 address bcp = code_base + bci;
2145 Bytecodes::Code c = (Bytecodes::Code)(*bcp);
2146
2147 bc_length = Bytecodes::length_for(c);
2148 if (bc_length == 0) {
2149 // More complicated bytecodes report a length of zero so
2150 // we have to try again a slightly different way.
2151 bc_length = Bytecodes::length_at(method(), bcp);
2152 }
2153
2154 assert(bc_length != 0, "impossible bytecode length");
2155
2156 switch (c) {
2157 case Bytecodes::_ldc:
2158 {
2159 u1 cp_index = *(bcp + 1);
2160 u2 new_index = find_new_index(cp_index);
2161
2162 if (StressLdcRewrite && new_index == 0) {
2163 // If we are stressing ldc -> ldc_w rewriting, then we
2164 // always need a new_index value.
2165 new_index = cp_index;
2166 }
2167 if (new_index != 0) {
2168 // the original index is mapped so we have more work to do
2169 if (!StressLdcRewrite && new_index <= max_jubyte) {
2170 // The new value can still use ldc instead of ldc_w
2171 // unless we are trying to stress ldc -> ldc_w rewriting
2172 log_trace(redefine, class, constantpool)
2173 ("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c), p2i(bcp), cp_index, new_index);
2174 // We checked that new_index fits in a u1 so this cast is safe
2175 *(bcp + 1) = (u1)new_index;
2176 } else {
2177 log_trace(redefine, class, constantpool)
2178 ("%s->ldc_w@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c), p2i(bcp), cp_index, new_index);
2179 // the new value needs ldc_w instead of ldc
2180 u_char inst_buffer[4]; // max instruction size is 4 bytes
2181 bcp = (address)inst_buffer;
2182 // construct new instruction sequence
2183 *bcp = Bytecodes::_ldc_w;
2184 bcp++;
2185 // Rewriter::rewrite_method() does not rewrite ldc -> ldc_w.
2186 // See comment below for difference between put_Java_u2()
2187 // and put_native_u2().
2188 Bytes::put_Java_u2(bcp, new_index);
2189
2190 Relocator rc(method, nullptr /* no RelocatorListener needed */);
2191 methodHandle m;
2192 {
2193 PauseNoSafepointVerifier pnsv(&nsv);
2194
2195 // ldc is 2 bytes and ldc_w is 3 bytes
2196 m = rc.insert_space_at(bci, 3, inst_buffer, CHECK);
2197 }
2198
2199 // return the new method so that the caller can update
2200 // the containing class
2201 *new_method_p = method = m;
2202 // switch our bytecode processing loop from the old method
2203 // to the new method
2204 code_base = method->code_base();
2205 code_length = method->code_size();
2206 bcp = code_base + bci;
2207 c = (Bytecodes::Code)(*bcp);
2208 bc_length = Bytecodes::length_for(c);
2209 assert(bc_length != 0, "sanity check");
2210 } // end we need ldc_w instead of ldc
2211 } // end if there is a mapped index
2212 } break;
2213
2214 // these bytecodes have a two-byte constant pool index
2215 case Bytecodes::_anewarray : // fall through
2216 case Bytecodes::_checkcast : // fall through
2217 case Bytecodes::_getfield : // fall through
2218 case Bytecodes::_getstatic : // fall through
2219 case Bytecodes::_instanceof : // fall through
2220 case Bytecodes::_invokedynamic : // fall through
2221 case Bytecodes::_invokeinterface: // fall through
2222 case Bytecodes::_invokespecial : // fall through
2223 case Bytecodes::_invokestatic : // fall through
2224 case Bytecodes::_invokevirtual : // fall through
2225 case Bytecodes::_ldc_w : // fall through
2226 case Bytecodes::_ldc2_w : // fall through
2227 case Bytecodes::_multianewarray : // fall through
2228 case Bytecodes::_new : // fall through
2229 case Bytecodes::_putfield : // fall through
2230 case Bytecodes::_putstatic :
2231 {
2232 address p = bcp + 1;
2233 int cp_index = Bytes::get_Java_u2(p);
2234 u2 new_index = find_new_index(cp_index);
2235 if (new_index != 0) {
2236 // the original index is mapped so update w/ new value
2237 log_trace(redefine, class, constantpool)
2238 ("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c),p2i(bcp), cp_index, new_index);
2239 // Rewriter::rewrite_method() uses put_native_u2() in this
2240 // situation because it is reusing the constant pool index
2241 // location for a native index into the ConstantPoolCache.
2242 // Since we are updating the constant pool index prior to
2243 // verification and ConstantPoolCache initialization, we
2244 // need to keep the new index in Java byte order.
2245 Bytes::put_Java_u2(p, new_index);
2246 }
2247 } break;
2248 default:
2249 break;
2250 }
2251 } // end for each bytecode
2252 } // end rewrite_cp_refs_in_method()
2253
2254
2255 // Rewrite constant pool references in the class_annotations field.
2256 bool VM_RedefineClasses::rewrite_cp_refs_in_class_annotations(InstanceKlass* scratch_class) {
2257
2258 AnnotationArray* class_annotations = scratch_class->class_annotations();
2259 if (class_annotations == nullptr || class_annotations->length() == 0) {
2260 // no class_annotations so nothing to do
2261 return true;
2262 }
2263
2264 log_debug(redefine, class, annotation)("class_annotations length=%d", class_annotations->length());
2265
2266 int byte_i = 0; // byte index into class_annotations
2267 return rewrite_cp_refs_in_annotations_typeArray(class_annotations, byte_i);
2268 }
2269
2270
2271 // Rewrite constant pool references in an annotations typeArray. This
2272 // "structure" is adapted from the RuntimeVisibleAnnotations_attribute
2273 // that is described in section 4.8.15 of the 2nd-edition of the VM spec:
2274 //
2275 // annotations_typeArray {
2276 // u2 num_annotations;
2277 // annotation annotations[num_annotations];
2278 // }
2279 //
2280 bool VM_RedefineClasses::rewrite_cp_refs_in_annotations_typeArray(
2281 AnnotationArray* annotations_typeArray, int &byte_i_ref) {
2282
2283 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2284 // not enough room for num_annotations field
2285 log_debug(redefine, class, annotation)("length() is too small for num_annotations field");
2286 return false;
2287 }
2288
2289 u2 num_annotations = Bytes::get_Java_u2((address)
2290 annotations_typeArray->adr_at(byte_i_ref));
2291 byte_i_ref += 2;
2292
2293 log_debug(redefine, class, annotation)("num_annotations=%d", num_annotations);
2294
2295 int calc_num_annotations = 0;
2296 for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
2297 if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray, byte_i_ref)) {
2298 log_debug(redefine, class, annotation)("bad annotation_struct at %d", calc_num_annotations);
2299 // propagate failure back to caller
2300 return false;
2301 }
2302 }
2303 assert(num_annotations == calc_num_annotations, "sanity check");
2304
2305 return true;
2306 } // end rewrite_cp_refs_in_annotations_typeArray()
2307
2308
2309 // Rewrite constant pool references in the annotation struct portion of
2310 // an annotations_typeArray. This "structure" is from section 4.8.15 of
2311 // the 2nd-edition of the VM spec:
2312 //
2313 // struct annotation {
2314 // u2 type_index;
2315 // u2 num_element_value_pairs;
2316 // {
2317 // u2 element_name_index;
2318 // element_value value;
2319 // } element_value_pairs[num_element_value_pairs];
2320 // }
2321 //
2322 bool VM_RedefineClasses::rewrite_cp_refs_in_annotation_struct(
2323 AnnotationArray* annotations_typeArray, int &byte_i_ref) {
2324 if ((byte_i_ref + 2 + 2) > annotations_typeArray->length()) {
2325 // not enough room for smallest annotation_struct
2326 log_debug(redefine, class, annotation)("length() is too small for annotation_struct");
2327 return false;
2328 }
2329
2330 u2 type_index = rewrite_cp_ref_in_annotation_data(annotations_typeArray,
2331 byte_i_ref, "type_index");
2332
2333 u2 num_element_value_pairs = Bytes::get_Java_u2((address)
2334 annotations_typeArray->adr_at(byte_i_ref));
2335 byte_i_ref += 2;
2336
2337 log_debug(redefine, class, annotation)
2338 ("type_index=%d num_element_value_pairs=%d", type_index, num_element_value_pairs);
2339
2340 int calc_num_element_value_pairs = 0;
2341 for (; calc_num_element_value_pairs < num_element_value_pairs;
2342 calc_num_element_value_pairs++) {
2343 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2344 // not enough room for another element_name_index, let alone
2345 // the rest of another component
2346 log_debug(redefine, class, annotation)("length() is too small for element_name_index");
2347 return false;
2348 }
2349
2350 u2 element_name_index = rewrite_cp_ref_in_annotation_data(
2351 annotations_typeArray, byte_i_ref,
2352 "element_name_index");
2353
2354 log_debug(redefine, class, annotation)("element_name_index=%d", element_name_index);
2355
2356 if (!rewrite_cp_refs_in_element_value(annotations_typeArray, byte_i_ref)) {
2357 log_debug(redefine, class, annotation)("bad element_value at %d", calc_num_element_value_pairs);
2358 // propagate failure back to caller
2359 return false;
2360 }
2361 } // end for each component
2362 assert(num_element_value_pairs == calc_num_element_value_pairs,
2363 "sanity check");
2364
2365 return true;
2366 } // end rewrite_cp_refs_in_annotation_struct()
2367
2368
2369 // Rewrite a constant pool reference at the current position in
2370 // annotations_typeArray if needed. Returns the original constant
2371 // pool reference if a rewrite was not needed or the new constant
2372 // pool reference if a rewrite was needed.
2373 u2 VM_RedefineClasses::rewrite_cp_ref_in_annotation_data(
2374 AnnotationArray* annotations_typeArray, int &byte_i_ref,
2375 const char * trace_mesg) {
2376
2377 address cp_index_addr = (address)
2378 annotations_typeArray->adr_at(byte_i_ref);
2379 u2 old_cp_index = Bytes::get_Java_u2(cp_index_addr);
2380 u2 new_cp_index = find_new_index(old_cp_index);
2381 if (new_cp_index != 0) {
2382 log_debug(redefine, class, annotation)("mapped old %s=%d", trace_mesg, old_cp_index);
2383 Bytes::put_Java_u2(cp_index_addr, new_cp_index);
2384 old_cp_index = new_cp_index;
2385 }
2386 byte_i_ref += 2;
2387 return old_cp_index;
2388 }
2389
2390
2391 // Rewrite constant pool references in the element_value portion of an
2392 // annotations_typeArray. This "structure" is from section 4.8.15.1 of
2393 // the 2nd-edition of the VM spec:
2394 //
2395 // struct element_value {
2396 // u1 tag;
2397 // union {
2398 // u2 const_value_index;
2399 // {
2400 // u2 type_name_index;
2401 // u2 const_name_index;
2402 // } enum_const_value;
2403 // u2 class_info_index;
2404 // annotation annotation_value;
2405 // struct {
2406 // u2 num_values;
2407 // element_value values[num_values];
2408 // } array_value;
2409 // } value;
2410 // }
2411 //
2412 bool VM_RedefineClasses::rewrite_cp_refs_in_element_value(
2413 AnnotationArray* annotations_typeArray, int &byte_i_ref) {
2414
2415 if ((byte_i_ref + 1) > annotations_typeArray->length()) {
2416 // not enough room for a tag let alone the rest of an element_value
2417 log_debug(redefine, class, annotation)("length() is too small for a tag");
2418 return false;
2419 }
2420
2421 u1 tag = annotations_typeArray->at(byte_i_ref);
2422 byte_i_ref++;
2423 log_debug(redefine, class, annotation)("tag='%c'", tag);
2424
2425 switch (tag) {
2426 // These BaseType tag values are from Table 4.2 in VM spec:
2427 case JVM_SIGNATURE_BYTE:
2428 case JVM_SIGNATURE_CHAR:
2429 case JVM_SIGNATURE_DOUBLE:
2430 case JVM_SIGNATURE_FLOAT:
2431 case JVM_SIGNATURE_INT:
2432 case JVM_SIGNATURE_LONG:
2433 case JVM_SIGNATURE_SHORT:
2434 case JVM_SIGNATURE_BOOLEAN:
2435
2436 // The remaining tag values are from Table 4.8 in the 2nd-edition of
2437 // the VM spec:
2438 case 's':
2439 {
2440 // For the above tag values (including the BaseType values),
2441 // value.const_value_index is right union field.
2442
2443 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2444 // not enough room for a const_value_index
2445 log_debug(redefine, class, annotation)("length() is too small for a const_value_index");
2446 return false;
2447 }
2448
2449 u2 const_value_index = rewrite_cp_ref_in_annotation_data(
2450 annotations_typeArray, byte_i_ref,
2451 "const_value_index");
2452
2453 log_debug(redefine, class, annotation)("const_value_index=%d", const_value_index);
2454 } break;
2455
2456 case 'e':
2457 {
2458 // for the above tag value, value.enum_const_value is right union field
2459
2460 if ((byte_i_ref + 4) > annotations_typeArray->length()) {
2461 // not enough room for a enum_const_value
2462 log_debug(redefine, class, annotation)("length() is too small for a enum_const_value");
2463 return false;
2464 }
2465
2466 u2 type_name_index = rewrite_cp_ref_in_annotation_data(
2467 annotations_typeArray, byte_i_ref,
2468 "type_name_index");
2469
2470 u2 const_name_index = rewrite_cp_ref_in_annotation_data(
2471 annotations_typeArray, byte_i_ref,
2472 "const_name_index");
2473
2474 log_debug(redefine, class, annotation)
2475 ("type_name_index=%d const_name_index=%d", type_name_index, const_name_index);
2476 } break;
2477
2478 case 'c':
2479 {
2480 // for the above tag value, value.class_info_index is right union field
2481
2482 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2483 // not enough room for a class_info_index
2484 log_debug(redefine, class, annotation)("length() is too small for a class_info_index");
2485 return false;
2486 }
2487
2488 u2 class_info_index = rewrite_cp_ref_in_annotation_data(
2489 annotations_typeArray, byte_i_ref,
2490 "class_info_index");
2491
2492 log_debug(redefine, class, annotation)("class_info_index=%d", class_info_index);
2493 } break;
2494
2495 case '@':
2496 // For the above tag value, value.attr_value is the right union
2497 // field. This is a nested annotation.
2498 if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray, byte_i_ref)) {
2499 // propagate failure back to caller
2500 return false;
2501 }
2502 break;
2503
2504 case JVM_SIGNATURE_ARRAY:
2505 {
2506 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2507 // not enough room for a num_values field
2508 log_debug(redefine, class, annotation)("length() is too small for a num_values field");
2509 return false;
2510 }
2511
2512 // For the above tag value, value.array_value is the right union
2513 // field. This is an array of nested element_value.
2514 u2 num_values = Bytes::get_Java_u2((address)
2515 annotations_typeArray->adr_at(byte_i_ref));
2516 byte_i_ref += 2;
2517 log_debug(redefine, class, annotation)("num_values=%d", num_values);
2518
2519 int calc_num_values = 0;
2520 for (; calc_num_values < num_values; calc_num_values++) {
2521 if (!rewrite_cp_refs_in_element_value(annotations_typeArray, byte_i_ref)) {
2522 log_debug(redefine, class, annotation)("bad nested element_value at %d", calc_num_values);
2523 // propagate failure back to caller
2524 return false;
2525 }
2526 }
2527 assert(num_values == calc_num_values, "sanity check");
2528 } break;
2529
2530 default:
2531 log_debug(redefine, class, annotation)("bad tag=0x%x", tag);
2532 return false;
2533 } // end decode tag field
2534
2535 return true;
2536 } // end rewrite_cp_refs_in_element_value()
2537
2538
2539 // Rewrite constant pool references in a fields_annotations field.
2540 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations(
2541 InstanceKlass* scratch_class) {
2542
2543 Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations();
2544
2545 if (fields_annotations == nullptr || fields_annotations->length() == 0) {
2546 // no fields_annotations so nothing to do
2547 return true;
2548 }
2549
2550 log_debug(redefine, class, annotation)("fields_annotations length=%d", fields_annotations->length());
2551
2552 for (int i = 0; i < fields_annotations->length(); i++) {
2553 AnnotationArray* field_annotations = fields_annotations->at(i);
2554 if (field_annotations == nullptr || field_annotations->length() == 0) {
2555 // this field does not have any annotations so skip it
2556 continue;
2557 }
2558
2559 int byte_i = 0; // byte index into field_annotations
2560 if (!rewrite_cp_refs_in_annotations_typeArray(field_annotations, byte_i)) {
2561 log_debug(redefine, class, annotation)("bad field_annotations at %d", i);
2562 // propagate failure back to caller
2563 return false;
2564 }
2565 }
2566
2567 return true;
2568 } // end rewrite_cp_refs_in_fields_annotations()
2569
2570
2571 // Rewrite constant pool references in a methods_annotations field.
2572 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations(
2573 InstanceKlass* scratch_class) {
2574
2575 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2576 Method* m = scratch_class->methods()->at(i);
2577 AnnotationArray* method_annotations = m->constMethod()->method_annotations();
2578
2579 if (method_annotations == nullptr || method_annotations->length() == 0) {
2580 // this method does not have any annotations so skip it
2581 continue;
2582 }
2583
2584 int byte_i = 0; // byte index into method_annotations
2585 if (!rewrite_cp_refs_in_annotations_typeArray(method_annotations, byte_i)) {
2586 log_debug(redefine, class, annotation)("bad method_annotations at %d", i);
2587 // propagate failure back to caller
2588 return false;
2589 }
2590 }
2591
2592 return true;
2593 } // end rewrite_cp_refs_in_methods_annotations()
2594
2595
2596 // Rewrite constant pool references in a methods_parameter_annotations
2597 // field. This "structure" is adapted from the
2598 // RuntimeVisibleParameterAnnotations_attribute described in section
2599 // 4.8.17 of the 2nd-edition of the VM spec:
2600 //
2601 // methods_parameter_annotations_typeArray {
2602 // u1 num_parameters;
2603 // {
2604 // u2 num_annotations;
2605 // annotation annotations[num_annotations];
2606 // } parameter_annotations[num_parameters];
2607 // }
2608 //
2609 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations(
2610 InstanceKlass* scratch_class) {
2611
2612 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2613 Method* m = scratch_class->methods()->at(i);
2614 AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations();
2615 if (method_parameter_annotations == nullptr
2616 || method_parameter_annotations->length() == 0) {
2617 // this method does not have any parameter annotations so skip it
2618 continue;
2619 }
2620
2621 if (method_parameter_annotations->length() < 1) {
2622 // not enough room for a num_parameters field
2623 log_debug(redefine, class, annotation)("length() is too small for a num_parameters field at %d", i);
2624 return false;
2625 }
2626
2627 int byte_i = 0; // byte index into method_parameter_annotations
2628
2629 u1 num_parameters = method_parameter_annotations->at(byte_i);
2630 byte_i++;
2631
2632 log_debug(redefine, class, annotation)("num_parameters=%d", num_parameters);
2633
2634 int calc_num_parameters = 0;
2635 for (; calc_num_parameters < num_parameters; calc_num_parameters++) {
2636 if (!rewrite_cp_refs_in_annotations_typeArray(method_parameter_annotations, byte_i)) {
2637 log_debug(redefine, class, annotation)("bad method_parameter_annotations at %d", calc_num_parameters);
2638 // propagate failure back to caller
2639 return false;
2640 }
2641 }
2642 assert(num_parameters == calc_num_parameters, "sanity check");
2643 }
2644
2645 return true;
2646 } // end rewrite_cp_refs_in_methods_parameter_annotations()
2647
2648
2649 // Rewrite constant pool references in a methods_default_annotations
2650 // field. This "structure" is adapted from the AnnotationDefault_attribute
2651 // that is described in section 4.8.19 of the 2nd-edition of the VM spec:
2652 //
2653 // methods_default_annotations_typeArray {
2654 // element_value default_value;
2655 // }
2656 //
2657 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations(
2658 InstanceKlass* scratch_class) {
2659
2660 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2661 Method* m = scratch_class->methods()->at(i);
2662 AnnotationArray* method_default_annotations = m->constMethod()->default_annotations();
2663 if (method_default_annotations == nullptr
2664 || method_default_annotations->length() == 0) {
2665 // this method does not have any default annotations so skip it
2666 continue;
2667 }
2668
2669 int byte_i = 0; // byte index into method_default_annotations
2670
2671 if (!rewrite_cp_refs_in_element_value(
2672 method_default_annotations, byte_i)) {
2673 log_debug(redefine, class, annotation)("bad default element_value at %d", i);
2674 // propagate failure back to caller
2675 return false;
2676 }
2677 }
2678
2679 return true;
2680 } // end rewrite_cp_refs_in_methods_default_annotations()
2681
2682
2683 // Rewrite constant pool references in a class_type_annotations field.
2684 bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations(
2685 InstanceKlass* scratch_class) {
2686
2687 AnnotationArray* class_type_annotations = scratch_class->class_type_annotations();
2688 if (class_type_annotations == nullptr || class_type_annotations->length() == 0) {
2689 // no class_type_annotations so nothing to do
2690 return true;
2691 }
2692
2693 log_debug(redefine, class, annotation)("class_type_annotations length=%d", class_type_annotations->length());
2694
2695 int byte_i = 0; // byte index into class_type_annotations
2696 return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations,
2697 byte_i, "ClassFile");
2698 } // end rewrite_cp_refs_in_class_type_annotations()
2699
2700
2701 // Rewrite constant pool references in a fields_type_annotations field.
2702 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations(InstanceKlass* scratch_class) {
2703
2704 Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations();
2705 if (fields_type_annotations == nullptr || fields_type_annotations->length() == 0) {
2706 // no fields_type_annotations so nothing to do
2707 return true;
2708 }
2709
2710 log_debug(redefine, class, annotation)("fields_type_annotations length=%d", fields_type_annotations->length());
2711
2712 for (int i = 0; i < fields_type_annotations->length(); i++) {
2713 AnnotationArray* field_type_annotations = fields_type_annotations->at(i);
2714 if (field_type_annotations == nullptr || field_type_annotations->length() == 0) {
2715 // this field does not have any annotations so skip it
2716 continue;
2717 }
2718
2719 int byte_i = 0; // byte index into field_type_annotations
2720 if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations,
2721 byte_i, "field_info")) {
2722 log_debug(redefine, class, annotation)("bad field_type_annotations at %d", i);
2723 // propagate failure back to caller
2724 return false;
2725 }
2726 }
2727
2728 return true;
2729 } // end rewrite_cp_refs_in_fields_type_annotations()
2730
2731
2732 // Rewrite constant pool references in a methods_type_annotations field.
2733 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations(
2734 InstanceKlass* scratch_class) {
2735
2736 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2737 Method* m = scratch_class->methods()->at(i);
2738 AnnotationArray* method_type_annotations = m->constMethod()->type_annotations();
2739
2740 if (method_type_annotations == nullptr || method_type_annotations->length() == 0) {
2741 // this method does not have any annotations so skip it
2742 continue;
2743 }
2744
2745 log_debug(redefine, class, annotation)("methods type_annotations length=%d", method_type_annotations->length());
2746
2747 int byte_i = 0; // byte index into method_type_annotations
2748 if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations,
2749 byte_i, "method_info")) {
2750 log_debug(redefine, class, annotation)("bad method_type_annotations at %d", i);
2751 // propagate failure back to caller
2752 return false;
2753 }
2754 }
2755
2756 return true;
2757 } // end rewrite_cp_refs_in_methods_type_annotations()
2758
2759
2760 // Rewrite constant pool references in a type_annotations
2761 // field. This "structure" is adapted from the
2762 // RuntimeVisibleTypeAnnotations_attribute described in
2763 // section 4.7.20 of the Java SE 8 Edition of the VM spec:
2764 //
2765 // type_annotations_typeArray {
2766 // u2 num_annotations;
2767 // type_annotation annotations[num_annotations];
2768 // }
2769 //
2770 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotations_typeArray(
2771 AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2772 const char * location_mesg) {
2773
2774 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2775 // not enough room for num_annotations field
2776 log_debug(redefine, class, annotation)("length() is too small for num_annotations field");
2777 return false;
2778 }
2779
2780 u2 num_annotations = Bytes::get_Java_u2((address)
2781 type_annotations_typeArray->adr_at(byte_i_ref));
2782 byte_i_ref += 2;
2783
2784 log_debug(redefine, class, annotation)("num_type_annotations=%d", num_annotations);
2785
2786 int calc_num_annotations = 0;
2787 for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
2788 if (!rewrite_cp_refs_in_type_annotation_struct(type_annotations_typeArray,
2789 byte_i_ref, location_mesg)) {
2790 log_debug(redefine, class, annotation)("bad type_annotation_struct at %d", calc_num_annotations);
2791 // propagate failure back to caller
2792 return false;
2793 }
2794 }
2795 assert(num_annotations == calc_num_annotations, "sanity check");
2796
2797 if (byte_i_ref != type_annotations_typeArray->length()) {
2798 log_debug(redefine, class, annotation)
2799 ("read wrong amount of bytes at end of processing type_annotations_typeArray (%d of %d bytes were read)",
2800 byte_i_ref, type_annotations_typeArray->length());
2801 return false;
2802 }
2803
2804 return true;
2805 } // end rewrite_cp_refs_in_type_annotations_typeArray()
2806
2807
2808 // Rewrite constant pool references in a type_annotation
2809 // field. This "structure" is adapted from the
2810 // RuntimeVisibleTypeAnnotations_attribute described in
2811 // section 4.7.20 of the Java SE 8 Edition of the VM spec:
2812 //
2813 // type_annotation {
2814 // u1 target_type;
2815 // union {
2816 // type_parameter_target;
2817 // supertype_target;
2818 // type_parameter_bound_target;
2819 // empty_target;
2820 // method_formal_parameter_target;
2821 // throws_target;
2822 // localvar_target;
2823 // catch_target;
2824 // offset_target;
2825 // type_argument_target;
2826 // } target_info;
2827 // type_path target_path;
2828 // annotation anno;
2829 // }
2830 //
2831 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotation_struct(
2832 AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2833 const char * location_mesg) {
2834
2835 if (!skip_type_annotation_target(type_annotations_typeArray,
2836 byte_i_ref, location_mesg)) {
2837 return false;
2838 }
2839
2840 if (!skip_type_annotation_type_path(type_annotations_typeArray, byte_i_ref)) {
2841 return false;
2842 }
2843
2844 if (!rewrite_cp_refs_in_annotation_struct(type_annotations_typeArray, byte_i_ref)) {
2845 return false;
2846 }
2847
2848 return true;
2849 } // end rewrite_cp_refs_in_type_annotation_struct()
2850
2851
2852 // Read, verify and skip over the target_type and target_info part
2853 // so that rewriting can continue in the later parts of the struct.
2854 //
2855 // u1 target_type;
2856 // union {
2857 // type_parameter_target;
2858 // supertype_target;
2859 // type_parameter_bound_target;
2860 // empty_target;
2861 // method_formal_parameter_target;
2862 // throws_target;
2863 // localvar_target;
2864 // catch_target;
2865 // offset_target;
2866 // type_argument_target;
2867 // } target_info;
2868 //
2869 bool VM_RedefineClasses::skip_type_annotation_target(
2870 AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2871 const char * location_mesg) {
2872
2873 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2874 // not enough room for a target_type let alone the rest of a type_annotation
2875 log_debug(redefine, class, annotation)("length() is too small for a target_type");
2876 return false;
2877 }
2878
2879 u1 target_type = type_annotations_typeArray->at(byte_i_ref);
2880 byte_i_ref += 1;
2881 log_debug(redefine, class, annotation)("target_type=0x%.2x", target_type);
2882 log_debug(redefine, class, annotation)("location=%s", location_mesg);
2883
2884 // Skip over target_info
2885 switch (target_type) {
2886 case 0x00:
2887 // kind: type parameter declaration of generic class or interface
2888 // location: ClassFile
2889 case 0x01:
2890 // kind: type parameter declaration of generic method or constructor
2891 // location: method_info
2892
2893 {
2894 // struct:
2895 // type_parameter_target {
2896 // u1 type_parameter_index;
2897 // }
2898 //
2899 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2900 log_debug(redefine, class, annotation)("length() is too small for a type_parameter_target");
2901 return false;
2902 }
2903
2904 u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2905 byte_i_ref += 1;
2906
2907 log_debug(redefine, class, annotation)("type_parameter_target: type_parameter_index=%d", type_parameter_index);
2908 } break;
2909
2910 case 0x10:
2911 // kind: type in extends clause of class or interface declaration
2912 // or in implements clause of interface declaration
2913 // location: ClassFile
2914
2915 {
2916 // struct:
2917 // supertype_target {
2918 // u2 supertype_index;
2919 // }
2920 //
2921 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2922 log_debug(redefine, class, annotation)("length() is too small for a supertype_target");
2923 return false;
2924 }
2925
2926 u2 supertype_index = Bytes::get_Java_u2((address)
2927 type_annotations_typeArray->adr_at(byte_i_ref));
2928 byte_i_ref += 2;
2929
2930 log_debug(redefine, class, annotation)("supertype_target: supertype_index=%d", supertype_index);
2931 } break;
2932
2933 case 0x11:
2934 // kind: type in bound of type parameter declaration of generic class or interface
2935 // location: ClassFile
2936 case 0x12:
2937 // kind: type in bound of type parameter declaration of generic method or constructor
2938 // location: method_info
2939
2940 {
2941 // struct:
2942 // type_parameter_bound_target {
2943 // u1 type_parameter_index;
2944 // u1 bound_index;
2945 // }
2946 //
2947 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2948 log_debug(redefine, class, annotation)("length() is too small for a type_parameter_bound_target");
2949 return false;
2950 }
2951
2952 u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2953 byte_i_ref += 1;
2954 u1 bound_index = type_annotations_typeArray->at(byte_i_ref);
2955 byte_i_ref += 1;
2956
2957 log_debug(redefine, class, annotation)
2958 ("type_parameter_bound_target: type_parameter_index=%d, bound_index=%d", type_parameter_index, bound_index);
2959 } break;
2960
2961 case 0x13:
2962 // kind: type in field declaration
2963 // location: field_info
2964 case 0x14:
2965 // kind: return type of method, or type of newly constructed object
2966 // location: method_info
2967 case 0x15:
2968 // kind: receiver type of method or constructor
2969 // location: method_info
2970
2971 {
2972 // struct:
2973 // empty_target {
2974 // }
2975 //
2976 log_debug(redefine, class, annotation)("empty_target");
2977 } break;
2978
2979 case 0x16:
2980 // kind: type in formal parameter declaration of method, constructor, or lambda expression
2981 // location: method_info
2982
2983 {
2984 // struct:
2985 // formal_parameter_target {
2986 // u1 formal_parameter_index;
2987 // }
2988 //
2989 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2990 log_debug(redefine, class, annotation)("length() is too small for a formal_parameter_target");
2991 return false;
2992 }
2993
2994 u1 formal_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2995 byte_i_ref += 1;
2996
2997 log_debug(redefine, class, annotation)
2998 ("formal_parameter_target: formal_parameter_index=%d", formal_parameter_index);
2999 } break;
3000
3001 case 0x17:
3002 // kind: type in throws clause of method or constructor
3003 // location: method_info
3004
3005 {
3006 // struct:
3007 // throws_target {
3008 // u2 throws_type_index
3009 // }
3010 //
3011 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
3012 log_debug(redefine, class, annotation)("length() is too small for a throws_target");
3013 return false;
3014 }
3015
3016 u2 throws_type_index = Bytes::get_Java_u2((address)
3017 type_annotations_typeArray->adr_at(byte_i_ref));
3018 byte_i_ref += 2;
3019
3020 log_debug(redefine, class, annotation)("throws_target: throws_type_index=%d", throws_type_index);
3021 } break;
3022
3023 case 0x40:
3024 // kind: type in local variable declaration
3025 // location: Code
3026 case 0x41:
3027 // kind: type in resource variable declaration
3028 // location: Code
3029
3030 {
3031 // struct:
3032 // localvar_target {
3033 // u2 table_length;
3034 // struct {
3035 // u2 start_pc;
3036 // u2 length;
3037 // u2 index;
3038 // } table[table_length];
3039 // }
3040 //
3041 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
3042 // not enough room for a table_length let alone the rest of a localvar_target
3043 log_debug(redefine, class, annotation)("length() is too small for a localvar_target table_length");
3044 return false;
3045 }
3046
3047 u2 table_length = Bytes::get_Java_u2((address)
3048 type_annotations_typeArray->adr_at(byte_i_ref));
3049 byte_i_ref += 2;
3050
3051 log_debug(redefine, class, annotation)("localvar_target: table_length=%d", table_length);
3052
3053 int table_struct_size = 2 + 2 + 2; // 3 u2 variables per table entry
3054 int table_size = table_length * table_struct_size;
3055
3056 if ((byte_i_ref + table_size) > type_annotations_typeArray->length()) {
3057 // not enough room for a table
3058 log_debug(redefine, class, annotation)("length() is too small for a table array of length %d", table_length);
3059 return false;
3060 }
3061
3062 // Skip over table
3063 byte_i_ref += table_size;
3064 } break;
3065
3066 case 0x42:
3067 // kind: type in exception parameter declaration
3068 // location: Code
3069
3070 {
3071 // struct:
3072 // catch_target {
3073 // u2 exception_table_index;
3074 // }
3075 //
3076 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
3077 log_debug(redefine, class, annotation)("length() is too small for a catch_target");
3078 return false;
3079 }
3080
3081 u2 exception_table_index = Bytes::get_Java_u2((address)
3082 type_annotations_typeArray->adr_at(byte_i_ref));
3083 byte_i_ref += 2;
3084
3085 log_debug(redefine, class, annotation)("catch_target: exception_table_index=%d", exception_table_index);
3086 } break;
3087
3088 case 0x43:
3089 // kind: type in instanceof expression
3090 // location: Code
3091 case 0x44:
3092 // kind: type in new expression
3093 // location: Code
3094 case 0x45:
3095 // kind: type in method reference expression using ::new
3096 // location: Code
3097 case 0x46:
3098 // kind: type in method reference expression using ::Identifier
3099 // location: Code
3100
3101 {
3102 // struct:
3103 // offset_target {
3104 // u2 offset;
3105 // }
3106 //
3107 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
3108 log_debug(redefine, class, annotation)("length() is too small for a offset_target");
3109 return false;
3110 }
3111
3112 u2 offset = Bytes::get_Java_u2((address)
3113 type_annotations_typeArray->adr_at(byte_i_ref));
3114 byte_i_ref += 2;
3115
3116 log_debug(redefine, class, annotation)("offset_target: offset=%d", offset);
3117 } break;
3118
3119 case 0x47:
3120 // kind: type in cast expression
3121 // location: Code
3122 case 0x48:
3123 // kind: type argument for generic constructor in new expression or
3124 // explicit constructor invocation statement
3125 // location: Code
3126 case 0x49:
3127 // kind: type argument for generic method in method invocation expression
3128 // location: Code
3129 case 0x4A:
3130 // kind: type argument for generic constructor in method reference expression using ::new
3131 // location: Code
3132 case 0x4B:
3133 // kind: type argument for generic method in method reference expression using ::Identifier
3134 // location: Code
3135
3136 {
3137 // struct:
3138 // type_argument_target {
3139 // u2 offset;
3140 // u1 type_argument_index;
3141 // }
3142 //
3143 if ((byte_i_ref + 3) > type_annotations_typeArray->length()) {
3144 log_debug(redefine, class, annotation)("length() is too small for a type_argument_target");
3145 return false;
3146 }
3147
3148 u2 offset = Bytes::get_Java_u2((address)
3149 type_annotations_typeArray->adr_at(byte_i_ref));
3150 byte_i_ref += 2;
3151 u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
3152 byte_i_ref += 1;
3153
3154 log_debug(redefine, class, annotation)
3155 ("type_argument_target: offset=%d, type_argument_index=%d", offset, type_argument_index);
3156 } break;
3157
3158 default:
3159 log_debug(redefine, class, annotation)("unknown target_type");
3160 #ifdef ASSERT
3161 ShouldNotReachHere();
3162 #endif
3163 return false;
3164 }
3165
3166 return true;
3167 } // end skip_type_annotation_target()
3168
3169
3170 // Read, verify and skip over the type_path part so that rewriting
3171 // can continue in the later parts of the struct.
3172 //
3173 // type_path {
3174 // u1 path_length;
3175 // {
3176 // u1 type_path_kind;
3177 // u1 type_argument_index;
3178 // } path[path_length];
3179 // }
3180 //
3181 bool VM_RedefineClasses::skip_type_annotation_type_path(
3182 AnnotationArray* type_annotations_typeArray, int &byte_i_ref) {
3183
3184 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
3185 // not enough room for a path_length let alone the rest of the type_path
3186 log_debug(redefine, class, annotation)("length() is too small for a type_path");
3187 return false;
3188 }
3189
3190 u1 path_length = type_annotations_typeArray->at(byte_i_ref);
3191 byte_i_ref += 1;
3192
3193 log_debug(redefine, class, annotation)("type_path: path_length=%d", path_length);
3194
3195 int calc_path_length = 0;
3196 for (; calc_path_length < path_length; calc_path_length++) {
3197 if ((byte_i_ref + 1 + 1) > type_annotations_typeArray->length()) {
3198 // not enough room for a path
3199 log_debug(redefine, class, annotation)
3200 ("length() is too small for path entry %d of %d", calc_path_length, path_length);
3201 return false;
3202 }
3203
3204 u1 type_path_kind = type_annotations_typeArray->at(byte_i_ref);
3205 byte_i_ref += 1;
3206 u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
3207 byte_i_ref += 1;
3208
3209 log_debug(redefine, class, annotation)
3210 ("type_path: path[%d]: type_path_kind=%d, type_argument_index=%d",
3211 calc_path_length, type_path_kind, type_argument_index);
3212
3213 if (type_path_kind > 3 || (type_path_kind != 3 && type_argument_index != 0)) {
3214 // not enough room for a path
3215 log_debug(redefine, class, annotation)("inconsistent type_path values");
3216 return false;
3217 }
3218 }
3219 assert(path_length == calc_path_length, "sanity check");
3220
3221 return true;
3222 } // end skip_type_annotation_type_path()
3223
3224
3225 // Rewrite constant pool references in the method's stackmap table.
3226 // These "structures" are adapted from the StackMapTable_attribute that
3227 // is described in section 4.8.4 of the 6.0 version of the VM spec
3228 // (dated 2005.10.26):
3229 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf
3230 //
3231 // stack_map {
3232 // u2 number_of_entries;
3233 // stack_map_frame entries[number_of_entries];
3234 // }
3235 //
3236 void VM_RedefineClasses::rewrite_cp_refs_in_stack_map_table(
3237 const methodHandle& method) {
3238
3239 if (!method->has_stackmap_table()) {
3240 return;
3241 }
3242
3243 AnnotationArray* stackmap_data = method->stackmap_data();
3244 address stackmap_p = (address)stackmap_data->adr_at(0);
3245 address stackmap_end = stackmap_p + stackmap_data->length();
3246
3247 assert(stackmap_p + 2 <= stackmap_end, "no room for number_of_entries");
3248 u2 number_of_entries = Bytes::get_Java_u2(stackmap_p);
3249 stackmap_p += 2;
3250
3251 log_debug(redefine, class, stackmap)("number_of_entries=%u", number_of_entries);
3252
3253 // walk through each stack_map_frame
3254 u2 calc_number_of_entries = 0;
3255 for (; calc_number_of_entries < number_of_entries; calc_number_of_entries++) {
3256 // The stack_map_frame structure is a u1 frame_type followed by
3257 // 0 or more bytes of data:
3258 //
3259 // union stack_map_frame {
3260 // same_frame;
3261 // same_locals_1_stack_item_frame;
3262 // same_locals_1_stack_item_frame_extended;
3263 // chop_frame;
3264 // same_frame_extended;
3265 // append_frame;
3266 // full_frame;
3267 // }
3268
3269 assert(stackmap_p + 1 <= stackmap_end, "no room for frame_type");
3270 u1 frame_type = *stackmap_p;
3271 stackmap_p++;
3272
3273 // same_frame {
3274 // u1 frame_type = SAME; /* 0-63 */
3275 // }
3276 if (frame_type <= StackMapReader::SAME_FRAME_END) {
3277 // nothing more to do for same_frame
3278 }
3279
3280 // same_locals_1_stack_item_frame {
3281 // u1 frame_type = SAME_LOCALS_1_STACK_ITEM; /* 64-127 */
3282 // verification_type_info stack[1];
3283 // }
3284 else if (frame_type >= StackMapReader::SAME_LOCALS_1_STACK_ITEM_FRAME_START &&
3285 frame_type <= StackMapReader::SAME_LOCALS_1_STACK_ITEM_FRAME_END) {
3286 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3287 calc_number_of_entries, frame_type);
3288 }
3289
3290 // reserved for future use
3291 else if (frame_type >= StackMapReader::RESERVED_START &&
3292 frame_type <= StackMapReader::RESERVED_END) {
3293 // nothing more to do for reserved frame_types
3294 }
3295
3296 // same_locals_1_stack_item_frame_extended {
3297 // u1 frame_type = SAME_LOCALS_1_STACK_ITEM_EXTENDED; /* 247 */
3298 // u2 offset_delta;
3299 // verification_type_info stack[1];
3300 // }
3301 else if (frame_type == StackMapReader::SAME_LOCALS_1_STACK_ITEM_EXTENDED) {
3302 stackmap_p += 2;
3303 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3304 calc_number_of_entries, frame_type);
3305 }
3306
3307 // chop_frame {
3308 // u1 frame_type = CHOP; /* 248-250 */
3309 // u2 offset_delta;
3310 // }
3311 else if (frame_type >= StackMapReader::CHOP_FRAME_START &&
3312 frame_type <= StackMapReader::CHOP_FRAME_END) {
3313 stackmap_p += 2;
3314 }
3315
3316 // same_frame_extended {
3317 // u1 frame_type = SAME_EXTENDED; /* 251 */
3318 // u2 offset_delta;
3319 // }
3320 else if (frame_type == StackMapReader::SAME_FRAME_EXTENDED) {
3321 stackmap_p += 2;
3322 }
3323
3324 // append_frame {
3325 // u1 frame_type = APPEND; /* 252-254 */
3326 // u2 offset_delta;
3327 // verification_type_info locals[frame_type - SAME_EXTENDED];
3328 // }
3329 else if (frame_type >= StackMapReader::APPEND_FRAME_START &&
3330 frame_type <= StackMapReader::APPEND_FRAME_END) {
3331 assert(stackmap_p + 2 <= stackmap_end,
3332 "no room for offset_delta");
3333 stackmap_p += 2;
3334 u1 len = frame_type - StackMapReader::APPEND_FRAME_START + 1;
3335 for (u1 i = 0; i < len; i++) {
3336 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3337 calc_number_of_entries, frame_type);
3338 }
3339 }
3340
3341 // full_frame {
3342 // u1 frame_type = FULL_FRAME; /* 255 */
3343 // u2 offset_delta;
3344 // u2 number_of_locals;
3345 // verification_type_info locals[number_of_locals];
3346 // u2 number_of_stack_items;
3347 // verification_type_info stack[number_of_stack_items];
3348 // }
3349 else if (frame_type == StackMapReader::FULL_FRAME) {
3350 assert(stackmap_p + 2 + 2 <= stackmap_end,
3351 "no room for smallest full_frame");
3352 stackmap_p += 2;
3353
3354 u2 number_of_locals = Bytes::get_Java_u2(stackmap_p);
3355 stackmap_p += 2;
3356
3357 for (u2 locals_i = 0; locals_i < number_of_locals; locals_i++) {
3358 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3359 calc_number_of_entries, frame_type);
3360 }
3361
3362 // Use the largest size for the number_of_stack_items, but only get
3363 // the right number of bytes.
3364 u2 number_of_stack_items = Bytes::get_Java_u2(stackmap_p);
3365 stackmap_p += 2;
3366
3367 for (u2 stack_i = 0; stack_i < number_of_stack_items; stack_i++) {
3368 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3369 calc_number_of_entries, frame_type);
3370 }
3371 }
3372 } // end while there is a stack_map_frame
3373 assert(number_of_entries == calc_number_of_entries, "sanity check");
3374 } // end rewrite_cp_refs_in_stack_map_table()
3375
3376
3377 // Rewrite constant pool references in the verification type info
3378 // portion of the method's stackmap table. These "structures" are
3379 // adapted from the StackMapTable_attribute that is described in
3380 // section 4.8.4 of the 6.0 version of the VM spec (dated 2005.10.26):
3381 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf
3382 //
3383 // The verification_type_info structure is a u1 tag followed by 0 or
3384 // more bytes of data:
3385 //
3386 // union verification_type_info {
3387 // Top_variable_info;
3388 // Integer_variable_info;
3389 // Float_variable_info;
3390 // Long_variable_info;
3391 // Double_variable_info;
3392 // Null_variable_info;
3393 // UninitializedThis_variable_info;
3394 // Object_variable_info;
3395 // Uninitialized_variable_info;
3396 // }
3397 //
3398 void VM_RedefineClasses::rewrite_cp_refs_in_verification_type_info(
3399 address& stackmap_p_ref, address stackmap_end, u2 frame_i,
3400 u1 frame_type) {
3401
3402 assert(stackmap_p_ref + 1 <= stackmap_end, "no room for tag");
3403 u1 tag = *stackmap_p_ref;
3404 stackmap_p_ref++;
3405
3406 switch (tag) {
3407 // Top_variable_info {
3408 // u1 tag = ITEM_Top; /* 0 */
3409 // }
3410 // verificationType.hpp has zero as ITEM_Bogus instead of ITEM_Top
3411 case 0: // fall through
3412
3413 // Integer_variable_info {
3414 // u1 tag = ITEM_Integer; /* 1 */
3415 // }
3416 case ITEM_Integer: // fall through
3417
3418 // Float_variable_info {
3419 // u1 tag = ITEM_Float; /* 2 */
3420 // }
3421 case ITEM_Float: // fall through
3422
3423 // Double_variable_info {
3424 // u1 tag = ITEM_Double; /* 3 */
3425 // }
3426 case ITEM_Double: // fall through
3427
3428 // Long_variable_info {
3429 // u1 tag = ITEM_Long; /* 4 */
3430 // }
3431 case ITEM_Long: // fall through
3432
3433 // Null_variable_info {
3434 // u1 tag = ITEM_Null; /* 5 */
3435 // }
3436 case ITEM_Null: // fall through
3437
3438 // UninitializedThis_variable_info {
3439 // u1 tag = ITEM_UninitializedThis; /* 6 */
3440 // }
3441 case ITEM_UninitializedThis:
3442 // nothing more to do for the above tag types
3443 break;
3444
3445 // Object_variable_info {
3446 // u1 tag = ITEM_Object; /* 7 */
3447 // u2 cpool_index;
3448 // }
3449 case ITEM_Object:
3450 {
3451 assert(stackmap_p_ref + 2 <= stackmap_end, "no room for cpool_index");
3452 u2 cpool_index = Bytes::get_Java_u2(stackmap_p_ref);
3453 u2 new_cp_index = find_new_index(cpool_index);
3454 if (new_cp_index != 0) {
3455 log_debug(redefine, class, stackmap)("mapped old cpool_index=%d", cpool_index);
3456 Bytes::put_Java_u2(stackmap_p_ref, new_cp_index);
3457 cpool_index = new_cp_index;
3458 }
3459 stackmap_p_ref += 2;
3460
3461 log_debug(redefine, class, stackmap)
3462 ("frame_i=%u, frame_type=%u, cpool_index=%d", frame_i, frame_type, cpool_index);
3463 } break;
3464
3465 // Uninitialized_variable_info {
3466 // u1 tag = ITEM_Uninitialized; /* 8 */
3467 // u2 offset;
3468 // }
3469 case ITEM_Uninitialized:
3470 assert(stackmap_p_ref + 2 <= stackmap_end, "no room for offset");
3471 stackmap_p_ref += 2;
3472 break;
3473
3474 default:
3475 log_debug(redefine, class, stackmap)("frame_i=%u, frame_type=%u, bad tag=0x%x", frame_i, frame_type, tag);
3476 ShouldNotReachHere();
3477 break;
3478 } // end switch (tag)
3479 } // end rewrite_cp_refs_in_verification_type_info()
3480
3481
3482 // Change the constant pool associated with klass scratch_class to scratch_cp.
3483 // scratch_cp_length elements are copied from scratch_cp to a smaller constant pool
3484 // and the smaller constant pool is associated with scratch_class.
3485 void VM_RedefineClasses::set_new_constant_pool(
3486 ClassLoaderData* loader_data,
3487 InstanceKlass* scratch_class, constantPoolHandle scratch_cp,
3488 int scratch_cp_length, TRAPS) {
3489 assert(scratch_cp->length() >= scratch_cp_length, "sanity check");
3490
3491 // scratch_cp is a merged constant pool and has enough space for a
3492 // worst case merge situation. We want to associate the minimum
3493 // sized constant pool with the klass to save space.
3494 ConstantPool* cp = ConstantPool::allocate(loader_data, scratch_cp_length, CHECK);
3495 constantPoolHandle smaller_cp(THREAD, cp);
3496
3497 // preserve version() value in the smaller copy
3498 int version = scratch_cp->version();
3499 assert(version != 0, "sanity check");
3500 smaller_cp->set_version(version);
3501
3502 // attach klass to new constant pool
3503 // reference to the cp holder is needed for copy_operands()
3504 smaller_cp->set_pool_holder(scratch_class);
3505
3506 smaller_cp->copy_fields(scratch_cp());
3507
3508 scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
3509 if (HAS_PENDING_EXCEPTION) {
3510 // Exception is handled in the caller
3511 loader_data->add_to_deallocate_list(smaller_cp());
3512 return;
3513 }
3514 scratch_cp = smaller_cp;
3515
3516 // attach new constant pool to klass
3517 scratch_class->set_constants(scratch_cp());
3518 scratch_cp->initialize_unresolved_klasses(loader_data, CHECK);
3519
3520 int i; // for portability
3521
3522 // update each field in klass to use new constant pool indices as needed
3523 int java_fields;
3524 int injected_fields;
3525 bool update_required = false;
3526 GrowableArray<FieldInfo>* fields = FieldInfoStream::create_FieldInfoArray(scratch_class->fieldinfo_stream(), &java_fields, &injected_fields);
3527 for (int i = 0; i < java_fields; i++) {
3528 FieldInfo* fi = fields->adr_at(i);
3529 jshort cur_index = fi->name_index();
3530 jshort new_index = find_new_index(cur_index);
3531 if (new_index != 0) {
3532 log_trace(redefine, class, constantpool)("field-name_index change: %d to %d", cur_index, new_index);
3533 fi->set_name_index(new_index);
3534 update_required = true;
3535 }
3536 cur_index = fi->signature_index();
3537 new_index = find_new_index(cur_index);
3538 if (new_index != 0) {
3539 log_trace(redefine, class, constantpool)("field-signature_index change: %d to %d", cur_index, new_index);
3540 fi->set_signature_index(new_index);
3541 update_required = true;
3542 }
3543 cur_index = fi->initializer_index();
3544 new_index = find_new_index(cur_index);
3545 if (new_index != 0) {
3546 log_trace(redefine, class, constantpool)("field-initval_index change: %d to %d", cur_index, new_index);
3547 fi->set_initializer_index(new_index);
3548 update_required = true;
3549 }
3550 cur_index = fi->generic_signature_index();
3551 new_index = find_new_index(cur_index);
3552 if (new_index != 0) {
3553 log_trace(redefine, class, constantpool)("field-generic_signature change: %d to %d", cur_index, new_index);
3554 fi->set_generic_signature_index(new_index);
3555 update_required = true;
3556 }
3557 }
3558 if (update_required) {
3559 Array<u1>* old_stream = scratch_class->fieldinfo_stream();
3560 assert(fields->length() == (java_fields + injected_fields), "Must be");
3561 Array<u1>* new_fis = FieldInfoStream::create_FieldInfoStream(fields, java_fields, injected_fields, scratch_class->class_loader_data(), CHECK);
3562 scratch_class->set_fieldinfo_stream(new_fis);
3563 MetadataFactory::free_array<u1>(scratch_class->class_loader_data(), old_stream);
3564
3565 Array<u1>* old_table = scratch_class->fieldinfo_search_table();
3566 Array<u1>* search_table = FieldInfoStream::create_search_table(scratch_class->constants(), new_fis, scratch_class->class_loader_data(), CHECK);
3567 scratch_class->set_fieldinfo_search_table(search_table);
3568 MetadataFactory::free_array<u1>(scratch_class->class_loader_data(), old_table);
3569
3570 DEBUG_ONLY(FieldInfoStream::validate_search_table(scratch_class->constants(), new_fis, search_table));
3571 }
3572
3573 // Update constant pool indices in the inner classes info to use
3574 // new constant indices as needed. The inner classes info is a
3575 // quadruple:
3576 // (inner_class_info, outer_class_info, inner_name, inner_access_flags)
3577 InnerClassesIterator iter(scratch_class);
3578 for (; !iter.done(); iter.next()) {
3579 int cur_index = iter.inner_class_info_index();
3580 if (cur_index == 0) {
3581 continue; // JVM spec. allows null inner class refs so skip it
3582 }
3583 u2 new_index = find_new_index(cur_index);
3584 if (new_index != 0) {
3585 log_trace(redefine, class, constantpool)("inner_class_info change: %d to %d", cur_index, new_index);
3586 iter.set_inner_class_info_index(new_index);
3587 }
3588 cur_index = iter.outer_class_info_index();
3589 new_index = find_new_index(cur_index);
3590 if (new_index != 0) {
3591 log_trace(redefine, class, constantpool)("outer_class_info change: %d to %d", cur_index, new_index);
3592 iter.set_outer_class_info_index(new_index);
3593 }
3594 cur_index = iter.inner_name_index();
3595 new_index = find_new_index(cur_index);
3596 if (new_index != 0) {
3597 log_trace(redefine, class, constantpool)("inner_name change: %d to %d", cur_index, new_index);
3598 iter.set_inner_name_index(new_index);
3599 }
3600 } // end for each inner class
3601
3602 // Attach each method in klass to the new constant pool and update
3603 // to use new constant pool indices as needed:
3604 Array<Method*>* methods = scratch_class->methods();
3605 for (i = methods->length() - 1; i >= 0; i--) {
3606 methodHandle method(THREAD, methods->at(i));
3607 method->set_constants(scratch_cp());
3608
3609 u2 new_index = find_new_index(method->name_index());
3610 if (new_index != 0) {
3611 log_trace(redefine, class, constantpool)
3612 ("method-name_index change: %d to %d", method->name_index(), new_index);
3613 method->set_name_index(new_index);
3614 }
3615 new_index = find_new_index(method->signature_index());
3616 if (new_index != 0) {
3617 log_trace(redefine, class, constantpool)
3618 ("method-signature_index change: %d to %d", method->signature_index(), new_index);
3619 method->set_signature_index(new_index);
3620 }
3621 new_index = find_new_index(method->generic_signature_index());
3622 if (new_index != 0) {
3623 log_trace(redefine, class, constantpool)
3624 ("method-generic_signature_index change: %d to %d", method->generic_signature_index(), new_index);
3625 method->constMethod()->set_generic_signature_index(new_index);
3626 }
3627
3628 // Update constant pool indices in the method's checked exception
3629 // table to use new constant indices as needed.
3630 int cext_length = method->checked_exceptions_length();
3631 if (cext_length > 0) {
3632 CheckedExceptionElement * cext_table =
3633 method->checked_exceptions_start();
3634 for (int j = 0; j < cext_length; j++) {
3635 int cur_index = cext_table[j].class_cp_index;
3636 int new_index = find_new_index(cur_index);
3637 if (new_index != 0) {
3638 log_trace(redefine, class, constantpool)("cext-class_cp_index change: %d to %d", cur_index, new_index);
3639 cext_table[j].class_cp_index = (u2)new_index;
3640 }
3641 } // end for each checked exception table entry
3642 } // end if there are checked exception table entries
3643
3644 // Update each catch type index in the method's exception table
3645 // to use new constant pool indices as needed. The exception table
3646 // holds quadruple entries of the form:
3647 // (beg_bci, end_bci, handler_bci, klass_index)
3648
3649 ExceptionTable ex_table(method());
3650 int ext_length = ex_table.length();
3651
3652 for (int j = 0; j < ext_length; j ++) {
3653 int cur_index = ex_table.catch_type_index(j);
3654 u2 new_index = find_new_index(cur_index);
3655 if (new_index != 0) {
3656 log_trace(redefine, class, constantpool)("ext-klass_index change: %d to %d", cur_index, new_index);
3657 ex_table.set_catch_type_index(j, new_index);
3658 }
3659 } // end for each exception table entry
3660
3661 // Update constant pool indices in the method's local variable
3662 // table to use new constant indices as needed. The local variable
3663 // table hold sextuple entries of the form:
3664 // (start_pc, length, name_index, descriptor_index, signature_index, slot)
3665 int lvt_length = method->localvariable_table_length();
3666 if (lvt_length > 0) {
3667 LocalVariableTableElement * lv_table =
3668 method->localvariable_table_start();
3669 for (int j = 0; j < lvt_length; j++) {
3670 int cur_index = lv_table[j].name_cp_index;
3671 int new_index = find_new_index(cur_index);
3672 if (new_index != 0) {
3673 log_trace(redefine, class, constantpool)("lvt-name_cp_index change: %d to %d", cur_index, new_index);
3674 lv_table[j].name_cp_index = (u2)new_index;
3675 }
3676 cur_index = lv_table[j].descriptor_cp_index;
3677 new_index = find_new_index(cur_index);
3678 if (new_index != 0) {
3679 log_trace(redefine, class, constantpool)("lvt-descriptor_cp_index change: %d to %d", cur_index, new_index);
3680 lv_table[j].descriptor_cp_index = (u2)new_index;
3681 }
3682 cur_index = lv_table[j].signature_cp_index;
3683 new_index = find_new_index(cur_index);
3684 if (new_index != 0) {
3685 log_trace(redefine, class, constantpool)("lvt-signature_cp_index change: %d to %d", cur_index, new_index);
3686 lv_table[j].signature_cp_index = (u2)new_index;
3687 }
3688 } // end for each local variable table entry
3689 } // end if there are local variable table entries
3690
3691 // Update constant pool indices in the method's method_parameters.
3692 int mp_length = method->method_parameters_length();
3693 if (mp_length > 0) {
3694 MethodParametersElement* elem = method->method_parameters_start();
3695 for (int j = 0; j < mp_length; j++) {
3696 const int cp_index = elem[j].name_cp_index;
3697 const int new_cp_index = find_new_index(cp_index);
3698 if (new_cp_index != 0) {
3699 elem[j].name_cp_index = (u2)new_cp_index;
3700 }
3701 }
3702 }
3703
3704 rewrite_cp_refs_in_stack_map_table(method);
3705 } // end for each method
3706 } // end set_new_constant_pool()
3707
3708
3709 // Unevolving classes may point to methods of the_class directly
3710 // from their constant pool caches, itables, and/or vtables. We
3711 // use the ClassLoaderDataGraph::classes_do() facility and this helper
3712 // to fix up these pointers. MethodData also points to old methods and
3713 // must be cleaned.
3714
3715 // Adjust cpools and vtables closure
3716 void VM_RedefineClasses::AdjustAndCleanMetadata::do_klass(Klass* k) {
3717
3718 // This is a very busy routine. We don't want too much tracing
3719 // printed out.
3720 bool trace_name_printed = false;
3721
3722 // If the class being redefined is java.lang.Object, we need to fix all
3723 // array class vtables also. The _has_redefined_Object flag is global.
3724 // Once the java.lang.Object has been redefined (by the current or one
3725 // of the previous VM_RedefineClasses operations) we have to always
3726 // adjust method entries for array classes.
3727 if (k->is_array_klass() && _has_redefined_Object) {
3728 k->vtable().adjust_method_entries(&trace_name_printed);
3729
3730 } else if (k->is_instance_klass()) {
3731 HandleMark hm(_thread);
3732 InstanceKlass *ik = InstanceKlass::cast(k);
3733
3734 // Clean MethodData of this class's methods so they don't refer to
3735 // old methods that are no longer running.
3736 Array<Method*>* methods = ik->methods();
3737 int num_methods = methods->length();
3738 for (int index = 0; index < num_methods; ++index) {
3739 if (methods->at(index)->method_data() != nullptr) {
3740 methods->at(index)->method_data()->clean_weak_method_links();
3741 }
3742 }
3743
3744 // Adjust all vtables, default methods and itables, to clean out old methods.
3745 ResourceMark rm(_thread);
3746 if (ik->vtable_length() > 0) {
3747 ik->vtable().adjust_method_entries(&trace_name_printed);
3748 ik->adjust_default_methods(&trace_name_printed);
3749 }
3750
3751 if (ik->itable_length() > 0) {
3752 ik->itable().adjust_method_entries(&trace_name_printed);
3753 }
3754
3755 // The constant pools in other classes (other_cp) can refer to
3756 // old methods. We have to update method information in
3757 // other_cp's cache. If other_cp has a previous version, then we
3758 // have to repeat the process for each previous version. The
3759 // constant pool cache holds the Method*s for non-virtual
3760 // methods and for virtual, final methods.
3761 //
3762 // Special case: if the current class is being redefined by the current
3763 // VM_RedefineClasses operation, then new_cp has already been attached
3764 // to the_class and old_cp has already been added as a previous version.
3765 // The new_cp doesn't have any cached references to old methods so it
3766 // doesn't need to be updated and we could optimize by skipping it.
3767 // However, the current class can be marked as being redefined by another
3768 // VM_RedefineClasses operation which has already executed its doit_prologue
3769 // and needs cpcache method entries adjusted. For simplicity, the cpcache
3770 // update is done unconditionally. It should result in doing nothing for
3771 // classes being redefined by the current VM_RedefineClasses operation.
3772 // Method entries in the previous version(s) are adjusted as well.
3773 ConstantPoolCache* cp_cache;
3774
3775 // this klass' constant pool cache may need adjustment
3776 ConstantPool* other_cp = ik->constants();
3777 cp_cache = other_cp->cache();
3778 if (cp_cache != nullptr) {
3779 cp_cache->adjust_method_entries(&trace_name_printed);
3780 }
3781
3782 // the previous versions' constant pool caches may need adjustment
3783 for (InstanceKlass* pv_node = ik->previous_versions();
3784 pv_node != nullptr;
3785 pv_node = pv_node->previous_versions()) {
3786 cp_cache = pv_node->constants()->cache();
3787 if (cp_cache != nullptr) {
3788 cp_cache->adjust_method_entries(&trace_name_printed);
3789 }
3790 }
3791 }
3792 }
3793
3794 void VM_RedefineClasses::update_jmethod_ids() {
3795 for (int j = 0; j < _matching_methods_length; ++j) {
3796 Method* old_method = _matching_old_methods[j];
3797 // The method_idnum should be within the range of 1..number-of-methods
3798 // until incremented later for obsolete methods.
3799 // The increment is so if a jmethodID is created for an old obsolete method
3800 // it gets a new jmethodID cache slot in the InstanceKlass.
3801 // They're cleaned out later when all methods of the previous version are purged.
3802 assert(old_method->method_idnum() <= _old_methods->length(),
3803 "shouldn't be incremented yet for obsolete methods");
3804 jmethodID jmid = old_method->find_jmethod_id_or_null();
3805 if (jmid != nullptr) {
3806 // There is a jmethodID, change it to point to the new method
3807 Method* new_method = _matching_new_methods[j];
3808 Method::change_method_associated_with_jmethod_id(jmid, new_method);
3809 assert(Method::resolve_jmethod_id(jmid) == _matching_new_methods[j],
3810 "should be replaced");
3811 }
3812 }
3813 }
3814
3815 int VM_RedefineClasses::check_methods_and_mark_as_obsolete() {
3816 int emcp_method_count = 0;
3817 int obsolete_count = 0;
3818 int old_index = 0;
3819 for (int j = 0; j < _matching_methods_length; ++j, ++old_index) {
3820 Method* old_method = _matching_old_methods[j];
3821 Method* new_method = _matching_new_methods[j];
3822 Method* old_array_method;
3823
3824 // Maintain an old_index into the _old_methods array by skipping
3825 // deleted methods
3826 while ((old_array_method = _old_methods->at(old_index)) != old_method) {
3827 ++old_index;
3828 }
3829
3830 if (MethodComparator::methods_EMCP(old_method, new_method)) {
3831 // The EMCP definition from JSR-163 requires the bytecodes to be
3832 // the same with the exception of constant pool indices which may
3833 // differ. However, the constants referred to by those indices
3834 // must be the same.
3835 //
3836 // We use methods_EMCP() for comparison since constant pool
3837 // merging can remove duplicate constant pool entries that were
3838 // present in the old method and removed from the rewritten new
3839 // method. A faster binary comparison function would consider the
3840 // old and new methods to be different when they are actually
3841 // EMCP.
3842 //
3843 // The old and new methods are EMCP and you would think that we
3844 // could get rid of one of them here and now and save some space.
3845 // However, the concept of EMCP only considers the bytecodes and
3846 // the constant pool entries in the comparison. Other things,
3847 // e.g., the line number table (LNT) or the local variable table
3848 // (LVT) don't count in the comparison. So the new (and EMCP)
3849 // method can have a new LNT that we need so we can't just
3850 // overwrite the new method with the old method.
3851 //
3852 // When this routine is called, we have already attached the new
3853 // methods to the_class so the old methods are effectively
3854 // overwritten. However, if an old method is still executing,
3855 // then the old method cannot be collected until sometime after
3856 // the old method call has returned. So the overwriting of old
3857 // methods by new methods will save us space except for those
3858 // (hopefully few) old methods that are still executing.
3859 //
3860 // A method refers to a ConstMethod* and this presents another
3861 // possible avenue to space savings. The ConstMethod* in the
3862 // new method contains possibly new attributes (LNT, LVT, etc).
3863 // At first glance, it seems possible to save space by replacing
3864 // the ConstMethod* in the old method with the ConstMethod*
3865 // from the new method. The old and new methods would share the
3866 // same ConstMethod* and we would save the space occupied by
3867 // the old ConstMethod*. However, the ConstMethod* contains
3868 // a back reference to the containing method. Sharing the
3869 // ConstMethod* between two methods could lead to confusion in
3870 // the code that uses the back reference. This would lead to
3871 // brittle code that could be broken in non-obvious ways now or
3872 // in the future.
3873 //
3874 // Another possibility is to copy the ConstMethod* from the new
3875 // method to the old method and then overwrite the new method with
3876 // the old method. Since the ConstMethod* contains the bytecodes
3877 // for the method embedded in the oop, this option would change
3878 // the bytecodes out from under any threads executing the old
3879 // method and make the thread's bcp invalid. Since EMCP requires
3880 // that the bytecodes be the same modulo constant pool indices, it
3881 // is straight forward to compute the correct new bcp in the new
3882 // ConstMethod* from the old bcp in the old ConstMethod*. The
3883 // time consuming part would be searching all the frames in all
3884 // of the threads to find all of the calls to the old method.
3885 //
3886 // It looks like we will have to live with the limited savings
3887 // that we get from effectively overwriting the old methods
3888 // when the new methods are attached to the_class.
3889
3890 // Count number of methods that are EMCP. The method will be marked
3891 // old but not obsolete if it is EMCP.
3892 emcp_method_count++;
3893
3894 // An EMCP method is _not_ obsolete. An obsolete method has a
3895 // different jmethodID than the current method. An EMCP method
3896 // has the same jmethodID as the current method. Having the
3897 // same jmethodID for all EMCP versions of a method allows for
3898 // a consistent view of the EMCP methods regardless of which
3899 // EMCP method you happen to have in hand. For example, a
3900 // breakpoint set in one EMCP method will work for all EMCP
3901 // versions of the method including the current one.
3902 } else {
3903 // mark obsolete methods as such
3904 old_method->set_is_obsolete();
3905 obsolete_count++;
3906
3907 // obsolete methods need a unique idnum so they become new entries in
3908 // the jmethodID cache in InstanceKlass
3909 assert(old_method->method_idnum() == new_method->method_idnum(), "must match");
3910 u2 num = InstanceKlass::cast(_the_class)->next_method_idnum();
3911 if (num != ConstMethod::UNSET_IDNUM) {
3912 old_method->set_method_idnum(num);
3913 }
3914
3915 // With tracing we try not to "yack" too much. The position of
3916 // this trace assumes there are fewer obsolete methods than
3917 // EMCP methods.
3918 if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3919 ResourceMark rm;
3920 log_trace(redefine, class, obsolete, mark)
3921 ("mark %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3922 }
3923 }
3924 old_method->set_is_old();
3925 }
3926 for (int i = 0; i < _deleted_methods_length; ++i) {
3927 Method* old_method = _deleted_methods[i];
3928
3929 assert(!old_method->has_vtable_index(),
3930 "cannot delete methods with vtable entries");;
3931
3932 // Mark all deleted methods as old, obsolete and deleted
3933 old_method->set_is_deleted();
3934 old_method->set_is_old();
3935 old_method->set_is_obsolete();
3936 ++obsolete_count;
3937 // With tracing we try not to "yack" too much. The position of
3938 // this trace assumes there are fewer obsolete methods than
3939 // EMCP methods.
3940 if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3941 ResourceMark rm;
3942 log_trace(redefine, class, obsolete, mark)
3943 ("mark deleted %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3944 }
3945 }
3946 assert((emcp_method_count + obsolete_count) == _old_methods->length(),
3947 "sanity check");
3948 log_trace(redefine, class, obsolete, mark)("EMCP_cnt=%d, obsolete_cnt=%d", emcp_method_count, obsolete_count);
3949 return emcp_method_count;
3950 }
3951
3952 // This internal class transfers the native function registration from old methods
3953 // to new methods. It is designed to handle both the simple case of unchanged
3954 // native methods and the complex cases of native method prefixes being added and/or
3955 // removed.
3956 // It expects only to be used during the VM_RedefineClasses op (a safepoint).
3957 //
3958 // This class is used after the new methods have been installed in "the_class".
3959 //
3960 // So, for example, the following must be handled. Where 'm' is a method and
3961 // a number followed by an underscore is a prefix.
3962 //
3963 // Old Name New Name
3964 // Simple transfer to new method m -> m
3965 // Add prefix m -> 1_m
3966 // Remove prefix 1_m -> m
3967 // Simultaneous add of prefixes m -> 3_2_1_m
3968 // Simultaneous removal of prefixes 3_2_1_m -> m
3969 // Simultaneous add and remove 1_m -> 2_m
3970 // Same, caused by prefix removal only 3_2_1_m -> 3_2_m
3971 //
3972 class TransferNativeFunctionRegistration {
3973 private:
3974 InstanceKlass* the_class;
3975 int prefix_count;
3976 char** prefixes;
3977
3978 // Recursively search the binary tree of possibly prefixed method names.
3979 // Iteration could be used if all agents were well behaved. Full tree walk is
3980 // more resilent to agents not cleaning up intermediate methods.
3981 // Branch at each depth in the binary tree is:
3982 // (1) without the prefix.
3983 // (2) with the prefix.
3984 // where 'prefix' is the prefix at that 'depth' (first prefix, second prefix,...)
3985 Method* search_prefix_name_space(int depth, char* name_str, size_t name_len,
3986 Symbol* signature) {
3987 TempNewSymbol name_symbol = SymbolTable::probe(name_str, (int)name_len);
3988 if (name_symbol != nullptr) {
3989 Method* method = the_class->lookup_method(name_symbol, signature);
3990 if (method != nullptr) {
3991 // Even if prefixed, intermediate methods must exist.
3992 if (method->is_native()) {
3993 // Wahoo, we found a (possibly prefixed) version of the method, return it.
3994 return method;
3995 }
3996 if (depth < prefix_count) {
3997 // Try applying further prefixes (other than this one).
3998 method = search_prefix_name_space(depth+1, name_str, name_len, signature);
3999 if (method != nullptr) {
4000 return method; // found
4001 }
4002
4003 // Try adding this prefix to the method name and see if it matches
4004 // another method name.
4005 char* prefix = prefixes[depth];
4006 size_t prefix_len = strlen(prefix);
4007 size_t trial_len = name_len + prefix_len;
4008 char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
4009 strcpy(trial_name_str, prefix);
4010 strcat(trial_name_str, name_str);
4011 method = search_prefix_name_space(depth+1, trial_name_str, trial_len,
4012 signature);
4013 if (method != nullptr) {
4014 // If found along this branch, it was prefixed, mark as such
4015 method->set_is_prefixed_native();
4016 return method; // found
4017 }
4018 }
4019 }
4020 }
4021 return nullptr; // This whole branch bore nothing
4022 }
4023
4024 // Return the method name with old prefixes stripped away.
4025 char* method_name_without_prefixes(Method* method) {
4026 Symbol* name = method->name();
4027 char* name_str = name->as_utf8();
4028
4029 // Old prefixing may be defunct, strip prefixes, if any.
4030 for (int i = prefix_count-1; i >= 0; i--) {
4031 char* prefix = prefixes[i];
4032 size_t prefix_len = strlen(prefix);
4033 if (strncmp(prefix, name_str, prefix_len) == 0) {
4034 name_str += prefix_len;
4035 }
4036 }
4037 return name_str;
4038 }
4039
4040 // Strip any prefixes off the old native method, then try to find a
4041 // (possibly prefixed) new native that matches it.
4042 Method* strip_and_search_for_new_native(Method* method) {
4043 ResourceMark rm;
4044 char* name_str = method_name_without_prefixes(method);
4045 return search_prefix_name_space(0, name_str, strlen(name_str),
4046 method->signature());
4047 }
4048
4049 public:
4050
4051 // Construct a native method transfer processor for this class.
4052 TransferNativeFunctionRegistration(InstanceKlass* _the_class) {
4053 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
4054
4055 the_class = _the_class;
4056 prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
4057 }
4058
4059 // Attempt to transfer any of the old or deleted methods that are native
4060 void transfer_registrations(Method** old_methods, int methods_length) {
4061 for (int j = 0; j < methods_length; j++) {
4062 Method* old_method = old_methods[j];
4063
4064 if (old_method->is_native() && old_method->has_native_function()) {
4065 Method* new_method = strip_and_search_for_new_native(old_method);
4066 if (new_method != nullptr) {
4067 // Actually set the native function in the new method.
4068 // Redefine does not send events (except CFLH), certainly not this
4069 // behind the scenes re-registration.
4070 new_method->set_native_function(old_method->native_function(),
4071 !Method::native_bind_event_is_interesting);
4072 }
4073 }
4074 }
4075 }
4076 };
4077
4078 // Don't lose the association between a native method and its JNI function.
4079 void VM_RedefineClasses::transfer_old_native_function_registrations(InstanceKlass* the_class) {
4080 TransferNativeFunctionRegistration transfer(the_class);
4081 transfer.transfer_registrations(_deleted_methods, _deleted_methods_length);
4082 transfer.transfer_registrations(_matching_old_methods, _matching_methods_length);
4083 }
4084
4085 // Deoptimize all compiled code that depends on the classes redefined.
4086 //
4087 // If the can_redefine_classes capability is obtained in the onload
4088 // phase or 'AlwaysRecordEvolDependencies' is true, then the compiler has
4089 // recorded all dependencies from startup. In that case we need only
4090 // deoptimize and throw away all compiled code that depends on the class.
4091 //
4092 // If can_redefine_classes is obtained sometime after the onload phase
4093 // (and 'AlwaysRecordEvolDependencies' is false) then the dependency
4094 // information may be incomplete. In that case the first call to
4095 // RedefineClasses causes all compiled code to be thrown away. As
4096 // can_redefine_classes has been obtained then all future compilations will
4097 // record dependencies so second and subsequent calls to RedefineClasses
4098 // need only throw away code that depends on the class.
4099 //
4100
4101 void VM_RedefineClasses::flush_dependent_code() {
4102 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
4103 assert(JvmtiExport::all_dependencies_are_recorded() || !AlwaysRecordEvolDependencies, "sanity check");
4104
4105 DeoptimizationScope deopt_scope;
4106
4107 // This is the first redefinition, mark all the nmethods for deoptimization
4108 if (!JvmtiExport::all_dependencies_are_recorded()) {
4109 CodeCache::mark_all_nmethods_for_evol_deoptimization(&deopt_scope);
4110 log_debug(redefine, class, nmethod)("Marked all nmethods for deopt");
4111 } else {
4112 CodeCache::mark_dependents_for_evol_deoptimization(&deopt_scope);
4113 log_debug(redefine, class, nmethod)("Marked dependent nmethods for deopt");
4114 }
4115
4116 deopt_scope.deoptimize_marked();
4117
4118 // From now on we know that the dependency information is complete
4119 JvmtiExport::set_all_dependencies_are_recorded(true);
4120 }
4121
4122 void VM_RedefineClasses::compute_added_deleted_matching_methods() {
4123 Method* old_method;
4124 Method* new_method;
4125
4126 _matching_old_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
4127 _matching_new_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
4128 _added_methods = NEW_RESOURCE_ARRAY(Method*, _new_methods->length());
4129 _deleted_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
4130
4131 _matching_methods_length = 0;
4132 _deleted_methods_length = 0;
4133 _added_methods_length = 0;
4134
4135 int nj = 0;
4136 int oj = 0;
4137 while (true) {
4138 if (oj >= _old_methods->length()) {
4139 if (nj >= _new_methods->length()) {
4140 break; // we've looked at everything, done
4141 }
4142 // New method at the end
4143 new_method = _new_methods->at(nj);
4144 _added_methods[_added_methods_length++] = new_method;
4145 ++nj;
4146 } else if (nj >= _new_methods->length()) {
4147 // Old method, at the end, is deleted
4148 old_method = _old_methods->at(oj);
4149 _deleted_methods[_deleted_methods_length++] = old_method;
4150 ++oj;
4151 } else {
4152 old_method = _old_methods->at(oj);
4153 new_method = _new_methods->at(nj);
4154 if (old_method->name() == new_method->name()) {
4155 if (old_method->signature() == new_method->signature()) {
4156 _matching_old_methods[_matching_methods_length ] = old_method;
4157 _matching_new_methods[_matching_methods_length++] = new_method;
4158 ++nj;
4159 ++oj;
4160 } else {
4161 // added overloaded have already been moved to the end,
4162 // so this is a deleted overloaded method
4163 _deleted_methods[_deleted_methods_length++] = old_method;
4164 ++oj;
4165 }
4166 } else { // names don't match
4167 if (old_method->name()->fast_compare(new_method->name()) > 0) {
4168 // new method
4169 _added_methods[_added_methods_length++] = new_method;
4170 ++nj;
4171 } else {
4172 // deleted method
4173 _deleted_methods[_deleted_methods_length++] = old_method;
4174 ++oj;
4175 }
4176 }
4177 }
4178 }
4179 assert(_matching_methods_length + _deleted_methods_length == _old_methods->length(), "sanity");
4180 assert(_matching_methods_length + _added_methods_length == _new_methods->length(), "sanity");
4181 }
4182
4183
4184 void VM_RedefineClasses::swap_annotations(InstanceKlass* the_class,
4185 InstanceKlass* scratch_class) {
4186 // Swap annotation fields values
4187 Annotations* old_annotations = the_class->annotations();
4188 the_class->set_annotations(scratch_class->annotations());
4189 scratch_class->set_annotations(old_annotations);
4190 }
4191
4192
4193 // Install the redefinition of a class:
4194 // - house keeping (flushing breakpoints and caches, deoptimizing
4195 // dependent compiled code)
4196 // - replacing parts in the_class with parts from scratch_class
4197 // - adding a weak reference to track the obsolete but interesting
4198 // parts of the_class
4199 // - adjusting constant pool caches and vtables in other classes
4200 // that refer to methods in the_class. These adjustments use the
4201 // ClassLoaderDataGraph::classes_do() facility which only allows
4202 // a helper method to be specified. The interesting parameters
4203 // that we would like to pass to the helper method are saved in
4204 // static global fields in the VM operation.
4205 void VM_RedefineClasses::redefine_single_class(Thread* current, jclass the_jclass,
4206 InstanceKlass* scratch_class) {
4207
4208 HandleMark hm(current); // make sure handles from this call are freed
4209
4210 if (log_is_enabled(Info, redefine, class, timer)) {
4211 _timer_rsc_phase1.start();
4212 }
4213
4214 InstanceKlass* the_class = get_ik(the_jclass);
4215
4216 // Set a flag to control and optimize adjusting method entries
4217 _has_redefined_Object |= the_class == vmClasses::Object_klass();
4218
4219 // Remove all breakpoints in methods of this class
4220 JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
4221 jvmti_breakpoints.clearall_in_class_at_safepoint(the_class);
4222
4223 _old_methods = the_class->methods();
4224 _new_methods = scratch_class->methods();
4225 _the_class = the_class;
4226 compute_added_deleted_matching_methods();
4227 update_jmethod_ids();
4228
4229 _any_class_has_resolved_methods = the_class->has_resolved_methods() || _any_class_has_resolved_methods;
4230
4231 // Attach new constant pool to the original klass. The original
4232 // klass still refers to the old constant pool (for now).
4233 scratch_class->constants()->set_pool_holder(the_class);
4234
4235 #if 0
4236 // In theory, with constant pool merging in place we should be able
4237 // to save space by using the new, merged constant pool in place of
4238 // the old constant pool(s). By "pool(s)" I mean the constant pool in
4239 // the klass version we are replacing now and any constant pool(s) in
4240 // previous versions of klass. Nice theory, doesn't work in practice.
4241 // When this code is enabled, even simple programs throw NullPointer
4242 // exceptions. I'm guessing that this is caused by some constant pool
4243 // cache difference between the new, merged constant pool and the
4244 // constant pool that was just being used by the klass. I'm keeping
4245 // this code around to archive the idea, but the code has to remain
4246 // disabled for now.
4247
4248 // Attach each old method to the new constant pool. This can be
4249 // done here since we are past the bytecode verification and
4250 // constant pool optimization phases.
4251 for (int i = _old_methods->length() - 1; i >= 0; i--) {
4252 Method* method = _old_methods->at(i);
4253 method->set_constants(scratch_class->constants());
4254 }
4255
4256 // NOTE: this doesn't work because you can redefine the same class in two
4257 // threads, each getting their own constant pool data appended to the
4258 // original constant pool. In order for the new methods to work when they
4259 // become old methods, they need to keep their updated copy of the constant pool.
4260
4261 {
4262 // walk all previous versions of the klass
4263 InstanceKlass *ik = the_class;
4264 PreviousVersionWalker pvw(ik);
4265 do {
4266 ik = pvw.next_previous_version();
4267 if (ik != nullptr) {
4268
4269 // attach previous version of klass to the new constant pool
4270 ik->set_constants(scratch_class->constants());
4271
4272 // Attach each method in the previous version of klass to the
4273 // new constant pool
4274 Array<Method*>* prev_methods = ik->methods();
4275 for (int i = prev_methods->length() - 1; i >= 0; i--) {
4276 Method* method = prev_methods->at(i);
4277 method->set_constants(scratch_class->constants());
4278 }
4279 }
4280 } while (ik != nullptr);
4281 }
4282 #endif
4283
4284 // Replace methods and constantpool
4285 the_class->set_methods(_new_methods);
4286 scratch_class->set_methods(_old_methods); // To prevent potential GCing of the old methods,
4287 // and to be able to undo operation easily.
4288
4289 Array<int>* old_ordering = the_class->method_ordering();
4290 the_class->set_method_ordering(scratch_class->method_ordering());
4291 scratch_class->set_method_ordering(old_ordering);
4292
4293 ConstantPool* old_constants = the_class->constants();
4294 the_class->set_constants(scratch_class->constants());
4295 scratch_class->set_constants(old_constants); // See the previous comment.
4296 #if 0
4297 // We are swapping the guts of "the new class" with the guts of "the
4298 // class". Since the old constant pool has just been attached to "the
4299 // new class", it seems logical to set the pool holder in the old
4300 // constant pool also. However, doing this will change the observable
4301 // class hierarchy for any old methods that are still executing. A
4302 // method can query the identity of its "holder" and this query uses
4303 // the method's constant pool link to find the holder. The change in
4304 // holding class from "the class" to "the new class" can confuse
4305 // things.
4306 //
4307 // Setting the old constant pool's holder will also cause
4308 // verification done during vtable initialization below to fail.
4309 // During vtable initialization, the vtable's class is verified to be
4310 // a subtype of the method's holder. The vtable's class is "the
4311 // class" and the method's holder is gotten from the constant pool
4312 // link in the method itself. For "the class"'s directly implemented
4313 // methods, the method holder is "the class" itself (as gotten from
4314 // the new constant pool). The check works fine in this case. The
4315 // check also works fine for methods inherited from super classes.
4316 //
4317 // Miranda methods are a little more complicated. A miranda method is
4318 // provided by an interface when the class implementing the interface
4319 // does not provide its own method. These interfaces are implemented
4320 // internally as an InstanceKlass. These special instanceKlasses
4321 // share the constant pool of the class that "implements" the
4322 // interface. By sharing the constant pool, the method holder of a
4323 // miranda method is the class that "implements" the interface. In a
4324 // non-redefine situation, the subtype check works fine. However, if
4325 // the old constant pool's pool holder is modified, then the check
4326 // fails because there is no class hierarchy relationship between the
4327 // vtable's class and "the new class".
4328
4329 old_constants->set_pool_holder(scratch_class());
4330 #endif
4331
4332 // track number of methods that are EMCP for add_previous_version() call below
4333 int emcp_method_count = check_methods_and_mark_as_obsolete();
4334 transfer_old_native_function_registrations(the_class);
4335
4336 if (scratch_class->get_cached_class_file() != the_class->get_cached_class_file()) {
4337 // 1. the_class doesn't have a cache yet, scratch_class does have a cache.
4338 // 2. The same class can be present twice in the scratch classes list or there
4339 // are multiple concurrent RetransformClasses calls on different threads.
4340 // the_class and scratch_class have the same cached bytes, but different buffers.
4341 // In such cases we need to deallocate one of the buffers.
4342 // 3. RedefineClasses and the_class has cached bytes from a previous transformation.
4343 // In the case we need to use class bytes from scratch_class.
4344 if (the_class->get_cached_class_file() != nullptr) {
4345 os::free(the_class->get_cached_class_file());
4346 }
4347 the_class->set_cached_class_file(scratch_class->get_cached_class_file());
4348 }
4349
4350 // null out in scratch class to not delete twice. The class to be redefined
4351 // always owns these bytes.
4352 scratch_class->set_cached_class_file(nullptr);
4353
4354 // Replace inner_classes
4355 Array<u2>* old_inner_classes = the_class->inner_classes();
4356 the_class->set_inner_classes(scratch_class->inner_classes());
4357 scratch_class->set_inner_classes(old_inner_classes);
4358
4359 // Initialize the vtable and interface table after
4360 // methods have been rewritten
4361 // no exception should happen here since we explicitly
4362 // do not check loader constraints.
4363 // compare_and_normalize_class_versions has already checked:
4364 // - classloaders unchanged, signatures unchanged
4365 // - all instanceKlasses for redefined classes reused & contents updated
4366 the_class->vtable().initialize_vtable();
4367 the_class->itable().initialize_itable();
4368
4369 // Update jmethodID cache if present.
4370 the_class->update_methods_jmethod_cache();
4371
4372 // Copy the "source debug extension" attribute from new class version
4373 the_class->set_source_debug_extension(
4374 scratch_class->source_debug_extension(),
4375 scratch_class->source_debug_extension() == nullptr ? 0 :
4376 (int)strlen(scratch_class->source_debug_extension()));
4377
4378 // Use of javac -g could be different in the old and the new
4379 if (scratch_class->has_localvariable_table() !=
4380 the_class->has_localvariable_table()) {
4381 the_class->set_has_localvariable_table(scratch_class->has_localvariable_table());
4382 }
4383
4384 swap_annotations(the_class, scratch_class);
4385
4386 // Replace minor version number of class file
4387 u2 old_minor_version = the_class->constants()->minor_version();
4388 the_class->constants()->set_minor_version(scratch_class->constants()->minor_version());
4389 scratch_class->constants()->set_minor_version(old_minor_version);
4390
4391 // Replace major version number of class file
4392 u2 old_major_version = the_class->constants()->major_version();
4393 the_class->constants()->set_major_version(scratch_class->constants()->major_version());
4394 scratch_class->constants()->set_major_version(old_major_version);
4395
4396 // Replace CP indexes for class and name+type of enclosing method
4397 u2 old_class_idx = the_class->enclosing_method_class_index();
4398 u2 old_method_idx = the_class->enclosing_method_method_index();
4399 the_class->set_enclosing_method_indices(
4400 scratch_class->enclosing_method_class_index(),
4401 scratch_class->enclosing_method_method_index());
4402 scratch_class->set_enclosing_method_indices(old_class_idx, old_method_idx);
4403
4404 if (!the_class->has_been_redefined()) {
4405 the_class->set_has_been_redefined();
4406 }
4407
4408 // Scratch class is unloaded but still needs cleaning, and skipping for CDS.
4409 scratch_class->set_is_scratch_class();
4410
4411 // keep track of previous versions of this class
4412 the_class->add_previous_version(scratch_class, emcp_method_count);
4413
4414 JFR_ONLY(Jfr::on_klass_redefinition(the_class, scratch_class);)
4415
4416 _timer_rsc_phase1.stop();
4417 if (log_is_enabled(Info, redefine, class, timer)) {
4418 _timer_rsc_phase2.start();
4419 }
4420
4421 if (the_class->oop_map_cache() != nullptr) {
4422 // Flush references to any obsolete methods from the oop map cache
4423 // so that obsolete methods are not pinned.
4424 the_class->oop_map_cache()->flush_obsolete_entries();
4425 }
4426
4427 increment_class_counter(the_class);
4428
4429 if (EventClassRedefinition::is_enabled()) {
4430 EventClassRedefinition event;
4431 event.set_classModificationCount(java_lang_Class::classRedefinedCount(the_class->java_mirror()));
4432 event.set_redefinedClass(the_class);
4433 event.set_redefinitionId(_id);
4434 event.commit();
4435 }
4436
4437 {
4438 ResourceMark rm(current);
4439 // increment the classRedefinedCount field in the_class and in any
4440 // direct and indirect subclasses of the_class
4441 physical_memory_size_type avail_mem = 0;
4442 // Return value ignored - defaulting to 0 on failure.
4443 (void)os::available_memory(avail_mem);
4444 log_info(redefine, class, load)
4445 ("redefined name=%s, count=%d (avail_mem=" PHYS_MEM_TYPE_FORMAT "K)",
4446 the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror()), avail_mem >> 10);
4447 Events::log_redefinition(current, "redefined class name=%s, count=%d",
4448 the_class->external_name(),
4449 java_lang_Class::classRedefinedCount(the_class->java_mirror()));
4450
4451 }
4452 _timer_rsc_phase2.stop();
4453
4454 } // end redefine_single_class()
4455
4456
4457 // Increment the classRedefinedCount field in the specific InstanceKlass
4458 // and in all direct and indirect subclasses.
4459 void VM_RedefineClasses::increment_class_counter(InstanceKlass* ik) {
4460 for (ClassHierarchyIterator iter(ik); !iter.done(); iter.next()) {
4461 // Only update instanceKlasses
4462 Klass* sub = iter.klass();
4463 if (sub->is_instance_klass()) {
4464 oop class_mirror = InstanceKlass::cast(sub)->java_mirror();
4465 Klass* class_oop = java_lang_Class::as_Klass(class_mirror);
4466 int new_count = java_lang_Class::classRedefinedCount(class_mirror) + 1;
4467 java_lang_Class::set_classRedefinedCount(class_mirror, new_count);
4468
4469 if (class_oop != _the_class) {
4470 // _the_class count is printed at end of redefine_single_class()
4471 log_debug(redefine, class, subclass)("updated count in subclass=%s to %d", ik->external_name(), new_count);
4472 }
4473 }
4474 }
4475 }
4476
4477 void VM_RedefineClasses::CheckClass::do_klass(Klass* k) {
4478 bool no_old_methods = true; // be optimistic
4479
4480 // Both array and instance classes have vtables.
4481 // a vtable should never contain old or obsolete methods
4482 ResourceMark rm(_thread);
4483 if (k->vtable_length() > 0 &&
4484 !k->vtable().check_no_old_or_obsolete_entries()) {
4485 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4486 log_trace(redefine, class, obsolete, metadata)
4487 ("klassVtable::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4488 k->signature_name());
4489 k->vtable().dump_vtable();
4490 }
4491 no_old_methods = false;
4492 }
4493
4494 if (k->is_instance_klass()) {
4495 HandleMark hm(_thread);
4496 InstanceKlass *ik = InstanceKlass::cast(k);
4497
4498 // an itable should never contain old or obsolete methods
4499 if (ik->itable_length() > 0 &&
4500 !ik->itable().check_no_old_or_obsolete_entries()) {
4501 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4502 log_trace(redefine, class, obsolete, metadata)
4503 ("klassItable::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4504 ik->signature_name());
4505 ik->itable().dump_itable();
4506 }
4507 no_old_methods = false;
4508 }
4509
4510 // the constant pool cache should never contain non-deleted old or obsolete methods
4511 if (ik->constants() != nullptr &&
4512 ik->constants()->cache() != nullptr &&
4513 !ik->constants()->cache()->check_no_old_or_obsolete_entries()) {
4514 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4515 log_trace(redefine, class, obsolete, metadata)
4516 ("cp-cache::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4517 ik->signature_name());
4518 ik->constants()->cache()->dump_cache();
4519 }
4520 no_old_methods = false;
4521 }
4522 }
4523
4524 // print and fail guarantee if old methods are found.
4525 if (!no_old_methods) {
4526 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4527 dump_methods();
4528 } else {
4529 log_trace(redefine, class)("Use the '-Xlog:redefine+class*:' option "
4530 "to see more info about the following guarantee() failure.");
4531 }
4532 guarantee(false, "OLD and/or OBSOLETE method(s) found");
4533 }
4534 }
4535
4536 u8 VM_RedefineClasses::next_id() {
4537 while (true) {
4538 u8 id = _id_counter;
4539 u8 next_id = id + 1;
4540 u8 result = AtomicAccess::cmpxchg(&_id_counter, id, next_id);
4541 if (result == id) {
4542 return next_id;
4543 }
4544 }
4545 }
4546
4547 void VM_RedefineClasses::dump_methods() {
4548 int j;
4549 log_trace(redefine, class, dump)("_old_methods --");
4550 for (j = 0; j < _old_methods->length(); ++j) {
4551 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4552 Method* m = _old_methods->at(j);
4553 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4554 m->access_flags().print_on(&log_stream);
4555 log_stream.print(" -- ");
4556 m->print_name(&log_stream);
4557 log_stream.cr();
4558 }
4559 log_trace(redefine, class, dump)("_new_methods --");
4560 for (j = 0; j < _new_methods->length(); ++j) {
4561 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4562 Method* m = _new_methods->at(j);
4563 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4564 m->access_flags().print_on(&log_stream);
4565 log_stream.print(" -- ");
4566 m->print_name(&log_stream);
4567 log_stream.cr();
4568 }
4569 log_trace(redefine, class, dump)("_matching_methods --");
4570 for (j = 0; j < _matching_methods_length; ++j) {
4571 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4572 Method* m = _matching_old_methods[j];
4573 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4574 m->access_flags().print_on(&log_stream);
4575 log_stream.print(" -- ");
4576 m->print_name();
4577 log_stream.cr();
4578
4579 m = _matching_new_methods[j];
4580 log_stream.print(" (%5d) ", m->vtable_index());
4581 m->access_flags().print_on(&log_stream);
4582 log_stream.cr();
4583 }
4584 log_trace(redefine, class, dump)("_deleted_methods --");
4585 for (j = 0; j < _deleted_methods_length; ++j) {
4586 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4587 Method* m = _deleted_methods[j];
4588 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4589 m->access_flags().print_on(&log_stream);
4590 log_stream.print(" -- ");
4591 m->print_name(&log_stream);
4592 log_stream.cr();
4593 }
4594 log_trace(redefine, class, dump)("_added_methods --");
4595 for (j = 0; j < _added_methods_length; ++j) {
4596 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4597 Method* m = _added_methods[j];
4598 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4599 m->access_flags().print_on(&log_stream);
4600 log_stream.print(" -- ");
4601 m->print_name(&log_stream);
4602 log_stream.cr();
4603 }
4604 }
4605
4606 void VM_RedefineClasses::print_on_error(outputStream* st) const {
4607 VM_Operation::print_on_error(st);
4608 if (_the_class != nullptr) {
4609 ResourceMark rm;
4610 st->print_cr(", redefining class %s", _the_class->external_name());
4611 }
4612 }