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
60 Array<Method*>* VM_RedefineClasses::_old_methods = NULL;
61 Array<Method*>* VM_RedefineClasses::_new_methods = NULL;
62 Method** VM_RedefineClasses::_matching_old_methods = NULL;
63 Method** VM_RedefineClasses::_matching_new_methods = NULL;
64 Method** VM_RedefineClasses::_deleted_methods = NULL;
65 Method** VM_RedefineClasses::_added_methods = NULL;
66 int VM_RedefineClasses::_matching_methods_length = 0;
67 int VM_RedefineClasses::_deleted_methods_length = 0;
68 int VM_RedefineClasses::_added_methods_length = 0;
69 bool VM_RedefineClasses::_has_redefined_Object = false;
70 bool VM_RedefineClasses::_has_null_class_loader = false;
71
72
VM_RedefineClasses(jint class_count,const jvmtiClassDefinition * class_defs,JvmtiClassLoadKind class_load_kind)73 VM_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
get_ik(jclass def)86 static 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.
lock_classes()93 void 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
unlock_classes()113 void 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
doit_prologue()123 bool 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
doit()192 void 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
doit_epilogue()258 void 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
is_modifiable_class(oop klass_mirror)283 bool 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.
append_entry(const constantPoolHandle & scratch_cp,int scratch_i,constantPoolHandle * merge_cp_p,int * merge_cp_length_p,TRAPS)312 void 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
find_or_append_indirect_entry(const constantPoolHandle & scratch_cp,int ref_i,constantPoolHandle * merge_cp_p,int * merge_cp_length_p,TRAPS)577 int 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.
append_operand(const constantPoolHandle & scratch_cp,int old_bs_i,constantPoolHandle * merge_cp_p,int * merge_cp_length_p,TRAPS)609 void 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
find_or_append_operand(const constantPoolHandle & scratch_cp,int old_bs_i,constantPoolHandle * merge_cp_p,int * merge_cp_length_p,TRAPS)652 int 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
finalize_operands_merge(const constantPoolHandle & merge_cp,TRAPS)678 void 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.
symcmp(const void * a,const void * b)704 static 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
check_nest_attributes(InstanceKlass * the_class,InstanceKlass * scratch_class)710 static 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
can_add_or_delete(Method * m)791 static 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
compare_and_normalize_class_versions(InstanceKlass * the_class,InstanceKlass * scratch_class)797 jvmtiError 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.
find_new_index(int old_index)1050 int 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.
find_new_operand_index(int old_index)1076 int 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.
is_unresolved_class_mismatch(const constantPoolHandle & cp1,int index1,const constantPoolHandle & cp2,int index2)1100 bool 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
load_new_class_versions(TRAPS)1127 jvmtiError 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 oop message = java_lang_Throwable::message(PENDING_EXCEPTION);
1214 if (message != NULL) {
1215 char* ex_msg = java_lang_String::as_utf8_string(message);
1216 log_info(redefine, class, load, exceptions)("link_class exception: '%s %s'",
1217 ex_name->as_C_string(), ex_msg);
1218 } else {
1219 log_info(redefine, class, load, exceptions)("link_class exception: '%s'",
1220 ex_name->as_C_string());
1221 }
1222 CLEAR_PENDING_EXCEPTION;
1223 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1224 return JVMTI_ERROR_OUT_OF_MEMORY;
1225 } else if (ex_name == vmSymbols::java_lang_NoClassDefFoundError()) {
1226 return JVMTI_ERROR_INVALID_CLASS;
1227 } else {
1228 return JVMTI_ERROR_INTERNAL;
1229 }
1230 }
1231 }
1232
1233 // Do the validity checks in compare_and_normalize_class_versions()
1234 // before verifying the byte codes. By doing these checks first, we
1235 // limit the number of functions that require redirection from
1236 // the_class to scratch_class. In particular, we don't have to
1237 // modify JNI GetSuperclass() and thus won't change its performance.
1238 jvmtiError res = compare_and_normalize_class_versions(the_class,
1239 scratch_class);
1240 if (res != JVMTI_ERROR_NONE) {
1241 return res;
1242 }
1243
1244 // verify what the caller passed us
1245 {
1246 // The bug 6214132 caused the verification to fail.
1247 // Information about the_class and scratch_class is temporarily
1248 // recorded into jvmtiThreadState. This data is used to redirect
1249 // the_class to scratch_class in the JVM_* functions called by the
1250 // verifier. Please, refer to jvmtiThreadState.hpp for the detailed
1251 // description.
1252 RedefineVerifyMark rvm(the_class, scratch_class, state);
1253 Verifier::verify(scratch_class, true, THREAD);
1254 }
1255
1256 if (HAS_PENDING_EXCEPTION) {
1257 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1258 log_info(redefine, class, load, exceptions)("verify_byte_codes exception: '%s'", ex_name->as_C_string());
1259 CLEAR_PENDING_EXCEPTION;
1260 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1261 return JVMTI_ERROR_OUT_OF_MEMORY;
1262 } else {
1263 // tell the caller the bytecodes are bad
1264 return JVMTI_ERROR_FAILS_VERIFICATION;
1265 }
1266 }
1267
1268 res = merge_cp_and_rewrite(the_class, scratch_class, THREAD);
1269 if (HAS_PENDING_EXCEPTION) {
1270 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1271 log_info(redefine, class, load, exceptions)("merge_cp_and_rewrite exception: '%s'", ex_name->as_C_string());
1272 CLEAR_PENDING_EXCEPTION;
1273 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1274 return JVMTI_ERROR_OUT_OF_MEMORY;
1275 } else {
1276 return JVMTI_ERROR_INTERNAL;
1277 }
1278 }
1279
1280 if (VerifyMergedCPBytecodes) {
1281 // verify what we have done during constant pool merging
1282 {
1283 RedefineVerifyMark rvm(the_class, scratch_class, state);
1284 Verifier::verify(scratch_class, true, THREAD);
1285 }
1286
1287 if (HAS_PENDING_EXCEPTION) {
1288 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1289 log_info(redefine, class, load, exceptions)
1290 ("verify_byte_codes post merge-CP exception: '%s'", ex_name->as_C_string());
1291 CLEAR_PENDING_EXCEPTION;
1292 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1293 return JVMTI_ERROR_OUT_OF_MEMORY;
1294 } else {
1295 // tell the caller that constant pool merging screwed up
1296 return JVMTI_ERROR_INTERNAL;
1297 }
1298 }
1299 }
1300
1301 Rewriter::rewrite(scratch_class, THREAD);
1302 if (!HAS_PENDING_EXCEPTION) {
1303 scratch_class->link_methods(THREAD);
1304 }
1305 if (HAS_PENDING_EXCEPTION) {
1306 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1307 log_info(redefine, class, load, exceptions)
1308 ("Rewriter::rewrite or link_methods exception: '%s'", ex_name->as_C_string());
1309 CLEAR_PENDING_EXCEPTION;
1310 if (ex_name == vmSymbols::java_lang_OutOfMemoryError()) {
1311 return JVMTI_ERROR_OUT_OF_MEMORY;
1312 } else {
1313 return JVMTI_ERROR_INTERNAL;
1314 }
1315 }
1316
1317 log_debug(redefine, class, load)
1318 ("loaded name=%s (avail_mem=" UINT64_FORMAT "K)", the_class->external_name(), os::available_memory() >> 10);
1319 }
1320
1321 return JVMTI_ERROR_NONE;
1322 }
1323
1324
1325 // Map old_index to new_index as needed. scratch_cp is only needed
1326 // for log calls.
map_index(const constantPoolHandle & scratch_cp,int old_index,int new_index)1327 void VM_RedefineClasses::map_index(const constantPoolHandle& scratch_cp,
1328 int old_index, int new_index) {
1329 if (find_new_index(old_index) != 0) {
1330 // old_index is already mapped
1331 return;
1332 }
1333
1334 if (old_index == new_index) {
1335 // no mapping is needed
1336 return;
1337 }
1338
1339 _index_map_p->at_put(old_index, new_index);
1340 _index_map_count++;
1341
1342 log_trace(redefine, class, constantpool)
1343 ("mapped tag %d at index %d to %d", scratch_cp->tag_at(old_index).value(), old_index, new_index);
1344 } // end map_index()
1345
1346
1347 // Map old_index to new_index as needed.
map_operand_index(int old_index,int new_index)1348 void VM_RedefineClasses::map_operand_index(int old_index, int new_index) {
1349 if (find_new_operand_index(old_index) != -1) {
1350 // old_index is already mapped
1351 return;
1352 }
1353
1354 if (old_index == new_index) {
1355 // no mapping is needed
1356 return;
1357 }
1358
1359 _operands_index_map_p->at_put(old_index, new_index);
1360 _operands_index_map_count++;
1361
1362 log_trace(redefine, class, constantpool)("mapped bootstrap specifier at index %d to %d", old_index, new_index);
1363 } // end map_index()
1364
1365
1366 // Merge old_cp and scratch_cp and return the results of the merge via
1367 // merge_cp_p. The number of entries in *merge_cp_p is returned via
1368 // merge_cp_length_p. The entries in old_cp occupy the same locations
1369 // in *merge_cp_p. Also creates a map of indices from entries in
1370 // scratch_cp to the corresponding entry in *merge_cp_p. Index map
1371 // entries are only created for entries in scratch_cp that occupy a
1372 // different location in *merged_cp_p.
merge_constant_pools(const constantPoolHandle & old_cp,const constantPoolHandle & scratch_cp,constantPoolHandle * merge_cp_p,int * merge_cp_length_p,TRAPS)1373 bool VM_RedefineClasses::merge_constant_pools(const constantPoolHandle& old_cp,
1374 const constantPoolHandle& scratch_cp, constantPoolHandle *merge_cp_p,
1375 int *merge_cp_length_p, TRAPS) {
1376
1377 if (merge_cp_p == NULL) {
1378 assert(false, "caller must provide scratch constantPool");
1379 return false; // robustness
1380 }
1381 if (merge_cp_length_p == NULL) {
1382 assert(false, "caller must provide scratch CP length");
1383 return false; // robustness
1384 }
1385 // Worst case we need old_cp->length() + scratch_cp()->length(),
1386 // but the caller might be smart so make sure we have at least
1387 // the minimum.
1388 if ((*merge_cp_p)->length() < old_cp->length()) {
1389 assert(false, "merge area too small");
1390 return false; // robustness
1391 }
1392
1393 log_info(redefine, class, constantpool)("old_cp_len=%d, scratch_cp_len=%d", old_cp->length(), scratch_cp->length());
1394
1395 {
1396 // Pass 0:
1397 // The old_cp is copied to *merge_cp_p; this means that any code
1398 // using old_cp does not have to change. This work looks like a
1399 // perfect fit for ConstantPool*::copy_cp_to(), but we need to
1400 // handle one special case:
1401 // - revert JVM_CONSTANT_Class to JVM_CONSTANT_UnresolvedClass
1402 // This will make verification happy.
1403
1404 int old_i; // index into old_cp
1405
1406 // index zero (0) is not used in constantPools
1407 for (old_i = 1; old_i < old_cp->length(); old_i++) {
1408 // leave debugging crumb
1409 jbyte old_tag = old_cp->tag_at(old_i).value();
1410 switch (old_tag) {
1411 case JVM_CONSTANT_Class:
1412 case JVM_CONSTANT_UnresolvedClass:
1413 // revert the copy to JVM_CONSTANT_UnresolvedClass
1414 // May be resolving while calling this so do the same for
1415 // JVM_CONSTANT_UnresolvedClass (klass_name_at() deals with transition)
1416 (*merge_cp_p)->temp_unresolved_klass_at_put(old_i,
1417 old_cp->klass_name_index_at(old_i));
1418 break;
1419
1420 case JVM_CONSTANT_Double:
1421 case JVM_CONSTANT_Long:
1422 // just copy the entry to *merge_cp_p, but double and long take
1423 // two constant pool entries
1424 ConstantPool::copy_entry_to(old_cp, old_i, *merge_cp_p, old_i, CHECK_0);
1425 old_i++;
1426 break;
1427
1428 default:
1429 // just copy the entry to *merge_cp_p
1430 ConstantPool::copy_entry_to(old_cp, old_i, *merge_cp_p, old_i, CHECK_0);
1431 break;
1432 }
1433 } // end for each old_cp entry
1434
1435 ConstantPool::copy_operands(old_cp, *merge_cp_p, CHECK_0);
1436 (*merge_cp_p)->extend_operands(scratch_cp, CHECK_0);
1437
1438 // We don't need to sanity check that *merge_cp_length_p is within
1439 // *merge_cp_p bounds since we have the minimum on-entry check above.
1440 (*merge_cp_length_p) = old_i;
1441 }
1442
1443 // merge_cp_len should be the same as old_cp->length() at this point
1444 // so this trace message is really a "warm-and-breathing" message.
1445 log_debug(redefine, class, constantpool)("after pass 0: merge_cp_len=%d", *merge_cp_length_p);
1446
1447 int scratch_i; // index into scratch_cp
1448 {
1449 // Pass 1a:
1450 // Compare scratch_cp entries to the old_cp entries that we have
1451 // already copied to *merge_cp_p. In this pass, we are eliminating
1452 // exact duplicates (matching entry at same index) so we only
1453 // compare entries in the common indice range.
1454 int increment = 1;
1455 int pass1a_length = MIN2(old_cp->length(), scratch_cp->length());
1456 for (scratch_i = 1; scratch_i < pass1a_length; scratch_i += increment) {
1457 switch (scratch_cp->tag_at(scratch_i).value()) {
1458 case JVM_CONSTANT_Double:
1459 case JVM_CONSTANT_Long:
1460 // double and long take two constant pool entries
1461 increment = 2;
1462 break;
1463
1464 default:
1465 increment = 1;
1466 break;
1467 }
1468
1469 bool match = scratch_cp->compare_entry_to(scratch_i, *merge_cp_p,
1470 scratch_i, CHECK_0);
1471 if (match) {
1472 // found a match at the same index so nothing more to do
1473 continue;
1474 } else if (is_unresolved_class_mismatch(scratch_cp, scratch_i,
1475 *merge_cp_p, scratch_i)) {
1476 // The mismatch in compare_entry_to() above is because of a
1477 // resolved versus unresolved class entry at the same index
1478 // with the same string value. Since Pass 0 reverted any
1479 // class entries to unresolved class entries in *merge_cp_p,
1480 // we go with the unresolved class entry.
1481 continue;
1482 }
1483
1484 int found_i = scratch_cp->find_matching_entry(scratch_i, *merge_cp_p,
1485 CHECK_0);
1486 if (found_i != 0) {
1487 guarantee(found_i != scratch_i,
1488 "compare_entry_to() and find_matching_entry() do not agree");
1489
1490 // Found a matching entry somewhere else in *merge_cp_p so
1491 // just need a mapping entry.
1492 map_index(scratch_cp, scratch_i, found_i);
1493 continue;
1494 }
1495
1496 // The find_matching_entry() call above could fail to find a match
1497 // due to a resolved versus unresolved class or string entry situation
1498 // like we solved above with the is_unresolved_*_mismatch() calls.
1499 // However, we would have to call is_unresolved_*_mismatch() over
1500 // all of *merge_cp_p (potentially) and that doesn't seem to be
1501 // worth the time.
1502
1503 // No match found so we have to append this entry and any unique
1504 // referenced entries to *merge_cp_p.
1505 append_entry(scratch_cp, scratch_i, merge_cp_p, merge_cp_length_p,
1506 CHECK_0);
1507 }
1508 }
1509
1510 log_debug(redefine, class, constantpool)
1511 ("after pass 1a: merge_cp_len=%d, scratch_i=%d, index_map_len=%d",
1512 *merge_cp_length_p, scratch_i, _index_map_count);
1513
1514 if (scratch_i < scratch_cp->length()) {
1515 // Pass 1b:
1516 // old_cp is smaller than scratch_cp so there are entries in
1517 // scratch_cp that we have not yet processed. We take care of
1518 // those now.
1519 int increment = 1;
1520 for (; scratch_i < scratch_cp->length(); scratch_i += increment) {
1521 switch (scratch_cp->tag_at(scratch_i).value()) {
1522 case JVM_CONSTANT_Double:
1523 case JVM_CONSTANT_Long:
1524 // double and long take two constant pool entries
1525 increment = 2;
1526 break;
1527
1528 default:
1529 increment = 1;
1530 break;
1531 }
1532
1533 int found_i =
1534 scratch_cp->find_matching_entry(scratch_i, *merge_cp_p, CHECK_0);
1535 if (found_i != 0) {
1536 // Found a matching entry somewhere else in *merge_cp_p so
1537 // just need a mapping entry.
1538 map_index(scratch_cp, scratch_i, found_i);
1539 continue;
1540 }
1541
1542 // No match found so we have to append this entry and any unique
1543 // referenced entries to *merge_cp_p.
1544 append_entry(scratch_cp, scratch_i, merge_cp_p, merge_cp_length_p,
1545 CHECK_0);
1546 }
1547
1548 log_debug(redefine, class, constantpool)
1549 ("after pass 1b: merge_cp_len=%d, scratch_i=%d, index_map_len=%d",
1550 *merge_cp_length_p, scratch_i, _index_map_count);
1551 }
1552 finalize_operands_merge(*merge_cp_p, THREAD);
1553
1554 return true;
1555 } // end merge_constant_pools()
1556
1557
1558 // Scoped object to clean up the constant pool(s) created for merging
1559 class MergeCPCleaner {
1560 ClassLoaderData* _loader_data;
1561 ConstantPool* _cp;
1562 ConstantPool* _scratch_cp;
1563 public:
MergeCPCleaner(ClassLoaderData * loader_data,ConstantPool * merge_cp)1564 MergeCPCleaner(ClassLoaderData* loader_data, ConstantPool* merge_cp) :
1565 _loader_data(loader_data), _cp(merge_cp), _scratch_cp(NULL) {}
~MergeCPCleaner()1566 ~MergeCPCleaner() {
1567 _loader_data->add_to_deallocate_list(_cp);
1568 if (_scratch_cp != NULL) {
1569 _loader_data->add_to_deallocate_list(_scratch_cp);
1570 }
1571 }
add_scratch_cp(ConstantPool * scratch_cp)1572 void add_scratch_cp(ConstantPool* scratch_cp) { _scratch_cp = scratch_cp; }
1573 };
1574
1575 // Merge constant pools between the_class and scratch_class and
1576 // potentially rewrite bytecodes in scratch_class to use the merged
1577 // constant pool.
merge_cp_and_rewrite(InstanceKlass * the_class,InstanceKlass * scratch_class,TRAPS)1578 jvmtiError VM_RedefineClasses::merge_cp_and_rewrite(
1579 InstanceKlass* the_class, InstanceKlass* scratch_class,
1580 TRAPS) {
1581 // worst case merged constant pool length is old and new combined
1582 int merge_cp_length = the_class->constants()->length()
1583 + scratch_class->constants()->length();
1584
1585 // Constant pools are not easily reused so we allocate a new one
1586 // each time.
1587 // merge_cp is created unsafe for concurrent GC processing. It
1588 // should be marked safe before discarding it. Even though
1589 // garbage, if it crosses a card boundary, it may be scanned
1590 // in order to find the start of the first complete object on the card.
1591 ClassLoaderData* loader_data = the_class->class_loader_data();
1592 ConstantPool* merge_cp_oop =
1593 ConstantPool::allocate(loader_data,
1594 merge_cp_length,
1595 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1596 MergeCPCleaner cp_cleaner(loader_data, merge_cp_oop);
1597
1598 HandleMark hm(THREAD); // make sure handles are cleared before
1599 // MergeCPCleaner clears out merge_cp_oop
1600 constantPoolHandle merge_cp(THREAD, merge_cp_oop);
1601
1602 // Get constants() from the old class because it could have been rewritten
1603 // while we were at a safepoint allocating a new constant pool.
1604 constantPoolHandle old_cp(THREAD, the_class->constants());
1605 constantPoolHandle scratch_cp(THREAD, scratch_class->constants());
1606
1607 // If the length changed, the class was redefined out from under us. Return
1608 // an error.
1609 if (merge_cp_length != the_class->constants()->length()
1610 + scratch_class->constants()->length()) {
1611 return JVMTI_ERROR_INTERNAL;
1612 }
1613
1614 // Update the version number of the constant pools (may keep scratch_cp)
1615 merge_cp->increment_and_save_version(old_cp->version());
1616 scratch_cp->increment_and_save_version(old_cp->version());
1617
1618 ResourceMark rm(THREAD);
1619 _index_map_count = 0;
1620 _index_map_p = new intArray(scratch_cp->length(), scratch_cp->length(), -1);
1621
1622 _operands_cur_length = ConstantPool::operand_array_length(old_cp->operands());
1623 _operands_index_map_count = 0;
1624 int operands_index_map_len = ConstantPool::operand_array_length(scratch_cp->operands());
1625 _operands_index_map_p = new intArray(operands_index_map_len, operands_index_map_len, -1);
1626
1627 // reference to the cp holder is needed for copy_operands()
1628 merge_cp->set_pool_holder(scratch_class);
1629 bool result = merge_constant_pools(old_cp, scratch_cp, &merge_cp,
1630 &merge_cp_length, THREAD);
1631 merge_cp->set_pool_holder(NULL);
1632
1633 if (!result) {
1634 // The merge can fail due to memory allocation failure or due
1635 // to robustness checks.
1636 return JVMTI_ERROR_INTERNAL;
1637 }
1638
1639 if (old_cp->has_dynamic_constant()) {
1640 merge_cp->set_has_dynamic_constant();
1641 scratch_cp->set_has_dynamic_constant();
1642 }
1643
1644 log_info(redefine, class, constantpool)("merge_cp_len=%d, index_map_len=%d", merge_cp_length, _index_map_count);
1645
1646 if (_index_map_count == 0) {
1647 // there is nothing to map between the new and merged constant pools
1648
1649 if (old_cp->length() == scratch_cp->length()) {
1650 // The old and new constant pools are the same length and the
1651 // index map is empty. This means that the three constant pools
1652 // are equivalent (but not the same). Unfortunately, the new
1653 // constant pool has not gone through link resolution nor have
1654 // the new class bytecodes gone through constant pool cache
1655 // rewriting so we can't use the old constant pool with the new
1656 // class.
1657
1658 // toss the merged constant pool at return
1659 } else if (old_cp->length() < scratch_cp->length()) {
1660 // The old constant pool has fewer entries than the new constant
1661 // pool and the index map is empty. This means the new constant
1662 // pool is a superset of the old constant pool. However, the old
1663 // class bytecodes have already gone through constant pool cache
1664 // rewriting so we can't use the new constant pool with the old
1665 // class.
1666
1667 // toss the merged constant pool at return
1668 } else {
1669 // The old constant pool has more entries than the new constant
1670 // pool and the index map is empty. This means that both the old
1671 // and merged constant pools are supersets of the new constant
1672 // pool.
1673
1674 // Replace the new constant pool with a shrunken copy of the
1675 // merged constant pool
1676 set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,
1677 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1678 // The new constant pool replaces scratch_cp so have cleaner clean it up.
1679 // It can't be cleaned up while there are handles to it.
1680 cp_cleaner.add_scratch_cp(scratch_cp());
1681 }
1682 } else {
1683 if (log_is_enabled(Trace, redefine, class, constantpool)) {
1684 // don't want to loop unless we are tracing
1685 int count = 0;
1686 for (int i = 1; i < _index_map_p->length(); i++) {
1687 int value = _index_map_p->at(i);
1688
1689 if (value != -1) {
1690 log_trace(redefine, class, constantpool)("index_map[%d]: old=%d new=%d", count, i, value);
1691 count++;
1692 }
1693 }
1694 }
1695
1696 // We have entries mapped between the new and merged constant pools
1697 // so we have to rewrite some constant pool references.
1698 if (!rewrite_cp_refs(scratch_class, THREAD)) {
1699 return JVMTI_ERROR_INTERNAL;
1700 }
1701
1702 // Replace the new constant pool with a shrunken copy of the
1703 // merged constant pool so now the rewritten bytecodes have
1704 // valid references; the previous new constant pool will get
1705 // GCed.
1706 set_new_constant_pool(loader_data, scratch_class, merge_cp, merge_cp_length,
1707 CHECK_(JVMTI_ERROR_OUT_OF_MEMORY));
1708 // The new constant pool replaces scratch_cp so have cleaner clean it up.
1709 // It can't be cleaned up while there are handles to it.
1710 cp_cleaner.add_scratch_cp(scratch_cp());
1711 }
1712
1713 return JVMTI_ERROR_NONE;
1714 } // end merge_cp_and_rewrite()
1715
1716
1717 // Rewrite constant pool references in klass scratch_class.
rewrite_cp_refs(InstanceKlass * scratch_class,TRAPS)1718 bool VM_RedefineClasses::rewrite_cp_refs(InstanceKlass* scratch_class,
1719 TRAPS) {
1720
1721 // rewrite constant pool references in the nest attributes:
1722 if (!rewrite_cp_refs_in_nest_attributes(scratch_class)) {
1723 // propagate failure back to caller
1724 return false;
1725 }
1726
1727 // rewrite constant pool references in the methods:
1728 if (!rewrite_cp_refs_in_methods(scratch_class, THREAD)) {
1729 // propagate failure back to caller
1730 return false;
1731 }
1732
1733 // rewrite constant pool references in the class_annotations:
1734 if (!rewrite_cp_refs_in_class_annotations(scratch_class, THREAD)) {
1735 // propagate failure back to caller
1736 return false;
1737 }
1738
1739 // rewrite constant pool references in the fields_annotations:
1740 if (!rewrite_cp_refs_in_fields_annotations(scratch_class, THREAD)) {
1741 // propagate failure back to caller
1742 return false;
1743 }
1744
1745 // rewrite constant pool references in the methods_annotations:
1746 if (!rewrite_cp_refs_in_methods_annotations(scratch_class, THREAD)) {
1747 // propagate failure back to caller
1748 return false;
1749 }
1750
1751 // rewrite constant pool references in the methods_parameter_annotations:
1752 if (!rewrite_cp_refs_in_methods_parameter_annotations(scratch_class,
1753 THREAD)) {
1754 // propagate failure back to caller
1755 return false;
1756 }
1757
1758 // rewrite constant pool references in the methods_default_annotations:
1759 if (!rewrite_cp_refs_in_methods_default_annotations(scratch_class,
1760 THREAD)) {
1761 // propagate failure back to caller
1762 return false;
1763 }
1764
1765 // rewrite constant pool references in the class_type_annotations:
1766 if (!rewrite_cp_refs_in_class_type_annotations(scratch_class, THREAD)) {
1767 // propagate failure back to caller
1768 return false;
1769 }
1770
1771 // rewrite constant pool references in the fields_type_annotations:
1772 if (!rewrite_cp_refs_in_fields_type_annotations(scratch_class, THREAD)) {
1773 // propagate failure back to caller
1774 return false;
1775 }
1776
1777 // rewrite constant pool references in the methods_type_annotations:
1778 if (!rewrite_cp_refs_in_methods_type_annotations(scratch_class, THREAD)) {
1779 // propagate failure back to caller
1780 return false;
1781 }
1782
1783 // There can be type annotations in the Code part of a method_info attribute.
1784 // These annotations are not accessible, even by reflection.
1785 // Currently they are not even parsed by the ClassFileParser.
1786 // If runtime access is added they will also need to be rewritten.
1787
1788 // rewrite source file name index:
1789 u2 source_file_name_idx = scratch_class->source_file_name_index();
1790 if (source_file_name_idx != 0) {
1791 u2 new_source_file_name_idx = find_new_index(source_file_name_idx);
1792 if (new_source_file_name_idx != 0) {
1793 scratch_class->set_source_file_name_index(new_source_file_name_idx);
1794 }
1795 }
1796
1797 // rewrite class generic signature index:
1798 u2 generic_signature_index = scratch_class->generic_signature_index();
1799 if (generic_signature_index != 0) {
1800 u2 new_generic_signature_index = find_new_index(generic_signature_index);
1801 if (new_generic_signature_index != 0) {
1802 scratch_class->set_generic_signature_index(new_generic_signature_index);
1803 }
1804 }
1805
1806 return true;
1807 } // end rewrite_cp_refs()
1808
1809 // Rewrite constant pool references in the NestHost and NestMembers attributes.
rewrite_cp_refs_in_nest_attributes(InstanceKlass * scratch_class)1810 bool VM_RedefineClasses::rewrite_cp_refs_in_nest_attributes(
1811 InstanceKlass* scratch_class) {
1812
1813 u2 cp_index = scratch_class->nest_host_index();
1814 if (cp_index != 0) {
1815 scratch_class->set_nest_host_index(find_new_index(cp_index));
1816 }
1817 Array<u2>* nest_members = scratch_class->nest_members();
1818 for (int i = 0; i < nest_members->length(); i++) {
1819 u2 cp_index = nest_members->at(i);
1820 nest_members->at_put(i, find_new_index(cp_index));
1821 }
1822 return true;
1823 }
1824
1825 // Rewrite constant pool references in the methods.
rewrite_cp_refs_in_methods(InstanceKlass * scratch_class,TRAPS)1826 bool VM_RedefineClasses::rewrite_cp_refs_in_methods(
1827 InstanceKlass* scratch_class, TRAPS) {
1828
1829 Array<Method*>* methods = scratch_class->methods();
1830
1831 if (methods == NULL || methods->length() == 0) {
1832 // no methods so nothing to do
1833 return true;
1834 }
1835
1836 // rewrite constant pool references in the methods:
1837 for (int i = methods->length() - 1; i >= 0; i--) {
1838 methodHandle method(THREAD, methods->at(i));
1839 methodHandle new_method;
1840 rewrite_cp_refs_in_method(method, &new_method, THREAD);
1841 if (!new_method.is_null()) {
1842 // the method has been replaced so save the new method version
1843 // even in the case of an exception. original method is on the
1844 // deallocation list.
1845 methods->at_put(i, new_method());
1846 }
1847 if (HAS_PENDING_EXCEPTION) {
1848 Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
1849 log_info(redefine, class, load, exceptions)("rewrite_cp_refs_in_method exception: '%s'", ex_name->as_C_string());
1850 // Need to clear pending exception here as the super caller sets
1851 // the JVMTI_ERROR_INTERNAL if the returned value is false.
1852 CLEAR_PENDING_EXCEPTION;
1853 return false;
1854 }
1855 }
1856
1857 return true;
1858 }
1859
1860
1861 // Rewrite constant pool references in the specific method. This code
1862 // was adapted from Rewriter::rewrite_method().
rewrite_cp_refs_in_method(methodHandle method,methodHandle * new_method_p,TRAPS)1863 void VM_RedefineClasses::rewrite_cp_refs_in_method(methodHandle method,
1864 methodHandle *new_method_p, TRAPS) {
1865
1866 *new_method_p = methodHandle(); // default is no new method
1867
1868 // We cache a pointer to the bytecodes here in code_base. If GC
1869 // moves the Method*, then the bytecodes will also move which
1870 // will likely cause a crash. We create a NoSafepointVerifier
1871 // object to detect whether we pass a possible safepoint in this
1872 // code block.
1873 NoSafepointVerifier nsv;
1874
1875 // Bytecodes and their length
1876 address code_base = method->code_base();
1877 int code_length = method->code_size();
1878
1879 int bc_length;
1880 for (int bci = 0; bci < code_length; bci += bc_length) {
1881 address bcp = code_base + bci;
1882 Bytecodes::Code c = (Bytecodes::Code)(*bcp);
1883
1884 bc_length = Bytecodes::length_for(c);
1885 if (bc_length == 0) {
1886 // More complicated bytecodes report a length of zero so
1887 // we have to try again a slightly different way.
1888 bc_length = Bytecodes::length_at(method(), bcp);
1889 }
1890
1891 assert(bc_length != 0, "impossible bytecode length");
1892
1893 switch (c) {
1894 case Bytecodes::_ldc:
1895 {
1896 int cp_index = *(bcp + 1);
1897 int new_index = find_new_index(cp_index);
1898
1899 if (StressLdcRewrite && new_index == 0) {
1900 // If we are stressing ldc -> ldc_w rewriting, then we
1901 // always need a new_index value.
1902 new_index = cp_index;
1903 }
1904 if (new_index != 0) {
1905 // the original index is mapped so we have more work to do
1906 if (!StressLdcRewrite && new_index <= max_jubyte) {
1907 // The new value can still use ldc instead of ldc_w
1908 // unless we are trying to stress ldc -> ldc_w rewriting
1909 log_trace(redefine, class, constantpool)
1910 ("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c), p2i(bcp), cp_index, new_index);
1911 *(bcp + 1) = new_index;
1912 } else {
1913 log_trace(redefine, class, constantpool)
1914 ("%s->ldc_w@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c), p2i(bcp), cp_index, new_index);
1915 // the new value needs ldc_w instead of ldc
1916 u_char inst_buffer[4]; // max instruction size is 4 bytes
1917 bcp = (address)inst_buffer;
1918 // construct new instruction sequence
1919 *bcp = Bytecodes::_ldc_w;
1920 bcp++;
1921 // Rewriter::rewrite_method() does not rewrite ldc -> ldc_w.
1922 // See comment below for difference between put_Java_u2()
1923 // and put_native_u2().
1924 Bytes::put_Java_u2(bcp, new_index);
1925
1926 Relocator rc(method, NULL /* no RelocatorListener needed */);
1927 methodHandle m;
1928 {
1929 PauseNoSafepointVerifier pnsv(&nsv);
1930
1931 // ldc is 2 bytes and ldc_w is 3 bytes
1932 m = rc.insert_space_at(bci, 3, inst_buffer, CHECK);
1933 }
1934
1935 // return the new method so that the caller can update
1936 // the containing class
1937 *new_method_p = method = m;
1938 // switch our bytecode processing loop from the old method
1939 // to the new method
1940 code_base = method->code_base();
1941 code_length = method->code_size();
1942 bcp = code_base + bci;
1943 c = (Bytecodes::Code)(*bcp);
1944 bc_length = Bytecodes::length_for(c);
1945 assert(bc_length != 0, "sanity check");
1946 } // end we need ldc_w instead of ldc
1947 } // end if there is a mapped index
1948 } break;
1949
1950 // these bytecodes have a two-byte constant pool index
1951 case Bytecodes::_anewarray : // fall through
1952 case Bytecodes::_checkcast : // fall through
1953 case Bytecodes::_getfield : // fall through
1954 case Bytecodes::_getstatic : // fall through
1955 case Bytecodes::_instanceof : // fall through
1956 case Bytecodes::_invokedynamic : // fall through
1957 case Bytecodes::_invokeinterface: // fall through
1958 case Bytecodes::_invokespecial : // fall through
1959 case Bytecodes::_invokestatic : // fall through
1960 case Bytecodes::_invokevirtual : // fall through
1961 case Bytecodes::_ldc_w : // fall through
1962 case Bytecodes::_ldc2_w : // fall through
1963 case Bytecodes::_multianewarray : // fall through
1964 case Bytecodes::_new : // fall through
1965 case Bytecodes::_putfield : // fall through
1966 case Bytecodes::_putstatic :
1967 {
1968 address p = bcp + 1;
1969 int cp_index = Bytes::get_Java_u2(p);
1970 int new_index = find_new_index(cp_index);
1971 if (new_index != 0) {
1972 // the original index is mapped so update w/ new value
1973 log_trace(redefine, class, constantpool)
1974 ("%s@" INTPTR_FORMAT " old=%d, new=%d", Bytecodes::name(c),p2i(bcp), cp_index, new_index);
1975 // Rewriter::rewrite_method() uses put_native_u2() in this
1976 // situation because it is reusing the constant pool index
1977 // location for a native index into the ConstantPoolCache.
1978 // Since we are updating the constant pool index prior to
1979 // verification and ConstantPoolCache initialization, we
1980 // need to keep the new index in Java byte order.
1981 Bytes::put_Java_u2(p, new_index);
1982 }
1983 } break;
1984 default:
1985 break;
1986 }
1987 } // end for each bytecode
1988
1989 // We also need to rewrite the parameter name indexes, if there is
1990 // method parameter data present
1991 if(method->has_method_parameters()) {
1992 const int len = method->method_parameters_length();
1993 MethodParametersElement* elem = method->method_parameters_start();
1994
1995 for (int i = 0; i < len; i++) {
1996 const u2 cp_index = elem[i].name_cp_index;
1997 const u2 new_cp_index = find_new_index(cp_index);
1998 if (new_cp_index != 0) {
1999 elem[i].name_cp_index = new_cp_index;
2000 }
2001 }
2002 }
2003 } // end rewrite_cp_refs_in_method()
2004
2005
2006 // Rewrite constant pool references in the class_annotations field.
rewrite_cp_refs_in_class_annotations(InstanceKlass * scratch_class,TRAPS)2007 bool VM_RedefineClasses::rewrite_cp_refs_in_class_annotations(
2008 InstanceKlass* scratch_class, TRAPS) {
2009
2010 AnnotationArray* class_annotations = scratch_class->class_annotations();
2011 if (class_annotations == NULL || class_annotations->length() == 0) {
2012 // no class_annotations so nothing to do
2013 return true;
2014 }
2015
2016 log_debug(redefine, class, annotation)("class_annotations length=%d", class_annotations->length());
2017
2018 int byte_i = 0; // byte index into class_annotations
2019 return rewrite_cp_refs_in_annotations_typeArray(class_annotations, byte_i,
2020 THREAD);
2021 }
2022
2023
2024 // Rewrite constant pool references in an annotations typeArray. This
2025 // "structure" is adapted from the RuntimeVisibleAnnotations_attribute
2026 // that is described in section 4.8.15 of the 2nd-edition of the VM spec:
2027 //
2028 // annotations_typeArray {
2029 // u2 num_annotations;
2030 // annotation annotations[num_annotations];
2031 // }
2032 //
rewrite_cp_refs_in_annotations_typeArray(AnnotationArray * annotations_typeArray,int & byte_i_ref,TRAPS)2033 bool VM_RedefineClasses::rewrite_cp_refs_in_annotations_typeArray(
2034 AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {
2035
2036 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2037 // not enough room for num_annotations field
2038 log_debug(redefine, class, annotation)("length() is too small for num_annotations field");
2039 return false;
2040 }
2041
2042 u2 num_annotations = Bytes::get_Java_u2((address)
2043 annotations_typeArray->adr_at(byte_i_ref));
2044 byte_i_ref += 2;
2045
2046 log_debug(redefine, class, annotation)("num_annotations=%d", num_annotations);
2047
2048 int calc_num_annotations = 0;
2049 for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
2050 if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray,
2051 byte_i_ref, THREAD)) {
2052 log_debug(redefine, class, annotation)("bad annotation_struct at %d", calc_num_annotations);
2053 // propagate failure back to caller
2054 return false;
2055 }
2056 }
2057 assert(num_annotations == calc_num_annotations, "sanity check");
2058
2059 return true;
2060 } // end rewrite_cp_refs_in_annotations_typeArray()
2061
2062
2063 // Rewrite constant pool references in the annotation struct portion of
2064 // an annotations_typeArray. This "structure" is from section 4.8.15 of
2065 // the 2nd-edition of the VM spec:
2066 //
2067 // struct annotation {
2068 // u2 type_index;
2069 // u2 num_element_value_pairs;
2070 // {
2071 // u2 element_name_index;
2072 // element_value value;
2073 // } element_value_pairs[num_element_value_pairs];
2074 // }
2075 //
rewrite_cp_refs_in_annotation_struct(AnnotationArray * annotations_typeArray,int & byte_i_ref,TRAPS)2076 bool VM_RedefineClasses::rewrite_cp_refs_in_annotation_struct(
2077 AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {
2078 if ((byte_i_ref + 2 + 2) > annotations_typeArray->length()) {
2079 // not enough room for smallest annotation_struct
2080 log_debug(redefine, class, annotation)("length() is too small for annotation_struct");
2081 return false;
2082 }
2083
2084 u2 type_index = rewrite_cp_ref_in_annotation_data(annotations_typeArray,
2085 byte_i_ref, "type_index", THREAD);
2086
2087 u2 num_element_value_pairs = Bytes::get_Java_u2((address)
2088 annotations_typeArray->adr_at(byte_i_ref));
2089 byte_i_ref += 2;
2090
2091 log_debug(redefine, class, annotation)
2092 ("type_index=%d num_element_value_pairs=%d", type_index, num_element_value_pairs);
2093
2094 int calc_num_element_value_pairs = 0;
2095 for (; calc_num_element_value_pairs < num_element_value_pairs;
2096 calc_num_element_value_pairs++) {
2097 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2098 // not enough room for another element_name_index, let alone
2099 // the rest of another component
2100 log_debug(redefine, class, annotation)("length() is too small for element_name_index");
2101 return false;
2102 }
2103
2104 u2 element_name_index = rewrite_cp_ref_in_annotation_data(
2105 annotations_typeArray, byte_i_ref,
2106 "element_name_index", THREAD);
2107
2108 log_debug(redefine, class, annotation)("element_name_index=%d", element_name_index);
2109
2110 if (!rewrite_cp_refs_in_element_value(annotations_typeArray,
2111 byte_i_ref, THREAD)) {
2112 log_debug(redefine, class, annotation)("bad element_value at %d", calc_num_element_value_pairs);
2113 // propagate failure back to caller
2114 return false;
2115 }
2116 } // end for each component
2117 assert(num_element_value_pairs == calc_num_element_value_pairs,
2118 "sanity check");
2119
2120 return true;
2121 } // end rewrite_cp_refs_in_annotation_struct()
2122
2123
2124 // Rewrite a constant pool reference at the current position in
2125 // annotations_typeArray if needed. Returns the original constant
2126 // pool reference if a rewrite was not needed or the new constant
2127 // pool reference if a rewrite was needed.
rewrite_cp_ref_in_annotation_data(AnnotationArray * annotations_typeArray,int & byte_i_ref,const char * trace_mesg,TRAPS)2128 u2 VM_RedefineClasses::rewrite_cp_ref_in_annotation_data(
2129 AnnotationArray* annotations_typeArray, int &byte_i_ref,
2130 const char * trace_mesg, TRAPS) {
2131
2132 address cp_index_addr = (address)
2133 annotations_typeArray->adr_at(byte_i_ref);
2134 u2 old_cp_index = Bytes::get_Java_u2(cp_index_addr);
2135 u2 new_cp_index = find_new_index(old_cp_index);
2136 if (new_cp_index != 0) {
2137 log_debug(redefine, class, annotation)("mapped old %s=%d", trace_mesg, old_cp_index);
2138 Bytes::put_Java_u2(cp_index_addr, new_cp_index);
2139 old_cp_index = new_cp_index;
2140 }
2141 byte_i_ref += 2;
2142 return old_cp_index;
2143 }
2144
2145
2146 // Rewrite constant pool references in the element_value portion of an
2147 // annotations_typeArray. This "structure" is from section 4.8.15.1 of
2148 // the 2nd-edition of the VM spec:
2149 //
2150 // struct element_value {
2151 // u1 tag;
2152 // union {
2153 // u2 const_value_index;
2154 // {
2155 // u2 type_name_index;
2156 // u2 const_name_index;
2157 // } enum_const_value;
2158 // u2 class_info_index;
2159 // annotation annotation_value;
2160 // struct {
2161 // u2 num_values;
2162 // element_value values[num_values];
2163 // } array_value;
2164 // } value;
2165 // }
2166 //
rewrite_cp_refs_in_element_value(AnnotationArray * annotations_typeArray,int & byte_i_ref,TRAPS)2167 bool VM_RedefineClasses::rewrite_cp_refs_in_element_value(
2168 AnnotationArray* annotations_typeArray, int &byte_i_ref, TRAPS) {
2169
2170 if ((byte_i_ref + 1) > annotations_typeArray->length()) {
2171 // not enough room for a tag let alone the rest of an element_value
2172 log_debug(redefine, class, annotation)("length() is too small for a tag");
2173 return false;
2174 }
2175
2176 u1 tag = annotations_typeArray->at(byte_i_ref);
2177 byte_i_ref++;
2178 log_debug(redefine, class, annotation)("tag='%c'", tag);
2179
2180 switch (tag) {
2181 // These BaseType tag values are from Table 4.2 in VM spec:
2182 case 'B': // byte
2183 case 'C': // char
2184 case 'D': // double
2185 case 'F': // float
2186 case 'I': // int
2187 case 'J': // long
2188 case 'S': // short
2189 case 'Z': // boolean
2190
2191 // The remaining tag values are from Table 4.8 in the 2nd-edition of
2192 // the VM spec:
2193 case 's':
2194 {
2195 // For the above tag values (including the BaseType values),
2196 // value.const_value_index is right union field.
2197
2198 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2199 // not enough room for a const_value_index
2200 log_debug(redefine, class, annotation)("length() is too small for a const_value_index");
2201 return false;
2202 }
2203
2204 u2 const_value_index = rewrite_cp_ref_in_annotation_data(
2205 annotations_typeArray, byte_i_ref,
2206 "const_value_index", THREAD);
2207
2208 log_debug(redefine, class, annotation)("const_value_index=%d", const_value_index);
2209 } break;
2210
2211 case 'e':
2212 {
2213 // for the above tag value, value.enum_const_value is right union field
2214
2215 if ((byte_i_ref + 4) > annotations_typeArray->length()) {
2216 // not enough room for a enum_const_value
2217 log_debug(redefine, class, annotation)("length() is too small for a enum_const_value");
2218 return false;
2219 }
2220
2221 u2 type_name_index = rewrite_cp_ref_in_annotation_data(
2222 annotations_typeArray, byte_i_ref,
2223 "type_name_index", THREAD);
2224
2225 u2 const_name_index = rewrite_cp_ref_in_annotation_data(
2226 annotations_typeArray, byte_i_ref,
2227 "const_name_index", THREAD);
2228
2229 log_debug(redefine, class, annotation)
2230 ("type_name_index=%d const_name_index=%d", type_name_index, const_name_index);
2231 } break;
2232
2233 case 'c':
2234 {
2235 // for the above tag value, value.class_info_index is right union field
2236
2237 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2238 // not enough room for a class_info_index
2239 log_debug(redefine, class, annotation)("length() is too small for a class_info_index");
2240 return false;
2241 }
2242
2243 u2 class_info_index = rewrite_cp_ref_in_annotation_data(
2244 annotations_typeArray, byte_i_ref,
2245 "class_info_index", THREAD);
2246
2247 log_debug(redefine, class, annotation)("class_info_index=%d", class_info_index);
2248 } break;
2249
2250 case '@':
2251 // For the above tag value, value.attr_value is the right union
2252 // field. This is a nested annotation.
2253 if (!rewrite_cp_refs_in_annotation_struct(annotations_typeArray,
2254 byte_i_ref, THREAD)) {
2255 // propagate failure back to caller
2256 return false;
2257 }
2258 break;
2259
2260 case '[':
2261 {
2262 if ((byte_i_ref + 2) > annotations_typeArray->length()) {
2263 // not enough room for a num_values field
2264 log_debug(redefine, class, annotation)("length() is too small for a num_values field");
2265 return false;
2266 }
2267
2268 // For the above tag value, value.array_value is the right union
2269 // field. This is an array of nested element_value.
2270 u2 num_values = Bytes::get_Java_u2((address)
2271 annotations_typeArray->adr_at(byte_i_ref));
2272 byte_i_ref += 2;
2273 log_debug(redefine, class, annotation)("num_values=%d", num_values);
2274
2275 int calc_num_values = 0;
2276 for (; calc_num_values < num_values; calc_num_values++) {
2277 if (!rewrite_cp_refs_in_element_value(
2278 annotations_typeArray, byte_i_ref, THREAD)) {
2279 log_debug(redefine, class, annotation)("bad nested element_value at %d", calc_num_values);
2280 // propagate failure back to caller
2281 return false;
2282 }
2283 }
2284 assert(num_values == calc_num_values, "sanity check");
2285 } break;
2286
2287 default:
2288 log_debug(redefine, class, annotation)("bad tag=0x%x", tag);
2289 return false;
2290 } // end decode tag field
2291
2292 return true;
2293 } // end rewrite_cp_refs_in_element_value()
2294
2295
2296 // Rewrite constant pool references in a fields_annotations field.
rewrite_cp_refs_in_fields_annotations(InstanceKlass * scratch_class,TRAPS)2297 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations(
2298 InstanceKlass* scratch_class, TRAPS) {
2299
2300 Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations();
2301
2302 if (fields_annotations == NULL || fields_annotations->length() == 0) {
2303 // no fields_annotations so nothing to do
2304 return true;
2305 }
2306
2307 log_debug(redefine, class, annotation)("fields_annotations length=%d", fields_annotations->length());
2308
2309 for (int i = 0; i < fields_annotations->length(); i++) {
2310 AnnotationArray* field_annotations = fields_annotations->at(i);
2311 if (field_annotations == NULL || field_annotations->length() == 0) {
2312 // this field does not have any annotations so skip it
2313 continue;
2314 }
2315
2316 int byte_i = 0; // byte index into field_annotations
2317 if (!rewrite_cp_refs_in_annotations_typeArray(field_annotations, byte_i,
2318 THREAD)) {
2319 log_debug(redefine, class, annotation)("bad field_annotations at %d", i);
2320 // propagate failure back to caller
2321 return false;
2322 }
2323 }
2324
2325 return true;
2326 } // end rewrite_cp_refs_in_fields_annotations()
2327
2328
2329 // Rewrite constant pool references in a methods_annotations field.
rewrite_cp_refs_in_methods_annotations(InstanceKlass * scratch_class,TRAPS)2330 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations(
2331 InstanceKlass* scratch_class, TRAPS) {
2332
2333 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2334 Method* m = scratch_class->methods()->at(i);
2335 AnnotationArray* method_annotations = m->constMethod()->method_annotations();
2336
2337 if (method_annotations == NULL || method_annotations->length() == 0) {
2338 // this method does not have any annotations so skip it
2339 continue;
2340 }
2341
2342 int byte_i = 0; // byte index into method_annotations
2343 if (!rewrite_cp_refs_in_annotations_typeArray(method_annotations, byte_i,
2344 THREAD)) {
2345 log_debug(redefine, class, annotation)("bad method_annotations at %d", i);
2346 // propagate failure back to caller
2347 return false;
2348 }
2349 }
2350
2351 return true;
2352 } // end rewrite_cp_refs_in_methods_annotations()
2353
2354
2355 // Rewrite constant pool references in a methods_parameter_annotations
2356 // field. This "structure" is adapted from the
2357 // RuntimeVisibleParameterAnnotations_attribute described in section
2358 // 4.8.17 of the 2nd-edition of the VM spec:
2359 //
2360 // methods_parameter_annotations_typeArray {
2361 // u1 num_parameters;
2362 // {
2363 // u2 num_annotations;
2364 // annotation annotations[num_annotations];
2365 // } parameter_annotations[num_parameters];
2366 // }
2367 //
rewrite_cp_refs_in_methods_parameter_annotations(InstanceKlass * scratch_class,TRAPS)2368 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations(
2369 InstanceKlass* scratch_class, TRAPS) {
2370
2371 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2372 Method* m = scratch_class->methods()->at(i);
2373 AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations();
2374 if (method_parameter_annotations == NULL
2375 || method_parameter_annotations->length() == 0) {
2376 // this method does not have any parameter annotations so skip it
2377 continue;
2378 }
2379
2380 if (method_parameter_annotations->length() < 1) {
2381 // not enough room for a num_parameters field
2382 log_debug(redefine, class, annotation)("length() is too small for a num_parameters field at %d", i);
2383 return false;
2384 }
2385
2386 int byte_i = 0; // byte index into method_parameter_annotations
2387
2388 u1 num_parameters = method_parameter_annotations->at(byte_i);
2389 byte_i++;
2390
2391 log_debug(redefine, class, annotation)("num_parameters=%d", num_parameters);
2392
2393 int calc_num_parameters = 0;
2394 for (; calc_num_parameters < num_parameters; calc_num_parameters++) {
2395 if (!rewrite_cp_refs_in_annotations_typeArray(
2396 method_parameter_annotations, byte_i, THREAD)) {
2397 log_debug(redefine, class, annotation)("bad method_parameter_annotations at %d", calc_num_parameters);
2398 // propagate failure back to caller
2399 return false;
2400 }
2401 }
2402 assert(num_parameters == calc_num_parameters, "sanity check");
2403 }
2404
2405 return true;
2406 } // end rewrite_cp_refs_in_methods_parameter_annotations()
2407
2408
2409 // Rewrite constant pool references in a methods_default_annotations
2410 // field. This "structure" is adapted from the AnnotationDefault_attribute
2411 // that is described in section 4.8.19 of the 2nd-edition of the VM spec:
2412 //
2413 // methods_default_annotations_typeArray {
2414 // element_value default_value;
2415 // }
2416 //
rewrite_cp_refs_in_methods_default_annotations(InstanceKlass * scratch_class,TRAPS)2417 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations(
2418 InstanceKlass* scratch_class, TRAPS) {
2419
2420 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2421 Method* m = scratch_class->methods()->at(i);
2422 AnnotationArray* method_default_annotations = m->constMethod()->default_annotations();
2423 if (method_default_annotations == NULL
2424 || method_default_annotations->length() == 0) {
2425 // this method does not have any default annotations so skip it
2426 continue;
2427 }
2428
2429 int byte_i = 0; // byte index into method_default_annotations
2430
2431 if (!rewrite_cp_refs_in_element_value(
2432 method_default_annotations, byte_i, THREAD)) {
2433 log_debug(redefine, class, annotation)("bad default element_value at %d", i);
2434 // propagate failure back to caller
2435 return false;
2436 }
2437 }
2438
2439 return true;
2440 } // end rewrite_cp_refs_in_methods_default_annotations()
2441
2442
2443 // Rewrite constant pool references in a class_type_annotations field.
rewrite_cp_refs_in_class_type_annotations(InstanceKlass * scratch_class,TRAPS)2444 bool VM_RedefineClasses::rewrite_cp_refs_in_class_type_annotations(
2445 InstanceKlass* scratch_class, TRAPS) {
2446
2447 AnnotationArray* class_type_annotations = scratch_class->class_type_annotations();
2448 if (class_type_annotations == NULL || class_type_annotations->length() == 0) {
2449 // no class_type_annotations so nothing to do
2450 return true;
2451 }
2452
2453 log_debug(redefine, class, annotation)("class_type_annotations length=%d", class_type_annotations->length());
2454
2455 int byte_i = 0; // byte index into class_type_annotations
2456 return rewrite_cp_refs_in_type_annotations_typeArray(class_type_annotations,
2457 byte_i, "ClassFile", THREAD);
2458 } // end rewrite_cp_refs_in_class_type_annotations()
2459
2460
2461 // Rewrite constant pool references in a fields_type_annotations field.
rewrite_cp_refs_in_fields_type_annotations(InstanceKlass * scratch_class,TRAPS)2462 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_type_annotations(
2463 InstanceKlass* scratch_class, TRAPS) {
2464
2465 Array<AnnotationArray*>* fields_type_annotations = scratch_class->fields_type_annotations();
2466 if (fields_type_annotations == NULL || fields_type_annotations->length() == 0) {
2467 // no fields_type_annotations so nothing to do
2468 return true;
2469 }
2470
2471 log_debug(redefine, class, annotation)("fields_type_annotations length=%d", fields_type_annotations->length());
2472
2473 for (int i = 0; i < fields_type_annotations->length(); i++) {
2474 AnnotationArray* field_type_annotations = fields_type_annotations->at(i);
2475 if (field_type_annotations == NULL || field_type_annotations->length() == 0) {
2476 // this field does not have any annotations so skip it
2477 continue;
2478 }
2479
2480 int byte_i = 0; // byte index into field_type_annotations
2481 if (!rewrite_cp_refs_in_type_annotations_typeArray(field_type_annotations,
2482 byte_i, "field_info", THREAD)) {
2483 log_debug(redefine, class, annotation)("bad field_type_annotations at %d", i);
2484 // propagate failure back to caller
2485 return false;
2486 }
2487 }
2488
2489 return true;
2490 } // end rewrite_cp_refs_in_fields_type_annotations()
2491
2492
2493 // Rewrite constant pool references in a methods_type_annotations field.
rewrite_cp_refs_in_methods_type_annotations(InstanceKlass * scratch_class,TRAPS)2494 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_type_annotations(
2495 InstanceKlass* scratch_class, TRAPS) {
2496
2497 for (int i = 0; i < scratch_class->methods()->length(); i++) {
2498 Method* m = scratch_class->methods()->at(i);
2499 AnnotationArray* method_type_annotations = m->constMethod()->type_annotations();
2500
2501 if (method_type_annotations == NULL || method_type_annotations->length() == 0) {
2502 // this method does not have any annotations so skip it
2503 continue;
2504 }
2505
2506 log_debug(redefine, class, annotation)("methods type_annotations length=%d", method_type_annotations->length());
2507
2508 int byte_i = 0; // byte index into method_type_annotations
2509 if (!rewrite_cp_refs_in_type_annotations_typeArray(method_type_annotations,
2510 byte_i, "method_info", THREAD)) {
2511 log_debug(redefine, class, annotation)("bad method_type_annotations at %d", i);
2512 // propagate failure back to caller
2513 return false;
2514 }
2515 }
2516
2517 return true;
2518 } // end rewrite_cp_refs_in_methods_type_annotations()
2519
2520
2521 // Rewrite constant pool references in a type_annotations
2522 // field. This "structure" is adapted from the
2523 // RuntimeVisibleTypeAnnotations_attribute described in
2524 // section 4.7.20 of the Java SE 8 Edition of the VM spec:
2525 //
2526 // type_annotations_typeArray {
2527 // u2 num_annotations;
2528 // type_annotation annotations[num_annotations];
2529 // }
2530 //
rewrite_cp_refs_in_type_annotations_typeArray(AnnotationArray * type_annotations_typeArray,int & byte_i_ref,const char * location_mesg,TRAPS)2531 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotations_typeArray(
2532 AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2533 const char * location_mesg, TRAPS) {
2534
2535 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2536 // not enough room for num_annotations field
2537 log_debug(redefine, class, annotation)("length() is too small for num_annotations field");
2538 return false;
2539 }
2540
2541 u2 num_annotations = Bytes::get_Java_u2((address)
2542 type_annotations_typeArray->adr_at(byte_i_ref));
2543 byte_i_ref += 2;
2544
2545 log_debug(redefine, class, annotation)("num_type_annotations=%d", num_annotations);
2546
2547 int calc_num_annotations = 0;
2548 for (; calc_num_annotations < num_annotations; calc_num_annotations++) {
2549 if (!rewrite_cp_refs_in_type_annotation_struct(type_annotations_typeArray,
2550 byte_i_ref, location_mesg, THREAD)) {
2551 log_debug(redefine, class, annotation)("bad type_annotation_struct at %d", calc_num_annotations);
2552 // propagate failure back to caller
2553 return false;
2554 }
2555 }
2556 assert(num_annotations == calc_num_annotations, "sanity check");
2557
2558 if (byte_i_ref != type_annotations_typeArray->length()) {
2559 log_debug(redefine, class, annotation)
2560 ("read wrong amount of bytes at end of processing type_annotations_typeArray (%d of %d bytes were read)",
2561 byte_i_ref, type_annotations_typeArray->length());
2562 return false;
2563 }
2564
2565 return true;
2566 } // end rewrite_cp_refs_in_type_annotations_typeArray()
2567
2568
2569 // Rewrite constant pool references in a type_annotation
2570 // field. This "structure" is adapted from the
2571 // RuntimeVisibleTypeAnnotations_attribute described in
2572 // section 4.7.20 of the Java SE 8 Edition of the VM spec:
2573 //
2574 // type_annotation {
2575 // u1 target_type;
2576 // union {
2577 // type_parameter_target;
2578 // supertype_target;
2579 // type_parameter_bound_target;
2580 // empty_target;
2581 // method_formal_parameter_target;
2582 // throws_target;
2583 // localvar_target;
2584 // catch_target;
2585 // offset_target;
2586 // type_argument_target;
2587 // } target_info;
2588 // type_path target_path;
2589 // annotation anno;
2590 // }
2591 //
rewrite_cp_refs_in_type_annotation_struct(AnnotationArray * type_annotations_typeArray,int & byte_i_ref,const char * location_mesg,TRAPS)2592 bool VM_RedefineClasses::rewrite_cp_refs_in_type_annotation_struct(
2593 AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2594 const char * location_mesg, TRAPS) {
2595
2596 if (!skip_type_annotation_target(type_annotations_typeArray,
2597 byte_i_ref, location_mesg, THREAD)) {
2598 return false;
2599 }
2600
2601 if (!skip_type_annotation_type_path(type_annotations_typeArray,
2602 byte_i_ref, THREAD)) {
2603 return false;
2604 }
2605
2606 if (!rewrite_cp_refs_in_annotation_struct(type_annotations_typeArray,
2607 byte_i_ref, THREAD)) {
2608 return false;
2609 }
2610
2611 return true;
2612 } // end rewrite_cp_refs_in_type_annotation_struct()
2613
2614
2615 // Read, verify and skip over the target_type and target_info part
2616 // so that rewriting can continue in the later parts of the struct.
2617 //
2618 // u1 target_type;
2619 // union {
2620 // type_parameter_target;
2621 // supertype_target;
2622 // type_parameter_bound_target;
2623 // empty_target;
2624 // method_formal_parameter_target;
2625 // throws_target;
2626 // localvar_target;
2627 // catch_target;
2628 // offset_target;
2629 // type_argument_target;
2630 // } target_info;
2631 //
skip_type_annotation_target(AnnotationArray * type_annotations_typeArray,int & byte_i_ref,const char * location_mesg,TRAPS)2632 bool VM_RedefineClasses::skip_type_annotation_target(
2633 AnnotationArray* type_annotations_typeArray, int &byte_i_ref,
2634 const char * location_mesg, TRAPS) {
2635
2636 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2637 // not enough room for a target_type let alone the rest of a type_annotation
2638 log_debug(redefine, class, annotation)("length() is too small for a target_type");
2639 return false;
2640 }
2641
2642 u1 target_type = type_annotations_typeArray->at(byte_i_ref);
2643 byte_i_ref += 1;
2644 log_debug(redefine, class, annotation)("target_type=0x%.2x", target_type);
2645 log_debug(redefine, class, annotation)("location=%s", location_mesg);
2646
2647 // Skip over target_info
2648 switch (target_type) {
2649 case 0x00:
2650 // kind: type parameter declaration of generic class or interface
2651 // location: ClassFile
2652 case 0x01:
2653 // kind: type parameter declaration of generic method or constructor
2654 // location: method_info
2655
2656 {
2657 // struct:
2658 // type_parameter_target {
2659 // u1 type_parameter_index;
2660 // }
2661 //
2662 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2663 log_debug(redefine, class, annotation)("length() is too small for a type_parameter_target");
2664 return false;
2665 }
2666
2667 u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2668 byte_i_ref += 1;
2669
2670 log_debug(redefine, class, annotation)("type_parameter_target: type_parameter_index=%d", type_parameter_index);
2671 } break;
2672
2673 case 0x10:
2674 // kind: type in extends clause of class or interface declaration
2675 // (including the direct superclass of an unsafe anonymous class declaration),
2676 // or in implements clause of interface declaration
2677 // location: ClassFile
2678
2679 {
2680 // struct:
2681 // supertype_target {
2682 // u2 supertype_index;
2683 // }
2684 //
2685 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2686 log_debug(redefine, class, annotation)("length() is too small for a supertype_target");
2687 return false;
2688 }
2689
2690 u2 supertype_index = Bytes::get_Java_u2((address)
2691 type_annotations_typeArray->adr_at(byte_i_ref));
2692 byte_i_ref += 2;
2693
2694 log_debug(redefine, class, annotation)("supertype_target: supertype_index=%d", supertype_index);
2695 } break;
2696
2697 case 0x11:
2698 // kind: type in bound of type parameter declaration of generic class or interface
2699 // location: ClassFile
2700 case 0x12:
2701 // kind: type in bound of type parameter declaration of generic method or constructor
2702 // location: method_info
2703
2704 {
2705 // struct:
2706 // type_parameter_bound_target {
2707 // u1 type_parameter_index;
2708 // u1 bound_index;
2709 // }
2710 //
2711 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2712 log_debug(redefine, class, annotation)("length() is too small for a type_parameter_bound_target");
2713 return false;
2714 }
2715
2716 u1 type_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2717 byte_i_ref += 1;
2718 u1 bound_index = type_annotations_typeArray->at(byte_i_ref);
2719 byte_i_ref += 1;
2720
2721 log_debug(redefine, class, annotation)
2722 ("type_parameter_bound_target: type_parameter_index=%d, bound_index=%d", type_parameter_index, bound_index);
2723 } break;
2724
2725 case 0x13:
2726 // kind: type in field declaration
2727 // location: field_info
2728 case 0x14:
2729 // kind: return type of method, or type of newly constructed object
2730 // location: method_info
2731 case 0x15:
2732 // kind: receiver type of method or constructor
2733 // location: method_info
2734
2735 {
2736 // struct:
2737 // empty_target {
2738 // }
2739 //
2740 log_debug(redefine, class, annotation)("empty_target");
2741 } break;
2742
2743 case 0x16:
2744 // kind: type in formal parameter declaration of method, constructor, or lambda expression
2745 // location: method_info
2746
2747 {
2748 // struct:
2749 // formal_parameter_target {
2750 // u1 formal_parameter_index;
2751 // }
2752 //
2753 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2754 log_debug(redefine, class, annotation)("length() is too small for a formal_parameter_target");
2755 return false;
2756 }
2757
2758 u1 formal_parameter_index = type_annotations_typeArray->at(byte_i_ref);
2759 byte_i_ref += 1;
2760
2761 log_debug(redefine, class, annotation)
2762 ("formal_parameter_target: formal_parameter_index=%d", formal_parameter_index);
2763 } break;
2764
2765 case 0x17:
2766 // kind: type in throws clause of method or constructor
2767 // location: method_info
2768
2769 {
2770 // struct:
2771 // throws_target {
2772 // u2 throws_type_index
2773 // }
2774 //
2775 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2776 log_debug(redefine, class, annotation)("length() is too small for a throws_target");
2777 return false;
2778 }
2779
2780 u2 throws_type_index = Bytes::get_Java_u2((address)
2781 type_annotations_typeArray->adr_at(byte_i_ref));
2782 byte_i_ref += 2;
2783
2784 log_debug(redefine, class, annotation)("throws_target: throws_type_index=%d", throws_type_index);
2785 } break;
2786
2787 case 0x40:
2788 // kind: type in local variable declaration
2789 // location: Code
2790 case 0x41:
2791 // kind: type in resource variable declaration
2792 // location: Code
2793
2794 {
2795 // struct:
2796 // localvar_target {
2797 // u2 table_length;
2798 // struct {
2799 // u2 start_pc;
2800 // u2 length;
2801 // u2 index;
2802 // } table[table_length];
2803 // }
2804 //
2805 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2806 // not enough room for a table_length let alone the rest of a localvar_target
2807 log_debug(redefine, class, annotation)("length() is too small for a localvar_target table_length");
2808 return false;
2809 }
2810
2811 u2 table_length = Bytes::get_Java_u2((address)
2812 type_annotations_typeArray->adr_at(byte_i_ref));
2813 byte_i_ref += 2;
2814
2815 log_debug(redefine, class, annotation)("localvar_target: table_length=%d", table_length);
2816
2817 int table_struct_size = 2 + 2 + 2; // 3 u2 variables per table entry
2818 int table_size = table_length * table_struct_size;
2819
2820 if ((byte_i_ref + table_size) > type_annotations_typeArray->length()) {
2821 // not enough room for a table
2822 log_debug(redefine, class, annotation)("length() is too small for a table array of length %d", table_length);
2823 return false;
2824 }
2825
2826 // Skip over table
2827 byte_i_ref += table_size;
2828 } break;
2829
2830 case 0x42:
2831 // kind: type in exception parameter declaration
2832 // location: Code
2833
2834 {
2835 // struct:
2836 // catch_target {
2837 // u2 exception_table_index;
2838 // }
2839 //
2840 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2841 log_debug(redefine, class, annotation)("length() is too small for a catch_target");
2842 return false;
2843 }
2844
2845 u2 exception_table_index = Bytes::get_Java_u2((address)
2846 type_annotations_typeArray->adr_at(byte_i_ref));
2847 byte_i_ref += 2;
2848
2849 log_debug(redefine, class, annotation)("catch_target: exception_table_index=%d", exception_table_index);
2850 } break;
2851
2852 case 0x43:
2853 // kind: type in instanceof expression
2854 // location: Code
2855 case 0x44:
2856 // kind: type in new expression
2857 // location: Code
2858 case 0x45:
2859 // kind: type in method reference expression using ::new
2860 // location: Code
2861 case 0x46:
2862 // kind: type in method reference expression using ::Identifier
2863 // location: Code
2864
2865 {
2866 // struct:
2867 // offset_target {
2868 // u2 offset;
2869 // }
2870 //
2871 if ((byte_i_ref + 2) > type_annotations_typeArray->length()) {
2872 log_debug(redefine, class, annotation)("length() is too small for a offset_target");
2873 return false;
2874 }
2875
2876 u2 offset = Bytes::get_Java_u2((address)
2877 type_annotations_typeArray->adr_at(byte_i_ref));
2878 byte_i_ref += 2;
2879
2880 log_debug(redefine, class, annotation)("offset_target: offset=%d", offset);
2881 } break;
2882
2883 case 0x47:
2884 // kind: type in cast expression
2885 // location: Code
2886 case 0x48:
2887 // kind: type argument for generic constructor in new expression or
2888 // explicit constructor invocation statement
2889 // location: Code
2890 case 0x49:
2891 // kind: type argument for generic method in method invocation expression
2892 // location: Code
2893 case 0x4A:
2894 // kind: type argument for generic constructor in method reference expression using ::new
2895 // location: Code
2896 case 0x4B:
2897 // kind: type argument for generic method in method reference expression using ::Identifier
2898 // location: Code
2899
2900 {
2901 // struct:
2902 // type_argument_target {
2903 // u2 offset;
2904 // u1 type_argument_index;
2905 // }
2906 //
2907 if ((byte_i_ref + 3) > type_annotations_typeArray->length()) {
2908 log_debug(redefine, class, annotation)("length() is too small for a type_argument_target");
2909 return false;
2910 }
2911
2912 u2 offset = Bytes::get_Java_u2((address)
2913 type_annotations_typeArray->adr_at(byte_i_ref));
2914 byte_i_ref += 2;
2915 u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
2916 byte_i_ref += 1;
2917
2918 log_debug(redefine, class, annotation)
2919 ("type_argument_target: offset=%d, type_argument_index=%d", offset, type_argument_index);
2920 } break;
2921
2922 default:
2923 log_debug(redefine, class, annotation)("unknown target_type");
2924 #ifdef ASSERT
2925 ShouldNotReachHere();
2926 #endif
2927 return false;
2928 }
2929
2930 return true;
2931 } // end skip_type_annotation_target()
2932
2933
2934 // Read, verify and skip over the type_path part so that rewriting
2935 // can continue in the later parts of the struct.
2936 //
2937 // type_path {
2938 // u1 path_length;
2939 // {
2940 // u1 type_path_kind;
2941 // u1 type_argument_index;
2942 // } path[path_length];
2943 // }
2944 //
skip_type_annotation_type_path(AnnotationArray * type_annotations_typeArray,int & byte_i_ref,TRAPS)2945 bool VM_RedefineClasses::skip_type_annotation_type_path(
2946 AnnotationArray* type_annotations_typeArray, int &byte_i_ref, TRAPS) {
2947
2948 if ((byte_i_ref + 1) > type_annotations_typeArray->length()) {
2949 // not enough room for a path_length let alone the rest of the type_path
2950 log_debug(redefine, class, annotation)("length() is too small for a type_path");
2951 return false;
2952 }
2953
2954 u1 path_length = type_annotations_typeArray->at(byte_i_ref);
2955 byte_i_ref += 1;
2956
2957 log_debug(redefine, class, annotation)("type_path: path_length=%d", path_length);
2958
2959 int calc_path_length = 0;
2960 for (; calc_path_length < path_length; calc_path_length++) {
2961 if ((byte_i_ref + 1 + 1) > type_annotations_typeArray->length()) {
2962 // not enough room for a path
2963 log_debug(redefine, class, annotation)
2964 ("length() is too small for path entry %d of %d", calc_path_length, path_length);
2965 return false;
2966 }
2967
2968 u1 type_path_kind = type_annotations_typeArray->at(byte_i_ref);
2969 byte_i_ref += 1;
2970 u1 type_argument_index = type_annotations_typeArray->at(byte_i_ref);
2971 byte_i_ref += 1;
2972
2973 log_debug(redefine, class, annotation)
2974 ("type_path: path[%d]: type_path_kind=%d, type_argument_index=%d",
2975 calc_path_length, type_path_kind, type_argument_index);
2976
2977 if (type_path_kind > 3 || (type_path_kind != 3 && type_argument_index != 0)) {
2978 // not enough room for a path
2979 log_debug(redefine, class, annotation)("inconsistent type_path values");
2980 return false;
2981 }
2982 }
2983 assert(path_length == calc_path_length, "sanity check");
2984
2985 return true;
2986 } // end skip_type_annotation_type_path()
2987
2988
2989 // Rewrite constant pool references in the method's stackmap table.
2990 // These "structures" are adapted from the StackMapTable_attribute that
2991 // is described in section 4.8.4 of the 6.0 version of the VM spec
2992 // (dated 2005.10.26):
2993 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf
2994 //
2995 // stack_map {
2996 // u2 number_of_entries;
2997 // stack_map_frame entries[number_of_entries];
2998 // }
2999 //
rewrite_cp_refs_in_stack_map_table(const methodHandle & method,TRAPS)3000 void VM_RedefineClasses::rewrite_cp_refs_in_stack_map_table(
3001 const methodHandle& method, TRAPS) {
3002
3003 if (!method->has_stackmap_table()) {
3004 return;
3005 }
3006
3007 AnnotationArray* stackmap_data = method->stackmap_data();
3008 address stackmap_p = (address)stackmap_data->adr_at(0);
3009 address stackmap_end = stackmap_p + stackmap_data->length();
3010
3011 assert(stackmap_p + 2 <= stackmap_end, "no room for number_of_entries");
3012 u2 number_of_entries = Bytes::get_Java_u2(stackmap_p);
3013 stackmap_p += 2;
3014
3015 log_debug(redefine, class, stackmap)("number_of_entries=%u", number_of_entries);
3016
3017 // walk through each stack_map_frame
3018 u2 calc_number_of_entries = 0;
3019 for (; calc_number_of_entries < number_of_entries; calc_number_of_entries++) {
3020 // The stack_map_frame structure is a u1 frame_type followed by
3021 // 0 or more bytes of data:
3022 //
3023 // union stack_map_frame {
3024 // same_frame;
3025 // same_locals_1_stack_item_frame;
3026 // same_locals_1_stack_item_frame_extended;
3027 // chop_frame;
3028 // same_frame_extended;
3029 // append_frame;
3030 // full_frame;
3031 // }
3032
3033 assert(stackmap_p + 1 <= stackmap_end, "no room for frame_type");
3034 u1 frame_type = *stackmap_p;
3035 stackmap_p++;
3036
3037 // same_frame {
3038 // u1 frame_type = SAME; /* 0-63 */
3039 // }
3040 if (frame_type <= 63) {
3041 // nothing more to do for same_frame
3042 }
3043
3044 // same_locals_1_stack_item_frame {
3045 // u1 frame_type = SAME_LOCALS_1_STACK_ITEM; /* 64-127 */
3046 // verification_type_info stack[1];
3047 // }
3048 else if (frame_type >= 64 && frame_type <= 127) {
3049 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3050 calc_number_of_entries, frame_type, THREAD);
3051 }
3052
3053 // reserved for future use
3054 else if (frame_type >= 128 && frame_type <= 246) {
3055 // nothing more to do for reserved frame_types
3056 }
3057
3058 // same_locals_1_stack_item_frame_extended {
3059 // u1 frame_type = SAME_LOCALS_1_STACK_ITEM_EXTENDED; /* 247 */
3060 // u2 offset_delta;
3061 // verification_type_info stack[1];
3062 // }
3063 else if (frame_type == 247) {
3064 stackmap_p += 2;
3065 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3066 calc_number_of_entries, frame_type, THREAD);
3067 }
3068
3069 // chop_frame {
3070 // u1 frame_type = CHOP; /* 248-250 */
3071 // u2 offset_delta;
3072 // }
3073 else if (frame_type >= 248 && frame_type <= 250) {
3074 stackmap_p += 2;
3075 }
3076
3077 // same_frame_extended {
3078 // u1 frame_type = SAME_FRAME_EXTENDED; /* 251*/
3079 // u2 offset_delta;
3080 // }
3081 else if (frame_type == 251) {
3082 stackmap_p += 2;
3083 }
3084
3085 // append_frame {
3086 // u1 frame_type = APPEND; /* 252-254 */
3087 // u2 offset_delta;
3088 // verification_type_info locals[frame_type - 251];
3089 // }
3090 else if (frame_type >= 252 && frame_type <= 254) {
3091 assert(stackmap_p + 2 <= stackmap_end,
3092 "no room for offset_delta");
3093 stackmap_p += 2;
3094 u1 len = frame_type - 251;
3095 for (u1 i = 0; i < len; i++) {
3096 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3097 calc_number_of_entries, frame_type, THREAD);
3098 }
3099 }
3100
3101 // full_frame {
3102 // u1 frame_type = FULL_FRAME; /* 255 */
3103 // u2 offset_delta;
3104 // u2 number_of_locals;
3105 // verification_type_info locals[number_of_locals];
3106 // u2 number_of_stack_items;
3107 // verification_type_info stack[number_of_stack_items];
3108 // }
3109 else if (frame_type == 255) {
3110 assert(stackmap_p + 2 + 2 <= stackmap_end,
3111 "no room for smallest full_frame");
3112 stackmap_p += 2;
3113
3114 u2 number_of_locals = Bytes::get_Java_u2(stackmap_p);
3115 stackmap_p += 2;
3116
3117 for (u2 locals_i = 0; locals_i < number_of_locals; locals_i++) {
3118 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3119 calc_number_of_entries, frame_type, THREAD);
3120 }
3121
3122 // Use the largest size for the number_of_stack_items, but only get
3123 // the right number of bytes.
3124 u2 number_of_stack_items = Bytes::get_Java_u2(stackmap_p);
3125 stackmap_p += 2;
3126
3127 for (u2 stack_i = 0; stack_i < number_of_stack_items; stack_i++) {
3128 rewrite_cp_refs_in_verification_type_info(stackmap_p, stackmap_end,
3129 calc_number_of_entries, frame_type, THREAD);
3130 }
3131 }
3132 } // end while there is a stack_map_frame
3133 assert(number_of_entries == calc_number_of_entries, "sanity check");
3134 } // end rewrite_cp_refs_in_stack_map_table()
3135
3136
3137 // Rewrite constant pool references in the verification type info
3138 // portion of the method's stackmap table. These "structures" are
3139 // adapted from the StackMapTable_attribute that is described in
3140 // section 4.8.4 of the 6.0 version of the VM spec (dated 2005.10.26):
3141 // file:///net/quincunx.sfbay/export/gbracha/ClassFile-Java6.pdf
3142 //
3143 // The verification_type_info structure is a u1 tag followed by 0 or
3144 // more bytes of data:
3145 //
3146 // union verification_type_info {
3147 // Top_variable_info;
3148 // Integer_variable_info;
3149 // Float_variable_info;
3150 // Long_variable_info;
3151 // Double_variable_info;
3152 // Null_variable_info;
3153 // UninitializedThis_variable_info;
3154 // Object_variable_info;
3155 // Uninitialized_variable_info;
3156 // }
3157 //
rewrite_cp_refs_in_verification_type_info(address & stackmap_p_ref,address stackmap_end,u2 frame_i,u1 frame_type,TRAPS)3158 void VM_RedefineClasses::rewrite_cp_refs_in_verification_type_info(
3159 address& stackmap_p_ref, address stackmap_end, u2 frame_i,
3160 u1 frame_type, TRAPS) {
3161
3162 assert(stackmap_p_ref + 1 <= stackmap_end, "no room for tag");
3163 u1 tag = *stackmap_p_ref;
3164 stackmap_p_ref++;
3165
3166 switch (tag) {
3167 // Top_variable_info {
3168 // u1 tag = ITEM_Top; /* 0 */
3169 // }
3170 // verificationType.hpp has zero as ITEM_Bogus instead of ITEM_Top
3171 case 0: // fall through
3172
3173 // Integer_variable_info {
3174 // u1 tag = ITEM_Integer; /* 1 */
3175 // }
3176 case ITEM_Integer: // fall through
3177
3178 // Float_variable_info {
3179 // u1 tag = ITEM_Float; /* 2 */
3180 // }
3181 case ITEM_Float: // fall through
3182
3183 // Double_variable_info {
3184 // u1 tag = ITEM_Double; /* 3 */
3185 // }
3186 case ITEM_Double: // fall through
3187
3188 // Long_variable_info {
3189 // u1 tag = ITEM_Long; /* 4 */
3190 // }
3191 case ITEM_Long: // fall through
3192
3193 // Null_variable_info {
3194 // u1 tag = ITEM_Null; /* 5 */
3195 // }
3196 case ITEM_Null: // fall through
3197
3198 // UninitializedThis_variable_info {
3199 // u1 tag = ITEM_UninitializedThis; /* 6 */
3200 // }
3201 case ITEM_UninitializedThis:
3202 // nothing more to do for the above tag types
3203 break;
3204
3205 // Object_variable_info {
3206 // u1 tag = ITEM_Object; /* 7 */
3207 // u2 cpool_index;
3208 // }
3209 case ITEM_Object:
3210 {
3211 assert(stackmap_p_ref + 2 <= stackmap_end, "no room for cpool_index");
3212 u2 cpool_index = Bytes::get_Java_u2(stackmap_p_ref);
3213 u2 new_cp_index = find_new_index(cpool_index);
3214 if (new_cp_index != 0) {
3215 log_debug(redefine, class, stackmap)("mapped old cpool_index=%d", cpool_index);
3216 Bytes::put_Java_u2(stackmap_p_ref, new_cp_index);
3217 cpool_index = new_cp_index;
3218 }
3219 stackmap_p_ref += 2;
3220
3221 log_debug(redefine, class, stackmap)
3222 ("frame_i=%u, frame_type=%u, cpool_index=%d", frame_i, frame_type, cpool_index);
3223 } break;
3224
3225 // Uninitialized_variable_info {
3226 // u1 tag = ITEM_Uninitialized; /* 8 */
3227 // u2 offset;
3228 // }
3229 case ITEM_Uninitialized:
3230 assert(stackmap_p_ref + 2 <= stackmap_end, "no room for offset");
3231 stackmap_p_ref += 2;
3232 break;
3233
3234 default:
3235 log_debug(redefine, class, stackmap)("frame_i=%u, frame_type=%u, bad tag=0x%x", frame_i, frame_type, tag);
3236 ShouldNotReachHere();
3237 break;
3238 } // end switch (tag)
3239 } // end rewrite_cp_refs_in_verification_type_info()
3240
3241
3242 // Change the constant pool associated with klass scratch_class to
3243 // scratch_cp. If shrink is true, then scratch_cp_length elements
3244 // are copied from scratch_cp to a smaller constant pool and the
3245 // smaller constant pool is associated with scratch_class.
set_new_constant_pool(ClassLoaderData * loader_data,InstanceKlass * scratch_class,constantPoolHandle scratch_cp,int scratch_cp_length,TRAPS)3246 void VM_RedefineClasses::set_new_constant_pool(
3247 ClassLoaderData* loader_data,
3248 InstanceKlass* scratch_class, constantPoolHandle scratch_cp,
3249 int scratch_cp_length, TRAPS) {
3250 assert(scratch_cp->length() >= scratch_cp_length, "sanity check");
3251
3252 // scratch_cp is a merged constant pool and has enough space for a
3253 // worst case merge situation. We want to associate the minimum
3254 // sized constant pool with the klass to save space.
3255 ConstantPool* cp = ConstantPool::allocate(loader_data, scratch_cp_length, CHECK);
3256 constantPoolHandle smaller_cp(THREAD, cp);
3257
3258 // preserve version() value in the smaller copy
3259 int version = scratch_cp->version();
3260 assert(version != 0, "sanity check");
3261 smaller_cp->set_version(version);
3262
3263 // attach klass to new constant pool
3264 // reference to the cp holder is needed for copy_operands()
3265 smaller_cp->set_pool_holder(scratch_class);
3266
3267 if (scratch_cp->has_dynamic_constant()) {
3268 smaller_cp->set_has_dynamic_constant();
3269 }
3270
3271 scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
3272 if (HAS_PENDING_EXCEPTION) {
3273 // Exception is handled in the caller
3274 loader_data->add_to_deallocate_list(smaller_cp());
3275 return;
3276 }
3277 scratch_cp = smaller_cp;
3278
3279 // attach new constant pool to klass
3280 scratch_class->set_constants(scratch_cp());
3281 scratch_cp->initialize_unresolved_klasses(loader_data, CHECK);
3282
3283 int i; // for portability
3284
3285 // update each field in klass to use new constant pool indices as needed
3286 for (JavaFieldStream fs(scratch_class); !fs.done(); fs.next()) {
3287 jshort cur_index = fs.name_index();
3288 jshort new_index = find_new_index(cur_index);
3289 if (new_index != 0) {
3290 log_trace(redefine, class, constantpool)("field-name_index change: %d to %d", cur_index, new_index);
3291 fs.set_name_index(new_index);
3292 }
3293 cur_index = fs.signature_index();
3294 new_index = find_new_index(cur_index);
3295 if (new_index != 0) {
3296 log_trace(redefine, class, constantpool)("field-signature_index change: %d to %d", cur_index, new_index);
3297 fs.set_signature_index(new_index);
3298 }
3299 cur_index = fs.initval_index();
3300 new_index = find_new_index(cur_index);
3301 if (new_index != 0) {
3302 log_trace(redefine, class, constantpool)("field-initval_index change: %d to %d", cur_index, new_index);
3303 fs.set_initval_index(new_index);
3304 }
3305 cur_index = fs.generic_signature_index();
3306 new_index = find_new_index(cur_index);
3307 if (new_index != 0) {
3308 log_trace(redefine, class, constantpool)("field-generic_signature change: %d to %d", cur_index, new_index);
3309 fs.set_generic_signature_index(new_index);
3310 }
3311 } // end for each field
3312
3313 // Update constant pool indices in the inner classes info to use
3314 // new constant indices as needed. The inner classes info is a
3315 // quadruple:
3316 // (inner_class_info, outer_class_info, inner_name, inner_access_flags)
3317 InnerClassesIterator iter(scratch_class);
3318 for (; !iter.done(); iter.next()) {
3319 int cur_index = iter.inner_class_info_index();
3320 if (cur_index == 0) {
3321 continue; // JVM spec. allows null inner class refs so skip it
3322 }
3323 int new_index = find_new_index(cur_index);
3324 if (new_index != 0) {
3325 log_trace(redefine, class, constantpool)("inner_class_info change: %d to %d", cur_index, new_index);
3326 iter.set_inner_class_info_index(new_index);
3327 }
3328 cur_index = iter.outer_class_info_index();
3329 new_index = find_new_index(cur_index);
3330 if (new_index != 0) {
3331 log_trace(redefine, class, constantpool)("outer_class_info change: %d to %d", cur_index, new_index);
3332 iter.set_outer_class_info_index(new_index);
3333 }
3334 cur_index = iter.inner_name_index();
3335 new_index = find_new_index(cur_index);
3336 if (new_index != 0) {
3337 log_trace(redefine, class, constantpool)("inner_name change: %d to %d", cur_index, new_index);
3338 iter.set_inner_name_index(new_index);
3339 }
3340 } // end for each inner class
3341
3342 // Attach each method in klass to the new constant pool and update
3343 // to use new constant pool indices as needed:
3344 Array<Method*>* methods = scratch_class->methods();
3345 for (i = methods->length() - 1; i >= 0; i--) {
3346 methodHandle method(THREAD, methods->at(i));
3347 method->set_constants(scratch_cp());
3348
3349 int new_index = find_new_index(method->name_index());
3350 if (new_index != 0) {
3351 log_trace(redefine, class, constantpool)
3352 ("method-name_index change: %d to %d", method->name_index(), new_index);
3353 method->set_name_index(new_index);
3354 }
3355 new_index = find_new_index(method->signature_index());
3356 if (new_index != 0) {
3357 log_trace(redefine, class, constantpool)
3358 ("method-signature_index change: %d to %d", method->signature_index(), new_index);
3359 method->set_signature_index(new_index);
3360 }
3361 new_index = find_new_index(method->generic_signature_index());
3362 if (new_index != 0) {
3363 log_trace(redefine, class, constantpool)
3364 ("method-generic_signature_index change: %d to %d", method->generic_signature_index(), new_index);
3365 method->set_generic_signature_index(new_index);
3366 }
3367
3368 // Update constant pool indices in the method's checked exception
3369 // table to use new constant indices as needed.
3370 int cext_length = method->checked_exceptions_length();
3371 if (cext_length > 0) {
3372 CheckedExceptionElement * cext_table =
3373 method->checked_exceptions_start();
3374 for (int j = 0; j < cext_length; j++) {
3375 int cur_index = cext_table[j].class_cp_index;
3376 int new_index = find_new_index(cur_index);
3377 if (new_index != 0) {
3378 log_trace(redefine, class, constantpool)("cext-class_cp_index change: %d to %d", cur_index, new_index);
3379 cext_table[j].class_cp_index = (u2)new_index;
3380 }
3381 } // end for each checked exception table entry
3382 } // end if there are checked exception table entries
3383
3384 // Update each catch type index in the method's exception table
3385 // to use new constant pool indices as needed. The exception table
3386 // holds quadruple entries of the form:
3387 // (beg_bci, end_bci, handler_bci, klass_index)
3388
3389 ExceptionTable ex_table(method());
3390 int ext_length = ex_table.length();
3391
3392 for (int j = 0; j < ext_length; j ++) {
3393 int cur_index = ex_table.catch_type_index(j);
3394 int new_index = find_new_index(cur_index);
3395 if (new_index != 0) {
3396 log_trace(redefine, class, constantpool)("ext-klass_index change: %d to %d", cur_index, new_index);
3397 ex_table.set_catch_type_index(j, new_index);
3398 }
3399 } // end for each exception table entry
3400
3401 // Update constant pool indices in the method's local variable
3402 // table to use new constant indices as needed. The local variable
3403 // table hold sextuple entries of the form:
3404 // (start_pc, length, name_index, descriptor_index, signature_index, slot)
3405 int lvt_length = method->localvariable_table_length();
3406 if (lvt_length > 0) {
3407 LocalVariableTableElement * lv_table =
3408 method->localvariable_table_start();
3409 for (int j = 0; j < lvt_length; j++) {
3410 int cur_index = lv_table[j].name_cp_index;
3411 int new_index = find_new_index(cur_index);
3412 if (new_index != 0) {
3413 log_trace(redefine, class, constantpool)("lvt-name_cp_index change: %d to %d", cur_index, new_index);
3414 lv_table[j].name_cp_index = (u2)new_index;
3415 }
3416 cur_index = lv_table[j].descriptor_cp_index;
3417 new_index = find_new_index(cur_index);
3418 if (new_index != 0) {
3419 log_trace(redefine, class, constantpool)("lvt-descriptor_cp_index change: %d to %d", cur_index, new_index);
3420 lv_table[j].descriptor_cp_index = (u2)new_index;
3421 }
3422 cur_index = lv_table[j].signature_cp_index;
3423 new_index = find_new_index(cur_index);
3424 if (new_index != 0) {
3425 log_trace(redefine, class, constantpool)("lvt-signature_cp_index change: %d to %d", cur_index, new_index);
3426 lv_table[j].signature_cp_index = (u2)new_index;
3427 }
3428 } // end for each local variable table entry
3429 } // end if there are local variable table entries
3430
3431 rewrite_cp_refs_in_stack_map_table(method, THREAD);
3432 } // end for each method
3433 } // end set_new_constant_pool()
3434
3435
3436 // Unevolving classes may point to methods of the_class directly
3437 // from their constant pool caches, itables, and/or vtables. We
3438 // use the ClassLoaderDataGraph::classes_do() facility and this helper
3439 // to fix up these pointers. MethodData also points to old methods and
3440 // must be cleaned.
3441
3442 // Adjust cpools and vtables closure
do_klass(Klass * k)3443 void VM_RedefineClasses::AdjustAndCleanMetadata::do_klass(Klass* k) {
3444
3445 // This is a very busy routine. We don't want too much tracing
3446 // printed out.
3447 bool trace_name_printed = false;
3448
3449 // If the class being redefined is java.lang.Object, we need to fix all
3450 // array class vtables also
3451 if (k->is_array_klass() && _has_redefined_Object) {
3452 k->vtable().adjust_method_entries(&trace_name_printed);
3453
3454 } else if (k->is_instance_klass()) {
3455 HandleMark hm(_thread);
3456 InstanceKlass *ik = InstanceKlass::cast(k);
3457
3458 // Clean MethodData of this class's methods so they don't refer to
3459 // old methods that are no longer running.
3460 Array<Method*>* methods = ik->methods();
3461 int num_methods = methods->length();
3462 for (int index = 0; index < num_methods; ++index) {
3463 if (methods->at(index)->method_data() != NULL) {
3464 methods->at(index)->method_data()->clean_weak_method_links();
3465 }
3466 }
3467
3468 // HotSpot specific optimization! HotSpot does not currently
3469 // support delegation from the bootstrap class loader to a
3470 // user-defined class loader. This means that if the bootstrap
3471 // class loader is the initiating class loader, then it will also
3472 // be the defining class loader. This also means that classes
3473 // loaded by the bootstrap class loader cannot refer to classes
3474 // loaded by a user-defined class loader. Note: a user-defined
3475 // class loader can delegate to the bootstrap class loader.
3476 //
3477 // If the current class being redefined has a user-defined class
3478 // loader as its defining class loader, then we can skip all
3479 // classes loaded by the bootstrap class loader.
3480 if (!_has_null_class_loader && ik->class_loader() == NULL) {
3481 return;
3482 }
3483
3484 // Adjust all vtables, default methods and itables, to clean out old methods.
3485 ResourceMark rm(_thread);
3486 if (ik->vtable_length() > 0) {
3487 ik->vtable().adjust_method_entries(&trace_name_printed);
3488 ik->adjust_default_methods(&trace_name_printed);
3489 }
3490
3491 if (ik->itable_length() > 0) {
3492 ik->itable().adjust_method_entries(&trace_name_printed);
3493 }
3494
3495 // The constant pools in other classes (other_cp) can refer to
3496 // old methods. We have to update method information in
3497 // other_cp's cache. If other_cp has a previous version, then we
3498 // have to repeat the process for each previous version. The
3499 // constant pool cache holds the Method*s for non-virtual
3500 // methods and for virtual, final methods.
3501 //
3502 // Special case: if the current class being redefined, then new_cp
3503 // has already been attached to the_class and old_cp has already
3504 // been added as a previous version. The new_cp doesn't have any
3505 // cached references to old methods so it doesn't need to be
3506 // updated. We can simply start with the previous version(s) in
3507 // that case.
3508 constantPoolHandle other_cp;
3509 ConstantPoolCache* cp_cache;
3510
3511 if (!ik->is_being_redefined()) {
3512 // this klass' constant pool cache may need adjustment
3513 other_cp = constantPoolHandle(ik->constants());
3514 cp_cache = other_cp->cache();
3515 if (cp_cache != NULL) {
3516 cp_cache->adjust_method_entries(&trace_name_printed);
3517 }
3518 }
3519
3520 // the previous versions' constant pool caches may need adjustment
3521 for (InstanceKlass* pv_node = ik->previous_versions();
3522 pv_node != NULL;
3523 pv_node = pv_node->previous_versions()) {
3524 cp_cache = pv_node->constants()->cache();
3525 if (cp_cache != NULL) {
3526 cp_cache->adjust_method_entries(&trace_name_printed);
3527 }
3528 }
3529 }
3530 }
3531
update_jmethod_ids()3532 void VM_RedefineClasses::update_jmethod_ids() {
3533 for (int j = 0; j < _matching_methods_length; ++j) {
3534 Method* old_method = _matching_old_methods[j];
3535 jmethodID jmid = old_method->find_jmethod_id_or_null();
3536 if (jmid != NULL) {
3537 // There is a jmethodID, change it to point to the new method
3538 methodHandle new_method_h(_matching_new_methods[j]);
3539 Method::change_method_associated_with_jmethod_id(jmid, new_method_h());
3540 assert(Method::resolve_jmethod_id(jmid) == _matching_new_methods[j],
3541 "should be replaced");
3542 }
3543 }
3544 // Update deleted jmethodID
3545 for (int j = 0; j < _deleted_methods_length; ++j) {
3546 Method* old_method = _deleted_methods[j];
3547 jmethodID jmid = old_method->find_jmethod_id_or_null();
3548 if (jmid != NULL) {
3549 // Change the jmethodID to point to NSME.
3550 Method::change_method_associated_with_jmethod_id(jmid, Universe::throw_no_such_method_error());
3551 }
3552 }
3553 }
3554
check_methods_and_mark_as_obsolete()3555 int VM_RedefineClasses::check_methods_and_mark_as_obsolete() {
3556 int emcp_method_count = 0;
3557 int obsolete_count = 0;
3558 int old_index = 0;
3559 for (int j = 0; j < _matching_methods_length; ++j, ++old_index) {
3560 Method* old_method = _matching_old_methods[j];
3561 Method* new_method = _matching_new_methods[j];
3562 Method* old_array_method;
3563
3564 // Maintain an old_index into the _old_methods array by skipping
3565 // deleted methods
3566 while ((old_array_method = _old_methods->at(old_index)) != old_method) {
3567 ++old_index;
3568 }
3569
3570 if (MethodComparator::methods_EMCP(old_method, new_method)) {
3571 // The EMCP definition from JSR-163 requires the bytecodes to be
3572 // the same with the exception of constant pool indices which may
3573 // differ. However, the constants referred to by those indices
3574 // must be the same.
3575 //
3576 // We use methods_EMCP() for comparison since constant pool
3577 // merging can remove duplicate constant pool entries that were
3578 // present in the old method and removed from the rewritten new
3579 // method. A faster binary comparison function would consider the
3580 // old and new methods to be different when they are actually
3581 // EMCP.
3582 //
3583 // The old and new methods are EMCP and you would think that we
3584 // could get rid of one of them here and now and save some space.
3585 // However, the concept of EMCP only considers the bytecodes and
3586 // the constant pool entries in the comparison. Other things,
3587 // e.g., the line number table (LNT) or the local variable table
3588 // (LVT) don't count in the comparison. So the new (and EMCP)
3589 // method can have a new LNT that we need so we can't just
3590 // overwrite the new method with the old method.
3591 //
3592 // When this routine is called, we have already attached the new
3593 // methods to the_class so the old methods are effectively
3594 // overwritten. However, if an old method is still executing,
3595 // then the old method cannot be collected until sometime after
3596 // the old method call has returned. So the overwriting of old
3597 // methods by new methods will save us space except for those
3598 // (hopefully few) old methods that are still executing.
3599 //
3600 // A method refers to a ConstMethod* and this presents another
3601 // possible avenue to space savings. The ConstMethod* in the
3602 // new method contains possibly new attributes (LNT, LVT, etc).
3603 // At first glance, it seems possible to save space by replacing
3604 // the ConstMethod* in the old method with the ConstMethod*
3605 // from the new method. The old and new methods would share the
3606 // same ConstMethod* and we would save the space occupied by
3607 // the old ConstMethod*. However, the ConstMethod* contains
3608 // a back reference to the containing method. Sharing the
3609 // ConstMethod* between two methods could lead to confusion in
3610 // the code that uses the back reference. This would lead to
3611 // brittle code that could be broken in non-obvious ways now or
3612 // in the future.
3613 //
3614 // Another possibility is to copy the ConstMethod* from the new
3615 // method to the old method and then overwrite the new method with
3616 // the old method. Since the ConstMethod* contains the bytecodes
3617 // for the method embedded in the oop, this option would change
3618 // the bytecodes out from under any threads executing the old
3619 // method and make the thread's bcp invalid. Since EMCP requires
3620 // that the bytecodes be the same modulo constant pool indices, it
3621 // is straight forward to compute the correct new bcp in the new
3622 // ConstMethod* from the old bcp in the old ConstMethod*. The
3623 // time consuming part would be searching all the frames in all
3624 // of the threads to find all of the calls to the old method.
3625 //
3626 // It looks like we will have to live with the limited savings
3627 // that we get from effectively overwriting the old methods
3628 // when the new methods are attached to the_class.
3629
3630 // Count number of methods that are EMCP. The method will be marked
3631 // old but not obsolete if it is EMCP.
3632 emcp_method_count++;
3633
3634 // An EMCP method is _not_ obsolete. An obsolete method has a
3635 // different jmethodID than the current method. An EMCP method
3636 // has the same jmethodID as the current method. Having the
3637 // same jmethodID for all EMCP versions of a method allows for
3638 // a consistent view of the EMCP methods regardless of which
3639 // EMCP method you happen to have in hand. For example, a
3640 // breakpoint set in one EMCP method will work for all EMCP
3641 // versions of the method including the current one.
3642 } else {
3643 // mark obsolete methods as such
3644 old_method->set_is_obsolete();
3645 obsolete_count++;
3646
3647 // obsolete methods need a unique idnum so they become new entries in
3648 // the jmethodID cache in InstanceKlass
3649 assert(old_method->method_idnum() == new_method->method_idnum(), "must match");
3650 u2 num = InstanceKlass::cast(_the_class)->next_method_idnum();
3651 if (num != ConstMethod::UNSET_IDNUM) {
3652 old_method->set_method_idnum(num);
3653 }
3654
3655 // With tracing we try not to "yack" too much. The position of
3656 // this trace assumes there are fewer obsolete methods than
3657 // EMCP methods.
3658 if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3659 ResourceMark rm;
3660 log_trace(redefine, class, obsolete, mark)
3661 ("mark %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3662 }
3663 }
3664 old_method->set_is_old();
3665 }
3666 for (int i = 0; i < _deleted_methods_length; ++i) {
3667 Method* old_method = _deleted_methods[i];
3668
3669 assert(!old_method->has_vtable_index(),
3670 "cannot delete methods with vtable entries");;
3671
3672 // Mark all deleted methods as old, obsolete and deleted
3673 old_method->set_is_deleted();
3674 old_method->set_is_old();
3675 old_method->set_is_obsolete();
3676 ++obsolete_count;
3677 // With tracing we try not to "yack" too much. The position of
3678 // this trace assumes there are fewer obsolete methods than
3679 // EMCP methods.
3680 if (log_is_enabled(Trace, redefine, class, obsolete, mark)) {
3681 ResourceMark rm;
3682 log_trace(redefine, class, obsolete, mark)
3683 ("mark deleted %s(%s) as obsolete", old_method->name()->as_C_string(), old_method->signature()->as_C_string());
3684 }
3685 }
3686 assert((emcp_method_count + obsolete_count) == _old_methods->length(),
3687 "sanity check");
3688 log_trace(redefine, class, obsolete, mark)("EMCP_cnt=%d, obsolete_cnt=%d", emcp_method_count, obsolete_count);
3689 return emcp_method_count;
3690 }
3691
3692 // This internal class transfers the native function registration from old methods
3693 // to new methods. It is designed to handle both the simple case of unchanged
3694 // native methods and the complex cases of native method prefixes being added and/or
3695 // removed.
3696 // It expects only to be used during the VM_RedefineClasses op (a safepoint).
3697 //
3698 // This class is used after the new methods have been installed in "the_class".
3699 //
3700 // So, for example, the following must be handled. Where 'm' is a method and
3701 // a number followed by an underscore is a prefix.
3702 //
3703 // Old Name New Name
3704 // Simple transfer to new method m -> m
3705 // Add prefix m -> 1_m
3706 // Remove prefix 1_m -> m
3707 // Simultaneous add of prefixes m -> 3_2_1_m
3708 // Simultaneous removal of prefixes 3_2_1_m -> m
3709 // Simultaneous add and remove 1_m -> 2_m
3710 // Same, caused by prefix removal only 3_2_1_m -> 3_2_m
3711 //
3712 class TransferNativeFunctionRegistration {
3713 private:
3714 InstanceKlass* the_class;
3715 int prefix_count;
3716 char** prefixes;
3717
3718 // Recursively search the binary tree of possibly prefixed method names.
3719 // Iteration could be used if all agents were well behaved. Full tree walk is
3720 // more resilent to agents not cleaning up intermediate methods.
3721 // Branch at each depth in the binary tree is:
3722 // (1) without the prefix.
3723 // (2) with the prefix.
3724 // where 'prefix' is the prefix at that 'depth' (first prefix, second prefix,...)
search_prefix_name_space(int depth,char * name_str,size_t name_len,Symbol * signature)3725 Method* search_prefix_name_space(int depth, char* name_str, size_t name_len,
3726 Symbol* signature) {
3727 TempNewSymbol name_symbol = SymbolTable::probe(name_str, (int)name_len);
3728 if (name_symbol != NULL) {
3729 Method* method = the_class->lookup_method(name_symbol, signature);
3730 if (method != NULL) {
3731 // Even if prefixed, intermediate methods must exist.
3732 if (method->is_native()) {
3733 // Wahoo, we found a (possibly prefixed) version of the method, return it.
3734 return method;
3735 }
3736 if (depth < prefix_count) {
3737 // Try applying further prefixes (other than this one).
3738 method = search_prefix_name_space(depth+1, name_str, name_len, signature);
3739 if (method != NULL) {
3740 return method; // found
3741 }
3742
3743 // Try adding this prefix to the method name and see if it matches
3744 // another method name.
3745 char* prefix = prefixes[depth];
3746 size_t prefix_len = strlen(prefix);
3747 size_t trial_len = name_len + prefix_len;
3748 char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
3749 strcpy(trial_name_str, prefix);
3750 strcat(trial_name_str, name_str);
3751 method = search_prefix_name_space(depth+1, trial_name_str, trial_len,
3752 signature);
3753 if (method != NULL) {
3754 // If found along this branch, it was prefixed, mark as such
3755 method->set_is_prefixed_native();
3756 return method; // found
3757 }
3758 }
3759 }
3760 }
3761 return NULL; // This whole branch bore nothing
3762 }
3763
3764 // Return the method name with old prefixes stripped away.
method_name_without_prefixes(Method * method)3765 char* method_name_without_prefixes(Method* method) {
3766 Symbol* name = method->name();
3767 char* name_str = name->as_utf8();
3768
3769 // Old prefixing may be defunct, strip prefixes, if any.
3770 for (int i = prefix_count-1; i >= 0; i--) {
3771 char* prefix = prefixes[i];
3772 size_t prefix_len = strlen(prefix);
3773 if (strncmp(prefix, name_str, prefix_len) == 0) {
3774 name_str += prefix_len;
3775 }
3776 }
3777 return name_str;
3778 }
3779
3780 // Strip any prefixes off the old native method, then try to find a
3781 // (possibly prefixed) new native that matches it.
strip_and_search_for_new_native(Method * method)3782 Method* strip_and_search_for_new_native(Method* method) {
3783 ResourceMark rm;
3784 char* name_str = method_name_without_prefixes(method);
3785 return search_prefix_name_space(0, name_str, strlen(name_str),
3786 method->signature());
3787 }
3788
3789 public:
3790
3791 // Construct a native method transfer processor for this class.
TransferNativeFunctionRegistration(InstanceKlass * _the_class)3792 TransferNativeFunctionRegistration(InstanceKlass* _the_class) {
3793 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
3794
3795 the_class = _the_class;
3796 prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
3797 }
3798
3799 // Attempt to transfer any of the old or deleted methods that are native
transfer_registrations(Method ** old_methods,int methods_length)3800 void transfer_registrations(Method** old_methods, int methods_length) {
3801 for (int j = 0; j < methods_length; j++) {
3802 Method* old_method = old_methods[j];
3803
3804 if (old_method->is_native() && old_method->has_native_function()) {
3805 Method* new_method = strip_and_search_for_new_native(old_method);
3806 if (new_method != NULL) {
3807 // Actually set the native function in the new method.
3808 // Redefine does not send events (except CFLH), certainly not this
3809 // behind the scenes re-registration.
3810 new_method->set_native_function(old_method->native_function(),
3811 !Method::native_bind_event_is_interesting);
3812 }
3813 }
3814 }
3815 }
3816 };
3817
3818 // Don't lose the association between a native method and its JNI function.
transfer_old_native_function_registrations(InstanceKlass * the_class)3819 void VM_RedefineClasses::transfer_old_native_function_registrations(InstanceKlass* the_class) {
3820 TransferNativeFunctionRegistration transfer(the_class);
3821 transfer.transfer_registrations(_deleted_methods, _deleted_methods_length);
3822 transfer.transfer_registrations(_matching_old_methods, _matching_methods_length);
3823 }
3824
3825 // Deoptimize all compiled code that depends on this class.
3826 //
3827 // If the can_redefine_classes capability is obtained in the onload
3828 // phase then the compiler has recorded all dependencies from startup.
3829 // In that case we need only deoptimize and throw away all compiled code
3830 // that depends on the class.
3831 //
3832 // If can_redefine_classes is obtained sometime after the onload
3833 // phase then the dependency information may be incomplete. In that case
3834 // the first call to RedefineClasses causes all compiled code to be
3835 // thrown away. As can_redefine_classes has been obtained then
3836 // all future compilations will record dependencies so second and
3837 // subsequent calls to RedefineClasses need only throw away code
3838 // that depends on the class.
3839 //
3840
3841 // First step is to walk the code cache for each class redefined and mark
3842 // dependent methods. Wait until all classes are processed to deoptimize everything.
mark_dependent_code(InstanceKlass * ik)3843 void VM_RedefineClasses::mark_dependent_code(InstanceKlass* ik) {
3844 assert_locked_or_safepoint(Compile_lock);
3845
3846 // All dependencies have been recorded from startup or this is a second or
3847 // subsequent use of RedefineClasses
3848 if (JvmtiExport::all_dependencies_are_recorded()) {
3849 CodeCache::mark_for_evol_deoptimization(ik);
3850 }
3851 }
3852
flush_dependent_code()3853 void VM_RedefineClasses::flush_dependent_code() {
3854 assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
3855
3856 bool deopt_needed;
3857
3858 // This is the first redefinition, mark all the nmethods for deoptimization
3859 if (!JvmtiExport::all_dependencies_are_recorded()) {
3860 log_debug(redefine, class, nmethod)("Marked all nmethods for deopt");
3861 CodeCache::mark_all_nmethods_for_evol_deoptimization();
3862 deopt_needed = true;
3863 } else {
3864 int deopt = CodeCache::mark_dependents_for_evol_deoptimization();
3865 log_debug(redefine, class, nmethod)("Marked %d dependent nmethods for deopt", deopt);
3866 deopt_needed = (deopt != 0);
3867 }
3868
3869 if (deopt_needed) {
3870 CodeCache::flush_evol_dependents();
3871 }
3872
3873 // From now on we know that the dependency information is complete
3874 JvmtiExport::set_all_dependencies_are_recorded(true);
3875 }
3876
compute_added_deleted_matching_methods()3877 void VM_RedefineClasses::compute_added_deleted_matching_methods() {
3878 Method* old_method;
3879 Method* new_method;
3880
3881 _matching_old_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
3882 _matching_new_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
3883 _added_methods = NEW_RESOURCE_ARRAY(Method*, _new_methods->length());
3884 _deleted_methods = NEW_RESOURCE_ARRAY(Method*, _old_methods->length());
3885
3886 _matching_methods_length = 0;
3887 _deleted_methods_length = 0;
3888 _added_methods_length = 0;
3889
3890 int nj = 0;
3891 int oj = 0;
3892 while (true) {
3893 if (oj >= _old_methods->length()) {
3894 if (nj >= _new_methods->length()) {
3895 break; // we've looked at everything, done
3896 }
3897 // New method at the end
3898 new_method = _new_methods->at(nj);
3899 _added_methods[_added_methods_length++] = new_method;
3900 ++nj;
3901 } else if (nj >= _new_methods->length()) {
3902 // Old method, at the end, is deleted
3903 old_method = _old_methods->at(oj);
3904 _deleted_methods[_deleted_methods_length++] = old_method;
3905 ++oj;
3906 } else {
3907 old_method = _old_methods->at(oj);
3908 new_method = _new_methods->at(nj);
3909 if (old_method->name() == new_method->name()) {
3910 if (old_method->signature() == new_method->signature()) {
3911 _matching_old_methods[_matching_methods_length ] = old_method;
3912 _matching_new_methods[_matching_methods_length++] = new_method;
3913 ++nj;
3914 ++oj;
3915 } else {
3916 // added overloaded have already been moved to the end,
3917 // so this is a deleted overloaded method
3918 _deleted_methods[_deleted_methods_length++] = old_method;
3919 ++oj;
3920 }
3921 } else { // names don't match
3922 if (old_method->name()->fast_compare(new_method->name()) > 0) {
3923 // new method
3924 _added_methods[_added_methods_length++] = new_method;
3925 ++nj;
3926 } else {
3927 // deleted method
3928 _deleted_methods[_deleted_methods_length++] = old_method;
3929 ++oj;
3930 }
3931 }
3932 }
3933 }
3934 assert(_matching_methods_length + _deleted_methods_length == _old_methods->length(), "sanity");
3935 assert(_matching_methods_length + _added_methods_length == _new_methods->length(), "sanity");
3936 }
3937
3938
swap_annotations(InstanceKlass * the_class,InstanceKlass * scratch_class)3939 void VM_RedefineClasses::swap_annotations(InstanceKlass* the_class,
3940 InstanceKlass* scratch_class) {
3941 // Swap annotation fields values
3942 Annotations* old_annotations = the_class->annotations();
3943 the_class->set_annotations(scratch_class->annotations());
3944 scratch_class->set_annotations(old_annotations);
3945 }
3946
3947
3948 // Install the redefinition of a class:
3949 // - house keeping (flushing breakpoints and caches, deoptimizing
3950 // dependent compiled code)
3951 // - replacing parts in the_class with parts from scratch_class
3952 // - adding a weak reference to track the obsolete but interesting
3953 // parts of the_class
3954 // - adjusting constant pool caches and vtables in other classes
3955 // that refer to methods in the_class. These adjustments use the
3956 // ClassLoaderDataGraph::classes_do() facility which only allows
3957 // a helper method to be specified. The interesting parameters
3958 // that we would like to pass to the helper method are saved in
3959 // static global fields in the VM operation.
redefine_single_class(jclass the_jclass,InstanceKlass * scratch_class,TRAPS)3960 void VM_RedefineClasses::redefine_single_class(jclass the_jclass,
3961 InstanceKlass* scratch_class, TRAPS) {
3962
3963 HandleMark hm(THREAD); // make sure handles from this call are freed
3964
3965 if (log_is_enabled(Info, redefine, class, timer)) {
3966 _timer_rsc_phase1.start();
3967 }
3968
3969 InstanceKlass* the_class = get_ik(the_jclass);
3970
3971 // Set some flags to control and optimize adjusting method entries
3972 _has_redefined_Object |= the_class == SystemDictionary::Object_klass();
3973 _has_null_class_loader |= the_class->class_loader() == NULL;
3974
3975 // Remove all breakpoints in methods of this class
3976 JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
3977 jvmti_breakpoints.clearall_in_class_at_safepoint(the_class);
3978
3979 // Mark all compiled code that depends on this class
3980 mark_dependent_code(the_class);
3981
3982 _old_methods = the_class->methods();
3983 _new_methods = scratch_class->methods();
3984 _the_class = the_class;
3985 compute_added_deleted_matching_methods();
3986 update_jmethod_ids();
3987
3988 _any_class_has_resolved_methods = the_class->has_resolved_methods() || _any_class_has_resolved_methods;
3989
3990 // Attach new constant pool to the original klass. The original
3991 // klass still refers to the old constant pool (for now).
3992 scratch_class->constants()->set_pool_holder(the_class);
3993
3994 #if 0
3995 // In theory, with constant pool merging in place we should be able
3996 // to save space by using the new, merged constant pool in place of
3997 // the old constant pool(s). By "pool(s)" I mean the constant pool in
3998 // the klass version we are replacing now and any constant pool(s) in
3999 // previous versions of klass. Nice theory, doesn't work in practice.
4000 // When this code is enabled, even simple programs throw NullPointer
4001 // exceptions. I'm guessing that this is caused by some constant pool
4002 // cache difference between the new, merged constant pool and the
4003 // constant pool that was just being used by the klass. I'm keeping
4004 // this code around to archive the idea, but the code has to remain
4005 // disabled for now.
4006
4007 // Attach each old method to the new constant pool. This can be
4008 // done here since we are past the bytecode verification and
4009 // constant pool optimization phases.
4010 for (int i = _old_methods->length() - 1; i >= 0; i--) {
4011 Method* method = _old_methods->at(i);
4012 method->set_constants(scratch_class->constants());
4013 }
4014
4015 // NOTE: this doesn't work because you can redefine the same class in two
4016 // threads, each getting their own constant pool data appended to the
4017 // original constant pool. In order for the new methods to work when they
4018 // become old methods, they need to keep their updated copy of the constant pool.
4019
4020 {
4021 // walk all previous versions of the klass
4022 InstanceKlass *ik = the_class;
4023 PreviousVersionWalker pvw(ik);
4024 do {
4025 ik = pvw.next_previous_version();
4026 if (ik != NULL) {
4027
4028 // attach previous version of klass to the new constant pool
4029 ik->set_constants(scratch_class->constants());
4030
4031 // Attach each method in the previous version of klass to the
4032 // new constant pool
4033 Array<Method*>* prev_methods = ik->methods();
4034 for (int i = prev_methods->length() - 1; i >= 0; i--) {
4035 Method* method = prev_methods->at(i);
4036 method->set_constants(scratch_class->constants());
4037 }
4038 }
4039 } while (ik != NULL);
4040 }
4041 #endif
4042
4043 // Replace methods and constantpool
4044 the_class->set_methods(_new_methods);
4045 scratch_class->set_methods(_old_methods); // To prevent potential GCing of the old methods,
4046 // and to be able to undo operation easily.
4047
4048 Array<int>* old_ordering = the_class->method_ordering();
4049 the_class->set_method_ordering(scratch_class->method_ordering());
4050 scratch_class->set_method_ordering(old_ordering);
4051
4052 ConstantPool* old_constants = the_class->constants();
4053 the_class->set_constants(scratch_class->constants());
4054 scratch_class->set_constants(old_constants); // See the previous comment.
4055 #if 0
4056 // We are swapping the guts of "the new class" with the guts of "the
4057 // class". Since the old constant pool has just been attached to "the
4058 // new class", it seems logical to set the pool holder in the old
4059 // constant pool also. However, doing this will change the observable
4060 // class hierarchy for any old methods that are still executing. A
4061 // method can query the identity of its "holder" and this query uses
4062 // the method's constant pool link to find the holder. The change in
4063 // holding class from "the class" to "the new class" can confuse
4064 // things.
4065 //
4066 // Setting the old constant pool's holder will also cause
4067 // verification done during vtable initialization below to fail.
4068 // During vtable initialization, the vtable's class is verified to be
4069 // a subtype of the method's holder. The vtable's class is "the
4070 // class" and the method's holder is gotten from the constant pool
4071 // link in the method itself. For "the class"'s directly implemented
4072 // methods, the method holder is "the class" itself (as gotten from
4073 // the new constant pool). The check works fine in this case. The
4074 // check also works fine for methods inherited from super classes.
4075 //
4076 // Miranda methods are a little more complicated. A miranda method is
4077 // provided by an interface when the class implementing the interface
4078 // does not provide its own method. These interfaces are implemented
4079 // internally as an InstanceKlass. These special instanceKlasses
4080 // share the constant pool of the class that "implements" the
4081 // interface. By sharing the constant pool, the method holder of a
4082 // miranda method is the class that "implements" the interface. In a
4083 // non-redefine situation, the subtype check works fine. However, if
4084 // the old constant pool's pool holder is modified, then the check
4085 // fails because there is no class hierarchy relationship between the
4086 // vtable's class and "the new class".
4087
4088 old_constants->set_pool_holder(scratch_class());
4089 #endif
4090
4091 // track number of methods that are EMCP for add_previous_version() call below
4092 int emcp_method_count = check_methods_and_mark_as_obsolete();
4093 transfer_old_native_function_registrations(the_class);
4094
4095 // The class file bytes from before any retransformable agents mucked
4096 // with them was cached on the scratch class, move to the_class.
4097 // Note: we still want to do this if nothing needed caching since it
4098 // should get cleared in the_class too.
4099 if (the_class->get_cached_class_file() == 0) {
4100 // the_class doesn't have a cache yet so copy it
4101 the_class->set_cached_class_file(scratch_class->get_cached_class_file());
4102 }
4103 else if (scratch_class->get_cached_class_file() !=
4104 the_class->get_cached_class_file()) {
4105 // The same class can be present twice in the scratch classes list or there
4106 // are multiple concurrent RetransformClasses calls on different threads.
4107 // In such cases we have to deallocate scratch_class cached_class_file.
4108 os::free(scratch_class->get_cached_class_file());
4109 }
4110
4111 // NULL out in scratch class to not delete twice. The class to be redefined
4112 // always owns these bytes.
4113 scratch_class->set_cached_class_file(NULL);
4114
4115 // Replace inner_classes
4116 Array<u2>* old_inner_classes = the_class->inner_classes();
4117 the_class->set_inner_classes(scratch_class->inner_classes());
4118 scratch_class->set_inner_classes(old_inner_classes);
4119
4120 // Initialize the vtable and interface table after
4121 // methods have been rewritten
4122 // no exception should happen here since we explicitly
4123 // do not check loader constraints.
4124 // compare_and_normalize_class_versions has already checked:
4125 // - classloaders unchanged, signatures unchanged
4126 // - all instanceKlasses for redefined classes reused & contents updated
4127 the_class->vtable().initialize_vtable(false, THREAD);
4128 the_class->itable().initialize_itable(false, THREAD);
4129 assert(!HAS_PENDING_EXCEPTION || (THREAD->pending_exception()->is_a(SystemDictionary::ThreadDeath_klass())), "redefine exception");
4130
4131 // Leave arrays of jmethodIDs and itable index cache unchanged
4132
4133 // Copy the "source file name" attribute from new class version
4134 the_class->set_source_file_name_index(
4135 scratch_class->source_file_name_index());
4136
4137 // Copy the "source debug extension" attribute from new class version
4138 the_class->set_source_debug_extension(
4139 scratch_class->source_debug_extension(),
4140 scratch_class->source_debug_extension() == NULL ? 0 :
4141 (int)strlen(scratch_class->source_debug_extension()));
4142
4143 // Use of javac -g could be different in the old and the new
4144 if (scratch_class->access_flags().has_localvariable_table() !=
4145 the_class->access_flags().has_localvariable_table()) {
4146
4147 AccessFlags flags = the_class->access_flags();
4148 if (scratch_class->access_flags().has_localvariable_table()) {
4149 flags.set_has_localvariable_table();
4150 } else {
4151 flags.clear_has_localvariable_table();
4152 }
4153 the_class->set_access_flags(flags);
4154 }
4155
4156 swap_annotations(the_class, scratch_class);
4157
4158 // Replace minor version number of class file
4159 u2 old_minor_version = the_class->minor_version();
4160 the_class->set_minor_version(scratch_class->minor_version());
4161 scratch_class->set_minor_version(old_minor_version);
4162
4163 // Replace major version number of class file
4164 u2 old_major_version = the_class->major_version();
4165 the_class->set_major_version(scratch_class->major_version());
4166 scratch_class->set_major_version(old_major_version);
4167
4168 // Replace CP indexes for class and name+type of enclosing method
4169 u2 old_class_idx = the_class->enclosing_method_class_index();
4170 u2 old_method_idx = the_class->enclosing_method_method_index();
4171 the_class->set_enclosing_method_indices(
4172 scratch_class->enclosing_method_class_index(),
4173 scratch_class->enclosing_method_method_index());
4174 scratch_class->set_enclosing_method_indices(old_class_idx, old_method_idx);
4175
4176 // Replace fingerprint data
4177 the_class->set_has_passed_fingerprint_check(scratch_class->has_passed_fingerprint_check());
4178 the_class->store_fingerprint(scratch_class->get_stored_fingerprint());
4179
4180 the_class->set_has_been_redefined();
4181
4182 if (!the_class->should_be_initialized()) {
4183 // Class was already initialized, so AOT has only seen the original version.
4184 // We need to let AOT look at it again.
4185 AOTLoader::load_for_klass(the_class, THREAD);
4186 }
4187
4188 // keep track of previous versions of this class
4189 the_class->add_previous_version(scratch_class, emcp_method_count);
4190
4191 _timer_rsc_phase1.stop();
4192 if (log_is_enabled(Info, redefine, class, timer)) {
4193 _timer_rsc_phase2.start();
4194 }
4195
4196 if (the_class->oop_map_cache() != NULL) {
4197 // Flush references to any obsolete methods from the oop map cache
4198 // so that obsolete methods are not pinned.
4199 the_class->oop_map_cache()->flush_obsolete_entries();
4200 }
4201
4202 increment_class_counter((InstanceKlass *)the_class, THREAD);
4203 {
4204 ResourceMark rm(THREAD);
4205 // increment the classRedefinedCount field in the_class and in any
4206 // direct and indirect subclasses of the_class
4207 log_info(redefine, class, load)
4208 ("redefined name=%s, count=%d (avail_mem=" UINT64_FORMAT "K)",
4209 the_class->external_name(), java_lang_Class::classRedefinedCount(the_class->java_mirror()), os::available_memory() >> 10);
4210 Events::log_redefinition(THREAD, "redefined class name=%s, count=%d",
4211 the_class->external_name(),
4212 java_lang_Class::classRedefinedCount(the_class->java_mirror()));
4213
4214 }
4215 _timer_rsc_phase2.stop();
4216 } // end redefine_single_class()
4217
4218
4219 // Increment the classRedefinedCount field in the specific InstanceKlass
4220 // and in all direct and indirect subclasses.
increment_class_counter(InstanceKlass * ik,TRAPS)4221 void VM_RedefineClasses::increment_class_counter(InstanceKlass *ik, TRAPS) {
4222 oop class_mirror = ik->java_mirror();
4223 Klass* class_oop = java_lang_Class::as_Klass(class_mirror);
4224 int new_count = java_lang_Class::classRedefinedCount(class_mirror) + 1;
4225 java_lang_Class::set_classRedefinedCount(class_mirror, new_count);
4226
4227 if (class_oop != _the_class) {
4228 // _the_class count is printed at end of redefine_single_class()
4229 log_debug(redefine, class, subclass)("updated count in subclass=%s to %d", ik->external_name(), new_count);
4230 }
4231
4232 for (Klass *subk = ik->subklass(); subk != NULL;
4233 subk = subk->next_sibling()) {
4234 if (subk->is_instance_klass()) {
4235 // Only update instanceKlasses
4236 InstanceKlass *subik = InstanceKlass::cast(subk);
4237 // recursively do subclasses of the current subclass
4238 increment_class_counter(subik, THREAD);
4239 }
4240 }
4241 }
4242
do_klass(Klass * k)4243 void VM_RedefineClasses::CheckClass::do_klass(Klass* k) {
4244 bool no_old_methods = true; // be optimistic
4245
4246 // Both array and instance classes have vtables.
4247 // a vtable should never contain old or obsolete methods
4248 ResourceMark rm(_thread);
4249 if (k->vtable_length() > 0 &&
4250 !k->vtable().check_no_old_or_obsolete_entries()) {
4251 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4252 log_trace(redefine, class, obsolete, metadata)
4253 ("klassVtable::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4254 k->signature_name());
4255 k->vtable().dump_vtable();
4256 }
4257 no_old_methods = false;
4258 }
4259
4260 if (k->is_instance_klass()) {
4261 HandleMark hm(_thread);
4262 InstanceKlass *ik = InstanceKlass::cast(k);
4263
4264 // an itable should never contain old or obsolete methods
4265 if (ik->itable_length() > 0 &&
4266 !ik->itable().check_no_old_or_obsolete_entries()) {
4267 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4268 log_trace(redefine, class, obsolete, metadata)
4269 ("klassItable::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4270 ik->signature_name());
4271 ik->itable().dump_itable();
4272 }
4273 no_old_methods = false;
4274 }
4275
4276 // the constant pool cache should never contain non-deleted old or obsolete methods
4277 if (ik->constants() != NULL &&
4278 ik->constants()->cache() != NULL &&
4279 !ik->constants()->cache()->check_no_old_or_obsolete_entries()) {
4280 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4281 log_trace(redefine, class, obsolete, metadata)
4282 ("cp-cache::check_no_old_or_obsolete_entries failure -- OLD or OBSOLETE method found -- class: %s",
4283 ik->signature_name());
4284 ik->constants()->cache()->dump_cache();
4285 }
4286 no_old_methods = false;
4287 }
4288 }
4289
4290 // print and fail guarantee if old methods are found.
4291 if (!no_old_methods) {
4292 if (log_is_enabled(Trace, redefine, class, obsolete, metadata)) {
4293 dump_methods();
4294 } else {
4295 log_trace(redefine, class)("Use the '-Xlog:redefine+class*:' option "
4296 "to see more info about the following guarantee() failure.");
4297 }
4298 guarantee(false, "OLD and/or OBSOLETE method(s) found");
4299 }
4300 }
4301
4302
dump_methods()4303 void VM_RedefineClasses::dump_methods() {
4304 int j;
4305 log_trace(redefine, class, dump)("_old_methods --");
4306 for (j = 0; j < _old_methods->length(); ++j) {
4307 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4308 Method* m = _old_methods->at(j);
4309 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4310 m->access_flags().print_on(&log_stream);
4311 log_stream.print(" -- ");
4312 m->print_name(&log_stream);
4313 log_stream.cr();
4314 }
4315 log_trace(redefine, class, dump)("_new_methods --");
4316 for (j = 0; j < _new_methods->length(); ++j) {
4317 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4318 Method* m = _new_methods->at(j);
4319 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4320 m->access_flags().print_on(&log_stream);
4321 log_stream.print(" -- ");
4322 m->print_name(&log_stream);
4323 log_stream.cr();
4324 }
4325 log_trace(redefine, class, dump)("_matching_methods --");
4326 for (j = 0; j < _matching_methods_length; ++j) {
4327 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4328 Method* m = _matching_old_methods[j];
4329 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4330 m->access_flags().print_on(&log_stream);
4331 log_stream.print(" -- ");
4332 m->print_name();
4333 log_stream.cr();
4334
4335 m = _matching_new_methods[j];
4336 log_stream.print(" (%5d) ", m->vtable_index());
4337 m->access_flags().print_on(&log_stream);
4338 log_stream.cr();
4339 }
4340 log_trace(redefine, class, dump)("_deleted_methods --");
4341 for (j = 0; j < _deleted_methods_length; ++j) {
4342 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4343 Method* m = _deleted_methods[j];
4344 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4345 m->access_flags().print_on(&log_stream);
4346 log_stream.print(" -- ");
4347 m->print_name(&log_stream);
4348 log_stream.cr();
4349 }
4350 log_trace(redefine, class, dump)("_added_methods --");
4351 for (j = 0; j < _added_methods_length; ++j) {
4352 LogStreamHandle(Trace, redefine, class, dump) log_stream;
4353 Method* m = _added_methods[j];
4354 log_stream.print("%4d (%5d) ", j, m->vtable_index());
4355 m->access_flags().print_on(&log_stream);
4356 log_stream.print(" -- ");
4357 m->print_name(&log_stream);
4358 log_stream.cr();
4359 }
4360 }
4361
print_on_error(outputStream * st) const4362 void VM_RedefineClasses::print_on_error(outputStream* st) const {
4363 VM_Operation::print_on_error(st);
4364 if (_the_class != NULL) {
4365 ResourceMark rm;
4366 st->print_cr(", redefining class %s", _the_class->external_name());
4367 }
4368 }
4369