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