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