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