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