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