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