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