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