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