Tue, 08 Jan 2013 14:04:25 -0500
8005048: NMT: #loaded classes needs to just show the # defined classes
Summary: Count number of instance classes so that it matches class metadata size
Reviewed-by: coleenp, acorn
1 /*
2 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 #include "precompiled.hpp"
26 #include "classfile/javaClasses.hpp"
27 #include "classfile/systemDictionary.hpp"
28 #include "classfile/verifier.hpp"
29 #include "classfile/vmSymbols.hpp"
30 #include "compiler/compileBroker.hpp"
31 #include "gc_implementation/shared/markSweep.inline.hpp"
32 #include "gc_interface/collectedHeap.inline.hpp"
33 #include "interpreter/oopMapCache.hpp"
34 #include "interpreter/rewriter.hpp"
35 #include "jvmtifiles/jvmti.h"
36 #include "memory/genOopClosures.inline.hpp"
37 #include "memory/metadataFactory.hpp"
38 #include "memory/oopFactory.hpp"
39 #include "oops/fieldStreams.hpp"
40 #include "oops/instanceClassLoaderKlass.hpp"
41 #include "oops/instanceKlass.hpp"
42 #include "oops/instanceMirrorKlass.hpp"
43 #include "oops/instanceOop.hpp"
44 #include "oops/klass.inline.hpp"
45 #include "oops/method.hpp"
46 #include "oops/oop.inline.hpp"
47 #include "oops/symbol.hpp"
48 #include "prims/jvmtiExport.hpp"
49 #include "prims/jvmtiRedefineClassesTrace.hpp"
50 #include "runtime/fieldDescriptor.hpp"
51 #include "runtime/handles.inline.hpp"
52 #include "runtime/javaCalls.hpp"
53 #include "runtime/mutexLocker.hpp"
54 #include "runtime/thread.inline.hpp"
55 #include "services/threadService.hpp"
56 #include "utilities/dtrace.hpp"
57 #ifndef SERIALGC
58 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
59 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
60 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
61 #include "gc_implementation/g1/g1RemSet.inline.hpp"
62 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
63 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
64 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
65 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
66 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
67 #include "oops/oop.pcgc.inline.hpp"
68 #endif
69 #ifdef COMPILER1
70 #include "c1/c1_Compiler.hpp"
71 #endif
73 #ifdef DTRACE_ENABLED
75 #ifndef USDT2
77 HS_DTRACE_PROBE_DECL4(hotspot, class__initialization__required,
78 char*, intptr_t, oop, intptr_t);
79 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__recursive,
80 char*, intptr_t, oop, intptr_t, int);
81 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__concurrent,
82 char*, intptr_t, oop, intptr_t, int);
83 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__erroneous,
84 char*, intptr_t, oop, intptr_t, int);
85 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__super__failed,
86 char*, intptr_t, oop, intptr_t, int);
87 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__clinit,
88 char*, intptr_t, oop, intptr_t, int);
89 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__error,
90 char*, intptr_t, oop, intptr_t, int);
91 HS_DTRACE_PROBE_DECL5(hotspot, class__initialization__end,
92 char*, intptr_t, oop, intptr_t, int);
94 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type) \
95 { \
96 char* data = NULL; \
97 int len = 0; \
98 Symbol* name = (clss)->name(); \
99 if (name != NULL) { \
100 data = (char*)name->bytes(); \
101 len = name->utf8_length(); \
102 } \
103 HS_DTRACE_PROBE4(hotspot, class__initialization__##type, \
104 data, len, (clss)->class_loader(), thread_type); \
105 }
107 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
108 { \
109 char* data = NULL; \
110 int len = 0; \
111 Symbol* name = (clss)->name(); \
112 if (name != NULL) { \
113 data = (char*)name->bytes(); \
114 len = name->utf8_length(); \
115 } \
116 HS_DTRACE_PROBE5(hotspot, class__initialization__##type, \
117 data, len, (clss)->class_loader(), thread_type, wait); \
118 }
119 #else /* USDT2 */
121 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
122 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
123 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
124 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
125 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
126 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
127 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
128 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
129 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type) \
130 { \
131 char* data = NULL; \
132 int len = 0; \
133 Symbol* name = (clss)->name(); \
134 if (name != NULL) { \
135 data = (char*)name->bytes(); \
136 len = name->utf8_length(); \
137 } \
138 HOTSPOT_CLASS_INITIALIZATION_##type( \
139 data, len, (clss)->class_loader(), thread_type); \
140 }
142 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
143 { \
144 char* data = NULL; \
145 int len = 0; \
146 Symbol* name = (clss)->name(); \
147 if (name != NULL) { \
148 data = (char*)name->bytes(); \
149 len = name->utf8_length(); \
150 } \
151 HOTSPOT_CLASS_INITIALIZATION_##type( \
152 data, len, (clss)->class_loader(), thread_type, wait); \
153 }
154 #endif /* USDT2 */
156 #else // ndef DTRACE_ENABLED
158 #define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
159 #define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
161 #endif // ndef DTRACE_ENABLED
163 volatile int InstanceKlass::_total_instanceKlass_count = 0;
165 Klass* InstanceKlass::allocate_instance_klass(ClassLoaderData* loader_data,
166 int vtable_len,
167 int itable_len,
168 int static_field_size,
169 int nonstatic_oop_map_size,
170 ReferenceType rt,
171 AccessFlags access_flags,
172 Symbol* name,
173 Klass* super_klass,
174 KlassHandle host_klass,
175 TRAPS) {
177 int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
178 access_flags.is_interface(),
179 !host_klass.is_null());
181 // Allocation
182 InstanceKlass* ik;
183 if (rt == REF_NONE) {
184 if (name == vmSymbols::java_lang_Class()) {
185 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
186 vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
187 access_flags, !host_klass.is_null());
188 } else if (name == vmSymbols::java_lang_ClassLoader() ||
189 (SystemDictionary::ClassLoader_klass_loaded() &&
190 super_klass != NULL &&
191 super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
192 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
193 vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
194 access_flags, !host_klass.is_null());
195 } else {
196 // normal class
197 ik = new (loader_data, size, THREAD) InstanceKlass(
198 vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
199 access_flags, !host_klass.is_null());
200 }
201 } else {
202 // reference klass
203 ik = new (loader_data, size, THREAD) InstanceRefKlass(
204 vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
205 access_flags, !host_klass.is_null());
206 }
208 Atomic::inc(&_total_instanceKlass_count);
209 return ik;
210 }
212 InstanceKlass::InstanceKlass(int vtable_len,
213 int itable_len,
214 int static_field_size,
215 int nonstatic_oop_map_size,
216 ReferenceType rt,
217 AccessFlags access_flags,
218 bool is_anonymous) {
219 No_Safepoint_Verifier no_safepoint; // until k becomes parsable
221 int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
222 access_flags.is_interface(), is_anonymous);
224 // The sizes of these these three variables are used for determining the
225 // size of the instanceKlassOop. It is critical that these are set to the right
226 // sizes before the first GC, i.e., when we allocate the mirror.
227 this->set_vtable_length(vtable_len);
228 this->set_itable_length(itable_len);
229 this->set_static_field_size(static_field_size);
230 this->set_nonstatic_oop_map_size(nonstatic_oop_map_size);
231 this->set_access_flags(access_flags);
232 this->set_is_anonymous(is_anonymous);
233 assert(this->size() == size, "wrong size for object");
235 this->set_array_klasses(NULL);
236 this->set_methods(NULL);
237 this->set_method_ordering(NULL);
238 this->set_local_interfaces(NULL);
239 this->set_transitive_interfaces(NULL);
240 this->init_implementor();
241 this->set_fields(NULL, 0);
242 this->set_constants(NULL);
243 this->set_class_loader_data(NULL);
244 this->set_protection_domain(NULL);
245 this->set_signers(NULL);
246 this->set_source_file_name(NULL);
247 this->set_source_debug_extension(NULL, 0);
248 this->set_array_name(NULL);
249 this->set_inner_classes(NULL);
250 this->set_static_oop_field_count(0);
251 this->set_nonstatic_field_size(0);
252 this->set_is_marked_dependent(false);
253 this->set_init_state(InstanceKlass::allocated);
254 this->set_init_thread(NULL);
255 this->set_init_lock(NULL);
256 this->set_reference_type(rt);
257 this->set_oop_map_cache(NULL);
258 this->set_jni_ids(NULL);
259 this->set_osr_nmethods_head(NULL);
260 this->set_breakpoints(NULL);
261 this->init_previous_versions();
262 this->set_generic_signature(NULL);
263 this->release_set_methods_jmethod_ids(NULL);
264 this->release_set_methods_cached_itable_indices(NULL);
265 this->set_annotations(NULL);
266 this->set_jvmti_cached_class_field_map(NULL);
267 this->set_initial_method_idnum(0);
269 // initialize the non-header words to zero
270 intptr_t* p = (intptr_t*)this;
271 for (int index = InstanceKlass::header_size(); index < size; index++) {
272 p[index] = NULL_WORD;
273 }
275 // Set temporary value until parseClassFile updates it with the real instance
276 // size.
277 this->set_layout_helper(Klass::instance_layout_helper(0, true));
278 }
281 // This function deallocates the metadata and C heap pointers that the
282 // InstanceKlass points to.
283 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
285 // Orphan the mirror first, CMS thinks it's still live.
286 java_lang_Class::set_klass(java_mirror(), NULL);
288 // Need to take this class off the class loader data list.
289 loader_data->remove_class(this);
291 // The array_klass for this class is created later, after error handling.
292 // For class redefinition, we keep the original class so this scratch class
293 // doesn't have an array class. Either way, assert that there is nothing
294 // to deallocate.
295 assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
297 // Release C heap allocated data that this might point to, which includes
298 // reference counting symbol names.
299 release_C_heap_structures();
301 Array<Method*>* ms = methods();
302 if (ms != Universe::the_empty_method_array()) {
303 for (int i = 0; i <= methods()->length() -1 ; i++) {
304 Method* method = methods()->at(i);
305 // Only want to delete methods that are not executing for RedefineClasses.
306 // The previous version will point to them so they're not totally dangling
307 assert (!method->on_stack(), "shouldn't be called with methods on stack");
308 MetadataFactory::free_metadata(loader_data, method);
309 }
310 MetadataFactory::free_array<Method*>(loader_data, methods());
311 }
312 set_methods(NULL);
314 if (method_ordering() != Universe::the_empty_int_array()) {
315 MetadataFactory::free_array<int>(loader_data, method_ordering());
316 }
317 set_method_ordering(NULL);
319 // This array is in Klass, but remove it with the InstanceKlass since
320 // this place would be the only caller and it can share memory with transitive
321 // interfaces.
322 if (secondary_supers() != Universe::the_empty_klass_array() &&
323 secondary_supers() != transitive_interfaces()) {
324 MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
325 }
326 set_secondary_supers(NULL);
328 // Only deallocate transitive interfaces if not empty, same as super class
329 // or same as local interfaces. See code in parseClassFile.
330 Array<Klass*>* ti = transitive_interfaces();
331 if (ti != Universe::the_empty_klass_array() && ti != local_interfaces()) {
332 // check that the interfaces don't come from super class
333 Array<Klass*>* sti = (super() == NULL) ? NULL :
334 InstanceKlass::cast(super())->transitive_interfaces();
335 if (ti != sti) {
336 MetadataFactory::free_array<Klass*>(loader_data, ti);
337 }
338 }
339 set_transitive_interfaces(NULL);
341 // local interfaces can be empty
342 Array<Klass*>* li = local_interfaces();
343 if (li != Universe::the_empty_klass_array()) {
344 MetadataFactory::free_array<Klass*>(loader_data, li);
345 }
346 set_local_interfaces(NULL);
348 MetadataFactory::free_array<jushort>(loader_data, fields());
349 set_fields(NULL, 0);
351 // If a method from a redefined class is using this constant pool, don't
352 // delete it, yet. The new class's previous version will point to this.
353 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
354 MetadataFactory::free_metadata(loader_data, constants());
355 set_constants(NULL);
357 if (inner_classes() != Universe::the_empty_short_array()) {
358 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
359 }
360 set_inner_classes(NULL);
362 // Null out Java heap objects, although these won't be walked to keep
363 // alive once this InstanceKlass is deallocated.
364 set_protection_domain(NULL);
365 set_signers(NULL);
366 set_init_lock(NULL);
367 set_annotations(NULL);
368 }
370 volatile oop InstanceKlass::init_lock() const {
371 volatile oop lock = _init_lock; // read once
372 assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
373 "only fully initialized state can have a null lock");
374 return lock;
375 }
377 // Set the initialization lock to null so the object can be GC'ed. Any racing
378 // threads to get this lock will see a null lock and will not lock.
379 // That's okay because they all check for initialized state after getting
380 // the lock and return.
381 void InstanceKlass::fence_and_clear_init_lock() {
382 // make sure previous stores are all done, notably the init_state.
383 OrderAccess::storestore();
384 klass_oop_store(&_init_lock, NULL);
385 assert(!is_not_initialized(), "class must be initialized now");
386 }
389 bool InstanceKlass::should_be_initialized() const {
390 return !is_initialized();
391 }
393 klassVtable* InstanceKlass::vtable() const {
394 return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
395 }
397 klassItable* InstanceKlass::itable() const {
398 return new klassItable(instanceKlassHandle(this));
399 }
401 void InstanceKlass::eager_initialize(Thread *thread) {
402 if (!EagerInitialization) return;
404 if (this->is_not_initialized()) {
405 // abort if the the class has a class initializer
406 if (this->class_initializer() != NULL) return;
408 // abort if it is java.lang.Object (initialization is handled in genesis)
409 Klass* super = this->super();
410 if (super == NULL) return;
412 // abort if the super class should be initialized
413 if (!InstanceKlass::cast(super)->is_initialized()) return;
415 // call body to expose the this pointer
416 instanceKlassHandle this_oop(thread, this);
417 eager_initialize_impl(this_oop);
418 }
419 }
422 void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_oop) {
423 EXCEPTION_MARK;
424 volatile oop init_lock = this_oop->init_lock();
425 ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
427 // abort if someone beat us to the initialization
428 if (!this_oop->is_not_initialized()) return; // note: not equivalent to is_initialized()
430 ClassState old_state = this_oop->init_state();
431 link_class_impl(this_oop, true, THREAD);
432 if (HAS_PENDING_EXCEPTION) {
433 CLEAR_PENDING_EXCEPTION;
434 // Abort if linking the class throws an exception.
436 // Use a test to avoid redundantly resetting the state if there's
437 // no change. Set_init_state() asserts that state changes make
438 // progress, whereas here we might just be spinning in place.
439 if( old_state != this_oop->_init_state )
440 this_oop->set_init_state (old_state);
441 } else {
442 // linking successfull, mark class as initialized
443 this_oop->set_init_state (fully_initialized);
444 this_oop->fence_and_clear_init_lock();
445 // trace
446 if (TraceClassInitialization) {
447 ResourceMark rm(THREAD);
448 tty->print_cr("[Initialized %s without side effects]", this_oop->external_name());
449 }
450 }
451 }
454 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
455 // process. The step comments refers to the procedure described in that section.
456 // Note: implementation moved to static method to expose the this pointer.
457 void InstanceKlass::initialize(TRAPS) {
458 if (this->should_be_initialized()) {
459 HandleMark hm(THREAD);
460 instanceKlassHandle this_oop(THREAD, this);
461 initialize_impl(this_oop, CHECK);
462 // Note: at this point the class may be initialized
463 // OR it may be in the state of being initialized
464 // in case of recursive initialization!
465 } else {
466 assert(is_initialized(), "sanity check");
467 }
468 }
471 bool InstanceKlass::verify_code(
472 instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
473 // 1) Verify the bytecodes
474 Verifier::Mode mode =
475 throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
476 return Verifier::verify(this_oop, mode, this_oop->should_verify_class(), CHECK_false);
477 }
480 // Used exclusively by the shared spaces dump mechanism to prevent
481 // classes mapped into the shared regions in new VMs from appearing linked.
483 void InstanceKlass::unlink_class() {
484 assert(is_linked(), "must be linked");
485 _init_state = loaded;
486 }
488 void InstanceKlass::link_class(TRAPS) {
489 assert(is_loaded(), "must be loaded");
490 if (!is_linked()) {
491 HandleMark hm(THREAD);
492 instanceKlassHandle this_oop(THREAD, this);
493 link_class_impl(this_oop, true, CHECK);
494 }
495 }
497 // Called to verify that a class can link during initialization, without
498 // throwing a VerifyError.
499 bool InstanceKlass::link_class_or_fail(TRAPS) {
500 assert(is_loaded(), "must be loaded");
501 if (!is_linked()) {
502 HandleMark hm(THREAD);
503 instanceKlassHandle this_oop(THREAD, this);
504 link_class_impl(this_oop, false, CHECK_false);
505 }
506 return is_linked();
507 }
509 bool InstanceKlass::link_class_impl(
510 instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
511 // check for error state
512 if (this_oop->is_in_error_state()) {
513 ResourceMark rm(THREAD);
514 THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
515 this_oop->external_name(), false);
516 }
517 // return if already verified
518 if (this_oop->is_linked()) {
519 return true;
520 }
522 // Timing
523 // timer handles recursion
524 assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
525 JavaThread* jt = (JavaThread*)THREAD;
527 // link super class before linking this class
528 instanceKlassHandle super(THREAD, this_oop->super());
529 if (super.not_null()) {
530 if (super->is_interface()) { // check if super class is an interface
531 ResourceMark rm(THREAD);
532 Exceptions::fthrow(
533 THREAD_AND_LOCATION,
534 vmSymbols::java_lang_IncompatibleClassChangeError(),
535 "class %s has interface %s as super class",
536 this_oop->external_name(),
537 super->external_name()
538 );
539 return false;
540 }
542 link_class_impl(super, throw_verifyerror, CHECK_false);
543 }
545 // link all interfaces implemented by this class before linking this class
546 Array<Klass*>* interfaces = this_oop->local_interfaces();
547 int num_interfaces = interfaces->length();
548 for (int index = 0; index < num_interfaces; index++) {
549 HandleMark hm(THREAD);
550 instanceKlassHandle ih(THREAD, interfaces->at(index));
551 link_class_impl(ih, throw_verifyerror, CHECK_false);
552 }
554 // in case the class is linked in the process of linking its superclasses
555 if (this_oop->is_linked()) {
556 return true;
557 }
559 // trace only the link time for this klass that includes
560 // the verification time
561 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
562 ClassLoader::perf_class_link_selftime(),
563 ClassLoader::perf_classes_linked(),
564 jt->get_thread_stat()->perf_recursion_counts_addr(),
565 jt->get_thread_stat()->perf_timers_addr(),
566 PerfClassTraceTime::CLASS_LINK);
568 // verification & rewriting
569 {
570 volatile oop init_lock = this_oop->init_lock();
571 ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
572 // rewritten will have been set if loader constraint error found
573 // on an earlier link attempt
574 // don't verify or rewrite if already rewritten
576 if (!this_oop->is_linked()) {
577 if (!this_oop->is_rewritten()) {
578 {
579 // Timer includes any side effects of class verification (resolution,
580 // etc), but not recursive entry into verify_code().
581 PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
582 ClassLoader::perf_class_verify_selftime(),
583 ClassLoader::perf_classes_verified(),
584 jt->get_thread_stat()->perf_recursion_counts_addr(),
585 jt->get_thread_stat()->perf_timers_addr(),
586 PerfClassTraceTime::CLASS_VERIFY);
587 bool verify_ok = verify_code(this_oop, throw_verifyerror, THREAD);
588 if (!verify_ok) {
589 return false;
590 }
591 }
593 // Just in case a side-effect of verify linked this class already
594 // (which can sometimes happen since the verifier loads classes
595 // using custom class loaders, which are free to initialize things)
596 if (this_oop->is_linked()) {
597 return true;
598 }
600 // also sets rewritten
601 this_oop->rewrite_class(CHECK_false);
602 }
604 // relocate jsrs and link methods after they are all rewritten
605 this_oop->relocate_and_link_methods(CHECK_false);
607 // Initialize the vtable and interface table after
608 // methods have been rewritten since rewrite may
609 // fabricate new Method*s.
610 // also does loader constraint checking
611 if (!this_oop()->is_shared()) {
612 ResourceMark rm(THREAD);
613 this_oop->vtable()->initialize_vtable(true, CHECK_false);
614 this_oop->itable()->initialize_itable(true, CHECK_false);
615 }
616 #ifdef ASSERT
617 else {
618 ResourceMark rm(THREAD);
619 this_oop->vtable()->verify(tty, true);
620 // In case itable verification is ever added.
621 // this_oop->itable()->verify(tty, true);
622 }
623 #endif
624 this_oop->set_init_state(linked);
625 if (JvmtiExport::should_post_class_prepare()) {
626 Thread *thread = THREAD;
627 assert(thread->is_Java_thread(), "thread->is_Java_thread()");
628 JvmtiExport::post_class_prepare((JavaThread *) thread, this_oop());
629 }
630 }
631 }
632 return true;
633 }
636 // Rewrite the byte codes of all of the methods of a class.
637 // The rewriter must be called exactly once. Rewriting must happen after
638 // verification but before the first method of the class is executed.
639 void InstanceKlass::rewrite_class(TRAPS) {
640 assert(is_loaded(), "must be loaded");
641 instanceKlassHandle this_oop(THREAD, this);
642 if (this_oop->is_rewritten()) {
643 assert(this_oop()->is_shared(), "rewriting an unshared class?");
644 return;
645 }
646 Rewriter::rewrite(this_oop, CHECK);
647 this_oop->set_rewritten();
648 }
650 // Now relocate and link method entry points after class is rewritten.
651 // This is outside is_rewritten flag. In case of an exception, it can be
652 // executed more than once.
653 void InstanceKlass::relocate_and_link_methods(TRAPS) {
654 assert(is_loaded(), "must be loaded");
655 instanceKlassHandle this_oop(THREAD, this);
656 Rewriter::relocate_and_link(this_oop, CHECK);
657 }
660 void InstanceKlass::initialize_impl(instanceKlassHandle this_oop, TRAPS) {
661 // Make sure klass is linked (verified) before initialization
662 // A class could already be verified, since it has been reflected upon.
663 this_oop->link_class(CHECK);
665 DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_oop()), -1);
667 bool wait = false;
669 // refer to the JVM book page 47 for description of steps
670 // Step 1
671 {
672 volatile oop init_lock = this_oop->init_lock();
673 ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
675 Thread *self = THREAD; // it's passed the current thread
677 // Step 2
678 // If we were to use wait() instead of waitInterruptibly() then
679 // we might end up throwing IE from link/symbol resolution sites
680 // that aren't expected to throw. This would wreak havoc. See 6320309.
681 while(this_oop->is_being_initialized() && !this_oop->is_reentrant_initialization(self)) {
682 wait = true;
683 ol.waitUninterruptibly(CHECK);
684 }
686 // Step 3
687 if (this_oop->is_being_initialized() && this_oop->is_reentrant_initialization(self)) {
688 DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_oop()), -1,wait);
689 return;
690 }
692 // Step 4
693 if (this_oop->is_initialized()) {
694 DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_oop()), -1,wait);
695 return;
696 }
698 // Step 5
699 if (this_oop->is_in_error_state()) {
700 DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_oop()), -1,wait);
701 ResourceMark rm(THREAD);
702 const char* desc = "Could not initialize class ";
703 const char* className = this_oop->external_name();
704 size_t msglen = strlen(desc) + strlen(className) + 1;
705 char* message = NEW_RESOURCE_ARRAY(char, msglen);
706 if (NULL == message) {
707 // Out of memory: can't create detailed error message
708 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
709 } else {
710 jio_snprintf(message, msglen, "%s%s", desc, className);
711 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
712 }
713 }
715 // Step 6
716 this_oop->set_init_state(being_initialized);
717 this_oop->set_init_thread(self);
718 }
720 // Step 7
721 Klass* super_klass = this_oop->super();
722 if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
723 super_klass->initialize(THREAD);
725 if (HAS_PENDING_EXCEPTION) {
726 Handle e(THREAD, PENDING_EXCEPTION);
727 CLEAR_PENDING_EXCEPTION;
728 {
729 EXCEPTION_MARK;
730 this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
731 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, superclass initialization error is thrown below
732 }
733 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
734 THROW_OOP(e());
735 }
736 }
738 if (this_oop->has_default_methods()) {
739 // Step 7.5: initialize any interfaces which have default methods
740 for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
741 Klass* iface = this_oop->local_interfaces()->at(i);
742 InstanceKlass* ik = InstanceKlass::cast(iface);
743 if (ik->has_default_methods() && ik->should_be_initialized()) {
744 ik->initialize(THREAD);
746 if (HAS_PENDING_EXCEPTION) {
747 Handle e(THREAD, PENDING_EXCEPTION);
748 CLEAR_PENDING_EXCEPTION;
749 {
750 EXCEPTION_MARK;
751 // Locks object, set state, and notify all waiting threads
752 this_oop->set_initialization_state_and_notify(
753 initialization_error, THREAD);
755 // ignore any exception thrown, superclass initialization error is
756 // thrown below
757 CLEAR_PENDING_EXCEPTION;
758 }
759 DTRACE_CLASSINIT_PROBE_WAIT(
760 super__failed, InstanceKlass::cast(this_oop()), -1, wait);
761 THROW_OOP(e());
762 }
763 }
764 }
765 }
767 // Step 8
768 {
769 assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
770 JavaThread* jt = (JavaThread*)THREAD;
771 DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_oop()), -1,wait);
772 // Timer includes any side effects of class initialization (resolution,
773 // etc), but not recursive entry into call_class_initializer().
774 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
775 ClassLoader::perf_class_init_selftime(),
776 ClassLoader::perf_classes_inited(),
777 jt->get_thread_stat()->perf_recursion_counts_addr(),
778 jt->get_thread_stat()->perf_timers_addr(),
779 PerfClassTraceTime::CLASS_CLINIT);
780 this_oop->call_class_initializer(THREAD);
781 }
783 // Step 9
784 if (!HAS_PENDING_EXCEPTION) {
785 this_oop->set_initialization_state_and_notify(fully_initialized, CHECK);
786 { ResourceMark rm(THREAD);
787 debug_only(this_oop->vtable()->verify(tty, true);)
788 }
789 }
790 else {
791 // Step 10 and 11
792 Handle e(THREAD, PENDING_EXCEPTION);
793 CLEAR_PENDING_EXCEPTION;
794 {
795 EXCEPTION_MARK;
796 this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
797 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
798 }
799 DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_oop()), -1,wait);
800 if (e->is_a(SystemDictionary::Error_klass())) {
801 THROW_OOP(e());
802 } else {
803 JavaCallArguments args(e);
804 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
805 vmSymbols::throwable_void_signature(),
806 &args);
807 }
808 }
809 DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_oop()), -1,wait);
810 }
813 // Note: implementation moved to static method to expose the this pointer.
814 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
815 instanceKlassHandle kh(THREAD, this);
816 set_initialization_state_and_notify_impl(kh, state, CHECK);
817 }
819 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
820 volatile oop init_lock = this_oop->init_lock();
821 ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
822 this_oop->set_init_state(state);
823 this_oop->fence_and_clear_init_lock();
824 ol.notify_all(CHECK);
825 }
827 // The embedded _implementor field can only record one implementor.
828 // When there are more than one implementors, the _implementor field
829 // is set to the interface Klass* itself. Following are the possible
830 // values for the _implementor field:
831 // NULL - no implementor
832 // implementor Klass* - one implementor
833 // self - more than one implementor
834 //
835 // The _implementor field only exists for interfaces.
836 void InstanceKlass::add_implementor(Klass* k) {
837 assert(Compile_lock->owned_by_self(), "");
838 assert(is_interface(), "not interface");
839 // Filter out my subinterfaces.
840 // (Note: Interfaces are never on the subklass list.)
841 if (InstanceKlass::cast(k)->is_interface()) return;
843 // Filter out subclasses whose supers already implement me.
844 // (Note: CHA must walk subclasses of direct implementors
845 // in order to locate indirect implementors.)
846 Klass* sk = InstanceKlass::cast(k)->super();
847 if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
848 // We only need to check one immediate superclass, since the
849 // implements_interface query looks at transitive_interfaces.
850 // Any supers of the super have the same (or fewer) transitive_interfaces.
851 return;
853 Klass* ik = implementor();
854 if (ik == NULL) {
855 set_implementor(k);
856 } else if (ik != this) {
857 // There is already an implementor. Use itself as an indicator of
858 // more than one implementors.
859 set_implementor(this);
860 }
862 // The implementor also implements the transitive_interfaces
863 for (int index = 0; index < local_interfaces()->length(); index++) {
864 InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
865 }
866 }
868 void InstanceKlass::init_implementor() {
869 if (is_interface()) {
870 set_implementor(NULL);
871 }
872 }
875 void InstanceKlass::process_interfaces(Thread *thread) {
876 // link this class into the implementors list of every interface it implements
877 Klass* this_as_klass_oop = this;
878 for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
879 assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
880 InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
881 assert(interf->is_interface(), "expected interface");
882 interf->add_implementor(this_as_klass_oop);
883 }
884 }
886 bool InstanceKlass::can_be_primary_super_slow() const {
887 if (is_interface())
888 return false;
889 else
890 return Klass::can_be_primary_super_slow();
891 }
893 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
894 // The secondaries are the implemented interfaces.
895 InstanceKlass* ik = InstanceKlass::cast(this);
896 Array<Klass*>* interfaces = ik->transitive_interfaces();
897 int num_secondaries = num_extra_slots + interfaces->length();
898 if (num_secondaries == 0) {
899 // Must share this for correct bootstrapping!
900 set_secondary_supers(Universe::the_empty_klass_array());
901 return NULL;
902 } else if (num_extra_slots == 0) {
903 // The secondary super list is exactly the same as the transitive interfaces.
904 // Redefine classes has to be careful not to delete this!
905 set_secondary_supers(interfaces);
906 return NULL;
907 } else {
908 // Copy transitive interfaces to a temporary growable array to be constructed
909 // into the secondary super list with extra slots.
910 GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
911 for (int i = 0; i < interfaces->length(); i++) {
912 secondaries->push(interfaces->at(i));
913 }
914 return secondaries;
915 }
916 }
918 bool InstanceKlass::compute_is_subtype_of(Klass* k) {
919 if (k->is_interface()) {
920 return implements_interface(k);
921 } else {
922 return Klass::compute_is_subtype_of(k);
923 }
924 }
926 bool InstanceKlass::implements_interface(Klass* k) const {
927 if (this == k) return true;
928 assert(k->is_interface(), "should be an interface class");
929 for (int i = 0; i < transitive_interfaces()->length(); i++) {
930 if (transitive_interfaces()->at(i) == k) {
931 return true;
932 }
933 }
934 return false;
935 }
937 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
938 if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
939 if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
940 report_java_out_of_memory("Requested array size exceeds VM limit");
941 JvmtiExport::post_array_size_exhausted();
942 THROW_OOP_0(Universe::out_of_memory_error_array_size());
943 }
944 int size = objArrayOopDesc::object_size(length);
945 Klass* ak = array_klass(n, CHECK_NULL);
946 KlassHandle h_ak (THREAD, ak);
947 objArrayOop o =
948 (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
949 return o;
950 }
952 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
953 if (TraceFinalizerRegistration) {
954 tty->print("Registered ");
955 i->print_value_on(tty);
956 tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
957 }
958 instanceHandle h_i(THREAD, i);
959 // Pass the handle as argument, JavaCalls::call expects oop as jobjects
960 JavaValue result(T_VOID);
961 JavaCallArguments args(h_i);
962 methodHandle mh (THREAD, Universe::finalizer_register_method());
963 JavaCalls::call(&result, mh, &args, CHECK_NULL);
964 return h_i();
965 }
967 instanceOop InstanceKlass::allocate_instance(TRAPS) {
968 bool has_finalizer_flag = has_finalizer(); // Query before possible GC
969 int size = size_helper(); // Query before forming handle.
971 KlassHandle h_k(THREAD, this);
973 instanceOop i;
975 i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
976 if (has_finalizer_flag && !RegisterFinalizersAtInit) {
977 i = register_finalizer(i, CHECK_NULL);
978 }
979 return i;
980 }
982 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
983 if (is_interface() || is_abstract()) {
984 ResourceMark rm(THREAD);
985 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
986 : vmSymbols::java_lang_InstantiationException(), external_name());
987 }
988 if (this == SystemDictionary::Class_klass()) {
989 ResourceMark rm(THREAD);
990 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
991 : vmSymbols::java_lang_IllegalAccessException(), external_name());
992 }
993 }
995 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
996 instanceKlassHandle this_oop(THREAD, this);
997 return array_klass_impl(this_oop, or_null, n, THREAD);
998 }
1000 Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_oop, bool or_null, int n, TRAPS) {
1001 if (this_oop->array_klasses() == NULL) {
1002 if (or_null) return NULL;
1004 ResourceMark rm;
1005 JavaThread *jt = (JavaThread *)THREAD;
1006 {
1007 // Atomic creation of array_klasses
1008 MutexLocker mc(Compile_lock, THREAD); // for vtables
1009 MutexLocker ma(MultiArray_lock, THREAD);
1011 // Check if update has already taken place
1012 if (this_oop->array_klasses() == NULL) {
1013 Klass* k = ObjArrayKlass::allocate_objArray_klass(this_oop->class_loader_data(), 1, this_oop, CHECK_NULL);
1014 this_oop->set_array_klasses(k);
1015 }
1016 }
1017 }
1018 // _this will always be set at this point
1019 ObjArrayKlass* oak = (ObjArrayKlass*)this_oop->array_klasses();
1020 if (or_null) {
1021 return oak->array_klass_or_null(n);
1022 }
1023 return oak->array_klass(n, CHECK_NULL);
1024 }
1026 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
1027 return array_klass_impl(or_null, 1, THREAD);
1028 }
1030 void InstanceKlass::call_class_initializer(TRAPS) {
1031 instanceKlassHandle ik (THREAD, this);
1032 call_class_initializer_impl(ik, THREAD);
1033 }
1035 static int call_class_initializer_impl_counter = 0; // for debugging
1037 Method* InstanceKlass::class_initializer() {
1038 Method* clinit = find_method(
1039 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1040 if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1041 return clinit;
1042 }
1043 return NULL;
1044 }
1046 void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_oop, TRAPS) {
1047 if (ReplayCompiles &&
1048 (ReplaySuppressInitializers == 1 ||
1049 ReplaySuppressInitializers >= 2 && this_oop->class_loader() != NULL)) {
1050 // Hide the existence of the initializer for the purpose of replaying the compile
1051 return;
1052 }
1054 methodHandle h_method(THREAD, this_oop->class_initializer());
1055 assert(!this_oop->is_initialized(), "we cannot initialize twice");
1056 if (TraceClassInitialization) {
1057 tty->print("%d Initializing ", call_class_initializer_impl_counter++);
1058 this_oop->name()->print_value();
1059 tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_oop());
1060 }
1061 if (h_method() != NULL) {
1062 JavaCallArguments args; // No arguments
1063 JavaValue result(T_VOID);
1064 JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1065 }
1066 }
1069 void InstanceKlass::mask_for(methodHandle method, int bci,
1070 InterpreterOopMap* entry_for) {
1071 // Dirty read, then double-check under a lock.
1072 if (_oop_map_cache == NULL) {
1073 // Otherwise, allocate a new one.
1074 MutexLocker x(OopMapCacheAlloc_lock);
1075 // First time use. Allocate a cache in C heap
1076 if (_oop_map_cache == NULL) {
1077 _oop_map_cache = new OopMapCache();
1078 }
1079 }
1080 // _oop_map_cache is constant after init; lookup below does is own locking.
1081 _oop_map_cache->lookup(method, bci, entry_for);
1082 }
1085 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1086 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1087 Symbol* f_name = fs.name();
1088 Symbol* f_sig = fs.signature();
1089 if (f_name == name && f_sig == sig) {
1090 fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
1091 return true;
1092 }
1093 }
1094 return false;
1095 }
1098 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1099 const int n = local_interfaces()->length();
1100 for (int i = 0; i < n; i++) {
1101 Klass* intf1 = local_interfaces()->at(i);
1102 assert(intf1->is_interface(), "just checking type");
1103 // search for field in current interface
1104 if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1105 assert(fd->is_static(), "interface field must be static");
1106 return intf1;
1107 }
1108 // search for field in direct superinterfaces
1109 Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1110 if (intf2 != NULL) return intf2;
1111 }
1112 // otherwise field lookup fails
1113 return NULL;
1114 }
1117 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1118 // search order according to newest JVM spec (5.4.3.2, p.167).
1119 // 1) search for field in current klass
1120 if (find_local_field(name, sig, fd)) {
1121 return const_cast<InstanceKlass*>(this);
1122 }
1123 // 2) search for field recursively in direct superinterfaces
1124 { Klass* intf = find_interface_field(name, sig, fd);
1125 if (intf != NULL) return intf;
1126 }
1127 // 3) apply field lookup recursively if superclass exists
1128 { Klass* supr = super();
1129 if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1130 }
1131 // 4) otherwise field lookup fails
1132 return NULL;
1133 }
1136 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1137 // search order according to newest JVM spec (5.4.3.2, p.167).
1138 // 1) search for field in current klass
1139 if (find_local_field(name, sig, fd)) {
1140 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1141 }
1142 // 2) search for field recursively in direct superinterfaces
1143 if (is_static) {
1144 Klass* intf = find_interface_field(name, sig, fd);
1145 if (intf != NULL) return intf;
1146 }
1147 // 3) apply field lookup recursively if superclass exists
1148 { Klass* supr = super();
1149 if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1150 }
1151 // 4) otherwise field lookup fails
1152 return NULL;
1153 }
1156 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1157 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1158 if (fs.offset() == offset) {
1159 fd->initialize(const_cast<InstanceKlass*>(this), fs.index());
1160 if (fd->is_static() == is_static) return true;
1161 }
1162 }
1163 return false;
1164 }
1167 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1168 Klass* klass = const_cast<InstanceKlass*>(this);
1169 while (klass != NULL) {
1170 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1171 return true;
1172 }
1173 klass = klass->super();
1174 }
1175 return false;
1176 }
1179 void InstanceKlass::methods_do(void f(Method* method)) {
1180 int len = methods()->length();
1181 for (int index = 0; index < len; index++) {
1182 Method* m = methods()->at(index);
1183 assert(m->is_method(), "must be method");
1184 f(m);
1185 }
1186 }
1189 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1190 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1191 if (fs.access_flags().is_static()) {
1192 fieldDescriptor fd;
1193 fd.initialize(this, fs.index());
1194 cl->do_field(&fd);
1195 }
1196 }
1197 }
1200 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, TRAPS), TRAPS) {
1201 instanceKlassHandle h_this(THREAD, this);
1202 do_local_static_fields_impl(h_this, f, CHECK);
1203 }
1206 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_oop, void f(fieldDescriptor* fd, TRAPS), TRAPS) {
1207 for (JavaFieldStream fs(this_oop()); !fs.done(); fs.next()) {
1208 if (fs.access_flags().is_static()) {
1209 fieldDescriptor fd;
1210 fd.initialize(this_oop(), fs.index());
1211 f(&fd, CHECK);
1212 }
1213 }
1214 }
1217 static int compare_fields_by_offset(int* a, int* b) {
1218 return a[0] - b[0];
1219 }
1221 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1222 InstanceKlass* super = superklass();
1223 if (super != NULL) {
1224 super->do_nonstatic_fields(cl);
1225 }
1226 fieldDescriptor fd;
1227 int length = java_fields_count();
1228 // In DebugInfo nonstatic fields are sorted by offset.
1229 int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1230 int j = 0;
1231 for (int i = 0; i < length; i += 1) {
1232 fd.initialize(this, i);
1233 if (!fd.is_static()) {
1234 fields_sorted[j + 0] = fd.offset();
1235 fields_sorted[j + 1] = i;
1236 j += 2;
1237 }
1238 }
1239 if (j > 0) {
1240 length = j;
1241 // _sort_Fn is defined in growableArray.hpp.
1242 qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1243 for (int i = 0; i < length; i += 2) {
1244 fd.initialize(this, fields_sorted[i + 1]);
1245 assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1246 cl->do_field(&fd);
1247 }
1248 }
1249 FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
1250 }
1253 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1254 if (array_klasses() != NULL)
1255 ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1256 }
1258 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1259 if (array_klasses() != NULL)
1260 ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1261 }
1264 void InstanceKlass::with_array_klasses_do(void f(Klass* k)) {
1265 f(this);
1266 array_klasses_do(f);
1267 }
1269 #ifdef ASSERT
1270 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
1271 int len = methods->length();
1272 for (int index = 0; index < len; index++) {
1273 Method* m = methods->at(index);
1274 assert(m->is_method(), "must be method");
1275 if (m->signature() == signature && m->name() == name) {
1276 return index;
1277 }
1278 }
1279 return -1;
1280 }
1281 #endif
1283 static int binary_search(Array<Method*>* methods, Symbol* name) {
1284 int len = methods->length();
1285 // methods are sorted, so do binary search
1286 int l = 0;
1287 int h = len - 1;
1288 while (l <= h) {
1289 int mid = (l + h) >> 1;
1290 Method* m = methods->at(mid);
1291 assert(m->is_method(), "must be method");
1292 int res = m->name()->fast_compare(name);
1293 if (res == 0) {
1294 return mid;
1295 } else if (res < 0) {
1296 l = mid + 1;
1297 } else {
1298 h = mid - 1;
1299 }
1300 }
1301 return -1;
1302 }
1304 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
1305 return InstanceKlass::find_method(methods(), name, signature);
1306 }
1308 Method* InstanceKlass::find_method(
1309 Array<Method*>* methods, Symbol* name, Symbol* signature) {
1310 int hit = binary_search(methods, name);
1311 if (hit != -1) {
1312 Method* m = methods->at(hit);
1313 // Do linear search to find matching signature. First, quick check
1314 // for common case
1315 if (m->signature() == signature) return m;
1316 // search downwards through overloaded methods
1317 int i;
1318 for (i = hit - 1; i >= 0; --i) {
1319 Method* m = methods->at(i);
1320 assert(m->is_method(), "must be method");
1321 if (m->name() != name) break;
1322 if (m->signature() == signature) return m;
1323 }
1324 // search upwards
1325 for (i = hit + 1; i < methods->length(); ++i) {
1326 Method* m = methods->at(i);
1327 assert(m->is_method(), "must be method");
1328 if (m->name() != name) break;
1329 if (m->signature() == signature) return m;
1330 }
1331 // not found
1332 #ifdef ASSERT
1333 int index = linear_search(methods, name, signature);
1334 assert(index == -1, err_msg("binary search should have found entry %d", index));
1335 #endif
1336 }
1337 return NULL;
1338 }
1340 int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
1341 return find_method_by_name(methods(), name, end);
1342 }
1344 int InstanceKlass::find_method_by_name(
1345 Array<Method*>* methods, Symbol* name, int* end_ptr) {
1346 assert(end_ptr != NULL, "just checking");
1347 int start = binary_search(methods, name);
1348 int end = start + 1;
1349 if (start != -1) {
1350 while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1351 while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1352 *end_ptr = end;
1353 return start;
1354 }
1355 return -1;
1356 }
1358 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature) const {
1359 Klass* klass = const_cast<InstanceKlass*>(this);
1360 while (klass != NULL) {
1361 Method* method = InstanceKlass::cast(klass)->find_method(name, signature);
1362 if (method != NULL) return method;
1363 klass = InstanceKlass::cast(klass)->super();
1364 }
1365 return NULL;
1366 }
1368 // lookup a method in all the interfaces that this class implements
1369 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1370 Symbol* signature) const {
1371 Array<Klass*>* all_ifs = transitive_interfaces();
1372 int num_ifs = all_ifs->length();
1373 InstanceKlass *ik = NULL;
1374 for (int i = 0; i < num_ifs; i++) {
1375 ik = InstanceKlass::cast(all_ifs->at(i));
1376 Method* m = ik->lookup_method(name, signature);
1377 if (m != NULL) {
1378 return m;
1379 }
1380 }
1381 return NULL;
1382 }
1384 /* jni_id_for_impl for jfieldIds only */
1385 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_oop, int offset) {
1386 MutexLocker ml(JfieldIdCreation_lock);
1387 // Retry lookup after we got the lock
1388 JNIid* probe = this_oop->jni_ids() == NULL ? NULL : this_oop->jni_ids()->find(offset);
1389 if (probe == NULL) {
1390 // Slow case, allocate new static field identifier
1391 probe = new JNIid(this_oop(), offset, this_oop->jni_ids());
1392 this_oop->set_jni_ids(probe);
1393 }
1394 return probe;
1395 }
1398 /* jni_id_for for jfieldIds only */
1399 JNIid* InstanceKlass::jni_id_for(int offset) {
1400 JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1401 if (probe == NULL) {
1402 probe = jni_id_for_impl(this, offset);
1403 }
1404 return probe;
1405 }
1407 u2 InstanceKlass::enclosing_method_data(int offset) {
1408 Array<jushort>* inner_class_list = inner_classes();
1409 if (inner_class_list == NULL) {
1410 return 0;
1411 }
1412 int length = inner_class_list->length();
1413 if (length % inner_class_next_offset == 0) {
1414 return 0;
1415 } else {
1416 int index = length - enclosing_method_attribute_size;
1417 assert(offset < enclosing_method_attribute_size, "invalid offset");
1418 return inner_class_list->at(index + offset);
1419 }
1420 }
1422 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1423 u2 method_index) {
1424 Array<jushort>* inner_class_list = inner_classes();
1425 assert (inner_class_list != NULL, "_inner_classes list is not set up");
1426 int length = inner_class_list->length();
1427 if (length % inner_class_next_offset == enclosing_method_attribute_size) {
1428 int index = length - enclosing_method_attribute_size;
1429 inner_class_list->at_put(
1430 index + enclosing_method_class_index_offset, class_index);
1431 inner_class_list->at_put(
1432 index + enclosing_method_method_index_offset, method_index);
1433 }
1434 }
1436 // Lookup or create a jmethodID.
1437 // This code is called by the VMThread and JavaThreads so the
1438 // locking has to be done very carefully to avoid deadlocks
1439 // and/or other cache consistency problems.
1440 //
1441 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
1442 size_t idnum = (size_t)method_h->method_idnum();
1443 jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1444 size_t length = 0;
1445 jmethodID id = NULL;
1447 // We use a double-check locking idiom here because this cache is
1448 // performance sensitive. In the normal system, this cache only
1449 // transitions from NULL to non-NULL which is safe because we use
1450 // release_set_methods_jmethod_ids() to advertise the new cache.
1451 // A partially constructed cache should never be seen by a racing
1452 // thread. We also use release_store_ptr() to save a new jmethodID
1453 // in the cache so a partially constructed jmethodID should never be
1454 // seen either. Cache reads of existing jmethodIDs proceed without a
1455 // lock, but cache writes of a new jmethodID requires uniqueness and
1456 // creation of the cache itself requires no leaks so a lock is
1457 // generally acquired in those two cases.
1458 //
1459 // If the RedefineClasses() API has been used, then this cache can
1460 // grow and we'll have transitions from non-NULL to bigger non-NULL.
1461 // Cache creation requires no leaks and we require safety between all
1462 // cache accesses and freeing of the old cache so a lock is generally
1463 // acquired when the RedefineClasses() API has been used.
1465 if (jmeths != NULL) {
1466 // the cache already exists
1467 if (!ik_h->idnum_can_increment()) {
1468 // the cache can't grow so we can just get the current values
1469 get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1470 } else {
1471 // cache can grow so we have to be more careful
1472 if (Threads::number_of_threads() == 0 ||
1473 SafepointSynchronize::is_at_safepoint()) {
1474 // we're single threaded or at a safepoint - no locking needed
1475 get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1476 } else {
1477 MutexLocker ml(JmethodIdCreation_lock);
1478 get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1479 }
1480 }
1481 }
1482 // implied else:
1483 // we need to allocate a cache so default length and id values are good
1485 if (jmeths == NULL || // no cache yet
1486 length <= idnum || // cache is too short
1487 id == NULL) { // cache doesn't contain entry
1489 // This function can be called by the VMThread so we have to do all
1490 // things that might block on a safepoint before grabbing the lock.
1491 // Otherwise, we can deadlock with the VMThread or have a cache
1492 // consistency issue. These vars keep track of what we might have
1493 // to free after the lock is dropped.
1494 jmethodID to_dealloc_id = NULL;
1495 jmethodID* to_dealloc_jmeths = NULL;
1497 // may not allocate new_jmeths or use it if we allocate it
1498 jmethodID* new_jmeths = NULL;
1499 if (length <= idnum) {
1500 // allocate a new cache that might be used
1501 size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
1502 new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
1503 memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1504 // cache size is stored in element[0], other elements offset by one
1505 new_jmeths[0] = (jmethodID)size;
1506 }
1508 // allocate a new jmethodID that might be used
1509 jmethodID new_id = NULL;
1510 if (method_h->is_old() && !method_h->is_obsolete()) {
1511 // The method passed in is old (but not obsolete), we need to use the current version
1512 Method* current_method = ik_h->method_with_idnum((int)idnum);
1513 assert(current_method != NULL, "old and but not obsolete, so should exist");
1514 new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
1515 } else {
1516 // It is the current version of the method or an obsolete method,
1517 // use the version passed in
1518 new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
1519 }
1521 if (Threads::number_of_threads() == 0 ||
1522 SafepointSynchronize::is_at_safepoint()) {
1523 // we're single threaded or at a safepoint - no locking needed
1524 id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1525 &to_dealloc_id, &to_dealloc_jmeths);
1526 } else {
1527 MutexLocker ml(JmethodIdCreation_lock);
1528 id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1529 &to_dealloc_id, &to_dealloc_jmeths);
1530 }
1532 // The lock has been dropped so we can free resources.
1533 // Free up either the old cache or the new cache if we allocated one.
1534 if (to_dealloc_jmeths != NULL) {
1535 FreeHeap(to_dealloc_jmeths);
1536 }
1537 // free up the new ID since it wasn't needed
1538 if (to_dealloc_id != NULL) {
1539 Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
1540 }
1541 }
1542 return id;
1543 }
1546 // Common code to fetch the jmethodID from the cache or update the
1547 // cache with the new jmethodID. This function should never do anything
1548 // that causes the caller to go to a safepoint or we can deadlock with
1549 // the VMThread or have cache consistency issues.
1550 //
1551 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
1552 instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
1553 jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
1554 jmethodID** to_dealloc_jmeths_p) {
1555 assert(new_id != NULL, "sanity check");
1556 assert(to_dealloc_id_p != NULL, "sanity check");
1557 assert(to_dealloc_jmeths_p != NULL, "sanity check");
1558 assert(Threads::number_of_threads() == 0 ||
1559 SafepointSynchronize::is_at_safepoint() ||
1560 JmethodIdCreation_lock->owned_by_self(), "sanity check");
1562 // reacquire the cache - we are locked, single threaded or at a safepoint
1563 jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1564 jmethodID id = NULL;
1565 size_t length = 0;
1567 if (jmeths == NULL || // no cache yet
1568 (length = (size_t)jmeths[0]) <= idnum) { // cache is too short
1569 if (jmeths != NULL) {
1570 // copy any existing entries from the old cache
1571 for (size_t index = 0; index < length; index++) {
1572 new_jmeths[index+1] = jmeths[index+1];
1573 }
1574 *to_dealloc_jmeths_p = jmeths; // save old cache for later delete
1575 }
1576 ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
1577 } else {
1578 // fetch jmethodID (if any) from the existing cache
1579 id = jmeths[idnum+1];
1580 *to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete
1581 }
1582 if (id == NULL) {
1583 // No matching jmethodID in the existing cache or we have a new
1584 // cache or we just grew the cache. This cache write is done here
1585 // by the first thread to win the foot race because a jmethodID
1586 // needs to be unique once it is generally available.
1587 id = new_id;
1589 // The jmethodID cache can be read while unlocked so we have to
1590 // make sure the new jmethodID is complete before installing it
1591 // in the cache.
1592 OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
1593 } else {
1594 *to_dealloc_id_p = new_id; // save new id for later delete
1595 }
1596 return id;
1597 }
1600 // Common code to get the jmethodID cache length and the jmethodID
1601 // value at index idnum if there is one.
1602 //
1603 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1604 size_t idnum, size_t *length_p, jmethodID* id_p) {
1605 assert(cache != NULL, "sanity check");
1606 assert(length_p != NULL, "sanity check");
1607 assert(id_p != NULL, "sanity check");
1609 // cache size is stored in element[0], other elements offset by one
1610 *length_p = (size_t)cache[0];
1611 if (*length_p <= idnum) { // cache is too short
1612 *id_p = NULL;
1613 } else {
1614 *id_p = cache[idnum+1]; // fetch jmethodID (if any)
1615 }
1616 }
1619 // Lookup a jmethodID, NULL if not found. Do no blocking, no allocations, no handles
1620 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
1621 size_t idnum = (size_t)method->method_idnum();
1622 jmethodID* jmeths = methods_jmethod_ids_acquire();
1623 size_t length; // length assigned as debugging crumb
1624 jmethodID id = NULL;
1625 if (jmeths != NULL && // If there is a cache
1626 (length = (size_t)jmeths[0]) > idnum) { // and if it is long enough,
1627 id = jmeths[idnum+1]; // Look up the id (may be NULL)
1628 }
1629 return id;
1630 }
1633 // Cache an itable index
1634 void InstanceKlass::set_cached_itable_index(size_t idnum, int index) {
1635 int* indices = methods_cached_itable_indices_acquire();
1636 int* to_dealloc_indices = NULL;
1638 // We use a double-check locking idiom here because this cache is
1639 // performance sensitive. In the normal system, this cache only
1640 // transitions from NULL to non-NULL which is safe because we use
1641 // release_set_methods_cached_itable_indices() to advertise the
1642 // new cache. A partially constructed cache should never be seen
1643 // by a racing thread. Cache reads and writes proceed without a
1644 // lock, but creation of the cache itself requires no leaks so a
1645 // lock is generally acquired in that case.
1646 //
1647 // If the RedefineClasses() API has been used, then this cache can
1648 // grow and we'll have transitions from non-NULL to bigger non-NULL.
1649 // Cache creation requires no leaks and we require safety between all
1650 // cache accesses and freeing of the old cache so a lock is generally
1651 // acquired when the RedefineClasses() API has been used.
1653 if (indices == NULL || idnum_can_increment()) {
1654 // we need a cache or the cache can grow
1655 MutexLocker ml(JNICachedItableIndex_lock);
1656 // reacquire the cache to see if another thread already did the work
1657 indices = methods_cached_itable_indices_acquire();
1658 size_t length = 0;
1659 // cache size is stored in element[0], other elements offset by one
1660 if (indices == NULL || (length = (size_t)indices[0]) <= idnum) {
1661 size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count());
1662 int* new_indices = NEW_C_HEAP_ARRAY(int, size+1, mtClass);
1663 new_indices[0] = (int)size;
1664 // copy any existing entries
1665 size_t i;
1666 for (i = 0; i < length; i++) {
1667 new_indices[i+1] = indices[i+1];
1668 }
1669 // Set all the rest to -1
1670 for (i = length; i < size; i++) {
1671 new_indices[i+1] = -1;
1672 }
1673 if (indices != NULL) {
1674 // We have an old cache to delete so save it for after we
1675 // drop the lock.
1676 to_dealloc_indices = indices;
1677 }
1678 release_set_methods_cached_itable_indices(indices = new_indices);
1679 }
1681 if (idnum_can_increment()) {
1682 // this cache can grow so we have to write to it safely
1683 indices[idnum+1] = index;
1684 }
1685 } else {
1686 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
1687 }
1689 if (!idnum_can_increment()) {
1690 // The cache cannot grow and this JNI itable index value does not
1691 // have to be unique like a jmethodID. If there is a race to set it,
1692 // it doesn't matter.
1693 indices[idnum+1] = index;
1694 }
1696 if (to_dealloc_indices != NULL) {
1697 // we allocated a new cache so free the old one
1698 FreeHeap(to_dealloc_indices);
1699 }
1700 }
1703 // Retrieve a cached itable index
1704 int InstanceKlass::cached_itable_index(size_t idnum) {
1705 int* indices = methods_cached_itable_indices_acquire();
1706 if (indices != NULL && ((size_t)indices[0]) > idnum) {
1707 // indices exist and are long enough, retrieve possible cached
1708 return indices[idnum+1];
1709 }
1710 return -1;
1711 }
1714 //
1715 // Walk the list of dependent nmethods searching for nmethods which
1716 // are dependent on the changes that were passed in and mark them for
1717 // deoptimization. Returns the number of nmethods found.
1718 //
1719 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
1720 assert_locked_or_safepoint(CodeCache_lock);
1721 int found = 0;
1722 nmethodBucket* b = _dependencies;
1723 while (b != NULL) {
1724 nmethod* nm = b->get_nmethod();
1725 // since dependencies aren't removed until an nmethod becomes a zombie,
1726 // the dependency list may contain nmethods which aren't alive.
1727 if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
1728 if (TraceDependencies) {
1729 ResourceMark rm;
1730 tty->print_cr("Marked for deoptimization");
1731 tty->print_cr(" context = %s", this->external_name());
1732 changes.print();
1733 nm->print();
1734 nm->print_dependencies();
1735 }
1736 nm->mark_for_deoptimization();
1737 found++;
1738 }
1739 b = b->next();
1740 }
1741 return found;
1742 }
1745 //
1746 // Add an nmethodBucket to the list of dependencies for this nmethod.
1747 // It's possible that an nmethod has multiple dependencies on this klass
1748 // so a count is kept for each bucket to guarantee that creation and
1749 // deletion of dependencies is consistent.
1750 //
1751 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
1752 assert_locked_or_safepoint(CodeCache_lock);
1753 nmethodBucket* b = _dependencies;
1754 nmethodBucket* last = NULL;
1755 while (b != NULL) {
1756 if (nm == b->get_nmethod()) {
1757 b->increment();
1758 return;
1759 }
1760 b = b->next();
1761 }
1762 _dependencies = new nmethodBucket(nm, _dependencies);
1763 }
1766 //
1767 // Decrement count of the nmethod in the dependency list and remove
1768 // the bucket competely when the count goes to 0. This method must
1769 // find a corresponding bucket otherwise there's a bug in the
1770 // recording of dependecies.
1771 //
1772 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
1773 assert_locked_or_safepoint(CodeCache_lock);
1774 nmethodBucket* b = _dependencies;
1775 nmethodBucket* last = NULL;
1776 while (b != NULL) {
1777 if (nm == b->get_nmethod()) {
1778 if (b->decrement() == 0) {
1779 if (last == NULL) {
1780 _dependencies = b->next();
1781 } else {
1782 last->set_next(b->next());
1783 }
1784 delete b;
1785 }
1786 return;
1787 }
1788 last = b;
1789 b = b->next();
1790 }
1791 #ifdef ASSERT
1792 tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
1793 nm->print();
1794 #endif // ASSERT
1795 ShouldNotReachHere();
1796 }
1799 #ifndef PRODUCT
1800 void InstanceKlass::print_dependent_nmethods(bool verbose) {
1801 nmethodBucket* b = _dependencies;
1802 int idx = 0;
1803 while (b != NULL) {
1804 nmethod* nm = b->get_nmethod();
1805 tty->print("[%d] count=%d { ", idx++, b->count());
1806 if (!verbose) {
1807 nm->print_on(tty, "nmethod");
1808 tty->print_cr(" } ");
1809 } else {
1810 nm->print();
1811 nm->print_dependencies();
1812 tty->print_cr("--- } ");
1813 }
1814 b = b->next();
1815 }
1816 }
1819 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
1820 nmethodBucket* b = _dependencies;
1821 while (b != NULL) {
1822 if (nm == b->get_nmethod()) {
1823 return true;
1824 }
1825 b = b->next();
1826 }
1827 return false;
1828 }
1829 #endif //PRODUCT
1832 // Garbage collection
1834 void InstanceKlass::oops_do(OopClosure* cl) {
1835 Klass::oops_do(cl);
1837 cl->do_oop(adr_protection_domain());
1838 cl->do_oop(adr_signers());
1839 cl->do_oop(adr_init_lock());
1841 // Don't walk the arrays since they are walked from the ClassLoaderData objects.
1842 }
1844 #ifdef ASSERT
1845 template <class T> void assert_is_in(T *p) {
1846 T heap_oop = oopDesc::load_heap_oop(p);
1847 if (!oopDesc::is_null(heap_oop)) {
1848 oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1849 assert(Universe::heap()->is_in(o), "should be in heap");
1850 }
1851 }
1852 template <class T> void assert_is_in_closed_subset(T *p) {
1853 T heap_oop = oopDesc::load_heap_oop(p);
1854 if (!oopDesc::is_null(heap_oop)) {
1855 oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1856 assert(Universe::heap()->is_in_closed_subset(o),
1857 err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
1858 }
1859 }
1860 template <class T> void assert_is_in_reserved(T *p) {
1861 T heap_oop = oopDesc::load_heap_oop(p);
1862 if (!oopDesc::is_null(heap_oop)) {
1863 oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1864 assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
1865 }
1866 }
1867 template <class T> void assert_nothing(T *p) {}
1869 #else
1870 template <class T> void assert_is_in(T *p) {}
1871 template <class T> void assert_is_in_closed_subset(T *p) {}
1872 template <class T> void assert_is_in_reserved(T *p) {}
1873 template <class T> void assert_nothing(T *p) {}
1874 #endif // ASSERT
1876 //
1877 // Macros that iterate over areas of oops which are specialized on type of
1878 // oop pointer either narrow or wide, depending on UseCompressedOops
1879 //
1880 // Parameters are:
1881 // T - type of oop to point to (either oop or narrowOop)
1882 // start_p - starting pointer for region to iterate over
1883 // count - number of oops or narrowOops to iterate over
1884 // do_oop - action to perform on each oop (it's arbitrary C code which
1885 // makes it more efficient to put in a macro rather than making
1886 // it a template function)
1887 // assert_fn - assert function which is template function because performance
1888 // doesn't matter when enabled.
1889 #define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
1890 T, start_p, count, do_oop, \
1891 assert_fn) \
1892 { \
1893 T* p = (T*)(start_p); \
1894 T* const end = p + (count); \
1895 while (p < end) { \
1896 (assert_fn)(p); \
1897 do_oop; \
1898 ++p; \
1899 } \
1900 }
1902 #define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
1903 T, start_p, count, do_oop, \
1904 assert_fn) \
1905 { \
1906 T* const start = (T*)(start_p); \
1907 T* p = start + (count); \
1908 while (start < p) { \
1909 --p; \
1910 (assert_fn)(p); \
1911 do_oop; \
1912 } \
1913 }
1915 #define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
1916 T, start_p, count, low, high, \
1917 do_oop, assert_fn) \
1918 { \
1919 T* const l = (T*)(low); \
1920 T* const h = (T*)(high); \
1921 assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
1922 mask_bits((intptr_t)h, sizeof(T)-1) == 0, \
1923 "bounded region must be properly aligned"); \
1924 T* p = (T*)(start_p); \
1925 T* end = p + (count); \
1926 if (p < l) p = l; \
1927 if (end > h) end = h; \
1928 while (p < end) { \
1929 (assert_fn)(p); \
1930 do_oop; \
1931 ++p; \
1932 } \
1933 }
1936 // The following macros call specialized macros, passing either oop or
1937 // narrowOop as the specialization type. These test the UseCompressedOops
1938 // flag.
1939 #define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn) \
1940 { \
1941 /* Compute oopmap block range. The common case \
1942 is nonstatic_oop_map_size == 1. */ \
1943 OopMapBlock* map = start_of_nonstatic_oop_maps(); \
1944 OopMapBlock* const end_map = map + nonstatic_oop_map_count(); \
1945 if (UseCompressedOops) { \
1946 while (map < end_map) { \
1947 InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop, \
1948 obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \
1949 do_oop, assert_fn) \
1950 ++map; \
1951 } \
1952 } else { \
1953 while (map < end_map) { \
1954 InstanceKlass_SPECIALIZED_OOP_ITERATE(oop, \
1955 obj->obj_field_addr<oop>(map->offset()), map->count(), \
1956 do_oop, assert_fn) \
1957 ++map; \
1958 } \
1959 } \
1960 }
1962 #define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn) \
1963 { \
1964 OopMapBlock* const start_map = start_of_nonstatic_oop_maps(); \
1965 OopMapBlock* map = start_map + nonstatic_oop_map_count(); \
1966 if (UseCompressedOops) { \
1967 while (start_map < map) { \
1968 --map; \
1969 InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop, \
1970 obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \
1971 do_oop, assert_fn) \
1972 } \
1973 } else { \
1974 while (start_map < map) { \
1975 --map; \
1976 InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop, \
1977 obj->obj_field_addr<oop>(map->offset()), map->count(), \
1978 do_oop, assert_fn) \
1979 } \
1980 } \
1981 }
1983 #define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop, \
1984 assert_fn) \
1985 { \
1986 /* Compute oopmap block range. The common case is \
1987 nonstatic_oop_map_size == 1, so we accept the \
1988 usually non-existent extra overhead of examining \
1989 all the maps. */ \
1990 OopMapBlock* map = start_of_nonstatic_oop_maps(); \
1991 OopMapBlock* const end_map = map + nonstatic_oop_map_count(); \
1992 if (UseCompressedOops) { \
1993 while (map < end_map) { \
1994 InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop, \
1995 obj->obj_field_addr<narrowOop>(map->offset()), map->count(), \
1996 low, high, \
1997 do_oop, assert_fn) \
1998 ++map; \
1999 } \
2000 } else { \
2001 while (map < end_map) { \
2002 InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop, \
2003 obj->obj_field_addr<oop>(map->offset()), map->count(), \
2004 low, high, \
2005 do_oop, assert_fn) \
2006 ++map; \
2007 } \
2008 } \
2009 }
2011 void InstanceKlass::oop_follow_contents(oop obj) {
2012 assert(obj != NULL, "can't follow the content of NULL object");
2013 MarkSweep::follow_klass(obj->klass());
2014 InstanceKlass_OOP_MAP_ITERATE( \
2015 obj, \
2016 MarkSweep::mark_and_push(p), \
2017 assert_is_in_closed_subset)
2018 }
2020 #ifndef SERIALGC
2021 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
2022 oop obj) {
2023 assert(obj != NULL, "can't follow the content of NULL object");
2024 PSParallelCompact::follow_klass(cm, obj->klass());
2025 // Only mark the header and let the scan of the meta-data mark
2026 // everything else.
2027 InstanceKlass_OOP_MAP_ITERATE( \
2028 obj, \
2029 PSParallelCompact::mark_and_push(cm, p), \
2030 assert_is_in)
2031 }
2032 #endif // SERIALGC
2034 // closure's do_metadata() method dictates whether the given closure should be
2035 // applied to the klass ptr in the object header.
2037 #define if_do_metadata_checked(closure, nv_suffix) \
2038 /* Make sure the non-virtual and the virtual versions match. */ \
2039 assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
2040 "Inconsistency in do_metadata"); \
2041 if (closure->do_metadata##nv_suffix())
2043 #define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix) \
2044 \
2045 int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
2046 SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2047 /* header */ \
2048 if_do_metadata_checked(closure, nv_suffix) { \
2049 closure->do_klass##nv_suffix(obj->klass()); \
2050 } \
2051 InstanceKlass_OOP_MAP_ITERATE( \
2052 obj, \
2053 SpecializationStats:: \
2054 record_do_oop_call##nv_suffix(SpecializationStats::ik); \
2055 (closure)->do_oop##nv_suffix(p), \
2056 assert_is_in_closed_subset) \
2057 return size_helper(); \
2058 }
2060 #ifndef SERIALGC
2061 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
2062 \
2063 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj, \
2064 OopClosureType* closure) { \
2065 SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
2066 /* header */ \
2067 if_do_metadata_checked(closure, nv_suffix) { \
2068 closure->do_klass##nv_suffix(obj->klass()); \
2069 } \
2070 /* instance variables */ \
2071 InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
2072 obj, \
2073 SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
2074 (closure)->do_oop##nv_suffix(p), \
2075 assert_is_in_closed_subset) \
2076 return size_helper(); \
2077 }
2078 #endif // !SERIALGC
2080 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
2081 \
2082 int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj, \
2083 OopClosureType* closure, \
2084 MemRegion mr) { \
2085 SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2086 if_do_metadata_checked(closure, nv_suffix) { \
2087 if (mr.contains(obj)) { \
2088 closure->do_klass##nv_suffix(obj->klass()); \
2089 } \
2090 } \
2091 InstanceKlass_BOUNDED_OOP_MAP_ITERATE( \
2092 obj, mr.start(), mr.end(), \
2093 (closure)->do_oop##nv_suffix(p), \
2094 assert_is_in_closed_subset) \
2095 return size_helper(); \
2096 }
2098 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2099 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2100 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2101 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2102 #ifndef SERIALGC
2103 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2104 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2105 #endif // !SERIALGC
2107 int InstanceKlass::oop_adjust_pointers(oop obj) {
2108 int size = size_helper();
2109 InstanceKlass_OOP_MAP_ITERATE( \
2110 obj, \
2111 MarkSweep::adjust_pointer(p), \
2112 assert_is_in)
2113 MarkSweep::adjust_klass(obj->klass());
2114 return size;
2115 }
2117 #ifndef SERIALGC
2118 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
2119 InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
2120 obj, \
2121 if (PSScavenge::should_scavenge(p)) { \
2122 pm->claim_or_forward_depth(p); \
2123 }, \
2124 assert_nothing )
2125 }
2127 int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
2128 int size = size_helper();
2129 InstanceKlass_OOP_MAP_ITERATE( \
2130 obj, \
2131 PSParallelCompact::adjust_pointer(p), \
2132 assert_is_in)
2133 obj->update_header(cm);
2134 return size;
2135 }
2137 #endif // SERIALGC
2139 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
2140 assert(is_loader_alive(is_alive), "this klass should be live");
2141 if (is_interface()) {
2142 if (ClassUnloading) {
2143 Klass* impl = implementor();
2144 if (impl != NULL) {
2145 if (!impl->is_loader_alive(is_alive)) {
2146 // remove this guy
2147 *adr_implementor() = NULL;
2148 }
2149 }
2150 }
2151 }
2152 }
2154 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
2155 #ifdef COMPILER2
2156 // Currently only used by C2.
2157 for (int m = 0; m < methods()->length(); m++) {
2158 MethodData* mdo = methods()->at(m)->method_data();
2159 if (mdo != NULL) {
2160 for (ProfileData* data = mdo->first_data();
2161 mdo->is_valid(data);
2162 data = mdo->next_data(data)) {
2163 data->clean_weak_klass_links(is_alive);
2164 }
2165 }
2166 }
2167 #else
2168 #ifdef ASSERT
2169 // Verify that we haven't started to use MDOs for C1.
2170 for (int m = 0; m < methods()->length(); m++) {
2171 MethodData* mdo = methods()->at(m)->method_data();
2172 assert(mdo == NULL, "Didn't expect C1 to use MDOs");
2173 }
2174 #endif // ASSERT
2175 #endif // !COMPILER2
2176 }
2179 static void remove_unshareable_in_class(Klass* k) {
2180 // remove klass's unshareable info
2181 k->remove_unshareable_info();
2182 }
2184 void InstanceKlass::remove_unshareable_info() {
2185 Klass::remove_unshareable_info();
2186 // Unlink the class
2187 if (is_linked()) {
2188 unlink_class();
2189 }
2190 init_implementor();
2192 constants()->remove_unshareable_info();
2194 for (int i = 0; i < methods()->length(); i++) {
2195 Method* m = methods()->at(i);
2196 m->remove_unshareable_info();
2197 }
2199 // Need to reinstate when reading back the class.
2200 set_init_lock(NULL);
2202 // do array classes also.
2203 array_klasses_do(remove_unshareable_in_class);
2204 }
2206 void restore_unshareable_in_class(Klass* k, TRAPS) {
2207 k->restore_unshareable_info(CHECK);
2208 }
2210 void InstanceKlass::restore_unshareable_info(TRAPS) {
2211 Klass::restore_unshareable_info(CHECK);
2212 instanceKlassHandle ik(THREAD, this);
2214 Array<Method*>* methods = ik->methods();
2215 int num_methods = methods->length();
2216 for (int index2 = 0; index2 < num_methods; ++index2) {
2217 methodHandle m(THREAD, methods->at(index2));
2218 m()->link_method(m, CHECK);
2219 // restore method's vtable by calling a virtual function
2220 m->restore_vtable();
2221 }
2222 if (JvmtiExport::has_redefined_a_class()) {
2223 // Reinitialize vtable because RedefineClasses may have changed some
2224 // entries in this vtable for super classes so the CDS vtable might
2225 // point to old or obsolete entries. RedefineClasses doesn't fix up
2226 // vtables in the shared system dictionary, only the main one.
2227 // It also redefines the itable too so fix that too.
2228 ResourceMark rm(THREAD);
2229 ik->vtable()->initialize_vtable(false, CHECK);
2230 ik->itable()->initialize_itable(false, CHECK);
2231 }
2233 // Allocate a simple java object for a lock.
2234 // This needs to be a java object because during class initialization
2235 // it can be held across a java call.
2236 typeArrayOop r = oopFactory::new_typeArray(T_INT, 0, CHECK);
2237 Handle h(THREAD, (oop)r);
2238 ik->set_init_lock(h());
2240 // restore constant pool resolved references
2241 ik->constants()->restore_unshareable_info(CHECK);
2243 ik->array_klasses_do(restore_unshareable_in_class, CHECK);
2244 }
2246 static void clear_all_breakpoints(Method* m) {
2247 m->clear_all_breakpoints();
2248 }
2250 void InstanceKlass::release_C_heap_structures() {
2251 // Deallocate oop map cache
2252 if (_oop_map_cache != NULL) {
2253 delete _oop_map_cache;
2254 _oop_map_cache = NULL;
2255 }
2257 // Deallocate JNI identifiers for jfieldIDs
2258 JNIid::deallocate(jni_ids());
2259 set_jni_ids(NULL);
2261 jmethodID* jmeths = methods_jmethod_ids_acquire();
2262 if (jmeths != (jmethodID*)NULL) {
2263 release_set_methods_jmethod_ids(NULL);
2264 FreeHeap(jmeths);
2265 }
2267 int* indices = methods_cached_itable_indices_acquire();
2268 if (indices != (int*)NULL) {
2269 release_set_methods_cached_itable_indices(NULL);
2270 FreeHeap(indices);
2271 }
2273 // release dependencies
2274 nmethodBucket* b = _dependencies;
2275 _dependencies = NULL;
2276 while (b != NULL) {
2277 nmethodBucket* next = b->next();
2278 delete b;
2279 b = next;
2280 }
2282 // Deallocate breakpoint records
2283 if (breakpoints() != 0x0) {
2284 methods_do(clear_all_breakpoints);
2285 assert(breakpoints() == 0x0, "should have cleared breakpoints");
2286 }
2288 // deallocate information about previous versions
2289 if (_previous_versions != NULL) {
2290 for (int i = _previous_versions->length() - 1; i >= 0; i--) {
2291 PreviousVersionNode * pv_node = _previous_versions->at(i);
2292 delete pv_node;
2293 }
2294 delete _previous_versions;
2295 _previous_versions = NULL;
2296 }
2298 // deallocate the cached class file
2299 if (_cached_class_file_bytes != NULL) {
2300 os::free(_cached_class_file_bytes, mtClass);
2301 _cached_class_file_bytes = NULL;
2302 _cached_class_file_len = 0;
2303 }
2305 // Decrement symbol reference counts associated with the unloaded class.
2306 if (_name != NULL) _name->decrement_refcount();
2307 // unreference array name derived from this class name (arrays of an unloaded
2308 // class can't be referenced anymore).
2309 if (_array_name != NULL) _array_name->decrement_refcount();
2310 if (_source_file_name != NULL) _source_file_name->decrement_refcount();
2311 if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
2313 assert(_total_instanceKlass_count >= 1, "Sanity check");
2314 Atomic::dec(&_total_instanceKlass_count);
2315 }
2317 void InstanceKlass::set_source_file_name(Symbol* n) {
2318 _source_file_name = n;
2319 if (_source_file_name != NULL) _source_file_name->increment_refcount();
2320 }
2322 void InstanceKlass::set_source_debug_extension(char* array, int length) {
2323 if (array == NULL) {
2324 _source_debug_extension = NULL;
2325 } else {
2326 // Adding one to the attribute length in order to store a null terminator
2327 // character could cause an overflow because the attribute length is
2328 // already coded with an u4 in the classfile, but in practice, it's
2329 // unlikely to happen.
2330 assert((length+1) > length, "Overflow checking");
2331 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2332 for (int i = 0; i < length; i++) {
2333 sde[i] = array[i];
2334 }
2335 sde[length] = '\0';
2336 _source_debug_extension = sde;
2337 }
2338 }
2340 address InstanceKlass::static_field_addr(int offset) {
2341 return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + (intptr_t)java_mirror());
2342 }
2345 const char* InstanceKlass::signature_name() const {
2346 const char* src = (const char*) (name()->as_C_string());
2347 const int src_length = (int)strlen(src);
2348 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
2349 int src_index = 0;
2350 int dest_index = 0;
2351 dest[dest_index++] = 'L';
2352 while (src_index < src_length) {
2353 dest[dest_index++] = src[src_index++];
2354 }
2355 dest[dest_index++] = ';';
2356 dest[dest_index] = '\0';
2357 return dest;
2358 }
2360 // different verisons of is_same_class_package
2361 bool InstanceKlass::is_same_class_package(Klass* class2) {
2362 Klass* class1 = this;
2363 oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2364 Symbol* classname1 = class1->name();
2366 if (class2->oop_is_objArray()) {
2367 class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2368 }
2369 oop classloader2;
2370 if (class2->oop_is_instance()) {
2371 classloader2 = InstanceKlass::cast(class2)->class_loader();
2372 } else {
2373 assert(class2->oop_is_typeArray(), "should be type array");
2374 classloader2 = NULL;
2375 }
2376 Symbol* classname2 = class2->name();
2378 return InstanceKlass::is_same_class_package(classloader1, classname1,
2379 classloader2, classname2);
2380 }
2382 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
2383 Klass* class1 = this;
2384 oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2385 Symbol* classname1 = class1->name();
2387 return InstanceKlass::is_same_class_package(classloader1, classname1,
2388 classloader2, classname2);
2389 }
2391 // return true if two classes are in the same package, classloader
2392 // and classname information is enough to determine a class's package
2393 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2394 oop class_loader2, Symbol* class_name2) {
2395 if (class_loader1 != class_loader2) {
2396 return false;
2397 } else if (class_name1 == class_name2) {
2398 return true; // skip painful bytewise comparison
2399 } else {
2400 ResourceMark rm;
2402 // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
2403 // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
2404 // Otherwise, we just compare jbyte values between the strings.
2405 const jbyte *name1 = class_name1->base();
2406 const jbyte *name2 = class_name2->base();
2408 const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
2409 const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
2411 if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
2412 // One of the two doesn't have a package. Only return true
2413 // if the other one also doesn't have a package.
2414 return last_slash1 == last_slash2;
2415 } else {
2416 // Skip over '['s
2417 if (*name1 == '[') {
2418 do {
2419 name1++;
2420 } while (*name1 == '[');
2421 if (*name1 != 'L') {
2422 // Something is terribly wrong. Shouldn't be here.
2423 return false;
2424 }
2425 }
2426 if (*name2 == '[') {
2427 do {
2428 name2++;
2429 } while (*name2 == '[');
2430 if (*name2 != 'L') {
2431 // Something is terribly wrong. Shouldn't be here.
2432 return false;
2433 }
2434 }
2436 // Check that package part is identical
2437 int length1 = last_slash1 - name1;
2438 int length2 = last_slash2 - name2;
2440 return UTF8::equal(name1, length1, name2, length2);
2441 }
2442 }
2443 }
2445 // Returns true iff super_method can be overridden by a method in targetclassname
2446 // See JSL 3rd edition 8.4.6.1
2447 // Assumes name-signature match
2448 // "this" is InstanceKlass of super_method which must exist
2449 // note that the InstanceKlass of the method in the targetclassname has not always been created yet
2450 bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2451 // Private methods can not be overridden
2452 if (super_method->is_private()) {
2453 return false;
2454 }
2455 // If super method is accessible, then override
2456 if ((super_method->is_protected()) ||
2457 (super_method->is_public())) {
2458 return true;
2459 }
2460 // Package-private methods are not inherited outside of package
2461 assert(super_method->is_package_private(), "must be package private");
2462 return(is_same_class_package(targetclassloader(), targetclassname));
2463 }
2465 /* defined for now in jvm.cpp, for historical reasons *--
2466 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2467 Symbol*& simple_name_result, TRAPS) {
2468 ...
2469 }
2470 */
2472 // tell if two classes have the same enclosing class (at package level)
2473 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
2474 Klass* class2_oop, TRAPS) {
2475 if (class2_oop == class1()) return true;
2476 if (!class2_oop->oop_is_instance()) return false;
2477 instanceKlassHandle class2(THREAD, class2_oop);
2479 // must be in same package before we try anything else
2480 if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
2481 return false;
2483 // As long as there is an outer1.getEnclosingClass,
2484 // shift the search outward.
2485 instanceKlassHandle outer1 = class1;
2486 for (;;) {
2487 // As we walk along, look for equalities between outer1 and class2.
2488 // Eventually, the walks will terminate as outer1 stops
2489 // at the top-level class around the original class.
2490 bool ignore_inner_is_member;
2491 Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2492 CHECK_false);
2493 if (next == NULL) break;
2494 if (next == class2()) return true;
2495 outer1 = instanceKlassHandle(THREAD, next);
2496 }
2498 // Now do the same for class2.
2499 instanceKlassHandle outer2 = class2;
2500 for (;;) {
2501 bool ignore_inner_is_member;
2502 Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2503 CHECK_false);
2504 if (next == NULL) break;
2505 // Might as well check the new outer against all available values.
2506 if (next == class1()) return true;
2507 if (next == outer1()) return true;
2508 outer2 = instanceKlassHandle(THREAD, next);
2509 }
2511 // If by this point we have not found an equality between the
2512 // two classes, we know they are in separate package members.
2513 return false;
2514 }
2517 jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2518 jint access = access_flags().as_int();
2520 // But check if it happens to be member class.
2521 instanceKlassHandle ik(THREAD, this);
2522 InnerClassesIterator iter(ik);
2523 for (; !iter.done(); iter.next()) {
2524 int ioff = iter.inner_class_info_index();
2525 // Inner class attribute can be zero, skip it.
2526 // Strange but true: JVM spec. allows null inner class refs.
2527 if (ioff == 0) continue;
2529 // only look at classes that are already loaded
2530 // since we are looking for the flags for our self.
2531 Symbol* inner_name = ik->constants()->klass_name_at(ioff);
2532 if ((ik->name() == inner_name)) {
2533 // This is really a member class.
2534 access = iter.inner_access_flags();
2535 break;
2536 }
2537 }
2538 // Remember to strip ACC_SUPER bit
2539 return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2540 }
2542 jint InstanceKlass::jvmti_class_status() const {
2543 jint result = 0;
2545 if (is_linked()) {
2546 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2547 }
2549 if (is_initialized()) {
2550 assert(is_linked(), "Class status is not consistent");
2551 result |= JVMTI_CLASS_STATUS_INITIALIZED;
2552 }
2553 if (is_in_error_state()) {
2554 result |= JVMTI_CLASS_STATUS_ERROR;
2555 }
2556 return result;
2557 }
2559 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2560 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2561 int method_table_offset_in_words = ioe->offset()/wordSize;
2562 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2563 / itableOffsetEntry::size();
2565 for (int cnt = 0 ; ; cnt ++, ioe ++) {
2566 // If the interface isn't implemented by the receiver class,
2567 // the VM should throw IncompatibleClassChangeError.
2568 if (cnt >= nof_interfaces) {
2569 THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
2570 }
2572 Klass* ik = ioe->interface_klass();
2573 if (ik == holder) break;
2574 }
2576 itableMethodEntry* ime = ioe->first_method_entry(this);
2577 Method* m = ime[index].method();
2578 if (m == NULL) {
2579 THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2580 }
2581 return m;
2582 }
2584 // On-stack replacement stuff
2585 void InstanceKlass::add_osr_nmethod(nmethod* n) {
2586 // only one compilation can be active
2587 NEEDS_CLEANUP
2588 // This is a short non-blocking critical region, so the no safepoint check is ok.
2589 OsrList_lock->lock_without_safepoint_check();
2590 assert(n->is_osr_method(), "wrong kind of nmethod");
2591 n->set_osr_link(osr_nmethods_head());
2592 set_osr_nmethods_head(n);
2593 // Raise the highest osr level if necessary
2594 if (TieredCompilation) {
2595 Method* m = n->method();
2596 m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2597 }
2598 // Remember to unlock again
2599 OsrList_lock->unlock();
2601 // Get rid of the osr methods for the same bci that have lower levels.
2602 if (TieredCompilation) {
2603 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2604 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2605 if (inv != NULL && inv->is_in_use()) {
2606 inv->make_not_entrant();
2607 }
2608 }
2609 }
2610 }
2613 void InstanceKlass::remove_osr_nmethod(nmethod* n) {
2614 // This is a short non-blocking critical region, so the no safepoint check is ok.
2615 OsrList_lock->lock_without_safepoint_check();
2616 assert(n->is_osr_method(), "wrong kind of nmethod");
2617 nmethod* last = NULL;
2618 nmethod* cur = osr_nmethods_head();
2619 int max_level = CompLevel_none; // Find the max comp level excluding n
2620 Method* m = n->method();
2621 // Search for match
2622 while(cur != NULL && cur != n) {
2623 if (TieredCompilation) {
2624 // Find max level before n
2625 max_level = MAX2(max_level, cur->comp_level());
2626 }
2627 last = cur;
2628 cur = cur->osr_link();
2629 }
2630 nmethod* next = NULL;
2631 if (cur == n) {
2632 next = cur->osr_link();
2633 if (last == NULL) {
2634 // Remove first element
2635 set_osr_nmethods_head(next);
2636 } else {
2637 last->set_osr_link(next);
2638 }
2639 }
2640 n->set_osr_link(NULL);
2641 if (TieredCompilation) {
2642 cur = next;
2643 while (cur != NULL) {
2644 // Find max level after n
2645 max_level = MAX2(max_level, cur->comp_level());
2646 cur = cur->osr_link();
2647 }
2648 m->set_highest_osr_comp_level(max_level);
2649 }
2650 // Remember to unlock again
2651 OsrList_lock->unlock();
2652 }
2654 nmethod* InstanceKlass::lookup_osr_nmethod(Method* const m, int bci, int comp_level, bool match_level) const {
2655 // This is a short non-blocking critical region, so the no safepoint check is ok.
2656 OsrList_lock->lock_without_safepoint_check();
2657 nmethod* osr = osr_nmethods_head();
2658 nmethod* best = NULL;
2659 while (osr != NULL) {
2660 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2661 // There can be a time when a c1 osr method exists but we are waiting
2662 // for a c2 version. When c2 completes its osr nmethod we will trash
2663 // the c1 version and only be able to find the c2 version. However
2664 // while we overflow in the c1 code at back branches we don't want to
2665 // try and switch to the same code as we are already running
2667 if (osr->method() == m &&
2668 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
2669 if (match_level) {
2670 if (osr->comp_level() == comp_level) {
2671 // Found a match - return it.
2672 OsrList_lock->unlock();
2673 return osr;
2674 }
2675 } else {
2676 if (best == NULL || (osr->comp_level() > best->comp_level())) {
2677 if (osr->comp_level() == CompLevel_highest_tier) {
2678 // Found the best possible - return it.
2679 OsrList_lock->unlock();
2680 return osr;
2681 }
2682 best = osr;
2683 }
2684 }
2685 }
2686 osr = osr->osr_link();
2687 }
2688 OsrList_lock->unlock();
2689 if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
2690 return best;
2691 }
2692 return NULL;
2693 }
2695 // -----------------------------------------------------------------------------------------------------
2696 // Printing
2698 #ifndef PRODUCT
2700 #define BULLET " - "
2702 static const char* state_names[] = {
2703 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
2704 };
2706 void InstanceKlass::print_on(outputStream* st) const {
2707 assert(is_klass(), "must be klass");
2708 Klass::print_on(st);
2710 st->print(BULLET"instance size: %d", size_helper()); st->cr();
2711 st->print(BULLET"klass size: %d", size()); st->cr();
2712 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
2713 st->print(BULLET"state: "); st->print_cr(state_names[_init_state]);
2714 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
2715 st->print(BULLET"super: "); super()->print_value_on_maybe_null(st); st->cr();
2716 st->print(BULLET"sub: ");
2717 Klass* sub = subklass();
2718 int n;
2719 for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
2720 if (n < MaxSubklassPrintSize) {
2721 sub->print_value_on(st);
2722 st->print(" ");
2723 }
2724 }
2725 if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
2726 st->cr();
2728 if (is_interface()) {
2729 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
2730 if (nof_implementors() == 1) {
2731 st->print_cr(BULLET"implementor: ");
2732 st->print(" ");
2733 implementor()->print_value_on(st);
2734 st->cr();
2735 }
2736 }
2738 st->print(BULLET"arrays: "); array_klasses()->print_value_on_maybe_null(st); st->cr();
2739 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr();
2740 if (Verbose) {
2741 Array<Method*>* method_array = methods();
2742 for(int i = 0; i < method_array->length(); i++) {
2743 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2744 }
2745 }
2746 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr();
2747 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
2748 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
2749 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();
2750 if (class_loader_data() != NULL) {
2751 st->print(BULLET"class loader data: ");
2752 class_loader_data()->print_value_on(st);
2753 st->cr();
2754 }
2755 st->print(BULLET"protection domain: "); ((InstanceKlass*)this)->protection_domain()->print_value_on(st); st->cr();
2756 st->print(BULLET"host class: "); host_klass()->print_value_on_maybe_null(st); st->cr();
2757 st->print(BULLET"signers: "); signers()->print_value_on(st); st->cr();
2758 st->print(BULLET"init_lock: "); ((oop)init_lock())->print_value_on(st); st->cr();
2759 if (source_file_name() != NULL) {
2760 st->print(BULLET"source file: ");
2761 source_file_name()->print_value_on(st);
2762 st->cr();
2763 }
2764 if (source_debug_extension() != NULL) {
2765 st->print(BULLET"source debug extension: ");
2766 st->print("%s", source_debug_extension());
2767 st->cr();
2768 }
2769 st->print(BULLET"annotations: "); annotations()->print_value_on(st); st->cr();
2770 {
2771 ResourceMark rm;
2772 // PreviousVersionInfo objects returned via PreviousVersionWalker
2773 // contain a GrowableArray of handles. We have to clean up the
2774 // GrowableArray _after_ the PreviousVersionWalker destructor
2775 // has destroyed the handles.
2776 {
2777 bool have_pv = false;
2778 PreviousVersionWalker pvw((InstanceKlass*)this);
2779 for (PreviousVersionInfo * pv_info = pvw.next_previous_version();
2780 pv_info != NULL; pv_info = pvw.next_previous_version()) {
2781 if (!have_pv)
2782 st->print(BULLET"previous version: ");
2783 have_pv = true;
2784 pv_info->prev_constant_pool_handle()()->print_value_on(st);
2785 }
2786 if (have_pv) st->cr();
2787 } // pvw is cleaned up
2788 } // rm is cleaned up
2790 if (generic_signature() != NULL) {
2791 st->print(BULLET"generic signature: ");
2792 generic_signature()->print_value_on(st);
2793 st->cr();
2794 }
2795 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
2796 st->print(BULLET"java mirror: "); java_mirror()->print_value_on(st); st->cr();
2797 st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable()); st->cr();
2798 st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
2799 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
2800 FieldPrinter print_static_field(st);
2801 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
2802 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
2803 FieldPrinter print_nonstatic_field(st);
2804 ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
2806 st->print(BULLET"non-static oop maps: ");
2807 OopMapBlock* map = start_of_nonstatic_oop_maps();
2808 OopMapBlock* end_map = map + nonstatic_oop_map_count();
2809 while (map < end_map) {
2810 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
2811 map++;
2812 }
2813 st->cr();
2814 }
2816 #endif //PRODUCT
2818 void InstanceKlass::print_value_on(outputStream* st) const {
2819 assert(is_klass(), "must be klass");
2820 name()->print_value_on(st);
2821 }
2823 #ifndef PRODUCT
2825 void FieldPrinter::do_field(fieldDescriptor* fd) {
2826 _st->print(BULLET);
2827 if (_obj == NULL) {
2828 fd->print_on(_st);
2829 _st->cr();
2830 } else {
2831 fd->print_on_for(_st, _obj);
2832 _st->cr();
2833 }
2834 }
2837 void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
2838 Klass::oop_print_on(obj, st);
2840 if (this == SystemDictionary::String_klass()) {
2841 typeArrayOop value = java_lang_String::value(obj);
2842 juint offset = java_lang_String::offset(obj);
2843 juint length = java_lang_String::length(obj);
2844 if (value != NULL &&
2845 value->is_typeArray() &&
2846 offset <= (juint) value->length() &&
2847 offset + length <= (juint) value->length()) {
2848 st->print(BULLET"string: ");
2849 Handle h_obj(obj);
2850 java_lang_String::print(h_obj, st);
2851 st->cr();
2852 if (!WizardMode) return; // that is enough
2853 }
2854 }
2856 st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
2857 FieldPrinter print_field(st, obj);
2858 do_nonstatic_fields(&print_field);
2860 if (this == SystemDictionary::Class_klass()) {
2861 st->print(BULLET"signature: ");
2862 java_lang_Class::print_signature(obj, st);
2863 st->cr();
2864 Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
2865 st->print(BULLET"fake entry for mirror: ");
2866 mirrored_klass->print_value_on_maybe_null(st);
2867 st->cr();
2868 st->print(BULLET"fake entry resolved_constructor: ");
2869 Method* ctor = java_lang_Class::resolved_constructor(obj);
2870 ctor->print_value_on_maybe_null(st);
2871 Klass* array_klass = java_lang_Class::array_klass(obj);
2872 st->cr();
2873 st->print(BULLET"fake entry for array: ");
2874 array_klass->print_value_on_maybe_null(st);
2875 st->cr();
2876 st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
2877 st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
2878 Klass* real_klass = java_lang_Class::as_Klass(obj);
2879 if (real_klass != NULL && real_klass->oop_is_instance()) {
2880 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
2881 }
2882 } else if (this == SystemDictionary::MethodType_klass()) {
2883 st->print(BULLET"signature: ");
2884 java_lang_invoke_MethodType::print_signature(obj, st);
2885 st->cr();
2886 }
2887 }
2889 #endif //PRODUCT
2891 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
2892 st->print("a ");
2893 name()->print_value_on(st);
2894 obj->print_address_on(st);
2895 if (this == SystemDictionary::String_klass()
2896 && java_lang_String::value(obj) != NULL) {
2897 ResourceMark rm;
2898 int len = java_lang_String::length(obj);
2899 int plen = (len < 24 ? len : 12);
2900 char* str = java_lang_String::as_utf8_string(obj, 0, plen);
2901 st->print(" = \"%s\"", str);
2902 if (len > plen)
2903 st->print("...[%d]", len);
2904 } else if (this == SystemDictionary::Class_klass()) {
2905 Klass* k = java_lang_Class::as_Klass(obj);
2906 st->print(" = ");
2907 if (k != NULL) {
2908 k->print_value_on(st);
2909 } else {
2910 const char* tname = type2name(java_lang_Class::primitive_type(obj));
2911 st->print("%s", tname ? tname : "type?");
2912 }
2913 } else if (this == SystemDictionary::MethodType_klass()) {
2914 st->print(" = ");
2915 java_lang_invoke_MethodType::print_signature(obj, st);
2916 } else if (java_lang_boxing_object::is_instance(obj)) {
2917 st->print(" = ");
2918 java_lang_boxing_object::print(obj, st);
2919 } else if (this == SystemDictionary::LambdaForm_klass()) {
2920 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
2921 if (vmentry != NULL) {
2922 st->print(" => ");
2923 vmentry->print_value_on(st);
2924 }
2925 } else if (this == SystemDictionary::MemberName_klass()) {
2926 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
2927 if (vmtarget != NULL) {
2928 st->print(" = ");
2929 vmtarget->print_value_on(st);
2930 } else {
2931 java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
2932 st->print(".");
2933 java_lang_invoke_MemberName::name(obj)->print_value_on(st);
2934 }
2935 }
2936 }
2938 const char* InstanceKlass::internal_name() const {
2939 return external_name();
2940 }
2942 // Verification
2944 class VerifyFieldClosure: public OopClosure {
2945 protected:
2946 template <class T> void do_oop_work(T* p) {
2947 oop obj = oopDesc::load_decode_heap_oop(p);
2948 if (!obj->is_oop_or_null()) {
2949 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
2950 Universe::print();
2951 guarantee(false, "boom");
2952 }
2953 }
2954 public:
2955 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); }
2956 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
2957 };
2959 void InstanceKlass::verify_on(outputStream* st) {
2960 Klass::verify_on(st);
2961 Thread *thread = Thread::current();
2963 #ifndef PRODUCT
2964 // Avoid redundant verifies
2965 if (_verify_count == Universe::verify_count()) return;
2966 _verify_count = Universe::verify_count();
2967 #endif
2968 // Verify that klass is present in SystemDictionary
2969 if (is_loaded() && !is_anonymous()) {
2970 Symbol* h_name = name();
2971 SystemDictionary::verify_obj_klass_present(h_name, class_loader_data());
2972 }
2974 // Verify static fields
2975 VerifyFieldClosure blk;
2977 // Verify vtables
2978 if (is_linked()) {
2979 ResourceMark rm(thread);
2980 // $$$ This used to be done only for m/s collections. Doing it
2981 // always seemed a valid generalization. (DLD -- 6/00)
2982 vtable()->verify(st);
2983 }
2985 // Verify first subklass
2986 if (subklass_oop() != NULL) {
2987 guarantee(subklass_oop()->is_metadata(), "should be in metaspace");
2988 guarantee(subklass_oop()->is_klass(), "should be klass");
2989 }
2991 // Verify siblings
2992 Klass* super = this->super();
2993 Klass* sib = next_sibling();
2994 if (sib != NULL) {
2995 if (sib == this) {
2996 fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
2997 }
2999 guarantee(sib->is_metadata(), "should be in metaspace");
3000 guarantee(sib->is_klass(), "should be klass");
3001 guarantee(sib->super() == super, "siblings should have same superklass");
3002 }
3004 // Verify implementor fields
3005 Klass* im = implementor();
3006 if (im != NULL) {
3007 guarantee(is_interface(), "only interfaces should have implementor set");
3008 guarantee(im->is_klass(), "should be klass");
3009 guarantee(!im->is_interface() || im == this,
3010 "implementors cannot be interfaces");
3011 }
3013 // Verify local interfaces
3014 if (local_interfaces()) {
3015 Array<Klass*>* local_interfaces = this->local_interfaces();
3016 for (int j = 0; j < local_interfaces->length(); j++) {
3017 Klass* e = local_interfaces->at(j);
3018 guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3019 }
3020 }
3022 // Verify transitive interfaces
3023 if (transitive_interfaces() != NULL) {
3024 Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
3025 for (int j = 0; j < transitive_interfaces->length(); j++) {
3026 Klass* e = transitive_interfaces->at(j);
3027 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3028 }
3029 }
3031 // Verify methods
3032 if (methods() != NULL) {
3033 Array<Method*>* methods = this->methods();
3034 for (int j = 0; j < methods->length(); j++) {
3035 guarantee(methods->at(j)->is_metadata(), "should be in metaspace");
3036 guarantee(methods->at(j)->is_method(), "non-method in methods array");
3037 }
3038 for (int j = 0; j < methods->length() - 1; j++) {
3039 Method* m1 = methods->at(j);
3040 Method* m2 = methods->at(j + 1);
3041 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3042 }
3043 }
3045 // Verify method ordering
3046 if (method_ordering() != NULL) {
3047 Array<int>* method_ordering = this->method_ordering();
3048 int length = method_ordering->length();
3049 if (JvmtiExport::can_maintain_original_method_order() ||
3050 (UseSharedSpaces && length != 0)) {
3051 guarantee(length == methods()->length(), "invalid method ordering length");
3052 jlong sum = 0;
3053 for (int j = 0; j < length; j++) {
3054 int original_index = method_ordering->at(j);
3055 guarantee(original_index >= 0, "invalid method ordering index");
3056 guarantee(original_index < length, "invalid method ordering index");
3057 sum += original_index;
3058 }
3059 // Verify sum of indices 0,1,...,length-1
3060 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3061 } else {
3062 guarantee(length == 0, "invalid method ordering length");
3063 }
3064 }
3066 // Verify JNI static field identifiers
3067 if (jni_ids() != NULL) {
3068 jni_ids()->verify(this);
3069 }
3071 // Verify other fields
3072 if (array_klasses() != NULL) {
3073 guarantee(array_klasses()->is_metadata(), "should be in metaspace");
3074 guarantee(array_klasses()->is_klass(), "should be klass");
3075 }
3076 if (constants() != NULL) {
3077 guarantee(constants()->is_metadata(), "should be in metaspace");
3078 guarantee(constants()->is_constantPool(), "should be constant pool");
3079 }
3080 if (protection_domain() != NULL) {
3081 guarantee(protection_domain()->is_oop(), "should be oop");
3082 }
3083 if (host_klass() != NULL) {
3084 guarantee(host_klass()->is_metadata(), "should be in metaspace");
3085 guarantee(host_klass()->is_klass(), "should be klass");
3086 }
3087 if (signers() != NULL) {
3088 guarantee(signers()->is_objArray(), "should be obj array");
3089 }
3090 }
3092 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3093 Klass::oop_verify_on(obj, st);
3094 VerifyFieldClosure blk;
3095 obj->oop_iterate_no_header(&blk);
3096 }
3099 // JNIid class for jfieldIDs only
3100 // Note to reviewers:
3101 // These JNI functions are just moved over to column 1 and not changed
3102 // in the compressed oops workspace.
3103 JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3104 _holder = holder;
3105 _offset = offset;
3106 _next = next;
3107 debug_only(_is_static_field_id = false;)
3108 }
3111 JNIid* JNIid::find(int offset) {
3112 JNIid* current = this;
3113 while (current != NULL) {
3114 if (current->offset() == offset) return current;
3115 current = current->next();
3116 }
3117 return NULL;
3118 }
3120 void JNIid::deallocate(JNIid* current) {
3121 while (current != NULL) {
3122 JNIid* next = current->next();
3123 delete current;
3124 current = next;
3125 }
3126 }
3129 void JNIid::verify(Klass* holder) {
3130 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields();
3131 int end_field_offset;
3132 end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3134 JNIid* current = this;
3135 while (current != NULL) {
3136 guarantee(current->holder() == holder, "Invalid klass in JNIid");
3137 #ifdef ASSERT
3138 int o = current->offset();
3139 if (current->is_static_field_id()) {
3140 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid");
3141 }
3142 #endif
3143 current = current->next();
3144 }
3145 }
3148 #ifdef ASSERT
3149 void InstanceKlass::set_init_state(ClassState state) {
3150 bool good_state = is_shared() ? (_init_state <= state)
3151 : (_init_state < state);
3152 assert(good_state || state == allocated, "illegal state transition");
3153 _init_state = (u1)state;
3154 }
3155 #endif
3158 // RedefineClasses() support for previous versions:
3160 // Purge previous versions
3161 static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
3162 if (ik->previous_versions() != NULL) {
3163 // This klass has previous versions so see what we can cleanup
3164 // while it is safe to do so.
3166 int deleted_count = 0; // leave debugging breadcrumbs
3167 int live_count = 0;
3168 ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
3169 ClassLoaderData::the_null_class_loader_data() :
3170 ik->class_loader_data();
3172 // RC_TRACE macro has an embedded ResourceMark
3173 RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
3174 ik->external_name(), ik->previous_versions()->length()));
3176 for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
3177 // check the previous versions array
3178 PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
3179 ConstantPool* cp_ref = pv_node->prev_constant_pool();
3180 assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
3182 ConstantPool* pvcp = cp_ref;
3183 if (!pvcp->on_stack()) {
3184 // If the constant pool isn't on stack, none of the methods
3185 // are executing. Delete all the methods, the constant pool and
3186 // and this previous version node.
3187 GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3188 if (method_refs != NULL) {
3189 for (int j = method_refs->length() - 1; j >= 0; j--) {
3190 Method* method = method_refs->at(j);
3191 assert(method != NULL, "method ref was unexpectedly cleared");
3192 method_refs->remove_at(j);
3193 // method will be freed with associated class.
3194 }
3195 }
3196 // Remove the constant pool
3197 delete pv_node;
3198 // Since we are traversing the array backwards, we don't have to
3199 // do anything special with the index.
3200 ik->previous_versions()->remove_at(i);
3201 deleted_count++;
3202 continue;
3203 } else {
3204 RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
3205 assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3206 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3207 live_count++;
3208 }
3210 // At least one method is live in this previous version, clean out
3211 // the others or mark them as obsolete.
3212 GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3213 if (method_refs != NULL) {
3214 RC_TRACE(0x00000200, ("purge: previous methods length=%d",
3215 method_refs->length()));
3216 for (int j = method_refs->length() - 1; j >= 0; j--) {
3217 Method* method = method_refs->at(j);
3218 assert(method != NULL, "method ref was unexpectedly cleared");
3220 // Remove the emcp method if it's not executing
3221 // If it's been made obsolete by a redefinition of a non-emcp
3222 // method, mark it as obsolete but leave it to clean up later.
3223 if (!method->on_stack()) {
3224 method_refs->remove_at(j);
3225 } else if (emcp_method_count == 0) {
3226 method->set_is_obsolete();
3227 } else {
3228 // RC_TRACE macro has an embedded ResourceMark
3229 RC_TRACE(0x00000200,
3230 ("purge: %s(%s): prev method @%d in version @%d is alive",
3231 method->name()->as_C_string(),
3232 method->signature()->as_C_string(), j, i));
3233 }
3234 }
3235 }
3236 }
3237 assert(ik->previous_versions()->length() == live_count, "sanity check");
3238 RC_TRACE(0x00000200,
3239 ("purge: previous version stats: live=%d, deleted=%d", live_count,
3240 deleted_count));
3241 }
3242 }
3244 // External interface for use during class unloading.
3245 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
3246 // Call with >0 emcp methods since they are not currently being redefined.
3247 purge_previous_versions_internal(ik, 1);
3248 }
3251 // Potentially add an information node that contains pointers to the
3252 // interesting parts of the previous version of the_class.
3253 // This is also where we clean out any unused references.
3254 // Note that while we delete nodes from the _previous_versions
3255 // array, we never delete the array itself until the klass is
3256 // unloaded. The has_been_redefined() query depends on that fact.
3257 //
3258 void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
3259 BitMap* emcp_methods, int emcp_method_count) {
3260 assert(Thread::current()->is_VM_thread(),
3261 "only VMThread can add previous versions");
3263 if (_previous_versions == NULL) {
3264 // This is the first previous version so make some space.
3265 // Start with 2 elements under the assumption that the class
3266 // won't be redefined much.
3267 _previous_versions = new (ResourceObj::C_HEAP, mtClass)
3268 GrowableArray<PreviousVersionNode *>(2, true);
3269 }
3271 ConstantPool* cp_ref = ikh->constants();
3273 // RC_TRACE macro has an embedded ResourceMark
3274 RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
3275 "on_stack=%d",
3276 ikh->external_name(), _previous_versions->length(), emcp_method_count,
3277 cp_ref->on_stack()));
3279 // If the constant pool for this previous version of the class
3280 // is not marked as being on the stack, then none of the methods
3281 // in this previous version of the class are on the stack so
3282 // we don't need to create a new PreviousVersionNode. However,
3283 // we still need to examine older previous versions below.
3284 Array<Method*>* old_methods = ikh->methods();
3286 if (cp_ref->on_stack()) {
3287 PreviousVersionNode * pv_node = NULL;
3288 if (emcp_method_count == 0) {
3289 // non-shared ConstantPool gets a reference
3290 pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), NULL);
3291 RC_TRACE(0x00000400,
3292 ("add: all methods are obsolete; flushing any EMCP refs"));
3293 } else {
3294 int local_count = 0;
3295 GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
3296 GrowableArray<Method*>(emcp_method_count, true);
3297 for (int i = 0; i < old_methods->length(); i++) {
3298 if (emcp_methods->at(i)) {
3299 // this old method is EMCP. Save it only if it's on the stack
3300 Method* old_method = old_methods->at(i);
3301 if (old_method->on_stack()) {
3302 method_refs->append(old_method);
3303 }
3304 if (++local_count >= emcp_method_count) {
3305 // no more EMCP methods so bail out now
3306 break;
3307 }
3308 }
3309 }
3310 // non-shared ConstantPool gets a reference
3311 pv_node = new PreviousVersionNode(cp_ref, !cp_ref->is_shared(), method_refs);
3312 }
3313 // append new previous version.
3314 _previous_versions->append(pv_node);
3315 }
3317 // Since the caller is the VMThread and we are at a safepoint, this
3318 // is a good time to clear out unused references.
3320 RC_TRACE(0x00000400, ("add: previous version length=%d",
3321 _previous_versions->length()));
3323 // Purge previous versions not executing on the stack
3324 purge_previous_versions_internal(this, emcp_method_count);
3326 int obsolete_method_count = old_methods->length() - emcp_method_count;
3328 if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3329 _previous_versions->length() > 0) {
3330 // We have a mix of obsolete and EMCP methods so we have to
3331 // clear out any matching EMCP method entries the hard way.
3332 int local_count = 0;
3333 for (int i = 0; i < old_methods->length(); i++) {
3334 if (!emcp_methods->at(i)) {
3335 // only obsolete methods are interesting
3336 Method* old_method = old_methods->at(i);
3337 Symbol* m_name = old_method->name();
3338 Symbol* m_signature = old_method->signature();
3340 // we might not have added the last entry
3341 for (int j = _previous_versions->length() - 1; j >= 0; j--) {
3342 // check the previous versions array for non executing obsolete methods
3343 PreviousVersionNode * pv_node = _previous_versions->at(j);
3345 GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3346 if (method_refs == NULL) {
3347 // We have run into a PreviousVersion generation where
3348 // all methods were made obsolete during that generation's
3349 // RedefineClasses() operation. At the time of that
3350 // operation, all EMCP methods were flushed so we don't
3351 // have to go back any further.
3352 //
3353 // A NULL method_refs is different than an empty method_refs.
3354 // We cannot infer any optimizations about older generations
3355 // from an empty method_refs for the current generation.
3356 break;
3357 }
3359 for (int k = method_refs->length() - 1; k >= 0; k--) {
3360 Method* method = method_refs->at(k);
3362 if (!method->is_obsolete() &&
3363 method->name() == m_name &&
3364 method->signature() == m_signature) {
3365 // The current RedefineClasses() call has made all EMCP
3366 // versions of this method obsolete so mark it as obsolete
3367 // and remove the reference.
3368 RC_TRACE(0x00000400,
3369 ("add: %s(%s): flush obsolete method @%d in version @%d",
3370 m_name->as_C_string(), m_signature->as_C_string(), k, j));
3372 method->set_is_obsolete();
3373 // Leave obsolete methods on the previous version list to
3374 // clean up later.
3375 break;
3376 }
3377 }
3379 // The previous loop may not find a matching EMCP method, but
3380 // that doesn't mean that we can optimize and not go any
3381 // further back in the PreviousVersion generations. The EMCP
3382 // method for this generation could have already been deleted,
3383 // but there still may be an older EMCP method that has not
3384 // been deleted.
3385 }
3387 if (++local_count >= obsolete_method_count) {
3388 // no more obsolete methods so bail out now
3389 break;
3390 }
3391 }
3392 }
3393 }
3394 } // end add_previous_version()
3397 // Determine if InstanceKlass has a previous version.
3398 bool InstanceKlass::has_previous_version() const {
3399 return (_previous_versions != NULL && _previous_versions->length() > 0);
3400 } // end has_previous_version()
3403 Method* InstanceKlass::method_with_idnum(int idnum) {
3404 Method* m = NULL;
3405 if (idnum < methods()->length()) {
3406 m = methods()->at(idnum);
3407 }
3408 if (m == NULL || m->method_idnum() != idnum) {
3409 for (int index = 0; index < methods()->length(); ++index) {
3410 m = methods()->at(index);
3411 if (m->method_idnum() == idnum) {
3412 return m;
3413 }
3414 }
3415 }
3416 return m;
3417 }
3420 // Construct a PreviousVersionNode entry for the array hung off
3421 // the InstanceKlass.
3422 PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
3423 bool prev_cp_is_weak, GrowableArray<Method*>* prev_EMCP_methods) {
3425 _prev_constant_pool = prev_constant_pool;
3426 _prev_cp_is_weak = prev_cp_is_weak;
3427 _prev_EMCP_methods = prev_EMCP_methods;
3428 }
3431 // Destroy a PreviousVersionNode
3432 PreviousVersionNode::~PreviousVersionNode() {
3433 if (_prev_constant_pool != NULL) {
3434 _prev_constant_pool = NULL;
3435 }
3437 if (_prev_EMCP_methods != NULL) {
3438 delete _prev_EMCP_methods;
3439 }
3440 }
3443 // Construct a PreviousVersionInfo entry
3444 PreviousVersionInfo::PreviousVersionInfo(PreviousVersionNode *pv_node) {
3445 _prev_constant_pool_handle = constantPoolHandle(); // NULL handle
3446 _prev_EMCP_method_handles = NULL;
3448 ConstantPool* cp = pv_node->prev_constant_pool();
3449 assert(cp != NULL, "constant pool ref was unexpectedly cleared");
3450 if (cp == NULL) {
3451 return; // robustness
3452 }
3454 // make the ConstantPool* safe to return
3455 _prev_constant_pool_handle = constantPoolHandle(cp);
3457 GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3458 if (method_refs == NULL) {
3459 // the InstanceKlass did not have any EMCP methods
3460 return;
3461 }
3463 _prev_EMCP_method_handles = new GrowableArray<methodHandle>(10);
3465 int n_methods = method_refs->length();
3466 for (int i = 0; i < n_methods; i++) {
3467 Method* method = method_refs->at(i);
3468 assert (method != NULL, "method has been cleared");
3469 if (method == NULL) {
3470 continue; // robustness
3471 }
3472 // make the Method* safe to return
3473 _prev_EMCP_method_handles->append(methodHandle(method));
3474 }
3475 }
3478 // Destroy a PreviousVersionInfo
3479 PreviousVersionInfo::~PreviousVersionInfo() {
3480 // Since _prev_EMCP_method_handles is not C-heap allocated, we
3481 // don't have to delete it.
3482 }
3485 // Construct a helper for walking the previous versions array
3486 PreviousVersionWalker::PreviousVersionWalker(InstanceKlass *ik) {
3487 _previous_versions = ik->previous_versions();
3488 _current_index = 0;
3489 // _hm needs no initialization
3490 _current_p = NULL;
3491 }
3494 // Destroy a PreviousVersionWalker
3495 PreviousVersionWalker::~PreviousVersionWalker() {
3496 // Delete the current info just in case the caller didn't walk to
3497 // the end of the previous versions list. No harm if _current_p is
3498 // already NULL.
3499 delete _current_p;
3501 // When _hm is destroyed, all the Handles returned in
3502 // PreviousVersionInfo objects will be destroyed.
3503 // Also, after this destructor is finished it will be
3504 // safe to delete the GrowableArray allocated in the
3505 // PreviousVersionInfo objects.
3506 }
3509 // Return the interesting information for the next previous version
3510 // of the klass. Returns NULL if there are no more previous versions.
3511 PreviousVersionInfo* PreviousVersionWalker::next_previous_version() {
3512 if (_previous_versions == NULL) {
3513 // no previous versions so nothing to return
3514 return NULL;
3515 }
3517 delete _current_p; // cleanup the previous info for the caller
3518 _current_p = NULL; // reset to NULL so we don't delete same object twice
3520 int length = _previous_versions->length();
3522 while (_current_index < length) {
3523 PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
3524 PreviousVersionInfo * pv_info = new (ResourceObj::C_HEAP, mtClass)
3525 PreviousVersionInfo(pv_node);
3527 constantPoolHandle cp_h = pv_info->prev_constant_pool_handle();
3528 assert (!cp_h.is_null(), "null cp found in previous version");
3530 // The caller will need to delete pv_info when they are done with it.
3531 _current_p = pv_info;
3532 return pv_info;
3533 }
3535 // all of the underlying nodes' info has been deleted
3536 return NULL;
3537 } // end next_previous_version()