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