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