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