Thu, 12 Nov 2015 09:53:17 +0100
8058563: InstanceKlass::_dependencies list isn't cleared from empty nmethodBucket entries
Reviewed-by: mgerdin, vlivanov
1 /*
2 * Copyright (c) 1997, 2015, 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 */
25 #include "precompiled.hpp"
26 #include "classfile/javaClasses.hpp"
27 #include "classfile/systemDictionary.hpp"
28 #include "classfile/verifier.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "compiler/compileBroker.hpp"
31 #include "gc_implementation/shared/markSweep.inline.hpp"
32 #include "gc_interface/collectedHeap.inline.hpp"
33 #include "interpreter/oopMapCache.hpp"
34 #include "interpreter/rewriter.hpp"
35 #include "jvmtifiles/jvmti.h"
36 #include "memory/genOopClosures.inline.hpp"
37 #include "memory/heapInspection.hpp"
38 #include "memory/iterator.inline.hpp"
39 #include "memory/metadataFactory.hpp"
40 #include "memory/oopFactory.hpp"
41 #include "oops/fieldStreams.hpp"
42 #include "oops/instanceClassLoaderKlass.hpp"
43 #include "oops/instanceKlass.hpp"
44 #include "oops/instanceMirrorKlass.hpp"
45 #include "oops/instanceOop.hpp"
46 #include "oops/klass.inline.hpp"
47 #include "oops/method.hpp"
48 #include "oops/oop.inline.hpp"
49 #include "oops/symbol.hpp"
50 #include "prims/jvmtiExport.hpp"
51 #include "prims/jvmtiRedefineClassesTrace.hpp"
52 #include "prims/jvmtiRedefineClasses.hpp"
53 #include "prims/jvmtiThreadState.hpp"
54 #include "prims/methodComparator.hpp"
55 #include "runtime/fieldDescriptor.hpp"
56 #include "runtime/handles.inline.hpp"
57 #include "runtime/javaCalls.hpp"
58 #include "runtime/mutexLocker.hpp"
59 #include "runtime/orderAccess.inline.hpp"
60 #include "runtime/thread.inline.hpp"
61 #include "services/classLoadingService.hpp"
62 #include "services/threadService.hpp"
63 #include "utilities/dtrace.hpp"
64 #include "utilities/macros.hpp"
65 #if INCLUDE_ALL_GCS
66 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
67 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
68 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
69 #include "gc_implementation/g1/g1RemSet.inline.hpp"
70 #include "gc_implementation/g1/heapRegionManager.inline.hpp"
71 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
72 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
73 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
74 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
75 #include "oops/oop.pcgc.inline.hpp"
76 #endif // INCLUDE_ALL_GCS
77 #ifdef COMPILER1
78 #include "c1/c1_Compiler.hpp"
79 #endif
81 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
83 #ifdef DTRACE_ENABLED
85 #ifndef USDT2
87 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
88 char*, intptr_t, oop, intptr_t);
89 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
90 char*, intptr_t, oop, intptr_t, int);
91 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
92 char*, intptr_t, oop, intptr_t, int);
93 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
94 char*, intptr_t, oop, intptr_t, int);
95 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
96 char*, intptr_t, oop, intptr_t, int);
97 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
98 char*, intptr_t, oop, intptr_t, int);
99 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
100 char*, intptr_t, oop, intptr_t, int);
101 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
102 char*, intptr_t, oop, intptr_t, int);
104 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type) \
105 { \
106 char* data = NULL; \
107 int len = 0; \
108 Symbol* name = (clss)->name(); \
109 if (name != NULL) { \
110 data = (char*)name->bytes(); \
111 len = name->utf8_length(); \
112 } \
113 HS_DTRACE_PROBE4(hotspot, class__initialization__##type, \
114 data, len, (void *)(clss)->class_loader(), thread_type); \
115 }
117 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
118 { \
119 char* data = NULL; \
120 int len = 0; \
121 Symbol* name = (clss)->name(); \
122 if (name != NULL) { \
123 data = (char*)name->bytes(); \
124 len = name->utf8_length(); \
125 } \
126 HS_DTRACE_PROBE5(hotspot, class__initialization__##type, \
127 data, len, (void *)(clss)->class_loader(), thread_type, wait); \
128 }
129 #else /* USDT2 */
131 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
132 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
133 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
134 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
135 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
136 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
137 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
138 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
139 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type) \
140 { \
141 char* data = NULL; \
142 int len = 0; \
143 Symbol* name = (clss)->name(); \
144 if (name != NULL) { \
145 data = (char*)name->bytes(); \
146 len = name->utf8_length(); \
147 } \
148 HOTSPOT_CLASS_INITIALIZATION_##type( \
149 data, len, (clss)->class_loader(), thread_type); \
150 }
152 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
153 { \
154 char* data = NULL; \
155 int len = 0; \
156 Symbol* name = (clss)->name(); \
157 if (name != NULL) { \
158 data = (char*)name->bytes(); \
159 len = name->utf8_length(); \
160 } \
161 HOTSPOT_CLASS_INITIALIZATION_##type( \
162 data, len, (clss)->class_loader(), thread_type, wait); \
163 }
164 #endif /* USDT2 */
166 #else // ndef DTRACE_ENABLED
168 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
169 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
171 #endif // ndef DTRACE_ENABLED
173 volatile int InstanceKlass::_total_instanceKlass_count = 0;
175 InstanceKlass* InstanceKlass::allocate_instance_klass(
176 ClassLoaderData* loader_data,
177 int vtable_len,
178 int itable_len,
179 int static_field_size,
180 int nonstatic_oop_map_size,
181 ReferenceType rt,
182 AccessFlags access_flags,
183 Symbol* name,
184 Klass* super_klass,
185 bool is_anonymous,
186 TRAPS) {
188 int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
189 access_flags.is_interface(), is_anonymous);
191 // Allocation
192 InstanceKlass* ik;
193 if (rt == REF_NONE) {
194 if (name == vmSymbols::java_lang_Class()) {
195 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
196 vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
197 access_flags, is_anonymous);
198 } else if (name == vmSymbols::java_lang_ClassLoader() ||
199 (SystemDictionary::ClassLoader_klass_loaded() &&
200 super_klass != NULL &&
201 super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
202 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
203 vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
204 access_flags, is_anonymous);
205 } else {
206 // normal class
207 ik = new (loader_data, size, THREAD) InstanceKlass(
208 vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
209 access_flags, is_anonymous);
210 }
211 } else {
212 // reference klass
213 ik = new (loader_data, size, THREAD) InstanceRefKlass(
214 vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
215 access_flags, is_anonymous);
216 }
218 // Check for pending exception before adding to the loader data and incrementing
219 // class count. Can get OOM here.
220 if (HAS_PENDING_EXCEPTION) {
221 return NULL;
222 }
224 // Add all classes to our internal class loader list here,
225 // including classes in the bootstrap (NULL) class loader.
226 loader_data->add_class(ik);
228 Atomic::inc(&_total_instanceKlass_count);
229 return ik;
230 }
233 // copy method ordering from resource area to Metaspace
234 void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
235 if (m != NULL) {
236 // allocate a new array and copy contents (memcpy?)
237 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
238 for (int i = 0; i < m->length(); i++) {
239 _method_ordering->at_put(i, m->at(i));
240 }
241 } else {
242 _method_ordering = Universe::the_empty_int_array();
243 }
244 }
246 // create a new array of vtable_indices for default methods
247 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
248 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
249 assert(default_vtable_indices() == NULL, "only create once");
250 set_default_vtable_indices(vtable_indices);
251 return vtable_indices;
252 }
254 InstanceKlass::InstanceKlass(int vtable_len,
255 int itable_len,
256 int static_field_size,
257 int nonstatic_oop_map_size,
258 ReferenceType rt,
259 AccessFlags access_flags,
260 bool is_anonymous) {
261 No_Safepoint_Verifier no_safepoint; // until k becomes parsable
263 int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
264 access_flags.is_interface(), is_anonymous);
266 set_vtable_length(vtable_len);
267 set_itable_length(itable_len);
268 set_static_field_size(static_field_size);
269 set_nonstatic_oop_map_size(nonstatic_oop_map_size);
270 set_access_flags(access_flags);
271 _misc_flags = 0; // initialize to zero
272 set_is_anonymous(is_anonymous);
273 assert(size() == iksize, "wrong size for object");
275 set_array_klasses(NULL);
276 set_methods(NULL);
277 set_method_ordering(NULL);
278 set_default_methods(NULL);
279 set_default_vtable_indices(NULL);
280 set_local_interfaces(NULL);
281 set_transitive_interfaces(NULL);
282 init_implementor();
283 set_fields(NULL, 0);
284 set_constants(NULL);
285 set_class_loader_data(NULL);
286 set_source_file_name_index(0);
287 set_source_debug_extension(NULL, 0);
288 set_array_name(NULL);
289 set_inner_classes(NULL);
290 set_static_oop_field_count(0);
291 set_nonstatic_field_size(0);
292 set_is_marked_dependent(false);
293 set_has_unloaded_dependent(false);
294 set_init_state(InstanceKlass::allocated);
295 set_init_thread(NULL);
296 set_reference_type(rt);
297 set_oop_map_cache(NULL);
298 set_jni_ids(NULL);
299 set_osr_nmethods_head(NULL);
300 set_breakpoints(NULL);
301 init_previous_versions();
302 set_generic_signature_index(0);
303 release_set_methods_jmethod_ids(NULL);
304 set_annotations(NULL);
305 set_jvmti_cached_class_field_map(NULL);
306 set_initial_method_idnum(0);
307 _dependencies = NULL;
308 set_jvmti_cached_class_field_map(NULL);
309 set_cached_class_file(NULL);
310 set_initial_method_idnum(0);
311 set_minor_version(0);
312 set_major_version(0);
313 NOT_PRODUCT(_verify_count = 0;)
315 // initialize the non-header words to zero
316 intptr_t* p = (intptr_t*)this;
317 for (int index = InstanceKlass::header_size(); index < iksize; index++) {
318 p[index] = NULL_WORD;
319 }
321 // Set temporary value until parseClassFile updates it with the real instance
322 // size.
323 set_layout_helper(Klass::instance_layout_helper(0, true));
324 }
327 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
328 Array<Method*>* methods) {
329 if (methods != NULL && methods != Universe::the_empty_method_array() &&
330 !methods->is_shared()) {
331 for (int i = 0; i < methods->length(); i++) {
332 Method* method = methods->at(i);
333 if (method == NULL) continue; // maybe null if error processing
334 // Only want to delete methods that are not executing for RedefineClasses.
335 // The previous version will point to them so they're not totally dangling
336 assert (!method->on_stack(), "shouldn't be called with methods on stack");
337 MetadataFactory::free_metadata(loader_data, method);
338 }
339 MetadataFactory::free_array<Method*>(loader_data, methods);
340 }
341 }
343 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
344 Klass* super_klass,
345 Array<Klass*>* local_interfaces,
346 Array<Klass*>* transitive_interfaces) {
347 // Only deallocate transitive interfaces if not empty, same as super class
348 // or same as local interfaces. See code in parseClassFile.
349 Array<Klass*>* ti = transitive_interfaces;
350 if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
351 // check that the interfaces don't come from super class
352 Array<Klass*>* sti = (super_klass == NULL) ? NULL :
353 InstanceKlass::cast(super_klass)->transitive_interfaces();
354 if (ti != sti && ti != NULL && !ti->is_shared()) {
355 MetadataFactory::free_array<Klass*>(loader_data, ti);
356 }
357 }
359 // local interfaces can be empty
360 if (local_interfaces != Universe::the_empty_klass_array() &&
361 local_interfaces != NULL && !local_interfaces->is_shared()) {
362 MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
363 }
364 }
366 // This function deallocates the metadata and C heap pointers that the
367 // InstanceKlass points to.
368 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
370 // Orphan the mirror first, CMS thinks it's still live.
371 if (java_mirror() != NULL) {
372 java_lang_Class::set_klass(java_mirror(), NULL);
373 }
375 // Need to take this class off the class loader data list.
376 loader_data->remove_class(this);
378 // The array_klass for this class is created later, after error handling.
379 // For class redefinition, we keep the original class so this scratch class
380 // doesn't have an array class. Either way, assert that there is nothing
381 // to deallocate.
382 assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
384 // Release C heap allocated data that this might point to, which includes
385 // reference counting symbol names.
386 release_C_heap_structures();
388 deallocate_methods(loader_data, methods());
389 set_methods(NULL);
391 if (method_ordering() != NULL &&
392 method_ordering() != Universe::the_empty_int_array() &&
393 !method_ordering()->is_shared()) {
394 MetadataFactory::free_array<int>(loader_data, method_ordering());
395 }
396 set_method_ordering(NULL);
398 // default methods can be empty
399 if (default_methods() != NULL &&
400 default_methods() != Universe::the_empty_method_array() &&
401 !default_methods()->is_shared()) {
402 MetadataFactory::free_array<Method*>(loader_data, default_methods());
403 }
404 // Do NOT deallocate the default methods, they are owned by superinterfaces.
405 set_default_methods(NULL);
407 // default methods vtable indices can be empty
408 if (default_vtable_indices() != NULL &&
409 !default_vtable_indices()->is_shared()) {
410 MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
411 }
412 set_default_vtable_indices(NULL);
415 // This array is in Klass, but remove it with the InstanceKlass since
416 // this place would be the only caller and it can share memory with transitive
417 // interfaces.
418 if (secondary_supers() != NULL &&
419 secondary_supers() != Universe::the_empty_klass_array() &&
420 secondary_supers() != transitive_interfaces() &&
421 !secondary_supers()->is_shared()) {
422 MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
423 }
424 set_secondary_supers(NULL);
426 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
427 set_transitive_interfaces(NULL);
428 set_local_interfaces(NULL);
430 if (fields() != NULL && !fields()->is_shared()) {
431 MetadataFactory::free_array<jushort>(loader_data, fields());
432 }
433 set_fields(NULL, 0);
435 // If a method from a redefined class is using this constant pool, don't
436 // delete it, yet. The new class's previous version will point to this.
437 if (constants() != NULL) {
438 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
439 if (!constants()->is_shared()) {
440 MetadataFactory::free_metadata(loader_data, constants());
441 }
442 // Delete any cached resolution errors for the constant pool
443 SystemDictionary::delete_resolution_error(constants());
445 set_constants(NULL);
446 }
448 if (inner_classes() != NULL &&
449 inner_classes() != Universe::the_empty_short_array() &&
450 !inner_classes()->is_shared()) {
451 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
452 }
453 set_inner_classes(NULL);
455 // We should deallocate the Annotations instance if it's not in shared spaces.
456 if (annotations() != NULL && !annotations()->is_shared()) {
457 MetadataFactory::free_metadata(loader_data, annotations());
458 }
459 set_annotations(NULL);
460 }
462 bool InstanceKlass::should_be_initialized() const {
463 return !is_initialized();
464 }
466 klassVtable* InstanceKlass::vtable() const {
467 return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
468 }
470 klassItable* InstanceKlass::itable() const {
471 return new klassItable(instanceKlassHandle(this));
472 }
474 void InstanceKlass::eager_initialize(Thread *thread) {
475 if (!EagerInitialization) return;
477 if (this->is_not_initialized()) {
478 // abort if the the class has a class initializer
479 if (this->class_initializer() != NULL) return;
481 // abort if it is java.lang.Object (initialization is handled in genesis)
482 Klass* super = this->super();
483 if (super == NULL) return;
485 // abort if the super class should be initialized
486 if (!InstanceKlass::cast(super)->is_initialized()) return;
488 // call body to expose the this pointer
489 instanceKlassHandle this_oop(thread, this);
490 eager_initialize_impl(this_oop);
491 }
492 }
494 // JVMTI spec thinks there are signers and protection domain in the
495 // instanceKlass. These accessors pretend these fields are there.
496 // The hprof specification also thinks these fields are in InstanceKlass.
497 oop InstanceKlass::protection_domain() const {
498 // return the protection_domain from the mirror
499 return java_lang_Class::protection_domain(java_mirror());
500 }
502 // To remove these from requires an incompatible change and CCC request.
503 objArrayOop InstanceKlass::signers() const {
504 // return the signers from the mirror
505 return java_lang_Class::signers(java_mirror());
506 }
508 oop InstanceKlass::init_lock() const {
509 // return the init lock from the mirror
510 oop lock = java_lang_Class::init_lock(java_mirror());
511 // Prevent reordering with any access of initialization state
512 OrderAccess::loadload();
513 assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
514 "only fully initialized state can have a null lock");
515 return lock;
516 }
518 // Set the initialization lock to null so the object can be GC'ed. Any racing
519 // threads to get this lock will see a null lock and will not lock.
520 // That's okay because they all check for initialized state after getting
521 // the lock and return.
522 void InstanceKlass::fence_and_clear_init_lock() {
523 // make sure previous stores are all done, notably the init_state.
524 OrderAccess::storestore();
525 java_lang_Class::set_init_lock(java_mirror(), NULL);
526 assert(!is_not_initialized(), "class must be initialized now");
527 }
529 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
530 EXCEPTION_MARK;
531 oop init_lock = this_oop->init_lock();
532 ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
534 // abort if someone beat us to the initialization
535 if (!this_oop->is_not_initialized()) return; // note: not equivalent to is_initialized()
537 ClassState old_state = this_oop->init_state();
538 link_class_impl(this_oop, true, THREAD);
539 if (HAS_PENDING_EXCEPTION) {
540 CLEAR_PENDING_EXCEPTION;
541 // Abort if linking the class throws an exception.
543 // Use a test to avoid redundantly resetting the state if there's
544 // no change. Set_init_state() asserts that state changes make
545 // progress, whereas here we might just be spinning in place.
546 if( old_state != this_oop->_init_state )
547 this_oop->set_init_state (old_state);
548 } else {
549 // linking successfull, mark class as initialized
550 this_oop->set_init_state (fully_initialized);
551 this_oop->fence_and_clear_init_lock();
552 // trace
553 if (TraceClassInitialization) {
554 ResourceMark rm(THREAD);
555 tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
556 }
557 }
558 }
561 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
562 // process. The step comments refers to the procedure described in that section.
563 // Note: implementation moved to static method to expose the this pointer.
564 void InstanceKlass::initialize(TRAPS) {
565 if (this->should_be_initialized()) {
566 HandleMark hm(THREAD);
567 instanceKlassHandle this_oop(THREAD, this);
568 initialize_impl(this_oop, CHECK);
569 // Note: at this point the class may be initialized
570 // OR it may be in the state of being initialized
571 // in case of recursive initialization!
572 } else {
573 assert(is_initialized(), "sanity check");
574 }
575 }
578 bool InstanceKlass::verify_code(
579 instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
580 // 1) Verify the bytecodes
581 Verifier::Mode mode =
582 throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
583 return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
584 }
587 // Used exclusively by the shared spaces dump mechanism to prevent
588 // classes mapped into the shared regions in new VMs from appearing linked.
590 void InstanceKlass::unlink_class() {
591 assert(is_linked(), "must be linked");
592 _init_state = loaded;
593 }
595 void InstanceKlass::link_class(TRAPS) {
596 assert(is_loaded(), "must be loaded");
597 if (!is_linked()) {
598 HandleMark hm(THREAD);
599 instanceKlassHandle this_oop(THREAD, this);
600 link_class_impl(this_oop, true, CHECK);
601 }
602 }
604 // Called to verify that a class can link during initialization, without
605 // throwing a VerifyError.
606 bool InstanceKlass::link_class_or_fail(TRAPS) {
607 assert(is_loaded(), "must be loaded");
608 if (!is_linked()) {
609 HandleMark hm(THREAD);
610 instanceKlassHandle this_oop(THREAD, this);
611 link_class_impl(this_oop, false, CHECK_false);
612 }
613 return is_linked();
614 }
616 bool InstanceKlass::link_class_impl(
617 instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
618 // check for error state
619 if (this_oop->is_in_error_state()) {
620 ResourceMark rm(THREAD);
621 THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
622 this_oop->external_name(), false);
623 }
624 // return if already verified
625 if (this_oop->is_linked()) {
626 return true;
627 }
629 // Timing
630 // timer handles recursion
631 assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
632 JavaThread* jt = (JavaThread*)THREAD;
634 // link super class before linking this class
635 instanceKlassHandle super(THREAD, this_oop->super());
636 if (super.not_null()) {
637 if (super->is_interface()) { // check if super class is an interface
638 ResourceMark rm(THREAD);
639 Exceptions::fthrow(
640 THREAD_AND_LOCATION,
641 vmSymbols::java_lang_IncompatibleClassChangeError(),
642 "class %s has interface %s as super class",
643 this_oop->external_name(),
644 super->external_name()
645 );
646 return false;
647 }
649 link_class_impl(super, throw_verifyerror, CHECK_false);
650 }
652 // link all interfaces implemented by this class before linking this class
653 Array<Klass*>* interfaces = this_oop->local_interfaces();
654 int num_interfaces = interfaces->length();
655 for (int index = 0; index < num_interfaces; index++) {
656 HandleMark hm(THREAD);
657 instanceKlassHandle ih(THREAD, interfaces->at(index));
658 link_class_impl(ih, throw_verifyerror, CHECK_false);
659 }
661 // in case the class is linked in the process of linking its superclasses
662 if (this_oop->is_linked()) {
663 return true;
664 }
666 // trace only the link time for this klass that includes
667 // the verification time
668 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
669 ClassLoader::perf_class_link_selftime(),
670 ClassLoader::perf_classes_linked(),
671 jt->get_thread_stat()->perf_recursion_counts_addr(),
672 jt->get_thread_stat()->perf_timers_addr(),
673 PerfClassTraceTime::CLASS_LINK);
675 // verification & rewriting
676 {
677 oop init_lock = this_oop->init_lock();
678 ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
679 // rewritten will have been set if loader constraint error found
680 // on an earlier link attempt
681 // don't verify or rewrite if already rewritten
683 if (!this_oop->is_linked()) {
684 if (!this_oop->is_rewritten()) {
685 {
686 // Timer includes any side effects of class verification (resolution,
687 // etc), but not recursive entry into verify_code().
688 PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
689 ClassLoader::perf_class_verify_selftime(),
690 ClassLoader::perf_classes_verified(),
691 jt->get_thread_stat()->perf_recursion_counts_addr(),
692 jt->get_thread_stat()->perf_timers_addr(),
693 PerfClassTraceTime::CLASS_VERIFY);
694 bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
695 if (!verify_ok) {
696 return false;
697 }
698 }
700 // Just in case a side-effect of verify linked this class already
701 // (which can sometimes happen since the verifier loads classes
702 // using custom class loaders, which are free to initialize things)
703 if (this_oop->is_linked()) {
704 return true;
705 }
707 // also sets rewritten
708 this_oop->rewrite_class(CHECK_false);
709 }
711 // relocate jsrs and link methods after they are all rewritten
712 this_oop->link_methods(CHECK_false);
714 // Initialize the vtable and interface table after
715 // methods have been rewritten since rewrite may
716 // fabricate new Method*s.
717 // also does loader constraint checking
718 if (!this_oop()->is_shared()) {
719 ResourceMark rm(THREAD);
720 this_oop->vtable()->initialize_vtable(true, CHECK_false);
721 this_oop->itable()->initialize_itable(true, CHECK_false);
722 }
723 #ifdef ASSERT
724 else {
725 ResourceMark rm(THREAD);
726 this_oop->vtable()->verify(tty, true);
727 // In case itable verification is ever added.
728 // this_oop->itable()->verify(tty, true);
729 }
730 #endif
731 this_oop->set_init_state(linked);
732 if (JvmtiExport::should_post_class_prepare()) {
733 Thread *thread = THREAD;
734 assert(thread->is_Java_thread(), "thread->is_Java_thread()");
735 JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
736 }
737 }
738 }
739 return true;
740 }
743 // Rewrite the byte codes of all of the methods of a class.
744 // The rewriter must be called exactly once. Rewriting must happen after
745 // verification but before the first method of the class is executed.
746 void InstanceKlass::rewrite_class(TRAPS) {
747 assert(is_loaded(), "must be loaded");
748 instanceKlassHandle this_oop(THREAD, this);
749 if (this_oop->is_rewritten()) {
750 assert(this_oop()->is_shared(), "rewriting an unshared class?");
751 return;
752 }
753 Rewriter::rewrite(this_oop, CHECK);
754 this_oop->set_rewritten();
755 }
757 // Now relocate and link method entry points after class is rewritten.
758 // This is outside is_rewritten flag. In case of an exception, it can be
759 // executed more than once.
760 void InstanceKlass::link_methods(TRAPS) {
761 int len = methods()->length();
762 for (int i = len-1; i >= 0; i--) {
763 methodHandle m(THREAD, methods()->at(i));
765 // Set up method entry points for compiler and interpreter .
766 m->link_method(m, CHECK);
768 // This is for JVMTI and unrelated to relocator but the last thing we do
769 #ifdef ASSERT
770 if (StressMethodComparator) {
771 ResourceMark rm(THREAD);
772 static int nmc = 0;
773 for (int j = i; j >= 0 && j >= i-4; j--) {
774 if ((++nmc % 1000) == 0) tty->print_cr("Have run MethodComparator %d times...", nmc);
775 bool z = MethodComparator::methods_EMCP(m(),
776 methods()->at(j));
777 if (j == i && !z) {
778 tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
779 assert(z, "method must compare equal to itself");
780 }
781 }
782 }
783 #endif //ASSERT
784 }
785 }
787 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
788 void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_oop, TRAPS) {
789 if (this_oop->has_default_methods()) {
790 for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
791 Klass* iface = this_oop->local_interfaces()->at(i);
792 InstanceKlass* ik = InstanceKlass::cast(iface);
793 if (ik->should_be_initialized()) {
794 if (ik->has_default_methods()) {
795 ik->initialize_super_interfaces(ik, THREAD);
796 }
797 // Only initialize() interfaces that "declare" concrete methods.
798 // has_default_methods drives searching superinterfaces since it
799 // means has_default_methods in its superinterface hierarchy
800 if (!HAS_PENDING_EXCEPTION && ik->declares_default_methods()) {
801 ik->initialize(THREAD);
802 }
803 if (HAS_PENDING_EXCEPTION) {
804 Handle e(THREAD, PENDING_EXCEPTION);
805 CLEAR_PENDING_EXCEPTION;
806 {
807 EXCEPTION_MARK;
808 // Locks object, set state, and notify all waiting threads
809 this_oop->set_initialization_state_and_notify(
810 initialization_error, THREAD);
812 // ignore any exception thrown, superclass initialization error is
813 // thrown below
814 CLEAR_PENDING_EXCEPTION;
815 }
816 THROW_OOP(e());
817 }
818 }
819 }
820 }
821 }
823 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
824 // Make sure klass is linked (verified) before initialization
825 // A class could already be verified, since it has been reflected upon.
826 this_oop->link_class(CHECK);
828 DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
830 bool wait = false;
832 // refer to the JVM book page 47 for description of steps
833 // Step 1
834 {
835 oop init_lock = this_oop->init_lock();
836 ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
838 Thread *self = THREAD; // it's passed the current thread
840 // Step 2
841 // If we were to use wait() instead of waitInterruptibly() then
842 // we might end up throwing IE from link/symbol resolution sites
843 // that aren't expected to throw. This would wreak havoc. See 6320309.
844 while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
845 wait = true;
846 ol.waitUninterruptibly(CHECK);
847 }
849 // Step 3
850 if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
851 DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
852 return;
853 }
855 // Step 4
856 if (this_oop->is_initialized()) {
857 DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
858 return;
859 }
861 // Step 5
862 if (this_oop->is_in_error_state()) {
863 DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
864 ResourceMark rm(THREAD);
865 const char* desc = "Could not initialize class ";
866 const char* className = this_oop->external_name();
867 size_t msglen = strlen(desc) + strlen(className) + 1;
868 char* message = NEW_RESOURCE_ARRAY(char, msglen);
869 if (NULL == message) {
870 // Out of memory: can't create detailed error message
871 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
872 } else {
873 jio_snprintf(message, msglen, "%s%s", desc, className);
874 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
875 }
876 }
878 // Step 6
879 this_oop->set_init_state(being_initialized);
880 this_oop->set_init_thread(self);
881 }
883 // Step 7
884 Klass* super_klass = this_oop->super();
885 if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
886 super_klass->initialize(THREAD);
888 if (HAS_PENDING_EXCEPTION) {
889 Handle e(THREAD, PENDING_EXCEPTION);
890 CLEAR_PENDING_EXCEPTION;
891 {
892 EXCEPTION_MARK;
893 this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
894 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, superclass initialization error is thrown below
895 }
896 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
897 THROW_OOP(e());
898 }
899 }
901 // Recursively initialize any superinterfaces that declare default methods
902 // Only need to recurse if has_default_methods which includes declaring and
903 // inheriting default methods
904 if (this_oop->has_default_methods()) {
905 this_oop->initialize_super_interfaces(this_oop, CHECK);
906 }
908 // Step 8
909 {
910 assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
911 JavaThread* jt = (JavaThread*)THREAD;
912 DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
913 // Timer includes any side effects of class initialization (resolution,
914 // etc), but not recursive entry into call_class_initializer().
915 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
916 ClassLoader::perf_class_init_selftime(),
917 ClassLoader::perf_classes_inited(),
918 jt->get_thread_stat()->perf_recursion_counts_addr(),
919 jt->get_thread_stat()->perf_timers_addr(),
920 PerfClassTraceTime::CLASS_CLINIT);
921 this_oop->call_class_initializer(THREAD);
922 }
924 // Step 9
925 if (!HAS_PENDING_EXCEPTION) {
926 this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
927 { ResourceMark rm(THREAD);
928 debug_only(this_oop->vtable()->verify(tty, true);)
929 }
930 }
931 else {
932 // Step 10 and 11
933 Handle e(THREAD, PENDING_EXCEPTION);
934 CLEAR_PENDING_EXCEPTION;
935 // JVMTI has already reported the pending exception
936 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
937 JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
938 {
939 EXCEPTION_MARK;
940 this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
941 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
942 // JVMTI has already reported the pending exception
943 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
944 JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
945 }
946 DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
947 if (e->is_a(SystemDictionary::Error_klass())) {
948 THROW_OOP(e());
949 } else {
950 JavaCallArguments args(e);
951 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
952 vmSymbols::throwable_void_signature(),
953 &args);
954 }
955 }
956 DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
957 }
960 // Note: implementation moved to static method to expose the this pointer.
961 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
962 instanceKlassHandle kh(THREAD, this);
963 set_initialization_state_and_notify_impl(kh, state, CHECK);
964 }
966 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
967 oop init_lock = this_oop->init_lock();
968 ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
969 this_oop->set_init_state(state);
970 this_oop->fence_and_clear_init_lock();
971 ol.notify_all(CHECK);
972 }
974 // The embedded _implementor field can only record one implementor.
975 // When there are more than one implementors, the _implementor field
976 // is set to the interface Klass* itself. Following are the possible
977 // values for the _implementor field:
978 // NULL - no implementor
979 // implementor Klass* - one implementor
980 // self - more than one implementor
981 //
982 // The _implementor field only exists for interfaces.
983 void InstanceKlass::add_implementor(Klass* k) {
984 assert(Compile_lock->owned_by_self(), "");
985 assert(is_interface(), "not interface");
986 // Filter out my subinterfaces.
987 // (Note: Interfaces are never on the subklass list.)
988 if (InstanceKlass::cast(k)->is_interface()) return;
990 // Filter out subclasses whose supers already implement me.
991 // (Note: CHA must walk subclasses of direct implementors
992 // in order to locate indirect implementors.)
993 Klass* sk = InstanceKlass::cast(k)->super();
994 if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
995 // We only need to check one immediate superclass, since the
996 // implements_interface query looks at transitive_interfaces.
997 // Any supers of the super have the same (or fewer) transitive_interfaces.
998 return;
1000 Klass* ik = implementor();
1001 if (ik == NULL) {
1002 set_implementor(k);
1003 } else if (ik != this) {
1004 // There is already an implementor. Use itself as an indicator of
1005 // more than one implementors.
1006 set_implementor(this);
1007 }
1009 // The implementor also implements the transitive_interfaces
1010 for (int index = 0; index < local_interfaces()->length(); index++) {
1011 InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
1012 }
1013 }
1015 void InstanceKlass::init_implementor() {
1016 if (is_interface()) {
1017 set_implementor(NULL);
1018 }
1019 }
1022 void InstanceKlass::process_interfaces(Thread *thread) {
1023 // link this class into the implementors list of every interface it implements
1024 Klass* this_as_klass_oop = this;
1025 for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1026 assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1027 InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
1028 assert(interf->is_interface(), "expected interface");
1029 interf->add_implementor(this_as_klass_oop);
1030 }
1031 }
1033 bool InstanceKlass::can_be_primary_super_slow() const {
1034 if (is_interface())
1035 return false;
1036 else
1037 return Klass::can_be_primary_super_slow();
1038 }
1040 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
1041 // The secondaries are the implemented interfaces.
1042 InstanceKlass* ik = InstanceKlass::cast(this);
1043 Array<Klass*>* interfaces = ik->transitive_interfaces();
1044 int num_secondaries = num_extra_slots + interfaces->length();
1045 if (num_secondaries == 0) {
1046 // Must share this for correct bootstrapping!
1047 set_secondary_supers(Universe::the_empty_klass_array());
1048 return NULL;
1049 } else if (num_extra_slots == 0) {
1050 // The secondary super list is exactly the same as the transitive interfaces.
1051 // Redefine classes has to be careful not to delete this!
1052 set_secondary_supers(interfaces);
1053 return NULL;
1054 } else {
1055 // Copy transitive interfaces to a temporary growable array to be constructed
1056 // into the secondary super list with extra slots.
1057 GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1058 for (int i = 0; i < interfaces->length(); i++) {
1059 secondaries->push(interfaces->at(i));
1060 }
1061 return secondaries;
1062 }
1063 }
1065 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
1066 if (k->is_interface()) {
1067 return implements_interface(k);
1068 } else {
1069 return Klass::compute_is_subtype_of(k);
1070 }
1071 }
1073 bool InstanceKlass::implements_interface(Klass* k) const {
1074 if (this == k) return true;
1075 assert(k->is_interface(), "should be an interface class");
1076 for (int i = 0; i < transitive_interfaces()->length(); i++) {
1077 if (transitive_interfaces()->at(i) == k) {
1078 return true;
1079 }
1080 }
1081 return false;
1082 }
1084 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1085 // Verify direct super interface
1086 if (this == k) return true;
1087 assert(k->is_interface(), "should be an interface class");
1088 for (int i = 0; i < local_interfaces()->length(); i++) {
1089 if (local_interfaces()->at(i) == k) {
1090 return true;
1091 }
1092 }
1093 return false;
1094 }
1096 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1097 if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
1098 if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
1099 report_java_out_of_memory("Requested array size exceeds VM limit");
1100 JvmtiExport::post_array_size_exhausted();
1101 THROW_OOP_0(Universe::out_of_memory_error_array_size());
1102 }
1103 int size = objArrayOopDesc::object_size(length);
1104 Klass* ak = array_klass(n, CHECK_NULL);
1105 KlassHandle h_ak (THREAD, ak);
1106 objArrayOop o =
1107 (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
1108 return o;
1109 }
1111 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1112 if (TraceFinalizerRegistration) {
1113 tty->print("Registered ");
1114 i->print_value_on(tty);
1115 tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
1116 }
1117 instanceHandle h_i(THREAD, i);
1118 // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1119 JavaValue result(T_VOID);
1120 JavaCallArguments args(h_i);
1121 methodHandle mh (THREAD, Universe::finalizer_register_method());
1122 JavaCalls::call(&result, mh, &args, CHECK_NULL);
1123 return h_i();
1124 }
1126 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1127 bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1128 int size = size_helper(); // Query before forming handle.
1130 KlassHandle h_k(THREAD, this);
1132 instanceOop i;
1134 i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
1135 if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1136 i = register_finalizer(i, CHECK_NULL);
1137 }
1138 return i;
1139 }
1141 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1142 if (is_interface() || is_abstract()) {
1143 ResourceMark rm(THREAD);
1144 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1145 : vmSymbols::java_lang_InstantiationException(), external_name());
1146 }
1147 if (this == SystemDictionary::Class_klass()) {
1148 ResourceMark rm(THREAD);
1149 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1150 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1151 }
1152 }
1154 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
1155 instanceKlassHandle this_oop(THREAD, this);
1156 return array_klass_impl(this_oop, or_null, n, THREAD);
1157 }
1159 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
1160 if (this_oop->array_klasses() == NULL) {
1161 if (or_null) return NULL;
1163 ResourceMark rm;
1164 JavaThread *jt = (JavaThread *)THREAD;
1165 {
1166 // Atomic creation of array_klasses
1167 MutexLocker mc(Compile_lock, THREAD); // for vtables
1168 MutexLocker ma(MultiArray_lock, THREAD);
1170 // Check if update has already taken place
1171 if (this_oop->array_klasses() == NULL) {
1172 Klass* k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
1173 this_oop->set_array_klasses(k);
1174 }
1175 }
1176 }
1177 // _this will always be set at this point
1178 ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
1179 if (or_null) {
1180 return oak->array_klass_or_null(n);
1181 }
1182 return oak->array_klass(n, CHECK_NULL);
1183 }
1185 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
1186 return array_klass_impl(or_null, 1, THREAD);
1187 }
1189 void InstanceKlass::call_class_initializer(TRAPS) {
1190 instanceKlassHandle ik (THREAD, this);
1191 call_class_initializer_impl(ik, THREAD);
1192 }
1194 static int call_class_initializer_impl_counter = 0; // for debugging
1196 Method* InstanceKlass::class_initializer() {
1197 Method* clinit = find_method(
1198 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1199 if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1200 return clinit;
1201 }
1202 return NULL;
1203 }
1205 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
1206 if (ReplayCompiles &&
1207 (ReplaySuppressInitializers == 1 ||
1208 ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
1209 // Hide the existence of the initializer for the purpose of replaying the compile
1210 return;
1211 }
1213 methodHandle h_method(THREAD, this_oop->class_initializer());
1214 assert(!this_oop->is_initialized(), "we cannot initialize twice");
1215 if (TraceClassInitialization) {
1216 tty->print("%d Initializing ", call_class_initializer_impl_counter++);
1217 this_oop->name()->print_value();
1218 tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
1219 }
1220 if (h_method() != NULL) {
1221 JavaCallArguments args; // No arguments
1222 JavaValue result(T_VOID);
1223 JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1224 }
1225 }
1228 void InstanceKlass::mask_for(methodHandle method, int bci,
1229 InterpreterOopMap* entry_for) {
1230 // Dirty read, then double-check under a lock.
1231 if (_oop_map_cache == NULL) {
1232 // Otherwise, allocate a new one.
1233 MutexLocker x(OopMapCacheAlloc_lock);
1234 // First time use. Allocate a cache in C heap
1235 if (_oop_map_cache == NULL) {
1236 // Release stores from OopMapCache constructor before assignment
1237 // to _oop_map_cache. C++ compilers on ppc do not emit the
1238 // required memory barrier only because of the volatile
1239 // qualifier of _oop_map_cache.
1240 OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
1241 }
1242 }
1243 // _oop_map_cache is constant after init; lookup below does is own locking.
1244 _oop_map_cache->lookup(method, bci, entry_for);
1245 }
1248 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1249 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1250 Symbol* f_name = fs.name();
1251 Symbol* f_sig = fs.signature();
1252 if (f_name == name && f_sig == sig) {
1253 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1254 return true;
1255 }
1256 }
1257 return false;
1258 }
1261 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1262 const int n = local_interfaces()->length();
1263 for (int i = 0; i < n; i++) {
1264 Klass* intf1 = local_interfaces()->at(i);
1265 assert(intf1->is_interface(), "just checking type");
1266 // search for field in current interface
1267 if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1268 assert(fd->is_static(), "interface field must be static");
1269 return intf1;
1270 }
1271 // search for field in direct superinterfaces
1272 Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1273 if (intf2 != NULL) return intf2;
1274 }
1275 // otherwise field lookup fails
1276 return NULL;
1277 }
1280 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1281 // search order according to newest JVM spec (5.4.3.2, p.167).
1282 // 1) search for field in current klass
1283 if (find_local_field(name, sig, fd)) {
1284 return const_cast<InstanceKlass*>(this);
1285 }
1286 // 2) search for field recursively in direct superinterfaces
1287 { Klass* intf = find_interface_field(name, sig, fd);
1288 if (intf != NULL) return intf;
1289 }
1290 // 3) apply field lookup recursively if superclass exists
1291 { Klass* supr = super();
1292 if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1293 }
1294 // 4) otherwise field lookup fails
1295 return NULL;
1296 }
1299 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1300 // search order according to newest JVM spec (5.4.3.2, p.167).
1301 // 1) search for field in current klass
1302 if (find_local_field(name, sig, fd)) {
1303 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1304 }
1305 // 2) search for field recursively in direct superinterfaces
1306 if (is_static) {
1307 Klass* intf = find_interface_field(name, sig, fd);
1308 if (intf != NULL) return intf;
1309 }
1310 // 3) apply field lookup recursively if superclass exists
1311 { Klass* supr = super();
1312 if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1313 }
1314 // 4) otherwise field lookup fails
1315 return NULL;
1316 }
1319 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1320 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1321 if (fs.offset() == offset) {
1322 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1323 if (fd->is_static() == is_static) return true;
1324 }
1325 }
1326 return false;
1327 }
1330 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1331 Klass* klass = const_cast<InstanceKlass*>(this);
1332 while (klass != NULL) {
1333 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1334 return true;
1335 }
1336 klass = klass->super();
1337 }
1338 return false;
1339 }
1342 void InstanceKlass::methods_do(void f(Method* method)) {
1343 int len = methods()->length();
1344 for (int index = 0; index < len; index++) {
1345 Method* m = methods()->at(index);
1346 assert(m->is_method(), "must be method");
1347 f(m);
1348 }
1349 }
1352 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1353 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1354 if (fs.access_flags().is_static()) {
1355 fieldDescriptor& fd = fs.field_descriptor();
1356 cl->do_field(&fd);
1357 }
1358 }
1359 }
1362 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1363 instanceKlassHandle h_this(THREAD, this);
1364 do_local_static_fields_impl(h_this, f, mirror, CHECK);
1365 }
1368 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
1369 void f(fieldDescriptor* fd, Handle mirror, TRAPS), Handle mirror, TRAPS) {
1370 for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
1371 if (fs.access_flags().is_static()) {
1372 fieldDescriptor& fd = fs.field_descriptor();
1373 f(&fd, mirror, CHECK);
1374 }
1375 }
1376 }
1379 static int compare_fields_by_offset(int* a, int* b) {
1380 return a[0] - b[0];
1381 }
1383 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1384 InstanceKlass* super = superklass();
1385 if (super != NULL) {
1386 super->do_nonstatic_fields(cl);
1387 }
1388 fieldDescriptor fd;
1389 int length = java_fields_count();
1390 // In DebugInfo nonstatic fields are sorted by offset.
1391 int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1392 int j = 0;
1393 for (int i = 0; i < length; i += 1) {
1394 fd.reinitialize(this, i);
1395 if (!fd.is_static()) {
1396 fields_sorted[j + 0] = fd.offset();
1397 fields_sorted[j + 1] = i;
1398 j += 2;
1399 }
1400 }
1401 if (j > 0) {
1402 length = j;
1403 // _sort_Fn is defined in growableArray.hpp.
1404 qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1405 for (int i = 0; i < length; i += 2) {
1406 fd.reinitialize(this, fields_sorted[i + 1]);
1407 assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1408 cl->do_field(&fd);
1409 }
1410 }
1411 FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
1412 }
1415 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1416 if (array_klasses() != NULL)
1417 ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1418 }
1420 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1421 if (array_klasses() != NULL)
1422 ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1423 }
1425 #ifdef ASSERT
1426 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
1427 int len = methods->length();
1428 for (int index = 0; index < len; index++) {
1429 Method* m = methods->at(index);
1430 assert(m->is_method(), "must be method");
1431 if (m->signature() == signature && m->name() == name) {
1432 return index;
1433 }
1434 }
1435 return -1;
1436 }
1437 #endif
1439 static int binary_search(Array<Method*>* methods, Symbol* name) {
1440 int len = methods->length();
1441 // methods are sorted, so do binary search
1442 int l = 0;
1443 int h = len - 1;
1444 while (l <= h) {
1445 int mid = (l + h) >> 1;
1446 Method* m = methods->at(mid);
1447 assert(m->is_method(), "must be method");
1448 int res = m->name()->fast_compare(name);
1449 if (res == 0) {
1450 return mid;
1451 } else if (res < 0) {
1452 l = mid + 1;
1453 } else {
1454 h = mid - 1;
1455 }
1456 }
1457 return -1;
1458 }
1460 // find_method looks up the name/signature in the local methods array
1461 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
1462 return find_method_impl(name, signature, false);
1463 }
1465 Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const {
1466 return InstanceKlass::find_method_impl(methods(), name, signature, skipping_overpass, false);
1467 }
1469 // find_instance_method looks up the name/signature in the local methods array
1470 // and skips over static methods
1471 Method* InstanceKlass::find_instance_method(
1472 Array<Method*>* methods, Symbol* name, Symbol* signature) {
1473 Method* meth = InstanceKlass::find_method_impl(methods, name, signature, false, true);
1474 return meth;
1475 }
1477 // find_instance_method looks up the name/signature in the local methods array
1478 // and skips over static methods
1479 Method* InstanceKlass::find_instance_method(Symbol* name, Symbol* signature) {
1480 return InstanceKlass::find_instance_method(methods(), name, signature);
1481 }
1483 // find_method looks up the name/signature in the local methods array
1484 Method* InstanceKlass::find_method(
1485 Array<Method*>* methods, Symbol* name, Symbol* signature) {
1486 return InstanceKlass::find_method_impl(methods, name, signature, false, false);
1487 }
1489 Method* InstanceKlass::find_method_impl(
1490 Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static) {
1491 int hit = find_method_index(methods, name, signature, skipping_overpass, skipping_static);
1492 return hit >= 0 ? methods->at(hit): NULL;
1493 }
1495 bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static) {
1496 return (m->signature() == signature) &&
1497 (!skipping_overpass || !m->is_overpass()) &&
1498 (!skipping_static || !m->is_static());
1499 }
1501 // Used directly for default_methods to find the index into the
1502 // default_vtable_indices, and indirectly by find_method
1503 // find_method_index looks in the local methods array to return the index
1504 // of the matching name/signature. If, overpass methods are being ignored,
1505 // the search continues to find a potential non-overpass match. This capability
1506 // is important during method resolution to prefer a static method, for example,
1507 // over an overpass method.
1508 int InstanceKlass::find_method_index(
1509 Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass, bool skipping_static) {
1510 int hit = binary_search(methods, name);
1511 if (hit != -1) {
1512 Method* m = methods->at(hit);
1514 // Do linear search to find matching signature. First, quick check
1515 // for common case, ignoring overpasses if requested.
1516 if (method_matches(m, signature, skipping_overpass, skipping_static)) return hit;
1518 // search downwards through overloaded methods
1519 int i;
1520 for (i = hit - 1; i >= 0; --i) {
1521 Method* m = methods->at(i);
1522 assert(m->is_method(), "must be method");
1523 if (m->name() != name) break;
1524 if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
1525 }
1526 // search upwards
1527 for (i = hit + 1; i < methods->length(); ++i) {
1528 Method* m = methods->at(i);
1529 assert(m->is_method(), "must be method");
1530 if (m->name() != name) break;
1531 if (method_matches(m, signature, skipping_overpass, skipping_static)) return i;
1532 }
1533 // not found
1534 #ifdef ASSERT
1535 int index = skipping_overpass || skipping_static ? -1 : linear_search(methods, name, signature);
1536 assert(index == -1, err_msg("binary search should have found entry %d", index));
1537 #endif
1538 }
1539 return -1;
1540 }
1541 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
1542 return find_method_by_name(methods(), name, end);
1543 }
1545 int InstanceKlass::find_method_by_name(
1546 Array<Method*>* methods, Symbol* name, int* end_ptr) {
1547 assert(end_ptr != NULL, "just checking");
1548 int start = binary_search(methods, name);
1549 int end = start + 1;
1550 if (start != -1) {
1551 while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1552 while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1553 *end_ptr = end;
1554 return start;
1555 }
1556 return -1;
1557 }
1559 // uncached_lookup_method searches both the local class methods array and all
1560 // superclasses methods arrays, skipping any overpass methods in superclasses.
1561 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
1562 MethodLookupMode lookup_mode = mode;
1563 Klass* klass = const_cast<InstanceKlass*>(this);
1564 while (klass != NULL) {
1565 Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, (lookup_mode == skip_overpass));
1566 if (method != NULL) {
1567 return method;
1568 }
1569 klass = InstanceKlass::cast(klass)->super();
1570 lookup_mode = skip_overpass; // Always ignore overpass methods in superclasses
1571 }
1572 return NULL;
1573 }
1575 #ifdef ASSERT
1576 // search through class hierarchy and return true if this class or
1577 // one of the superclasses was redefined
1578 bool InstanceKlass::has_redefined_this_or_super() const {
1579 const InstanceKlass* klass = this;
1580 while (klass != NULL) {
1581 if (klass->has_been_redefined()) {
1582 return true;
1583 }
1584 klass = InstanceKlass::cast(klass->super());
1585 }
1586 return false;
1587 }
1588 #endif
1590 // lookup a method in the default methods list then in all transitive interfaces
1591 // Do NOT return private or static methods
1592 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1593 Symbol* signature) const {
1594 Method* m = NULL;
1595 if (default_methods() != NULL) {
1596 m = find_method(default_methods(), name, signature);
1597 }
1598 // Look up interfaces
1599 if (m == NULL) {
1600 m = lookup_method_in_all_interfaces(name, signature, normal);
1601 }
1602 return m;
1603 }
1605 // lookup a method in all the interfaces that this class implements
1606 // Do NOT return private or static methods, new in JDK8 which are not externally visible
1607 // They should only be found in the initial InterfaceMethodRef
1608 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1609 Symbol* signature,
1610 MethodLookupMode mode) const {
1611 Array<Klass*>* all_ifs = transitive_interfaces();
1612 int num_ifs = all_ifs->length();
1613 InstanceKlass *ik = NULL;
1614 for (int i = 0; i < num_ifs; i++) {
1615 ik = InstanceKlass::cast(all_ifs->at(i));
1616 Method* m = ik->lookup_method(name, signature);
1617 if (m != NULL && m->is_public() && !m->is_static() &&
1618 ((mode != skip_defaults) || !m->is_default_method())) {
1619 return m;
1620 }
1621 }
1622 return NULL;
1623 }
1625 /* jni_id_for_impl for jfieldIds only */
1626 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
1627 MutexLocker ml(JfieldIdCreation_lock);
1628 // Retry lookup after we got the lock
1629 JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
1630 if (probe == NULL) {
1631 // Slow case, allocate new static field identifier
1632 probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
1633 this_oop->set_jni_ids(probe);
1634 }
1635 return probe;
1636 }
1639 /* jni_id_for for jfieldIds only */
1640 JNIid* InstanceKlass::jni_id_for(int offset) {
1641 JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1642 if (probe == NULL) {
1643 probe = jni_id_for_impl(this, offset);
1644 }
1645 return probe;
1646 }
1648 u2 InstanceKlass::enclosing_method_data(int offset) {
1649 Array<jushort>* inner_class_list = inner_classes();
1650 if (inner_class_list == NULL) {
1651 return 0;
1652 }
1653 int length = inner_class_list->length();
1654 if (length % inner_class_next_offset == 0) {
1655 return 0;
1656 } else {
1657 int index = length - enclosing_method_attribute_size;
1658 assert(offset < enclosing_method_attribute_size, "invalid offset");
1659 return inner_class_list->at(index + offset);
1660 }
1661 }
1663 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1664 u2 method_index) {
1665 Array<jushort>* inner_class_list = inner_classes();
1666 assert (inner_class_list != NULL, "_inner_classes list is not set up");
1667 int length = inner_class_list->length();
1668 if (length % inner_class_next_offset == enclosing_method_attribute_size) {
1669 int index = length - enclosing_method_attribute_size;
1670 inner_class_list->at_put(
1671 index + enclosing_method_class_index_offset, class_index);
1672 inner_class_list->at_put(
1673 index + enclosing_method_method_index_offset, method_index);
1674 }
1675 }
1677 // Lookup or create a jmethodID.
1678 // This code is called by the VMThread and JavaThreads so the
1679 // locking has to be done very carefully to avoid deadlocks
1680 // and/or other cache consistency problems.
1681 //
1682 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
1683 size_t idnum = (size_t)method_h->method_idnum();
1684 jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1685 size_t length = 0;
1686 jmethodID id = NULL;
1688 // We use a double-check locking idiom here because this cache is
1689 // performance sensitive. In the normal system, this cache only
1690 // transitions from NULL to non-NULL which is safe because we use
1691 // release_set_methods_jmethod_ids() to advertise the new cache.
1692 // A partially constructed cache should never be seen by a racing
1693 // thread. We also use release_store_ptr() to save a new jmethodID
1694 // in the cache so a partially constructed jmethodID should never be
1695 // seen either. Cache reads of existing jmethodIDs proceed without a
1696 // lock, but cache writes of a new jmethodID requires uniqueness and
1697 // creation of the cache itself requires no leaks so a lock is
1698 // generally acquired in those two cases.
1699 //
1700 // If the RedefineClasses() API has been used, then this cache can
1701 // grow and we'll have transitions from non-NULL to bigger non-NULL.
1702 // Cache creation requires no leaks and we require safety between all
1703 // cache accesses and freeing of the old cache so a lock is generally
1704 // acquired when the RedefineClasses() API has been used.
1706 if (jmeths != NULL) {
1707 // the cache already exists
1708 if (!ik_h->idnum_can_increment()) {
1709 // the cache can't grow so we can just get the current values
1710 get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1711 } else {
1712 // cache can grow so we have to be more careful
1713 if (Threads::number_of_threads() == 0 ||
1714 SafepointSynchronize::is_at_safepoint()) {
1715 // we're single threaded or at a safepoint - no locking needed
1716 get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1717 } else {
1718 MutexLocker ml(JmethodIdCreation_lock);
1719 get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1720 }
1721 }
1722 }
1723 // implied else:
1724 // we need to allocate a cache so default length and id values are good
1726 if (jmeths == NULL || // no cache yet
1727 length <= idnum || // cache is too short
1728 id == NULL) { // cache doesn't contain entry
1730 // This function can be called by the VMThread so we have to do all
1731 // things that might block on a safepoint before grabbing the lock.
1732 // Otherwise, we can deadlock with the VMThread or have a cache
1733 // consistency issue. These vars keep track of what we might have
1734 // to free after the lock is dropped.
1735 jmethodID to_dealloc_id = NULL;
1736 jmethodID* to_dealloc_jmeths = NULL;
1738 // may not allocate new_jmeths or use it if we allocate it
1739 jmethodID* new_jmeths = NULL;
1740 if (length <= idnum) {
1741 // allocate a new cache that might be used
1742 size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
1743 new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
1744 memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1745 // cache size is stored in element[0], other elements offset by one
1746 new_jmeths[0] = (jmethodID)size;
1747 }
1749 // allocate a new jmethodID that might be used
1750 jmethodID new_id = NULL;
1751 if (method_h->is_old() && !method_h->is_obsolete()) {
1752 // The method passed in is old (but not obsolete), we need to use the current version
1753 Method* current_method = ik_h->method_with_idnum((int)idnum);
1754 assert(current_method != NULL, "old and but not obsolete, so should exist");
1755 new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
1756 } else {
1757 // It is the current version of the method or an obsolete method,
1758 // use the version passed in
1759 new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
1760 }
1762 if (Threads::number_of_threads() == 0 ||
1763 SafepointSynchronize::is_at_safepoint()) {
1764 // we're single threaded or at a safepoint - no locking needed
1765 id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1766 &to_dealloc_id, &to_dealloc_jmeths);
1767 } else {
1768 MutexLocker ml(JmethodIdCreation_lock);
1769 id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1770 &to_dealloc_id, &to_dealloc_jmeths);
1771 }
1773 // The lock has been dropped so we can free resources.
1774 // Free up either the old cache or the new cache if we allocated one.
1775 if (to_dealloc_jmeths != NULL) {
1776 FreeHeap(to_dealloc_jmeths);
1777 }
1778 // free up the new ID since it wasn't needed
1779 if (to_dealloc_id != NULL) {
1780 Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
1781 }
1782 }
1783 return id;
1784 }
1787 // Common code to fetch the jmethodID from the cache or update the
1788 // cache with the new jmethodID. This function should never do anything
1789 // that causes the caller to go to a safepoint or we can deadlock with
1790 // the VMThread or have cache consistency issues.
1791 //
1792 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
1793 instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
1794 jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
1795 jmethodID** to_dealloc_jmeths_p) {
1796 assert(new_id != NULL, "sanity check");
1797 assert(to_dealloc_id_p != NULL, "sanity check");
1798 assert(to_dealloc_jmeths_p != NULL, "sanity check");
1799 assert(Threads::number_of_threads() == 0 ||
1800 SafepointSynchronize::is_at_safepoint() ||
1801 JmethodIdCreation_lock->owned_by_self(), "sanity check");
1803 // reacquire the cache - we are locked, single threaded or at a safepoint
1804 jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1805 jmethodID id = NULL;
1806 size_t length = 0;
1808 if (jmeths == NULL || // no cache yet
1809 (length = (size_t)jmeths[0]) <= idnum) { // cache is too short
1810 if (jmeths != NULL) {
1811 // copy any existing entries from the old cache
1812 for (size_t index = 0; index < length; index++) {
1813 new_jmeths[index+1] = jmeths[index+1];
1814 }
1815 *to_dealloc_jmeths_p = jmeths; // save old cache for later delete
1816 }
1817 ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
1818 } else {
1819 // fetch jmethodID (if any) from the existing cache
1820 id = jmeths[idnum+1];
1821 *to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete
1822 }
1823 if (id == NULL) {
1824 // No matching jmethodID in the existing cache or we have a new
1825 // cache or we just grew the cache. This cache write is done here
1826 // by the first thread to win the foot race because a jmethodID
1827 // needs to be unique once it is generally available.
1828 id = new_id;
1830 // The jmethodID cache can be read while unlocked so we have to
1831 // make sure the new jmethodID is complete before installing it
1832 // in the cache.
1833 OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
1834 } else {
1835 *to_dealloc_id_p = new_id; // save new id for later delete
1836 }
1837 return id;
1838 }
1841 // Common code to get the jmethodID cache length and the jmethodID
1842 // value at index idnum if there is one.
1843 //
1844 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1845 size_t idnum, size_t *length_p, jmethodID* id_p) {
1846 assert(cache != NULL, "sanity check");
1847 assert(length_p != NULL, "sanity check");
1848 assert(id_p != NULL, "sanity check");
1850 // cache size is stored in element[0], other elements offset by one
1851 *length_p = (size_t)cache[0];
1852 if (*length_p <= idnum) { // cache is too short
1853 *id_p = NULL;
1854 } else {
1855 *id_p = cache[idnum+1]; // fetch jmethodID (if any)
1856 }
1857 }
1860 // Lookup a jmethodID, NULL if not found. Do no blocking, no allocations, no handles
1861 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
1862 size_t idnum = (size_t)method->method_idnum();
1863 jmethodID* jmeths = methods_jmethod_ids_acquire();
1864 size_t length; // length assigned as debugging crumb
1865 jmethodID id = NULL;
1866 if (jmeths != NULL && // If there is a cache
1867 (length = (size_t)jmeths[0]) > idnum) { // and if it is long enough,
1868 id = jmeths[idnum+1]; // Look up the id (may be NULL)
1869 }
1870 return id;
1871 }
1873 int nmethodBucket::decrement() {
1874 return Atomic::add(-1, (volatile int *)&_count);
1875 }
1877 //
1878 // Walk the list of dependent nmethods searching for nmethods which
1879 // are dependent on the changes that were passed in and mark them for
1880 // deoptimization. Returns the number of nmethods found.
1881 //
1882 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
1883 assert_locked_or_safepoint(CodeCache_lock);
1884 int found = 0;
1885 nmethodBucket* b = _dependencies;
1886 while (b != NULL) {
1887 nmethod* nm = b->get_nmethod();
1888 // since dependencies aren't removed until an nmethod becomes a zombie,
1889 // the dependency list may contain nmethods which aren't alive.
1890 if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
1891 if (TraceDependencies) {
1892 ResourceMark rm;
1893 tty->print_cr("Marked for deoptimization");
1894 tty->print_cr(" context = %s", this->external_name());
1895 changes.print();
1896 nm->print();
1897 nm->print_dependencies();
1898 }
1899 nm->mark_for_deoptimization();
1900 found++;
1901 }
1902 b = b->next();
1903 }
1904 return found;
1905 }
1907 void InstanceKlass::clean_dependent_nmethods() {
1908 assert_locked_or_safepoint(CodeCache_lock);
1910 if (has_unloaded_dependent()) {
1911 nmethodBucket* b = _dependencies;
1912 nmethodBucket* last = NULL;
1913 while (b != NULL) {
1914 assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
1916 nmethodBucket* next = b->next();
1918 if (b->count() == 0) {
1919 if (last == NULL) {
1920 _dependencies = next;
1921 } else {
1922 last->set_next(next);
1923 }
1924 delete b;
1925 // last stays the same.
1926 } else {
1927 last = b;
1928 }
1930 b = next;
1931 }
1932 set_has_unloaded_dependent(false);
1933 }
1934 #ifdef ASSERT
1935 else {
1936 // Verification
1937 for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
1938 assert(b->count() >= 0, err_msg("bucket count: %d", b->count()));
1939 assert(b->count() != 0, "empty buckets need to be cleaned");
1940 }
1941 }
1942 #endif
1943 }
1945 //
1946 // Add an nmethodBucket to the list of dependencies for this nmethod.
1947 // It's possible that an nmethod has multiple dependencies on this klass
1948 // so a count is kept for each bucket to guarantee that creation and
1949 // deletion of dependencies is consistent.
1950 //
1951 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
1952 assert_locked_or_safepoint(CodeCache_lock);
1953 nmethodBucket* b = _dependencies;
1954 nmethodBucket* last = NULL;
1955 while (b != NULL) {
1956 if (nm == b->get_nmethod()) {
1957 b->increment();
1958 return;
1959 }
1960 b = b->next();
1961 }
1962 _dependencies = new nmethodBucket(nm, _dependencies);
1963 }
1966 //
1967 // Decrement count of the nmethod in the dependency list and remove
1968 // the bucket competely when the count goes to 0. This method must
1969 // find a corresponding bucket otherwise there's a bug in the
1970 // recording of dependecies.
1971 //
1972 void InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) {
1973 assert_locked_or_safepoint(CodeCache_lock);
1974 nmethodBucket* b = _dependencies;
1975 nmethodBucket* last = NULL;
1976 while (b != NULL) {
1977 if (nm == b->get_nmethod()) {
1978 int val = b->decrement();
1979 guarantee(val >= 0, err_msg("Underflow: %d", val));
1980 if (val == 0) {
1981 if (delete_immediately) {
1982 if (last == NULL) {
1983 _dependencies = b->next();
1984 } else {
1985 last->set_next(b->next());
1986 }
1987 delete b;
1988 } else {
1989 // The deletion of this entry is deferred until a later, potentially parallel GC phase.
1990 set_has_unloaded_dependent(true);
1991 }
1992 }
1993 return;
1994 }
1995 last = b;
1996 b = b->next();
1997 }
1998 #ifdef ASSERT
1999 tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
2000 nm->print();
2001 #endif // ASSERT
2002 ShouldNotReachHere();
2003 }
2006 #ifndef PRODUCT
2007 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2008 nmethodBucket* b = _dependencies;
2009 int idx = 0;
2010 while (b != NULL) {
2011 nmethod* nm = b->get_nmethod();
2012 tty->print("[%d] count=%d { ", idx++, b->count());
2013 if (!verbose) {
2014 nm->print_on(tty, "nmethod");
2015 tty->print_cr(" } ");
2016 } else {
2017 nm->print();
2018 nm->print_dependencies();
2019 tty->print_cr("--- } ");
2020 }
2021 b = b->next();
2022 }
2023 }
2026 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2027 nmethodBucket* b = _dependencies;
2028 while (b != NULL) {
2029 if (nm == b->get_nmethod()) {
2030 #ifdef ASSERT
2031 int count = b->count();
2032 assert(count >= 0, err_msg("count shouldn't be negative: %d", count));
2033 #endif
2034 return true;
2035 }
2036 b = b->next();
2037 }
2038 return false;
2039 }
2040 #endif //PRODUCT
2043 // Garbage collection
2045 #ifdef ASSERT
2046 template <class T> void assert_is_in(T *p) {
2047 T heap_oop = oopDesc::load_heap_oop(p);
2048 if (!oopDesc::is_null(heap_oop)) {
2049 oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
2050 assert(Universe::heap()->is_in(o), "should be in heap");
2051 }
2052 }
2053 template <class T> void assert_is_in_closed_subset(T *p) {
2054 T heap_oop = oopDesc::load_heap_oop(p);
2055 if (!oopDesc::is_null(heap_oop)) {
2056 oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
2057 assert(Universe::heap()->is_in_closed_subset(o),
2058 err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
2059 }
2060 }
2061 template <class T> void assert_is_in_reserved(T *p) {
2062 T heap_oop = oopDesc::load_heap_oop(p);
2063 if (!oopDesc::is_null(heap_oop)) {
2064 oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
2065 assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
2066 }
2067 }
2068 template <class T> void assert_nothing(T *p) {}
2070 #else
2071 template <class T> void assert_is_in(T *p) {}
2072 template <class T> void assert_is_in_closed_subset(T *p) {}
2073 template <class T> void assert_is_in_reserved(T *p) {}
2074 template <class T> void assert_nothing(T *p) {}
2075 #endif // ASSERT
2077 //
2078 // Macros that iterate over areas of oops which are specialized on type of
2079 // oop pointer either narrow or wide, depending on UseCompressedOops
2080 //
2081 // Parameters are:
2082 // T - type of oop to point to (either oop or narrowOop)
2083 // start_p - starting pointer for region to iterate over
2084 // count - number of oops or narrowOops to iterate over
2085 // do_oop - action to perform on each oop (it's arbitrary C code which
2086 // makes it more efficient to put in a macro rather than making
2087 // it a template function)
2088 // assert_fn - assert function which is template function because performance
2089 // doesn't matter when enabled.
2090 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
2091 T, start_p, count, do_oop, \
2092 assert_fn) \
2093 { \
2094 T* p = (T*)(start_p); \
2095 T* const end = p + (count); \
2096 while (p < end) { \
2097 (assert_fn)(p); \
2098 do_oop; \
2099 ++p; \
2100 } \
2101 }
2103 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
2104 T, start_p, count, do_oop, \
2105 assert_fn) \
2106 { \
2107 T* const start = (T*)(start_p); \
2108 T* p = start + (count); \
2109 while (start < p) { \
2110 --p; \
2111 (assert_fn)(p); \
2112 do_oop; \
2113 } \
2114 }
2116 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
2117 T, start_p, count, low, high, \
2118 do_oop, assert_fn) \
2119 { \
2120 T* const l = (T*)(low); \
2121 T* const h = (T*)(high); \
2122 assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
2123 mask_bits((intptr_t)h, sizeof(T)-1) == 0, \
2124 "bounded region must be properly aligned"); \
2125 T* p = (T*)(start_p); \
2126 T* end = p + (count); \
2127 if (p < l) p = l; \
2128 if (end > h) end = h; \
2129 while (p < end) { \
2130 (assert_fn)(p); \
2131 do_oop; \
2132 ++p; \
2133 } \
2134 }
2137 // The following macros call specialized macros, passing either oop or
2138 // narrowOop as the specialization type. These test the UseCompressedOops
2139 // flag.
2140 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn) \
2141 { \
2142 /* Compute oopmap block range. The common case \
2143 is nonstatic_oop_map_size == 1. */ \
2144 OopMapBlock* map = start_of_nonstatic_oop_maps(); \
2145 OopMapBlock* const end_map = map + nonstatic_oop_map_count(); \
2146 if (UseCompressedOops) { \
2147 while (map < end_map) { \
2148 InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop, \
2149 obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \
2150 do_oop, assert_fn) \
2151 ++map; \
2152 } \
2153 } else { \
2154 while (map < end_map) { \
2155 InstanceKlass_SPECIALIZED_OOP_ITERATE(oop, \
2156 obj->obj_field_addr<oop>(map->offset()), map->count(), \
2157 do_oop, assert_fn) \
2158 ++map; \
2159 } \
2160 } \
2161 }
2163 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn) \
2164 { \
2165 OopMapBlock* const start_map = start_of_nonstatic_oop_maps(); \
2166 OopMapBlock* map = start_map + nonstatic_oop_map_count(); \
2167 if (UseCompressedOops) { \
2168 while (start_map < map) { \
2169 --map; \
2170 InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop, \
2171 obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \
2172 do_oop, assert_fn) \
2173 } \
2174 } else { \
2175 while (start_map < map) { \
2176 --map; \
2177 InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop, \
2178 obj->obj_field_addr<oop>(map->offset()), map->count(), \
2179 do_oop, assert_fn) \
2180 } \
2181 } \
2182 }
2184 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop, \
2185 assert_fn) \
2186 { \
2187 /* Compute oopmap block range. The common case is \
2188 nonstatic_oop_map_size == 1, so we accept the \
2189 usually non-existent extra overhead of examining \
2190 all the maps. */ \
2191 OopMapBlock* map = start_of_nonstatic_oop_maps(); \
2192 OopMapBlock* const end_map = map + nonstatic_oop_map_count(); \
2193 if (UseCompressedOops) { \
2194 while (map < end_map) { \
2195 InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop, \
2196 obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \
2197 low, high, \
2198 do_oop, assert_fn) \
2199 ++map; \
2200 } \
2201 } else { \
2202 while (map < end_map) { \
2203 InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop, \
2204 obj->obj_field_addr<oop>(map->offset()), map->count(), \
2205 low, high, \
2206 do_oop, assert_fn) \
2207 ++map; \
2208 } \
2209 } \
2210 }
2212 void InstanceKlass::oop_follow_contents(oop obj) {
2213 assert(obj != NULL, "can't follow the content of NULL object");
2214 MarkSweep::follow_klass(obj->klass());
2215 InstanceKlass_OOP_MAP_ITERATE( \
2216 obj, \
2217 MarkSweep::mark_and_push(p), \
2218 assert_is_in_closed_subset)
2219 }
2221 #if INCLUDE_ALL_GCS
2222 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
2223 oop obj) {
2224 assert(obj != NULL, "can't follow the content of NULL object");
2225 PSParallelCompact::follow_klass(cm, obj->klass());
2226 // Only mark the header and let the scan of the meta-data mark
2227 // everything else.
2228 InstanceKlass_OOP_MAP_ITERATE( \
2229 obj, \
2230 PSParallelCompact::mark_and_push(cm, p), \
2231 assert_is_in)
2232 }
2233 #endif // INCLUDE_ALL_GCS
2235 // closure's do_metadata() method dictates whether the given closure should be
2236 // applied to the klass ptr in the object header.
2238 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix) \
2239 \
2240 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
2241 SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2242 /* header */ \
2243 if_do_metadata_checked(closure, nv_suffix) { \
2244 closure->do_klass##nv_suffix(obj->klass()); \
2245 } \
2246 InstanceKlass_OOP_MAP_ITERATE( \
2247 obj, \
2248 SpecializationStats:: \
2249 record_do_oop_call##nv_suffix(SpecializationStats::ik); \
2250 (closure)->do_oop##nv_suffix(p), \
2251 assert_is_in_closed_subset) \
2252 return size_helper(); \
2253 }
2255 #if INCLUDE_ALL_GCS
2256 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
2257 \
2258 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj, \
2259 OopClosureType* closure) { \
2260 SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
2261 \
2262 assert_should_ignore_metadata(closure, nv_suffix); \
2263 \
2264 /* instance variables */ \
2265 InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
2266 obj, \
2267 SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
2268 (closure)->do_oop##nv_suffix(p), \
2269 assert_is_in_closed_subset) \
2270 return size_helper(); \
2271 }
2272 #endif // INCLUDE_ALL_GCS
2274 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
2275 \
2276 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj, \
2277 OopClosureType* closure, \
2278 MemRegion mr) { \
2279 SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2280 if_do_metadata_checked(closure, nv_suffix) { \
2281 if (mr.contains(obj)) { \
2282 closure->do_klass##nv_suffix(obj->klass()); \
2283 } \
2284 } \
2285 InstanceKlass_BOUNDED_OOP_MAP_ITERATE( \
2286 obj, mr.start(), mr.end(), \
2287 (closure)->do_oop##nv_suffix(p), \
2288 assert_is_in_closed_subset) \
2289 return size_helper(); \
2290 }
2292 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2293 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2294 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2295 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2296 #if INCLUDE_ALL_GCS
2297 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2298 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2299 #endif // INCLUDE_ALL_GCS
2301 int InstanceKlass::oop_adjust_pointers(oop obj) {
2302 int size = size_helper();
2303 InstanceKlass_OOP_MAP_ITERATE( \
2304 obj, \
2305 MarkSweep::adjust_pointer(p), \
2306 assert_is_in)
2307 return size;
2308 }
2310 #if INCLUDE_ALL_GCS
2311 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
2312 InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
2313 obj, \
2314 if (PSScavenge::should_scavenge(p)) { \
2315 pm->claim_or_forward_depth(p); \
2316 }, \
2317 assert_nothing )
2318 }
2320 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
2321 int size = size_helper();
2322 InstanceKlass_OOP_MAP_ITERATE( \
2323 obj, \
2324 PSParallelCompact::adjust_pointer(p), \
2325 assert_is_in)
2326 return size;
2327 }
2329 #endif // INCLUDE_ALL_GCS
2331 void InstanceKlass::clean_weak_instanceklass_links(BoolObjectClosure* is_alive) {
2332 clean_implementors_list(is_alive);
2333 clean_method_data(is_alive);
2335 clean_dependent_nmethods();
2336 }
2338 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
2339 assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
2340 if (is_interface()) {
2341 if (ClassUnloading) {
2342 Klass* impl = implementor();
2343 if (impl != NULL) {
2344 if (!impl->is_loader_alive(is_alive)) {
2345 // remove this guy
2346 Klass** klass = adr_implementor();
2347 assert(klass != NULL, "null klass");
2348 if (klass != NULL) {
2349 *klass = NULL;
2350 }
2351 }
2352 }
2353 }
2354 }
2355 }
2357 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
2358 for (int m = 0; m < methods()->length(); m++) {
2359 MethodData* mdo = methods()->at(m)->method_data();
2360 if (mdo != NULL) {
2361 mdo->clean_method_data(is_alive);
2362 }
2363 }
2364 }
2367 static void remove_unshareable_in_class(Klass* k) {
2368 // remove klass's unshareable info
2369 k->remove_unshareable_info();
2370 }
2372 void InstanceKlass::remove_unshareable_info() {
2373 Klass::remove_unshareable_info();
2374 // Unlink the class
2375 if (is_linked()) {
2376 unlink_class();
2377 }
2378 init_implementor();
2380 constants()->remove_unshareable_info();
2382 for (int i = 0; i < methods()->length(); i++) {
2383 Method* m = methods()->at(i);
2384 m->remove_unshareable_info();
2385 }
2387 // do array classes also.
2388 array_klasses_do(remove_unshareable_in_class);
2389 }
2391 static void restore_unshareable_in_class(Klass* k, TRAPS) {
2392 // Array classes have null protection domain.
2393 // --> see ArrayKlass::complete_create_array_klass()
2394 k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
2395 }
2397 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
2398 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
2399 instanceKlassHandle ik(THREAD, this);
2401 Array<Method*>* methods = ik->methods();
2402 int num_methods = methods->length();
2403 for (int index2 = 0; index2 < num_methods; ++index2) {
2404 methodHandle m(THREAD, methods->at(index2));
2405 m->restore_unshareable_info(CHECK);
2406 }
2407 if (JvmtiExport::has_redefined_a_class()) {
2408 // Reinitialize vtable because RedefineClasses may have changed some
2409 // entries in this vtable for super classes so the CDS vtable might
2410 // point to old or obsolete entries. RedefineClasses doesn't fix up
2411 // vtables in the shared system dictionary, only the main one.
2412 // It also redefines the itable too so fix that too.
2413 ResourceMark rm(THREAD);
2414 ik->vtable()->initialize_vtable(false, CHECK);
2415 ik->itable()->initialize_itable(false, CHECK);
2416 }
2418 // restore constant pool resolved references
2419 ik->constants()->restore_unshareable_info(CHECK);
2421 ik->array_klasses_do(restore_unshareable_in_class, CHECK);
2422 }
2424 // returns true IFF is_in_error_state() has been changed as a result of this call.
2425 bool InstanceKlass::check_sharing_error_state() {
2426 assert(DumpSharedSpaces, "should only be called during dumping");
2427 bool old_state = is_in_error_state();
2429 if (!is_in_error_state()) {
2430 bool bad = false;
2431 for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
2432 if (sup->is_in_error_state()) {
2433 bad = true;
2434 break;
2435 }
2436 }
2437 if (!bad) {
2438 Array<Klass*>* interfaces = transitive_interfaces();
2439 for (int i = 0; i < interfaces->length(); i++) {
2440 Klass* iface = interfaces->at(i);
2441 if (InstanceKlass::cast(iface)->is_in_error_state()) {
2442 bad = true;
2443 break;
2444 }
2445 }
2446 }
2448 if (bad) {
2449 set_in_error_state();
2450 }
2451 }
2453 return (old_state != is_in_error_state());
2454 }
2456 static void clear_all_breakpoints(Method* m) {
2457 m->clear_all_breakpoints();
2458 }
2461 void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
2462 // notify the debugger
2463 if (JvmtiExport::should_post_class_unload()) {
2464 JvmtiExport::post_class_unload(ik);
2465 }
2467 // notify ClassLoadingService of class unload
2468 ClassLoadingService::notify_class_unloaded(ik);
2469 }
2471 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2472 // Clean up C heap
2473 ik->release_C_heap_structures();
2474 ik->constants()->release_C_heap_structures();
2475 }
2477 void InstanceKlass::release_C_heap_structures() {
2479 // Can't release the constant pool here because the constant pool can be
2480 // deallocated separately from the InstanceKlass for default methods and
2481 // redefine classes.
2483 // Deallocate oop map cache
2484 if (_oop_map_cache != NULL) {
2485 delete _oop_map_cache;
2486 _oop_map_cache = NULL;
2487 }
2489 // Deallocate JNI identifiers for jfieldIDs
2490 JNIid::deallocate(jni_ids());
2491 set_jni_ids(NULL);
2493 jmethodID* jmeths = methods_jmethod_ids_acquire();
2494 if (jmeths != (jmethodID*)NULL) {
2495 release_set_methods_jmethod_ids(NULL);
2496 FreeHeap(jmeths);
2497 }
2499 // Deallocate MemberNameTable
2500 {
2501 Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
2502 MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
2503 MemberNameTable* mnt = member_names();
2504 if (mnt != NULL) {
2505 delete mnt;
2506 set_member_names(NULL);
2507 }
2508 }
2510 // release dependencies
2511 nmethodBucket* b = _dependencies;
2512 _dependencies = NULL;
2513 while (b != NULL) {
2514 nmethodBucket* next = b->next();
2515 delete b;
2516 b = next;
2517 }
2519 // Deallocate breakpoint records
2520 if (breakpoints() != 0x0) {
2521 methods_do(clear_all_breakpoints);
2522 assert(breakpoints() == 0x0, "should have cleared breakpoints");
2523 }
2525 // deallocate information about previous versions
2526 if (_previous_versions != NULL) {
2527 for (int i = _previous_versions->length() - 1; i >= 0; i--) {
2528 PreviousVersionNode * pv_node = _previous_versions->at(i);
2529 delete pv_node;
2530 }
2531 delete _previous_versions;
2532 _previous_versions = NULL;
2533 }
2535 // deallocate the cached class file
2536 if (_cached_class_file != NULL) {
2537 os::free(_cached_class_file, mtClass);
2538 _cached_class_file = NULL;
2539 }
2541 // Decrement symbol reference counts associated with the unloaded class.
2542 if (_name != NULL) _name->decrement_refcount();
2543 // unreference array name derived from this class name (arrays of an unloaded
2544 // class can't be referenced anymore).
2545 if (_array_name != NULL) _array_name->decrement_refcount();
2546 if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
2548 assert(_total_instanceKlass_count >= 1, "Sanity check");
2549 Atomic::dec(&_total_instanceKlass_count);
2550 }
2552 void InstanceKlass::set_source_debug_extension(char* array, int length) {
2553 if (array == NULL) {
2554 _source_debug_extension = NULL;
2555 } else {
2556 // Adding one to the attribute length in order to store a null terminator
2557 // character could cause an overflow because the attribute length is
2558 // already coded with an u4 in the classfile, but in practice, it's
2559 // unlikely to happen.
2560 assert((length+1) > length, "Overflow checking");
2561 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2562 for (int i = 0; i < length; i++) {
2563 sde[i] = array[i];
2564 }
2565 sde[length] = '\0';
2566 _source_debug_extension = sde;
2567 }
2568 }
2570 address InstanceKlass::static_field_addr(int offset) {
2571 return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
2572 }
2575 const char* InstanceKlass::signature_name() const {
2576 int hash_len = 0;
2577 char hash_buf[40];
2579 // If this is an anonymous class, append a hash to make the name unique
2580 if (is_anonymous()) {
2581 assert(EnableInvokeDynamic, "EnableInvokeDynamic was not set.");
2582 intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2583 sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
2584 hash_len = (int)strlen(hash_buf);
2585 }
2587 // Get the internal name as a c string
2588 const char* src = (const char*) (name()->as_C_string());
2589 const int src_length = (int)strlen(src);
2591 char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2593 // Add L as type indicator
2594 int dest_index = 0;
2595 dest[dest_index++] = 'L';
2597 // Add the actual class name
2598 for (int src_index = 0; src_index < src_length; ) {
2599 dest[dest_index++] = src[src_index++];
2600 }
2602 // If we have a hash, append it
2603 for (int hash_index = 0; hash_index < hash_len; ) {
2604 dest[dest_index++] = hash_buf[hash_index++];
2605 }
2607 // Add the semicolon and the NULL
2608 dest[dest_index++] = ';';
2609 dest[dest_index] = '\0';
2610 return dest;
2611 }
2613 // different verisons of is_same_class_package
2614 bool InstanceKlass::is_same_class_package(Klass* class2) {
2615 Klass* class1 = this;
2616 oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2617 Symbol* classname1 = class1->name();
2619 if (class2->oop_is_objArray()) {
2620 class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2621 }
2622 oop classloader2;
2623 if (class2->oop_is_instance()) {
2624 classloader2 = InstanceKlass::cast(class2)->class_loader();
2625 } else {
2626 assert(class2->oop_is_typeArray(), "should be type array");
2627 classloader2 = NULL;
2628 }
2629 Symbol* classname2 = class2->name();
2631 return InstanceKlass::is_same_class_package(classloader1, classname1,
2632 classloader2, classname2);
2633 }
2635 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
2636 Klass* class1 = this;
2637 oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2638 Symbol* classname1 = class1->name();
2640 return InstanceKlass::is_same_class_package(classloader1, classname1,
2641 classloader2, classname2);
2642 }
2644 // return true if two classes are in the same package, classloader
2645 // and classname information is enough to determine a class's package
2646 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2647 oop class_loader2, Symbol* class_name2) {
2648 if (class_loader1 != class_loader2) {
2649 return false;
2650 } else if (class_name1 == class_name2) {
2651 return true; // skip painful bytewise comparison
2652 } else {
2653 ResourceMark rm;
2655 // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
2656 // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
2657 // Otherwise, we just compare jbyte values between the strings.
2658 const jbyte *name1 = class_name1->base();
2659 const jbyte *name2 = class_name2->base();
2661 const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
2662 const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
2664 if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
2665 // One of the two doesn't have a package. Only return true
2666 // if the other one also doesn't have a package.
2667 return last_slash1 == last_slash2;
2668 } else {
2669 // Skip over '['s
2670 if (*name1 == '[') {
2671 do {
2672 name1++;
2673 } while (*name1 == '[');
2674 if (*name1 != 'L') {
2675 // Something is terribly wrong. Shouldn't be here.
2676 return false;
2677 }
2678 }
2679 if (*name2 == '[') {
2680 do {
2681 name2++;
2682 } while (*name2 == '[');
2683 if (*name2 != 'L') {
2684 // Something is terribly wrong. Shouldn't be here.
2685 return false;
2686 }
2687 }
2689 // Check that package part is identical
2690 int length1 = last_slash1 - name1;
2691 int length2 = last_slash2 - name2;
2693 return UTF8::equal(name1, length1, name2, length2);
2694 }
2695 }
2696 }
2698 // Returns true iff super_method can be overridden by a method in targetclassname
2699 // See JSL 3rd edition 8.4.6.1
2700 // Assumes name-signature match
2701 // "this" is InstanceKlass of super_method which must exist
2702 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2703 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2704 // Private methods can not be overridden
2705 if (super_method->is_private()) {
2706 return false;
2707 }
2708 // If super method is accessible, then override
2709 if ((super_method->is_protected()) ||
2710 (super_method->is_public())) {
2711 return true;
2712 }
2713 // Package-private methods are not inherited outside of package
2714 assert(super_method->is_package_private(), "must be package private");
2715 return(is_same_class_package(targetclassloader(), targetclassname));
2716 }
2718 /* defined for now in jvm.cpp, for historical reasons *--
2719 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2720 Symbol*& simple_name_result, TRAPS) {
2721 ...
2722 }
2723 */
2725 // tell if two classes have the same enclosing class (at package level)
2726 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
2727 Klass* class2_oop, TRAPS) {
2728 if (class2_oop == class1()) return true;
2729 if (!class2_oop->oop_is_instance()) return false;
2730 instanceKlassHandle class2(THREAD, class2_oop);
2732 // must be in same package before we try anything else
2733 if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
2734 return false;
2736 // As long as there is an outer1.getEnclosingClass,
2737 // shift the search outward.
2738 instanceKlassHandle outer1 = class1;
2739 for (;;) {
2740 // As we walk along, look for equalities between outer1 and class2.
2741 // Eventually, the walks will terminate as outer1 stops
2742 // at the top-level class around the original class.
2743 bool ignore_inner_is_member;
2744 Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2745 CHECK_false);
2746 if (next == NULL) break;
2747 if (next == class2()) return true;
2748 outer1 = instanceKlassHandle(THREAD, next);
2749 }
2751 // Now do the same for class2.
2752 instanceKlassHandle outer2 = class2;
2753 for (;;) {
2754 bool ignore_inner_is_member;
2755 Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2756 CHECK_false);
2757 if (next == NULL) break;
2758 // Might as well check the new outer against all available values.
2759 if (next == class1()) return true;
2760 if (next == outer1()) return true;
2761 outer2 = instanceKlassHandle(THREAD, next);
2762 }
2764 // If by this point we have not found an equality between the
2765 // two classes, we know they are in separate package members.
2766 return false;
2767 }
2770 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2771 jint access = access_flags().as_int();
2773 // But check if it happens to be member class.
2774 instanceKlassHandle ik(THREAD, this);
2775 InnerClassesIterator iter(ik);
2776 for (; !iter.done(); iter.next()) {
2777 int ioff = iter.inner_class_info_index();
2778 // Inner class attribute can be zero, skip it.
2779 // Strange but true: JVM spec. allows null inner class refs.
2780 if (ioff == 0) continue;
2782 // only look at classes that are already loaded
2783 // since we are looking for the flags for our self.
2784 Symbol* inner_name = ik->constants()->klass_name_at(ioff);
2785 if ((ik->name() == inner_name)) {
2786 // This is really a member class.
2787 access = iter.inner_access_flags();
2788 break;
2789 }
2790 }
2791 // Remember to strip ACC_SUPER bit
2792 return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2793 }
2795 jint InstanceKlass::jvmti_class_status() const {
2796 jint result = 0;
2798 if (is_linked()) {
2799 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2800 }
2802 if (is_initialized()) {
2803 assert(is_linked(), "Class status is not consistent");
2804 result |= JVMTI_CLASS_STATUS_INITIALIZED;
2805 }
2806 if (is_in_error_state()) {
2807 result |= JVMTI_CLASS_STATUS_ERROR;
2808 }
2809 return result;
2810 }
2812 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2813 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2814 int method_table_offset_in_words = ioe->offset()/wordSize;
2815 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2816 / itableOffsetEntry::size();
2818 for (int cnt = 0 ; ; cnt ++, ioe ++) {
2819 // If the interface isn't implemented by the receiver class,
2820 // the VM should throw IncompatibleClassChangeError.
2821 if (cnt >= nof_interfaces) {
2822 THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
2823 }
2825 Klass* ik = ioe->interface_klass();
2826 if (ik == holder) break;
2827 }
2829 itableMethodEntry* ime = ioe->first_method_entry(this);
2830 Method* m = ime[index].method();
2831 if (m == NULL) {
2832 THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2833 }
2834 return m;
2835 }
2838 #if INCLUDE_JVMTI
2839 // update default_methods for redefineclasses for methods that are
2840 // not yet in the vtable due to concurrent subclass define and superinterface
2841 // redefinition
2842 // Note: those in the vtable, should have been updated via adjust_method_entries
2843 void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {
2844 // search the default_methods for uses of either obsolete or EMCP methods
2845 if (default_methods() != NULL) {
2846 for (int index = 0; index < default_methods()->length(); index ++) {
2847 Method* old_method = default_methods()->at(index);
2848 if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
2849 continue; // skip uninteresting entries
2850 }
2851 assert(!old_method->is_deleted(), "default methods may not be deleted");
2853 Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
2855 assert(new_method != NULL, "method_with_idnum() should not be NULL");
2856 assert(old_method != new_method, "sanity check");
2858 default_methods()->at_put(index, new_method);
2859 if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
2860 if (!(*trace_name_printed)) {
2861 // RC_TRACE_MESG macro has an embedded ResourceMark
2862 RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
2863 external_name(),
2864 old_method->method_holder()->external_name()));
2865 *trace_name_printed = true;
2866 }
2867 RC_TRACE(0x00100000, ("default method update: %s(%s) ",
2868 new_method->name()->as_C_string(),
2869 new_method->signature()->as_C_string()));
2870 }
2871 }
2872 }
2873 }
2874 #endif // INCLUDE_JVMTI
2876 // On-stack replacement stuff
2877 void InstanceKlass::add_osr_nmethod(nmethod* n) {
2878 // only one compilation can be active
2879 NEEDS_CLEANUP
2880 // This is a short non-blocking critical region, so the no safepoint check is ok.
2881 OsrList_lock->lock_without_safepoint_check();
2882 assert(n->is_osr_method(), "wrong kind of nmethod");
2883 n->set_osr_link(osr_nmethods_head());
2884 set_osr_nmethods_head(n);
2885 // Raise the highest osr level if necessary
2886 if (TieredCompilation) {
2887 Method* m = n->method();
2888 m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2889 }
2890 // Remember to unlock again
2891 OsrList_lock->unlock();
2893 // Get rid of the osr methods for the same bci that have lower levels.
2894 if (TieredCompilation) {
2895 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2896 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2897 if (inv != NULL && inv->is_in_use()) {
2898 inv->make_not_entrant();
2899 }
2900 }
2901 }
2902 }
2905 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
2906 // This is a short non-blocking critical region, so the no safepoint check is ok.
2907 OsrList_lock->lock_without_safepoint_check();
2908 assert(n->is_osr_method(), "wrong kind of nmethod");
2909 nmethod* last = NULL;
2910 nmethod* cur = osr_nmethods_head();
2911 int max_level = CompLevel_none; // Find the max comp level excluding n
2912 Method* m = n->method();
2913 // Search for match
2914 while(cur != NULL && cur != n) {
2915 if (TieredCompilation && m == cur->method()) {
2916 // Find max level before n
2917 max_level = MAX2(max_level, cur->comp_level());
2918 }
2919 last = cur;
2920 cur = cur->osr_link();
2921 }
2922 nmethod* next = NULL;
2923 if (cur == n) {
2924 next = cur->osr_link();
2925 if (last == NULL) {
2926 // Remove first element
2927 set_osr_nmethods_head(next);
2928 } else {
2929 last->set_osr_link(next);
2930 }
2931 }
2932 n->set_osr_link(NULL);
2933 if (TieredCompilation) {
2934 cur = next;
2935 while (cur != NULL) {
2936 // Find max level after n
2937 if (m == cur->method()) {
2938 max_level = MAX2(max_level, cur->comp_level());
2939 }
2940 cur = cur->osr_link();
2941 }
2942 m->set_highest_osr_comp_level(max_level);
2943 }
2944 // Remember to unlock again
2945 OsrList_lock->unlock();
2946 }
2948 int InstanceKlass::mark_osr_nmethods(const Method* m) {
2949 // This is a short non-blocking critical region, so the no safepoint check is ok.
2950 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2951 nmethod* osr = osr_nmethods_head();
2952 int found = 0;
2953 while (osr != NULL) {
2954 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2955 if (osr->method() == m) {
2956 osr->mark_for_deoptimization();
2957 found++;
2958 }
2959 osr = osr->osr_link();
2960 }
2961 return found;
2962 }
2964 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
2965 // This is a short non-blocking critical region, so the no safepoint check is ok.
2966 OsrList_lock->lock_without_safepoint_check();
2967 nmethod* osr = osr_nmethods_head();
2968 nmethod* best = NULL;
2969 while (osr != NULL) {
2970 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2971 // There can be a time when a c1 osr method exists but we are waiting
2972 // for a c2 version. When c2 completes its osr nmethod we will trash
2973 // the c1 version and only be able to find the c2 version. However
2974 // while we overflow in the c1 code at back branches we don't want to
2975 // try and switch to the same code as we are already running
2977 if (osr->method() == m &&
2978 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
2979 if (match_level) {
2980 if (osr->comp_level() == comp_level) {
2981 // Found a match - return it.
2982 OsrList_lock->unlock();
2983 return osr;
2984 }
2985 } else {
2986 if (best == NULL || (osr->comp_level() > best->comp_level())) {
2987 if (osr->comp_level() == CompLevel_highest_tier) {
2988 // Found the best possible - return it.
2989 OsrList_lock->unlock();
2990 return osr;
2991 }
2992 best = osr;
2993 }
2994 }
2995 }
2996 osr = osr->osr_link();
2997 }
2998 OsrList_lock->unlock();
2999 if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
3000 return best;
3001 }
3002 return NULL;
3003 }
3005 bool InstanceKlass::add_member_name(Handle mem_name) {
3006 jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
3007 MutexLocker ml(MemberNameTable_lock);
3008 DEBUG_ONLY(No_Safepoint_Verifier nsv);
3010 // Check if method has been redefined while taking out MemberNameTable_lock, if so
3011 // return false. We cannot cache obsolete methods. They will crash when the function
3012 // is called!
3013 Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());
3014 if (method->is_obsolete()) {
3015 return false;
3016 } else if (method->is_old()) {
3017 // Replace method with redefined version
3018 java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));
3019 }
3021 if (_member_names == NULL) {
3022 _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
3023 }
3024 _member_names->add_member_name(mem_name_wref);
3025 return true;
3026 }
3028 // -----------------------------------------------------------------------------------------------------
3029 // Printing
3031 #ifndef PRODUCT
3033 #define BULLET " - "
3035 static const char* state_names[] = {
3036 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3037 };
3039 static void print_vtable(intptr_t* start, int len, outputStream* st) {
3040 for (int i = 0; i < len; i++) {
3041 intptr_t e = start[i];
3042 st->print("%d : " INTPTR_FORMAT, i, e);
3043 if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
3044 st->print(" ");
3045 ((Metadata*)e)->print_value_on(st);
3046 }
3047 st->cr();
3048 }
3049 }
3051 void InstanceKlass::print_on(outputStream* st) const {
3052 assert(is_klass(), "must be klass");
3053 Klass::print_on(st);
3055 st->print(BULLET"instance size: %d", size_helper()); st->cr();
3056 st->print(BULLET"klass size: %d", size()); st->cr();
3057 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
3058 st->print(BULLET"state: "); st->print_cr("%s", state_names[_init_state]);
3059 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
3060 st->print(BULLET"super: "); super()->print_value_on_maybe_null(st); st->cr();
3061 st->print(BULLET"sub: ");
3062 Klass* sub = subklass();
3063 int n;
3064 for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3065 if (n < MaxSubklassPrintSize) {
3066 sub->print_value_on(st);
3067 st->print(" ");
3068 }
3069 }
3070 if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
3071 st->cr();
3073 if (is_interface()) {
3074 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
3075 if (nof_implementors() == 1) {
3076 st->print_cr(BULLET"implementor: ");
3077 st->print(" ");
3078 implementor()->print_value_on(st);
3079 st->cr();
3080 }
3081 }
3083 st->print(BULLET"arrays: "); array_klasses()->print_value_on_maybe_null(st); st->cr();
3084 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
3085 if (Verbose || WizardMode) {
3086 Array<Method*>* method_array = methods();
3087 for (int i = 0; i < method_array->length(); i++) {
3088 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3089 }
3090 }
3091 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
3092 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr();
3093 if (Verbose && default_methods() != NULL) {
3094 Array<Method*>* method_array = default_methods();
3095 for (int i = 0; i < method_array->length(); i++) {
3096 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3097 }
3098 }
3099 if (default_vtable_indices() != NULL) {
3100 st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr();
3101 }
3102 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
3103 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3104 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();
3105 if (class_loader_data() != NULL) {
3106 st->print(BULLET"class loader data: ");
3107 class_loader_data()->print_value_on(st);
3108 st->cr();
3109 }
3110 st->print(BULLET"host class: "); host_klass()->print_value_on_maybe_null(st); st->cr();
3111 if (source_file_name() != NULL) {
3112 st->print(BULLET"source file: ");
3113 source_file_name()->print_value_on(st);
3114 st->cr();
3115 }
3116 if (source_debug_extension() != NULL) {
3117 st->print(BULLET"source debug extension: ");
3118 st->print("%s", source_debug_extension());
3119 st->cr();
3120 }
3121 st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr();
3122 st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr();
3123 st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr();
3124 st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr();
3125 {
3126 bool have_pv = false;
3127 PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
3128 for (PreviousVersionNode * pv_node = pvw.next_previous_version();
3129 pv_node != NULL; pv_node = pvw.next_previous_version()) {
3130 if (!have_pv)
3131 st->print(BULLET"previous version: ");
3132 have_pv = true;
3133 pv_node->prev_constant_pool()->print_value_on(st);
3134 }
3135 if (have_pv) st->cr();
3136 } // pvw is cleaned up
3138 if (generic_signature() != NULL) {
3139 st->print(BULLET"generic signature: ");
3140 generic_signature()->print_value_on(st);
3141 st->cr();
3142 }
3143 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
3144 st->print(BULLET"java mirror: "); java_mirror()->print_value_on(st); st->cr();
3145 st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable()); st->cr();
3146 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
3147 st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
3148 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st);
3149 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3150 FieldPrinter print_static_field(st);
3151 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3152 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3153 FieldPrinter print_nonstatic_field(st);
3154 ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
3156 st->print(BULLET"non-static oop maps: ");
3157 OopMapBlock* map = start_of_nonstatic_oop_maps();
3158 OopMapBlock* end_map = map + nonstatic_oop_map_count();
3159 while (map < end_map) {
3160 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3161 map++;
3162 }
3163 st->cr();
3164 }
3166 #endif //PRODUCT
3168 void InstanceKlass::print_value_on(outputStream* st) const {
3169 assert(is_klass(), "must be klass");
3170 if (Verbose || WizardMode) access_flags().print_on(st);
3171 name()->print_value_on(st);
3172 }
3174 #ifndef PRODUCT
3176 void FieldPrinter::do_field(fieldDescriptor* fd) {
3177 _st->print(BULLET);
3178 if (_obj == NULL) {
3179 fd->print_on(_st);
3180 _st->cr();
3181 } else {
3182 fd->print_on_for(_st, _obj);
3183 _st->cr();
3184 }
3185 }
3188 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3189 Klass::oop_print_on(obj, st);
3191 if (this == SystemDictionary::String_klass()) {
3192 typeArrayOop value = java_lang_String::value(obj);
3193 juint offset = java_lang_String::offset(obj);
3194 juint length = java_lang_String::length(obj);
3195 if (value != NULL &&
3196 value->is_typeArray() &&
3197 offset <= (juint) value->length() &&
3198 offset + length <= (juint) value->length()) {
3199 st->print(BULLET"string: ");
3200 java_lang_String::print(obj, st);
3201 st->cr();
3202 if (!WizardMode) return; // that is enough
3203 }
3204 }
3206 st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3207 FieldPrinter print_field(st, obj);
3208 do_nonstatic_fields(&print_field);
3210 if (this == SystemDictionary::Class_klass()) {
3211 st->print(BULLET"signature: ");
3212 java_lang_Class::print_signature(obj, st);
3213 st->cr();
3214 Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3215 st->print(BULLET"fake entry for mirror: ");
3216 mirrored_klass->print_value_on_maybe_null(st);
3217 st->cr();
3218 Klass* array_klass = java_lang_Class::array_klass(obj);
3219 st->print(BULLET"fake entry for array: ");
3220 array_klass->print_value_on_maybe_null(st);
3221 st->cr();
3222 st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3223 st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3224 Klass* real_klass = java_lang_Class::as_Klass(obj);
3225 if (real_klass != NULL && real_klass->oop_is_instance()) {
3226 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3227 }
3228 } else if (this == SystemDictionary::MethodType_klass()) {
3229 st->print(BULLET"signature: ");
3230 java_lang_invoke_MethodType::print_signature(obj, st);
3231 st->cr();
3232 }
3233 }
3235 #endif //PRODUCT
3237 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3238 st->print("a ");
3239 name()->print_value_on(st);
3240 obj->print_address_on(st);
3241 if (this == SystemDictionary::String_klass()
3242 && java_lang_String::value(obj) != NULL) {
3243 ResourceMark rm;
3244 int len = java_lang_String::length(obj);
3245 int plen = (len < 24 ? len : 12);
3246 char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3247 st->print(" = \"%s\"", str);
3248 if (len > plen)
3249 st->print("...[%d]", len);
3250 } else if (this == SystemDictionary::Class_klass()) {
3251 Klass* k = java_lang_Class::as_Klass(obj);
3252 st->print(" = ");
3253 if (k != NULL) {
3254 k->print_value_on(st);
3255 } else {
3256 const char* tname = type2name(java_lang_Class::primitive_type(obj));
3257 st->print("%s", tname ? tname : "type?");
3258 }
3259 } else if (this == SystemDictionary::MethodType_klass()) {
3260 st->print(" = ");
3261 java_lang_invoke_MethodType::print_signature(obj, st);
3262 } else if (java_lang_boxing_object::is_instance(obj)) {
3263 st->print(" = ");
3264 java_lang_boxing_object::print(obj, st);
3265 } else if (this == SystemDictionary::LambdaForm_klass()) {
3266 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3267 if (vmentry != NULL) {
3268 st->print(" => ");
3269 vmentry->print_value_on(st);
3270 }
3271 } else if (this == SystemDictionary::MemberName_klass()) {
3272 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3273 if (vmtarget != NULL) {
3274 st->print(" = ");
3275 vmtarget->print_value_on(st);
3276 } else {
3277 java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3278 st->print(".");
3279 java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3280 }
3281 }
3282 }
3284 const char* InstanceKlass::internal_name() const {
3285 return external_name();
3286 }
3288 #if INCLUDE_SERVICES
3289 // Size Statistics
3290 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3291 Klass::collect_statistics(sz);
3293 sz->_inst_size = HeapWordSize * size_helper();
3294 sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
3295 sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
3296 sz->_nonstatic_oopmap_bytes = HeapWordSize *
3297 ((is_interface() || is_anonymous()) ?
3298 align_object_offset(nonstatic_oop_map_size()) :
3299 nonstatic_oop_map_size());
3301 int n = 0;
3302 n += (sz->_methods_array_bytes = sz->count_array(methods()));
3303 n += (sz->_method_ordering_bytes = sz->count_array(method_ordering()));
3304 n += (sz->_local_interfaces_bytes = sz->count_array(local_interfaces()));
3305 n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3306 n += (sz->_fields_bytes = sz->count_array(fields()));
3307 n += (sz->_inner_classes_bytes = sz->count_array(inner_classes()));
3308 sz->_ro_bytes += n;
3310 const ConstantPool* cp = constants();
3311 if (cp) {
3312 cp->collect_statistics(sz);
3313 }
3315 const Annotations* anno = annotations();
3316 if (anno) {
3317 anno->collect_statistics(sz);
3318 }
3320 const Array<Method*>* methods_array = methods();
3321 if (methods()) {
3322 for (int i = 0; i < methods_array->length(); i++) {
3323 Method* method = methods_array->at(i);
3324 if (method) {
3325 sz->_method_count ++;
3326 method->collect_statistics(sz);
3327 }
3328 }
3329 }
3330 }
3331 #endif // INCLUDE_SERVICES
3333 // Verification
3335 class VerifyFieldClosure: public OopClosure {
3336 protected:
3337 template <class T> void do_oop_work(T* p) {
3338 oop obj = oopDesc::load_decode_heap_oop(p);
3339 if (!obj->is_oop_or_null()) {
3340 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
3341 Universe::print();
3342 guarantee(false, "boom");
3343 }
3344 }
3345 public:
3346 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); }
3347 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3348 };
3350 void InstanceKlass::verify_on(outputStream* st) {
3351 #ifndef PRODUCT
3352 // Avoid redundant verifies, this really should be in product.
3353 if (_verify_count == Universe::verify_count()) return;
3354 _verify_count = Universe::verify_count();
3355 #endif
3357 // Verify Klass
3358 Klass::verify_on(st);
3360 // Verify that klass is present in ClassLoaderData
3361 guarantee(class_loader_data()->contains_klass(this),
3362 "this class isn't found in class loader data");
3364 // Verify vtables
3365 if (is_linked()) {
3366 ResourceMark rm;
3367 // $$$ This used to be done only for m/s collections. Doing it
3368 // always seemed a valid generalization. (DLD -- 6/00)
3369 vtable()->verify(st);
3370 }
3372 // Verify first subklass
3373 if (subklass_oop() != NULL) {
3374 guarantee(subklass_oop()->is_klass(), "should be klass");
3375 }
3377 // Verify siblings
3378 Klass* super = this->super();
3379 Klass* sib = next_sibling();
3380 if (sib != NULL) {
3381 if (sib == this) {
3382 fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
3383 }
3385 guarantee(sib->is_klass(), "should be klass");
3386 guarantee(sib->super() == super, "siblings should have same superklass");
3387 }
3389 // Verify implementor fields
3390 Klass* im = implementor();
3391 if (im != NULL) {
3392 guarantee(is_interface(), "only interfaces should have implementor set");
3393 guarantee(im->is_klass(), "should be klass");
3394 guarantee(!im->is_interface() || im == this,
3395 "implementors cannot be interfaces");
3396 }
3398 // Verify local interfaces
3399 if (local_interfaces()) {
3400 Array<Klass*>* local_interfaces = this->local_interfaces();
3401 for (int j = 0; j < local_interfaces->length(); j++) {
3402 Klass* e = local_interfaces->at(j);
3403 guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3404 }
3405 }
3407 // Verify transitive interfaces
3408 if (transitive_interfaces() != NULL) {
3409 Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
3410 for (int j = 0; j < transitive_interfaces->length(); j++) {
3411 Klass* e = transitive_interfaces->at(j);
3412 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3413 }
3414 }
3416 // Verify methods
3417 if (methods() != NULL) {
3418 Array<Method*>* methods = this->methods();
3419 for (int j = 0; j < methods->length(); j++) {
3420 guarantee(methods->at(j)->is_method(), "non-method in methods array");
3421 }
3422 for (int j = 0; j < methods->length() - 1; j++) {
3423 Method* m1 = methods->at(j);
3424 Method* m2 = methods->at(j + 1);
3425 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3426 }
3427 }
3429 // Verify method ordering
3430 if (method_ordering() != NULL) {
3431 Array<int>* method_ordering = this->method_ordering();
3432 int length = method_ordering->length();
3433 if (JvmtiExport::can_maintain_original_method_order() ||
3434 ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3435 guarantee(length == methods()->length(), "invalid method ordering length");
3436 jlong sum = 0;
3437 for (int j = 0; j < length; j++) {
3438 int original_index = method_ordering->at(j);
3439 guarantee(original_index >= 0, "invalid method ordering index");
3440 guarantee(original_index < length, "invalid method ordering index");
3441 sum += original_index;
3442 }
3443 // Verify sum of indices 0,1,...,length-1
3444 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3445 } else {
3446 guarantee(length == 0, "invalid method ordering length");
3447 }
3448 }
3450 // Verify default methods
3451 if (default_methods() != NULL) {
3452 Array<Method*>* methods = this->default_methods();
3453 for (int j = 0; j < methods->length(); j++) {
3454 guarantee(methods->at(j)->is_method(), "non-method in methods array");
3455 }
3456 for (int j = 0; j < methods->length() - 1; j++) {
3457 Method* m1 = methods->at(j);
3458 Method* m2 = methods->at(j + 1);
3459 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3460 }
3461 }
3463 // Verify JNI static field identifiers
3464 if (jni_ids() != NULL) {
3465 jni_ids()->verify(this);
3466 }
3468 // Verify other fields
3469 if (array_klasses() != NULL) {
3470 guarantee(array_klasses()->is_klass(), "should be klass");
3471 }
3472 if (constants() != NULL) {
3473 guarantee(constants()->is_constantPool(), "should be constant pool");
3474 }
3475 const Klass* host = host_klass();
3476 if (host != NULL) {
3477 guarantee(host->is_klass(), "should be klass");
3478 }
3479 }
3481 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3482 Klass::oop_verify_on(obj, st);
3483 VerifyFieldClosure blk;
3484 obj->oop_iterate_no_header(&blk);
3485 }
3488 // JNIid class for jfieldIDs only
3489 // Note to reviewers:
3490 // These JNI functions are just moved over to column 1 and not changed
3491 // in the compressed oops workspace.
3492 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3493 _holder = holder;
3494 _offset = offset;
3495 _next = next;
3496 debug_only(_is_static_field_id = false;)
3497 }
3500 JNIid* JNIid::find(int offset) {
3501 JNIid* current = this;
3502 while (current != NULL) {
3503 if (current->offset() == offset) return current;
3504 current = current->next();
3505 }
3506 return NULL;
3507 }
3509 void JNIid::deallocate(JNIid* current) {
3510 while (current != NULL) {
3511 JNIid* next = current->next();
3512 delete current;
3513 current = next;
3514 }
3515 }
3518 void JNIid::verify(Klass* holder) {
3519 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields();
3520 int end_field_offset;
3521 end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3523 JNIid* current = this;
3524 while (current != NULL) {
3525 guarantee(current->holder() == holder, "Invalid klass in JNIid");
3526 #ifdef ASSERT
3527 int o = current->offset();
3528 if (current->is_static_field_id()) {
3529 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid");
3530 }
3531 #endif
3532 current = current->next();
3533 }
3534 }
3537 #ifdef ASSERT
3538 void InstanceKlass::set_init_state(ClassState state) {
3539 bool good_state = is_shared() ? (_init_state <= state)
3540 : (_init_state < state);
3541 assert(good_state || state == allocated, "illegal state transition");
3542 _init_state = (u1)state;
3543 }
3544 #endif
3547 // RedefineClasses() support for previous versions:
3549 // Purge previous versions
3550 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
3551 if (ik->previous_versions() != NULL) {
3552 // This klass has previous versions so see what we can cleanup
3553 // while it is safe to do so.
3555 int deleted_count = 0; // leave debugging breadcrumbs
3556 int live_count = 0;
3557 ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
3558 ClassLoaderData::the_null_class_loader_data() :
3559 ik->class_loader_data();
3561 // RC_TRACE macro has an embedded ResourceMark
3562 RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
3563 ik->external_name(), ik->previous_versions()->length()));
3565 for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
3566 // check the previous versions array
3567 PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
3568 ConstantPool* cp_ref = pv_node->prev_constant_pool();
3569 assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
3571 ConstantPool* pvcp = cp_ref;
3572 if (!pvcp->on_stack()) {
3573 // If the constant pool isn't on stack, none of the methods
3574 // are executing. Delete all the methods, the constant pool and
3575 // and this previous version node.
3576 GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3577 if (method_refs != NULL) {
3578 for (int j = method_refs->length() - 1; j >= 0; j--) {
3579 Method* method = method_refs->at(j);
3580 assert(method != NULL, "method ref was unexpectedly cleared");
3581 method_refs->remove_at(j);
3582 // method will be freed with associated class.
3583 }
3584 }
3585 // Remove the constant pool
3586 delete pv_node;
3587 // Since we are traversing the array backwards, we don't have to
3588 // do anything special with the index.
3589 ik->previous_versions()->remove_at(i);
3590 deleted_count++;
3591 continue;
3592 } else {
3593 RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
3594 assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3595 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3596 live_count++;
3597 }
3599 // At least one method is live in this previous version, clean out
3600 // the others or mark them as obsolete.
3601 GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3602 if (method_refs != NULL) {
3603 RC_TRACE(0x00000200, ("purge: previous methods length=%d",
3604 method_refs->length()));
3605 for (int j = method_refs->length() - 1; j >= 0; j--) {
3606 Method* method = method_refs->at(j);
3607 assert(method != NULL, "method ref was unexpectedly cleared");
3609 // Remove the emcp method if it's not executing
3610 // If it's been made obsolete by a redefinition of a non-emcp
3611 // method, mark it as obsolete but leave it to clean up later.
3612 if (!method->on_stack()) {
3613 method_refs->remove_at(j);
3614 } else if (emcp_method_count == 0) {
3615 method->set_is_obsolete();
3616 } else {
3617 // RC_TRACE macro has an embedded ResourceMark
3618 RC_TRACE(0x00000200,
3619 ("purge: %s(%s): prev method @%d in version @%d is alive",
3620 method->name()->as_C_string(),
3621 method->signature()->as_C_string(), j, i));
3622 }
3623 }
3624 }
3625 }
3626 assert(ik->previous_versions()->length() == live_count, "sanity check");
3627 RC_TRACE(0x00000200,
3628 ("purge: previous version stats: live=%d, deleted=%d", live_count,
3629 deleted_count));
3630 }
3631 }
3633 // External interface for use during class unloading.
3634 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
3635 // Call with >0 emcp methods since they are not currently being redefined.
3636 purge_previous_versions_internal(ik, 1);
3637 }
3640 // Potentially add an information node that contains pointers to the
3641 // interesting parts of the previous version of the_class.
3642 // This is also where we clean out any unused references.
3643 // Note that while we delete nodes from the _previous_versions
3644 // array, we never delete the array itself until the klass is
3645 // unloaded. The has_been_redefined() query depends on that fact.
3646 //
3647 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
3648 BitMap* emcp_methods, int emcp_method_count) {
3649 assert(Thread::current()->is_VM_thread(),
3650 "only VMThread can add previous versions");
3652 if (_previous_versions == NULL) {
3653 // This is the first previous version so make some space.
3654 // Start with 2 elements under the assumption that the class
3655 // won't be redefined much.
3656 _previous_versions = new (ResourceObj::C_HEAP, mtClass)
3657 GrowableArray<PreviousVersionNode *>(2, true);
3658 }
3660 ConstantPool* cp_ref = ikh->constants();
3662 // RC_TRACE macro has an embedded ResourceMark
3663 RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
3664 "on_stack=%d",
3665 ikh->external_name(), _previous_versions->length(), emcp_method_count,
3666 cp_ref->on_stack()));
3668 // If the constant pool for this previous version of the class
3669 // is not marked as being on the stack, then none of the methods
3670 // in this previous version of the class are on the stack so
3671 // we don't need to create a new PreviousVersionNode. However,
3672 // we still need to examine older previous versions below.
3673 Array<Method*>* old_methods = ikh->methods();
3675 if (cp_ref->on_stack()) {
3676 PreviousVersionNode * pv_node = NULL;
3677 if (emcp_method_count == 0) {
3678 // non-shared ConstantPool gets a reference
3679 pv_node = new PreviousVersionNode(cp_ref, NULL);
3680 RC_TRACE(0x00000400,
3681 ("add: all methods are obsolete; flushing any EMCP refs"));
3682 } else {
3683 int local_count = 0;
3684 GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
3685 GrowableArray<Method*>(emcp_method_count, true);
3686 for (int i = 0; i < old_methods->length(); i++) {
3687 if (emcp_methods->at(i)) {
3688 // this old method is EMCP. Save it only if it's on the stack
3689 Method* old_method = old_methods->at(i);
3690 if (old_method->on_stack()) {
3691 method_refs->append(old_method);
3692 }
3693 if (++local_count >= emcp_method_count) {
3694 // no more EMCP methods so bail out now
3695 break;
3696 }
3697 }
3698 }
3699 // non-shared ConstantPool gets a reference
3700 pv_node = new PreviousVersionNode(cp_ref, method_refs);
3701 }
3702 // append new previous version.
3703 _previous_versions->append(pv_node);
3704 }
3706 // Since the caller is the VMThread and we are at a safepoint, this
3707 // is a good time to clear out unused references.
3709 RC_TRACE(0x00000400, ("add: previous version length=%d",
3710 _previous_versions->length()));
3712 // Purge previous versions not executing on the stack
3713 purge_previous_versions_internal(this, emcp_method_count);
3715 int obsolete_method_count = old_methods->length() - emcp_method_count;
3717 if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3718 _previous_versions->length() > 0) {
3719 // We have a mix of obsolete and EMCP methods so we have to
3720 // clear out any matching EMCP method entries the hard way.
3721 int local_count = 0;
3722 for (int i = 0; i < old_methods->length(); i++) {
3723 if (!emcp_methods->at(i)) {
3724 // only obsolete methods are interesting
3725 Method* old_method = old_methods->at(i);
3726 Symbol* m_name = old_method->name();
3727 Symbol* m_signature = old_method->signature();
3729 // we might not have added the last entry
3730 for (int j = _previous_versions->length() - 1; j >= 0; j--) {
3731 // check the previous versions array for non executing obsolete methods
3732 PreviousVersionNode * pv_node = _previous_versions->at(j);
3734 GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3735 if (method_refs == NULL) {
3736 // We have run into a PreviousVersion generation where
3737 // all methods were made obsolete during that generation's
3738 // RedefineClasses() operation. At the time of that
3739 // operation, all EMCP methods were flushed so we don't
3740 // have to go back any further.
3741 //
3742 // A NULL method_refs is different than an empty method_refs.
3743 // We cannot infer any optimizations about older generations
3744 // from an empty method_refs for the current generation.
3745 break;
3746 }
3748 for (int k = method_refs->length() - 1; k >= 0; k--) {
3749 Method* method = method_refs->at(k);
3751 if (!method->is_obsolete() &&
3752 method->name() == m_name &&
3753 method->signature() == m_signature) {
3754 // The current RedefineClasses() call has made all EMCP
3755 // versions of this method obsolete so mark it as obsolete
3756 // and remove the reference.
3757 RC_TRACE(0x00000400,
3758 ("add: %s(%s): flush obsolete method @%d in version @%d",
3759 m_name->as_C_string(), m_signature->as_C_string(), k, j));
3761 method->set_is_obsolete();
3762 // Leave obsolete methods on the previous version list to
3763 // clean up later.
3764 break;
3765 }
3766 }
3768 // The previous loop may not find a matching EMCP method, but
3769 // that doesn't mean that we can optimize and not go any
3770 // further back in the PreviousVersion generations. The EMCP
3771 // method for this generation could have already been deleted,
3772 // but there still may be an older EMCP method that has not
3773 // been deleted.
3774 }
3776 if (++local_count >= obsolete_method_count) {
3777 // no more obsolete methods so bail out now
3778 break;
3779 }
3780 }
3781 }
3782 }
3783 } // end add_previous_version()
3786 // Determine if InstanceKlass has a previous version.
3787 bool InstanceKlass::has_previous_version() const {
3788 return (_previous_versions != NULL && _previous_versions->length() > 0);
3789 } // end has_previous_version()
3792 InstanceKlass* InstanceKlass::get_klass_version(int version) {
3793 if (constants()->version() == version) {
3794 return this;
3795 }
3796 PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
3797 for (PreviousVersionNode * pv_node = pvw.next_previous_version();
3798 pv_node != NULL; pv_node = pvw.next_previous_version()) {
3799 ConstantPool* prev_cp = pv_node->prev_constant_pool();
3800 if (prev_cp->version() == version) {
3801 return prev_cp->pool_holder();
3802 }
3803 }
3804 return NULL; // None found
3805 }
3808 Method* InstanceKlass::method_with_idnum(int idnum) {
3809 Method* m = NULL;
3810 if (idnum < methods()->length()) {
3811 m = methods()->at(idnum);
3812 }
3813 if (m == NULL || m->method_idnum() != idnum) {
3814 for (int index = 0; index < methods()->length(); ++index) {
3815 m = methods()->at(index);
3816 if (m->method_idnum() == idnum) {
3817 return m;
3818 }
3819 }
3820 // None found, return null for the caller to handle.
3821 return NULL;
3822 }
3823 return m;
3824 }
3827 Method* InstanceKlass::method_with_orig_idnum(int idnum) {
3828 if (idnum >= methods()->length()) {
3829 return NULL;
3830 }
3831 Method* m = methods()->at(idnum);
3832 if (m != NULL && m->orig_method_idnum() == idnum) {
3833 return m;
3834 }
3835 // Obsolete method idnum does not match the original idnum
3836 for (int index = 0; index < methods()->length(); ++index) {
3837 m = methods()->at(index);
3838 if (m->orig_method_idnum() == idnum) {
3839 return m;
3840 }
3841 }
3842 // None found, return null for the caller to handle.
3843 return NULL;
3844 }
3847 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
3848 InstanceKlass* holder = get_klass_version(version);
3849 if (holder == NULL) {
3850 return NULL; // The version of klass is gone, no method is found
3851 }
3852 Method* method = holder->method_with_orig_idnum(idnum);
3853 return method;
3854 }
3857 jint InstanceKlass::get_cached_class_file_len() {
3858 return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
3859 }
3861 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
3862 return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
3863 }
3866 // Construct a PreviousVersionNode entry for the array hung off
3867 // the InstanceKlass.
3868 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
3869 GrowableArray<Method*>* prev_EMCP_methods) {
3871 _prev_constant_pool = prev_constant_pool;
3872 _prev_EMCP_methods = prev_EMCP_methods;
3873 }
3876 // Destroy a PreviousVersionNode
3877 PreviousVersionNode::~PreviousVersionNode() {
3878 if (_prev_constant_pool != NULL) {
3879 _prev_constant_pool = NULL;
3880 }
3882 if (_prev_EMCP_methods != NULL) {
3883 delete _prev_EMCP_methods;
3884 }
3885 }
3887 // Construct a helper for walking the previous versions array
3888 PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
3889 _thread = thread;
3890 _previous_versions = ik->previous_versions();
3891 _current_index = 0;
3892 _current_p = NULL;
3893 _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
3894 }
3897 // Return the interesting information for the next previous version
3898 // of the klass. Returns NULL if there are no more previous versions.
3899 PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
3900 if (_previous_versions == NULL) {
3901 // no previous versions so nothing to return
3902 return NULL;
3903 }
3905 _current_p = NULL; // reset to NULL
3906 _current_constant_pool_handle = NULL;
3908 int length = _previous_versions->length();
3910 while (_current_index < length) {
3911 PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
3913 // Save a handle to the constant pool for this previous version,
3914 // which keeps all the methods from being deallocated.
3915 _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
3916 _current_p = pv_node;
3917 return pv_node;
3918 }
3920 return NULL;
3921 } // end next_previous_version()