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