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