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