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 // field not found. Try to search for an accessor-method-pair 1173 bool found = false; 1174 int length = sig->utf8_length(); 1175 if (length > 0) { 1176 // extract original signature+ one \0 char 1177 char fSig[length+1]; 1178 sig->as_C_string(fSig,length+1); 1179 1180 // the signature of the get-Method is two chars longer + \0 1181 char get_sig[length+3]; 1182 sprintf(get_sig,"()%s",fSig); 1183 1184 // the signature of the put-Method is three chars longer + \0 1185 char put_sig[length+4]; 1186 sprintf(put_sig,"(%s)V",fSig); 1187 1188 // Look through all methods in the class. 1189 Array<Method*>* methods = this->methods(); 1190 for (int i = 0; i < methods->length(); i++) { 1191 Method* m = methods->at(i); 1192 1193 // extract name of accessor-field 1194 u2 af = m->accessor_field_name(); 1195 // Is zero an valid index? 1196 if (af != 0) { 1197 Symbol* fn = m->constMethod()->constants()->symbol_at(af); 1198 char mname[name->utf8_length()+1]; 1199 name->as_C_string(mname,name->utf8_length()+1); 1200 // if fieldname matches. record match and store name and 1201 // signature in fielddescriptor 1202 if (fn->equals(mname)) { 1203 found = true; 1204 fd->set_field_name_from_accessor(af); 1205 fd->set_sig_for_accessor(sig); 1206 if (m->signature()->equals(get_sig)) { 1207 // remember get method 1208 fd->set_get_accessor(m->method_idnum()); 1209 }else if (m->signature()->equals(put_sig)) { 1210 // remember put method 1211 fd->set_put_accessor(m->method_idnum()); 1212 } 1213 } 1214 } 1215 } 1216 } 1217 if (found) { 1218 // initialize accesor-values in fielddescriptor 1219 fd->reinitialize_accessor(const_cast<InstanceKlass*>(this)); 1220 // is the fielddescriptor a valid accessor-fielddescriptor? 1221 return fd->is_accessor(); 1222 } 1223 return false; 1224 } 1225 1226 1227 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const { 1228 const int n = local_interfaces()->length(); 1229 for (int i = 0; i < n; i++) { 1230 Klass* intf1 = local_interfaces()->at(i); 1231 assert(intf1->is_interface(), "just checking type"); 1232 // search for field in current interface 1233 if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) { 1234 assert(fd->is_static(), "interface field must be static"); 1235 return intf1; 1236 } 1237 // search for field in direct superinterfaces 1238 Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd); 1239 if (intf2 != NULL) return intf2; 1240 } 1241 // otherwise field lookup fails 1242 return NULL; 1243 } 1244 1245 1246 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const { 1247 // search order according to newest JVM spec (5.4.3.2, p.167). 1248 // 1) search for field in current klass 1249 if (find_local_field(name, sig, fd)) { 1250 return const_cast<InstanceKlass*>(this); 1251 } 1252 // 2) search for field recursively in direct superinterfaces 1253 { Klass* intf = find_interface_field(name, sig, fd); 1254 if (intf != NULL) return intf; 1255 } 1256 // 3) apply field lookup recursively if superclass exists 1257 { Klass* supr = super(); 1258 if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd); 1259 } 1260 // 4) otherwise field lookup fails 1261 return NULL; 1262 } 1263 1264 1265 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const { 1266 // search order according to newest JVM spec (5.4.3.2, p.167). 1267 // 1) search for field in current klass 1268 if (find_local_field(name, sig, fd)) { 1269 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this); 1270 } 1271 // 2) search for field recursively in direct superinterfaces 1272 if (is_static) { 1273 Klass* intf = find_interface_field(name, sig, fd); 1274 if (intf != NULL) return intf; 1275 } 1276 // 3) apply field lookup recursively if superclass exists 1277 { Klass* supr = super(); 1278 if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd); 1279 } 1280 // 4) otherwise field lookup fails 1281 return NULL; 1282 } 1283 1284 1285 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const { 1286 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1287 if (fs.offset() == offset) { 1288 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index()); 1289 if (fd->is_static() == is_static) return true; 1290 } 1291 } 1292 return false; 1293 } 1294 1295 1296 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const { 1297 Klass* klass = const_cast<InstanceKlass*>(this); 1298 while (klass != NULL) { 1299 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) { 1300 return true; 1301 } 1302 klass = klass->super(); 1303 } 1304 return false; 1305 } 1306 1307 1308 void InstanceKlass::methods_do(void f(Method* method)) { 1309 // Methods aren't stable until they are loaded. This can be read outside 1310 // a lock through the ClassLoaderData for profiling 1311 if (!is_loaded()) { 1312 return; 1313 } 1314 1315 int len = methods()->length(); 1316 for (int index = 0; index < len; index++) { 1317 Method* m = methods()->at(index); 1318 assert(m->is_method(), "must be method"); 1319 f(m); 1320 } 1321 } 1322 1323 1324 void InstanceKlass::do_local_static_fields(FieldClosure* cl) { 1325 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1326 if (fs.access_flags().is_static()) { 1327 fieldDescriptor& fd = fs.field_descriptor(); 1328 cl->do_field(&fd); 1329 } 1330 } 1331 } 1332 1333 1334 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) { 1335 instanceKlassHandle h_this(THREAD, this); 1336 do_local_static_fields_impl(h_this, f, mirror, CHECK); 1337 } 1338 1339 1340 void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k, 1341 void f(fieldDescriptor* fd, Handle, TRAPS), Handle mirror, TRAPS) { 1342 for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) { 1343 if (fs.access_flags().is_static()) { 1344 fieldDescriptor& fd = fs.field_descriptor(); 1345 f(&fd, mirror, CHECK); 1346 } 1347 } 1348 } 1349 1350 1351 static int compare_fields_by_offset(int* a, int* b) { 1352 return a[0] - b[0]; 1353 } 1354 1355 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) { 1356 InstanceKlass* super = superklass(); 1357 if (super != NULL) { 1358 super->do_nonstatic_fields(cl); 1359 } 1360 fieldDescriptor fd; 1361 int length = java_fields_count(); 1362 // In DebugInfo nonstatic fields are sorted by offset. 1363 int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass); 1364 int j = 0; 1365 for (int i = 0; i < length; i += 1) { 1366 fd.reinitialize(this, i); 1367 if (!fd.is_static()) { 1368 fields_sorted[j + 0] = fd.offset(); 1369 fields_sorted[j + 1] = i; 1370 j += 2; 1371 } 1372 } 1373 if (j > 0) { 1374 length = j; 1375 // _sort_Fn is defined in growableArray.hpp. 1376 qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset); 1377 for (int i = 0; i < length; i += 2) { 1378 fd.reinitialize(this, fields_sorted[i + 1]); 1379 assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields"); 1380 cl->do_field(&fd); 1381 } 1382 } 1383 FREE_C_HEAP_ARRAY(int, fields_sorted); 1384 } 1385 1386 1387 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) { 1388 if (array_klasses() != NULL) 1389 ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD); 1390 } 1391 1392 void InstanceKlass::array_klasses_do(void f(Klass* k)) { 1393 if (array_klasses() != NULL) 1394 ArrayKlass::cast(array_klasses())->array_klasses_do(f); 1395 } 1396 1397 #ifdef ASSERT 1398 static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) { 1399 int len = methods->length(); 1400 for (int index = 0; index < len; index++) { 1401 Method* m = methods->at(index); 1402 assert(m->is_method(), "must be method"); 1403 if (m->signature() == signature && m->name() == name) { 1404 return index; 1405 } 1406 } 1407 return -1; 1408 } 1409 #endif 1410 1411 static int binary_search(Array<Method*>* methods, Symbol* name) { 1412 int len = methods->length(); 1413 // methods are sorted, so do binary search 1414 int l = 0; 1415 int h = len - 1; 1416 while (l <= h) { 1417 int mid = (l + h) >> 1; 1418 Method* m = methods->at(mid); 1419 assert(m->is_method(), "must be method"); 1420 int res = m->name()->fast_compare(name); 1421 if (res == 0) { 1422 return mid; 1423 } else if (res < 0) { 1424 l = mid + 1; 1425 } else { 1426 h = mid - 1; 1427 } 1428 } 1429 return -1; 1430 } 1431 1432 // find_method looks up the name/signature in the local methods array 1433 Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const { 1434 return find_method_impl(name, signature, find_overpass, find_static, find_private); 1435 } 1436 1437 Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, 1438 OverpassLookupMode overpass_mode, 1439 StaticLookupMode static_mode, 1440 PrivateLookupMode private_mode) const { 1441 return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode); 1442 } 1443 1444 // find_instance_method looks up the name/signature in the local methods array 1445 // and skips over static methods 1446 Method* InstanceKlass::find_instance_method( 1447 Array<Method*>* methods, Symbol* name, Symbol* signature) { 1448 Method* meth = InstanceKlass::find_method_impl(methods, name, signature, 1449 find_overpass, skip_static, find_private); 1450 assert(((meth == NULL) || !meth->is_static()), "find_instance_method should have skipped statics"); 1451 return meth; 1452 } 1453 1454 // find_instance_method looks up the name/signature in the local methods array 1455 // and skips over static methods 1456 Method* InstanceKlass::find_instance_method(Symbol* name, Symbol* signature) { 1457 return InstanceKlass::find_instance_method(methods(), name, signature); 1458 } 1459 1460 // Find looks up the name/signature in the local methods array 1461 // and filters on the overpass, static and private flags 1462 // This returns the first one found 1463 // note that the local methods array can have up to one overpass, one static 1464 // and one instance (private or not) with the same name/signature 1465 Method* InstanceKlass::find_local_method(Symbol* name, Symbol* signature, 1466 OverpassLookupMode overpass_mode, 1467 StaticLookupMode static_mode, 1468 PrivateLookupMode private_mode) const { 1469 return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode); 1470 } 1471 1472 // Find looks up the name/signature in the local methods array 1473 // and filters on the overpass, static and private flags 1474 // This returns the first one found 1475 // note that the local methods array can have up to one overpass, one static 1476 // and one instance (private or not) with the same name/signature 1477 Method* InstanceKlass::find_local_method(Array<Method*>* methods, 1478 Symbol* name, Symbol* signature, 1479 OverpassLookupMode overpass_mode, 1480 StaticLookupMode static_mode, 1481 PrivateLookupMode private_mode) { 1482 return InstanceKlass::find_method_impl(methods, name, signature, overpass_mode, static_mode, private_mode); 1483 } 1484 1485 1486 // find_method looks up the name/signature in the local methods array 1487 Method* InstanceKlass::find_method( 1488 Array<Method*>* methods, Symbol* name, Symbol* signature) { 1489 return InstanceKlass::find_method_impl(methods, name, signature, find_overpass, find_static, find_private); 1490 } 1491 1492 Method* InstanceKlass::find_method_impl( 1493 Array<Method*>* methods, Symbol* name, Symbol* signature, 1494 OverpassLookupMode overpass_mode, StaticLookupMode static_mode, 1495 PrivateLookupMode private_mode) { 1496 int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode); 1497 return hit >= 0 ? methods->at(hit): NULL; 1498 } 1499 1500 bool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static, bool skipping_private) { 1501 return ((m->signature() == signature) && 1502 (!skipping_overpass || !m->is_overpass()) && 1503 (!skipping_static || !m->is_static()) && 1504 (!skipping_private || !m->is_private())); 1505 } 1506 1507 // Used directly for default_methods to find the index into the 1508 // default_vtable_indices, and indirectly by find_method 1509 // find_method_index looks in the local methods array to return the index 1510 // of the matching name/signature. If, overpass methods are being ignored, 1511 // the search continues to find a potential non-overpass match. This capability 1512 // is important during method resolution to prefer a static method, for example, 1513 // over an overpass method. 1514 // There is the possibility in any _method's array to have the same name/signature 1515 // for a static method, an overpass method and a local instance method 1516 // To correctly catch a given method, the search criteria may need 1517 // to explicitly skip the other two. For local instance methods, it 1518 // is often necessary to skip private methods 1519 int InstanceKlass::find_method_index( 1520 Array<Method*>* methods, Symbol* name, Symbol* signature, 1521 OverpassLookupMode overpass_mode, StaticLookupMode static_mode, 1522 PrivateLookupMode private_mode) { 1523 bool skipping_overpass = (overpass_mode == skip_overpass); 1524 bool skipping_static = (static_mode == skip_static); 1525 bool skipping_private = (private_mode == skip_private); 1526 int hit = binary_search(methods, name); 1527 if (hit != -1) { 1528 Method* m = methods->at(hit); 1529 1530 // Do linear search to find matching signature. First, quick check 1531 // for common case, ignoring overpasses if requested. 1532 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return hit; 1533 1534 // search downwards through overloaded methods 1535 int i; 1536 for (i = hit - 1; i >= 0; --i) { 1537 Method* m = methods->at(i); 1538 assert(m->is_method(), "must be method"); 1539 if (m->name() != name) break; 1540 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i; 1541 } 1542 // search upwards 1543 for (i = hit + 1; i < methods->length(); ++i) { 1544 Method* m = methods->at(i); 1545 assert(m->is_method(), "must be method"); 1546 if (m->name() != name) break; 1547 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i; 1548 } 1549 // not found 1550 #ifdef ASSERT 1551 int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : linear_search(methods, name, signature); 1552 assert(index == -1, "binary search should have found entry %d", index); 1553 #endif 1554 } 1555 return -1; 1556 } 1557 int InstanceKlass::find_method_by_name(Symbol* name, int* end) { 1558 return find_method_by_name(methods(), name, end); 1559 } 1560 1561 int InstanceKlass::find_method_by_name( 1562 Array<Method*>* methods, Symbol* name, int* end_ptr) { 1563 assert(end_ptr != NULL, "just checking"); 1564 int start = binary_search(methods, name); 1565 int end = start + 1; 1566 if (start != -1) { 1567 while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start; 1568 while (end < methods->length() && (methods->at(end))->name() == name) ++end; 1569 *end_ptr = end; 1570 return start; 1571 } 1572 return -1; 1573 } 1574 1575 // uncached_lookup_method searches both the local class methods array and all 1576 // superclasses methods arrays, skipping any overpass methods in superclasses. 1577 Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const { 1578 OverpassLookupMode overpass_local_mode = overpass_mode; 1579 Klass* klass = const_cast<InstanceKlass*>(this); 1580 while (klass != NULL) { 1581 Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, overpass_local_mode, find_static, find_private); 1582 if (method != NULL) { 1583 return method; 1584 } 1585 klass = klass->super(); 1586 overpass_local_mode = skip_overpass; // Always ignore overpass methods in superclasses 1587 } 1588 return NULL; 1589 } 1590 1591 #ifdef ASSERT 1592 // search through class hierarchy and return true if this class or 1593 // one of the superclasses was redefined 1594 bool InstanceKlass::has_redefined_this_or_super() { 1595 Klass* klass = this; 1596 while (klass != NULL) { 1597 if (InstanceKlass::cast(klass)->has_been_redefined()) { 1598 return true; 1599 } 1600 klass = klass->super(); 1601 } 1602 return false; 1603 } 1604 #endif 1605 1606 // lookup a method in the default methods list then in all transitive interfaces 1607 // Do NOT return private or static methods 1608 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name, 1609 Symbol* signature) const { 1610 Method* m = NULL; 1611 if (default_methods() != NULL) { 1612 m = find_method(default_methods(), name, signature); 1613 } 1614 // Look up interfaces 1615 if (m == NULL) { 1616 m = lookup_method_in_all_interfaces(name, signature, find_defaults); 1617 } 1618 return m; 1619 } 1620 1621 // lookup a method in all the interfaces that this class implements 1622 // Do NOT return private or static methods, new in JDK8 which are not externally visible 1623 // They should only be found in the initial InterfaceMethodRef 1624 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name, 1625 Symbol* signature, 1626 DefaultsLookupMode defaults_mode) const { 1627 Array<Klass*>* all_ifs = transitive_interfaces(); 1628 int num_ifs = all_ifs->length(); 1629 InstanceKlass *ik = NULL; 1630 for (int i = 0; i < num_ifs; i++) { 1631 ik = InstanceKlass::cast(all_ifs->at(i)); 1632 Method* m = ik->lookup_method(name, signature); 1633 if (m != NULL && m->is_public() && !m->is_static() && 1634 ((defaults_mode != skip_defaults) || !m->is_default_method())) { 1635 return m; 1636 } 1637 } 1638 return NULL; 1639 } 1640 1641 /* jni_id_for_impl for jfieldIds only */ 1642 JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_k, int offset) { 1643 MutexLocker ml(JfieldIdCreation_lock); 1644 // Retry lookup after we got the lock 1645 JNIid* probe = this_k->jni_ids() == NULL ? NULL : this_k->jni_ids()->find(offset); 1646 if (probe == NULL) { 1647 // Slow case, allocate new static field identifier 1648 probe = new JNIid(this_k(), offset, this_k->jni_ids()); 1649 this_k->set_jni_ids(probe); 1650 } 1651 return probe; 1652 } 1653 1654 1655 /* jni_id_for for jfieldIds only */ 1656 JNIid* InstanceKlass::jni_id_for(int offset) { 1657 JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset); 1658 if (probe == NULL) { 1659 probe = jni_id_for_impl(this, offset); 1660 } 1661 return probe; 1662 } 1663 1664 u2 InstanceKlass::enclosing_method_data(int offset) { 1665 Array<jushort>* inner_class_list = inner_classes(); 1666 if (inner_class_list == NULL) { 1667 return 0; 1668 } 1669 int length = inner_class_list->length(); 1670 if (length % inner_class_next_offset == 0) { 1671 return 0; 1672 } else { 1673 int index = length - enclosing_method_attribute_size; 1674 assert(offset < enclosing_method_attribute_size, "invalid offset"); 1675 return inner_class_list->at(index + offset); 1676 } 1677 } 1678 1679 void InstanceKlass::set_enclosing_method_indices(u2 class_index, 1680 u2 method_index) { 1681 Array<jushort>* inner_class_list = inner_classes(); 1682 assert (inner_class_list != NULL, "_inner_classes list is not set up"); 1683 int length = inner_class_list->length(); 1684 if (length % inner_class_next_offset == enclosing_method_attribute_size) { 1685 int index = length - enclosing_method_attribute_size; 1686 inner_class_list->at_put( 1687 index + enclosing_method_class_index_offset, class_index); 1688 inner_class_list->at_put( 1689 index + enclosing_method_method_index_offset, method_index); 1690 } 1691 } 1692 1693 // Lookup or create a jmethodID. 1694 // This code is called by the VMThread and JavaThreads so the 1695 // locking has to be done very carefully to avoid deadlocks 1696 // and/or other cache consistency problems. 1697 // 1698 jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, const methodHandle& method_h) { 1699 size_t idnum = (size_t)method_h->method_idnum(); 1700 jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire(); 1701 size_t length = 0; 1702 jmethodID id = NULL; 1703 1704 // We use a double-check locking idiom here because this cache is 1705 // performance sensitive. In the normal system, this cache only 1706 // transitions from NULL to non-NULL which is safe because we use 1707 // release_set_methods_jmethod_ids() to advertise the new cache. 1708 // A partially constructed cache should never be seen by a racing 1709 // thread. We also use release_store_ptr() to save a new jmethodID 1710 // in the cache so a partially constructed jmethodID should never be 1711 // seen either. Cache reads of existing jmethodIDs proceed without a 1712 // lock, but cache writes of a new jmethodID requires uniqueness and 1713 // creation of the cache itself requires no leaks so a lock is 1714 // generally acquired in those two cases. 1715 // 1716 // If the RedefineClasses() API has been used, then this cache can 1717 // grow and we'll have transitions from non-NULL to bigger non-NULL. 1718 // Cache creation requires no leaks and we require safety between all 1719 // cache accesses and freeing of the old cache so a lock is generally 1720 // acquired when the RedefineClasses() API has been used. 1721 1722 if (jmeths != NULL) { 1723 // the cache already exists 1724 if (!ik_h->idnum_can_increment()) { 1725 // the cache can't grow so we can just get the current values 1726 get_jmethod_id_length_value(jmeths, idnum, &length, &id); 1727 } else { 1728 // cache can grow so we have to be more careful 1729 if (Threads::number_of_threads() == 0 || 1730 SafepointSynchronize::is_at_safepoint()) { 1731 // we're single threaded or at a safepoint - no locking needed 1732 get_jmethod_id_length_value(jmeths, idnum, &length, &id); 1733 } else { 1734 MutexLocker ml(JmethodIdCreation_lock); 1735 get_jmethod_id_length_value(jmeths, idnum, &length, &id); 1736 } 1737 } 1738 } 1739 // implied else: 1740 // we need to allocate a cache so default length and id values are good 1741 1742 if (jmeths == NULL || // no cache yet 1743 length <= idnum || // cache is too short 1744 id == NULL) { // cache doesn't contain entry 1745 1746 // This function can be called by the VMThread so we have to do all 1747 // things that might block on a safepoint before grabbing the lock. 1748 // Otherwise, we can deadlock with the VMThread or have a cache 1749 // consistency issue. These vars keep track of what we might have 1750 // to free after the lock is dropped. 1751 jmethodID to_dealloc_id = NULL; 1752 jmethodID* to_dealloc_jmeths = NULL; 1753 1754 // may not allocate new_jmeths or use it if we allocate it 1755 jmethodID* new_jmeths = NULL; 1756 if (length <= idnum) { 1757 // allocate a new cache that might be used 1758 size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count()); 1759 new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass); 1760 memset(new_jmeths, 0, (size+1)*sizeof(jmethodID)); 1761 // cache size is stored in element[0], other elements offset by one 1762 new_jmeths[0] = (jmethodID)size; 1763 } 1764 1765 // allocate a new jmethodID that might be used 1766 jmethodID new_id = NULL; 1767 if (method_h->is_old() && !method_h->is_obsolete()) { 1768 // The method passed in is old (but not obsolete), we need to use the current version 1769 Method* current_method = ik_h->method_with_idnum((int)idnum); 1770 assert(current_method != NULL, "old and but not obsolete, so should exist"); 1771 new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method); 1772 } else { 1773 // It is the current version of the method or an obsolete method, 1774 // use the version passed in 1775 new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h()); 1776 } 1777 1778 if (Threads::number_of_threads() == 0 || 1779 SafepointSynchronize::is_at_safepoint()) { 1780 // we're single threaded or at a safepoint - no locking needed 1781 id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths, 1782 &to_dealloc_id, &to_dealloc_jmeths); 1783 } else { 1784 MutexLocker ml(JmethodIdCreation_lock); 1785 id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths, 1786 &to_dealloc_id, &to_dealloc_jmeths); 1787 } 1788 1789 // The lock has been dropped so we can free resources. 1790 // Free up either the old cache or the new cache if we allocated one. 1791 if (to_dealloc_jmeths != NULL) { 1792 FreeHeap(to_dealloc_jmeths); 1793 } 1794 // free up the new ID since it wasn't needed 1795 if (to_dealloc_id != NULL) { 1796 Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id); 1797 } 1798 } 1799 return id; 1800 } 1801 1802 // Figure out how many jmethodIDs haven't been allocated, and make 1803 // sure space for them is pre-allocated. This makes getting all 1804 // method ids much, much faster with classes with more than 8 1805 // methods, and has a *substantial* effect on performance with jvmti 1806 // code that loads all jmethodIDs for all classes. 1807 void InstanceKlass::ensure_space_for_methodids(int start_offset) { 1808 int new_jmeths = 0; 1809 int length = methods()->length(); 1810 for (int index = start_offset; index < length; index++) { 1811 Method* m = methods()->at(index); 1812 jmethodID id = m->find_jmethod_id_or_null(); 1813 if (id == NULL) { 1814 new_jmeths++; 1815 } 1816 } 1817 if (new_jmeths != 0) { 1818 Method::ensure_jmethod_ids(class_loader_data(), new_jmeths); 1819 } 1820 } 1821 1822 // Common code to fetch the jmethodID from the cache or update the 1823 // cache with the new jmethodID. This function should never do anything 1824 // that causes the caller to go to a safepoint or we can deadlock with 1825 // the VMThread or have cache consistency issues. 1826 // 1827 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update( 1828 instanceKlassHandle ik_h, size_t idnum, jmethodID new_id, 1829 jmethodID* new_jmeths, jmethodID* to_dealloc_id_p, 1830 jmethodID** to_dealloc_jmeths_p) { 1831 assert(new_id != NULL, "sanity check"); 1832 assert(to_dealloc_id_p != NULL, "sanity check"); 1833 assert(to_dealloc_jmeths_p != NULL, "sanity check"); 1834 assert(Threads::number_of_threads() == 0 || 1835 SafepointSynchronize::is_at_safepoint() || 1836 JmethodIdCreation_lock->owned_by_self(), "sanity check"); 1837 1838 // reacquire the cache - we are locked, single threaded or at a safepoint 1839 jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire(); 1840 jmethodID id = NULL; 1841 size_t length = 0; 1842 1843 if (jmeths == NULL || // no cache yet 1844 (length = (size_t)jmeths[0]) <= idnum) { // cache is too short 1845 if (jmeths != NULL) { 1846 // copy any existing entries from the old cache 1847 for (size_t index = 0; index < length; index++) { 1848 new_jmeths[index+1] = jmeths[index+1]; 1849 } 1850 *to_dealloc_jmeths_p = jmeths; // save old cache for later delete 1851 } 1852 ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths); 1853 } else { 1854 // fetch jmethodID (if any) from the existing cache 1855 id = jmeths[idnum+1]; 1856 *to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete 1857 } 1858 if (id == NULL) { 1859 // No matching jmethodID in the existing cache or we have a new 1860 // cache or we just grew the cache. This cache write is done here 1861 // by the first thread to win the foot race because a jmethodID 1862 // needs to be unique once it is generally available. 1863 id = new_id; 1864 1865 // The jmethodID cache can be read while unlocked so we have to 1866 // make sure the new jmethodID is complete before installing it 1867 // in the cache. 1868 OrderAccess::release_store_ptr(&jmeths[idnum+1], id); 1869 } else { 1870 *to_dealloc_id_p = new_id; // save new id for later delete 1871 } 1872 return id; 1873 } 1874 1875 1876 // Common code to get the jmethodID cache length and the jmethodID 1877 // value at index idnum if there is one. 1878 // 1879 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache, 1880 size_t idnum, size_t *length_p, jmethodID* id_p) { 1881 assert(cache != NULL, "sanity check"); 1882 assert(length_p != NULL, "sanity check"); 1883 assert(id_p != NULL, "sanity check"); 1884 1885 // cache size is stored in element[0], other elements offset by one 1886 *length_p = (size_t)cache[0]; 1887 if (*length_p <= idnum) { // cache is too short 1888 *id_p = NULL; 1889 } else { 1890 *id_p = cache[idnum+1]; // fetch jmethodID (if any) 1891 } 1892 } 1893 1894 1895 // Lookup a jmethodID, NULL if not found. Do no blocking, no allocations, no handles 1896 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) { 1897 size_t idnum = (size_t)method->method_idnum(); 1898 jmethodID* jmeths = methods_jmethod_ids_acquire(); 1899 size_t length; // length assigned as debugging crumb 1900 jmethodID id = NULL; 1901 if (jmeths != NULL && // If there is a cache 1902 (length = (size_t)jmeths[0]) > idnum) { // and if it is long enough, 1903 id = jmeths[idnum+1]; // Look up the id (may be NULL) 1904 } 1905 return id; 1906 } 1907 1908 int nmethodBucket::decrement() { 1909 return Atomic::add(-1, (volatile int *)&_count); 1910 } 1911 1912 // 1913 // Walk the list of dependent nmethods searching for nmethods which 1914 // are dependent on the changes that were passed in and mark them for 1915 // deoptimization. Returns the number of nmethods found. 1916 // 1917 int nmethodBucket::mark_dependent_nmethods(nmethodBucket* deps, DepChange& changes) { 1918 assert_locked_or_safepoint(CodeCache_lock); 1919 int found = 0; 1920 for (nmethodBucket* b = deps; b != NULL; b = b->next()) { 1921 nmethod* nm = b->get_nmethod(); 1922 // since dependencies aren't removed until an nmethod becomes a zombie, 1923 // the dependency list may contain nmethods which aren't alive. 1924 if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) { 1925 if (TraceDependencies) { 1926 ResourceMark rm; 1927 tty->print_cr("Marked for deoptimization"); 1928 changes.print(); 1929 nm->print(); 1930 nm->print_dependencies(); 1931 } 1932 nm->mark_for_deoptimization(); 1933 found++; 1934 } 1935 } 1936 return found; 1937 } 1938 1939 // 1940 // Add an nmethodBucket to the list of dependencies for this nmethod. 1941 // It's possible that an nmethod has multiple dependencies on this klass 1942 // so a count is kept for each bucket to guarantee that creation and 1943 // deletion of dependencies is consistent. Returns new head of the list. 1944 // 1945 nmethodBucket* nmethodBucket::add_dependent_nmethod(nmethodBucket* deps, nmethod* nm) { 1946 assert_locked_or_safepoint(CodeCache_lock); 1947 for (nmethodBucket* b = deps; b != NULL; b = b->next()) { 1948 if (nm == b->get_nmethod()) { 1949 b->increment(); 1950 return deps; 1951 } 1952 } 1953 return new nmethodBucket(nm, deps); 1954 } 1955 1956 // 1957 // Decrement count of the nmethod in the dependency list and remove 1958 // the bucket completely when the count goes to 0. This method must 1959 // find a corresponding bucket otherwise there's a bug in the 1960 // recording of dependencies. Returns true if the bucket was deleted, 1961 // or marked ready for reclaimation. 1962 bool nmethodBucket::remove_dependent_nmethod(nmethodBucket** deps, nmethod* nm, bool delete_immediately) { 1963 assert_locked_or_safepoint(CodeCache_lock); 1964 1965 nmethodBucket* first = *deps; 1966 nmethodBucket* last = NULL; 1967 1968 for (nmethodBucket* b = first; b != NULL; b = b->next()) { 1969 if (nm == b->get_nmethod()) { 1970 int val = b->decrement(); 1971 guarantee(val >= 0, "Underflow: %d", val); 1972 if (val == 0) { 1973 if (delete_immediately) { 1974 if (last == NULL) { 1975 *deps = b->next(); 1976 } else { 1977 last->set_next(b->next()); 1978 } 1979 delete b; 1980 } 1981 } 1982 return true; 1983 } 1984 last = b; 1985 } 1986 1987 #ifdef ASSERT 1988 tty->print_raw_cr("### can't find dependent nmethod"); 1989 nm->print(); 1990 #endif // ASSERT 1991 ShouldNotReachHere(); 1992 return false; 1993 } 1994 1995 // Convenience overload, for callers that don't want to delete the nmethodBucket entry. 1996 bool nmethodBucket::remove_dependent_nmethod(nmethodBucket* deps, nmethod* nm) { 1997 nmethodBucket** deps_addr = &deps; 1998 return remove_dependent_nmethod(deps_addr, nm, false /* Don't delete */); 1999 } 2000 2001 // 2002 // Reclaim all unused buckets. Returns new head of the list. 2003 // 2004 nmethodBucket* nmethodBucket::clean_dependent_nmethods(nmethodBucket* deps) { 2005 nmethodBucket* first = deps; 2006 nmethodBucket* last = NULL; 2007 nmethodBucket* b = first; 2008 2009 while (b != NULL) { 2010 assert(b->count() >= 0, "bucket count: %d", b->count()); 2011 nmethodBucket* next = b->next(); 2012 if (b->count() == 0) { 2013 if (last == NULL) { 2014 first = next; 2015 } else { 2016 last->set_next(next); 2017 } 2018 delete b; 2019 // last stays the same. 2020 } else { 2021 last = b; 2022 } 2023 b = next; 2024 } 2025 return first; 2026 } 2027 2028 #ifndef PRODUCT 2029 void nmethodBucket::print_dependent_nmethods(nmethodBucket* deps, bool verbose) { 2030 int idx = 0; 2031 for (nmethodBucket* b = deps; b != NULL; b = b->next()) { 2032 nmethod* nm = b->get_nmethod(); 2033 tty->print("[%d] count=%d { ", idx++, b->count()); 2034 if (!verbose) { 2035 nm->print_on(tty, "nmethod"); 2036 tty->print_cr(" } "); 2037 } else { 2038 nm->print(); 2039 nm->print_dependencies(); 2040 tty->print_cr("--- } "); 2041 } 2042 } 2043 } 2044 2045 bool nmethodBucket::is_dependent_nmethod(nmethodBucket* deps, nmethod* nm) { 2046 for (nmethodBucket* b = deps; b != NULL; b = b->next()) { 2047 if (nm == b->get_nmethod()) { 2048 #ifdef ASSERT 2049 int count = b->count(); 2050 assert(count >= 0, "count shouldn't be negative: %d", count); 2051 #endif 2052 return true; 2053 } 2054 } 2055 return false; 2056 } 2057 #endif //PRODUCT 2058 2059 int InstanceKlass::mark_dependent_nmethods(DepChange& changes) { 2060 assert_locked_or_safepoint(CodeCache_lock); 2061 return nmethodBucket::mark_dependent_nmethods(_dependencies, changes); 2062 } 2063 2064 void InstanceKlass::clean_dependent_nmethods() { 2065 assert_locked_or_safepoint(CodeCache_lock); 2066 2067 if (has_unloaded_dependent()) { 2068 _dependencies = nmethodBucket::clean_dependent_nmethods(_dependencies); 2069 set_has_unloaded_dependent(false); 2070 } 2071 #ifdef ASSERT 2072 else { 2073 // Verification 2074 for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) { 2075 assert(b->count() >= 0, "bucket count: %d", b->count()); 2076 assert(b->count() != 0, "empty buckets need to be cleaned"); 2077 } 2078 } 2079 #endif 2080 } 2081 2082 void InstanceKlass::add_dependent_nmethod(nmethod* nm) { 2083 assert_locked_or_safepoint(CodeCache_lock); 2084 _dependencies = nmethodBucket::add_dependent_nmethod(_dependencies, nm); 2085 } 2086 2087 void InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) { 2088 assert_locked_or_safepoint(CodeCache_lock); 2089 2090 if (nmethodBucket::remove_dependent_nmethod(&_dependencies, nm, delete_immediately)) { 2091 set_has_unloaded_dependent(true); 2092 } 2093 } 2094 2095 #ifndef PRODUCT 2096 void InstanceKlass::print_dependent_nmethods(bool verbose) { 2097 nmethodBucket::print_dependent_nmethods(_dependencies, verbose); 2098 } 2099 2100 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) { 2101 return nmethodBucket::is_dependent_nmethod(_dependencies, nm); 2102 } 2103 #endif //PRODUCT 2104 2105 void InstanceKlass::clean_weak_instanceklass_links(BoolObjectClosure* is_alive) { 2106 clean_implementors_list(is_alive); 2107 clean_method_data(is_alive); 2108 2109 clean_dependent_nmethods(); 2110 } 2111 2112 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) { 2113 assert(class_loader_data()->is_alive(is_alive), "this klass should be live"); 2114 if (is_interface()) { 2115 if (ClassUnloading) { 2116 Klass* impl = implementor(); 2117 if (impl != NULL) { 2118 if (!impl->is_loader_alive(is_alive)) { 2119 // remove this guy 2120 Klass** klass = adr_implementor(); 2121 assert(klass != NULL, "null klass"); 2122 if (klass != NULL) { 2123 *klass = NULL; 2124 } 2125 } 2126 } 2127 } 2128 } 2129 } 2130 2131 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) { 2132 for (int m = 0; m < methods()->length(); m++) { 2133 MethodData* mdo = methods()->at(m)->method_data(); 2134 if (mdo != NULL) { 2135 mdo->clean_method_data(is_alive); 2136 } 2137 } 2138 } 2139 2140 2141 static void remove_unshareable_in_class(Klass* k) { 2142 // remove klass's unshareable info 2143 k->remove_unshareable_info(); 2144 } 2145 2146 void InstanceKlass::remove_unshareable_info() { 2147 Klass::remove_unshareable_info(); 2148 // Unlink the class 2149 if (is_linked()) { 2150 unlink_class(); 2151 } 2152 init_implementor(); 2153 2154 constants()->remove_unshareable_info(); 2155 2156 for (int i = 0; i < methods()->length(); i++) { 2157 Method* m = methods()->at(i); 2158 m->remove_unshareable_info(); 2159 } 2160 2161 // do array classes also. 2162 array_klasses_do(remove_unshareable_in_class); 2163 } 2164 2165 static void restore_unshareable_in_class(Klass* k, TRAPS) { 2166 // Array classes have null protection domain. 2167 // --> see ArrayKlass::complete_create_array_klass() 2168 k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK); 2169 } 2170 2171 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) { 2172 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK); 2173 instanceKlassHandle ik(THREAD, this); 2174 2175 Array<Method*>* methods = ik->methods(); 2176 int num_methods = methods->length(); 2177 for (int index2 = 0; index2 < num_methods; ++index2) { 2178 methodHandle m(THREAD, methods->at(index2)); 2179 m->restore_unshareable_info(CHECK); 2180 } 2181 if (JvmtiExport::has_redefined_a_class()) { 2182 // Reinitialize vtable because RedefineClasses may have changed some 2183 // entries in this vtable for super classes so the CDS vtable might 2184 // point to old or obsolete entries. RedefineClasses doesn't fix up 2185 // vtables in the shared system dictionary, only the main one. 2186 // It also redefines the itable too so fix that too. 2187 ResourceMark rm(THREAD); 2188 ik->vtable()->initialize_vtable(false, CHECK); 2189 ik->itable()->initialize_itable(false, CHECK); 2190 } 2191 2192 // restore constant pool resolved references 2193 ik->constants()->restore_unshareable_info(CHECK); 2194 2195 ik->array_klasses_do(restore_unshareable_in_class, CHECK); 2196 } 2197 2198 // returns true IFF is_in_error_state() has been changed as a result of this call. 2199 bool InstanceKlass::check_sharing_error_state() { 2200 assert(DumpSharedSpaces, "should only be called during dumping"); 2201 bool old_state = is_in_error_state(); 2202 2203 if (!is_in_error_state()) { 2204 bool bad = false; 2205 for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) { 2206 if (sup->is_in_error_state()) { 2207 bad = true; 2208 break; 2209 } 2210 } 2211 if (!bad) { 2212 Array<Klass*>* interfaces = transitive_interfaces(); 2213 for (int i = 0; i < interfaces->length(); i++) { 2214 Klass* iface = interfaces->at(i); 2215 if (InstanceKlass::cast(iface)->is_in_error_state()) { 2216 bad = true; 2217 break; 2218 } 2219 } 2220 } 2221 2222 if (bad) { 2223 set_in_error_state(); 2224 } 2225 } 2226 2227 return (old_state != is_in_error_state()); 2228 } 2229 2230 static void clear_all_breakpoints(Method* m) { 2231 m->clear_all_breakpoints(); 2232 } 2233 2234 2235 void InstanceKlass::notify_unload_class(InstanceKlass* ik) { 2236 // notify the debugger 2237 if (JvmtiExport::should_post_class_unload()) { 2238 JvmtiExport::post_class_unload(ik); 2239 } 2240 2241 // notify ClassLoadingService of class unload 2242 ClassLoadingService::notify_class_unloaded(ik); 2243 } 2244 2245 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) { 2246 // Clean up C heap 2247 ik->release_C_heap_structures(); 2248 ik->constants()->release_C_heap_structures(); 2249 } 2250 2251 void InstanceKlass::release_C_heap_structures() { 2252 2253 // Can't release the constant pool here because the constant pool can be 2254 // deallocated separately from the InstanceKlass for default methods and 2255 // redefine classes. 2256 2257 // Deallocate oop map cache 2258 if (_oop_map_cache != NULL) { 2259 delete _oop_map_cache; 2260 _oop_map_cache = NULL; 2261 } 2262 2263 // Deallocate JNI identifiers for jfieldIDs 2264 JNIid::deallocate(jni_ids()); 2265 set_jni_ids(NULL); 2266 2267 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2268 if (jmeths != (jmethodID*)NULL) { 2269 release_set_methods_jmethod_ids(NULL); 2270 FreeHeap(jmeths); 2271 } 2272 2273 // Deallocate MemberNameTable 2274 { 2275 Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock; 2276 MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag); 2277 MemberNameTable* mnt = member_names(); 2278 if (mnt != NULL) { 2279 delete mnt; 2280 set_member_names(NULL); 2281 } 2282 } 2283 2284 // release dependencies 2285 nmethodBucket* b = _dependencies; 2286 _dependencies = NULL; 2287 while (b != NULL) { 2288 nmethodBucket* next = b->next(); 2289 delete b; 2290 b = next; 2291 } 2292 2293 // Deallocate breakpoint records 2294 if (breakpoints() != 0x0) { 2295 methods_do(clear_all_breakpoints); 2296 assert(breakpoints() == 0x0, "should have cleared breakpoints"); 2297 } 2298 2299 // deallocate the cached class file 2300 if (_cached_class_file != NULL) { 2301 os::free(_cached_class_file); 2302 _cached_class_file = NULL; 2303 } 2304 2305 // Decrement symbol reference counts associated with the unloaded class. 2306 if (_name != NULL) _name->decrement_refcount(); 2307 // unreference array name derived from this class name (arrays of an unloaded 2308 // class can't be referenced anymore). 2309 if (_array_name != NULL) _array_name->decrement_refcount(); 2310 if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension); 2311 2312 assert(_total_instanceKlass_count >= 1, "Sanity check"); 2313 Atomic::dec(&_total_instanceKlass_count); 2314 } 2315 2316 void InstanceKlass::set_source_debug_extension(char* array, int length) { 2317 if (array == NULL) { 2318 _source_debug_extension = NULL; 2319 } else { 2320 // Adding one to the attribute length in order to store a null terminator 2321 // character could cause an overflow because the attribute length is 2322 // already coded with an u4 in the classfile, but in practice, it's 2323 // unlikely to happen. 2324 assert((length+1) > length, "Overflow checking"); 2325 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass); 2326 for (int i = 0; i < length; i++) { 2327 sde[i] = array[i]; 2328 } 2329 sde[length] = '\0'; 2330 _source_debug_extension = sde; 2331 } 2332 } 2333 2334 address InstanceKlass::static_field_addr(int offset) { 2335 return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror())); 2336 } 2337 2338 2339 const char* InstanceKlass::signature_name() const { 2340 int hash_len = 0; 2341 char hash_buf[40]; 2342 2343 // If this is an anonymous class, append a hash to make the name unique 2344 if (is_anonymous()) { 2345 intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0; 2346 jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash); 2347 hash_len = (int)strlen(hash_buf); 2348 } 2349 2350 // Get the internal name as a c string 2351 const char* src = (const char*) (name()->as_C_string()); 2352 const int src_length = (int)strlen(src); 2353 2354 char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3); 2355 2356 // Add L as type indicator 2357 int dest_index = 0; 2358 dest[dest_index++] = 'L'; 2359 2360 // Add the actual class name 2361 for (int src_index = 0; src_index < src_length; ) { 2362 dest[dest_index++] = src[src_index++]; 2363 } 2364 2365 // If we have a hash, append it 2366 for (int hash_index = 0; hash_index < hash_len; ) { 2367 dest[dest_index++] = hash_buf[hash_index++]; 2368 } 2369 2370 // Add the semicolon and the NULL 2371 dest[dest_index++] = ';'; 2372 dest[dest_index] = '\0'; 2373 return dest; 2374 } 2375 2376 // different verisons of is_same_class_package 2377 bool InstanceKlass::is_same_class_package(Klass* class2) { 2378 if (class2->is_objArray_klass()) { 2379 class2 = ObjArrayKlass::cast(class2)->bottom_klass(); 2380 } 2381 oop classloader2 = class2->class_loader(); 2382 Symbol* classname2 = class2->name(); 2383 2384 return InstanceKlass::is_same_class_package(class_loader(), name(), 2385 classloader2, classname2); 2386 } 2387 2388 bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) { 2389 return InstanceKlass::is_same_class_package(class_loader(), name(), 2390 classloader2, classname2); 2391 } 2392 2393 // return true if two classes are in the same package, classloader 2394 // and classname information is enough to determine a class's package 2395 bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1, 2396 oop class_loader2, Symbol* class_name2) { 2397 if (class_loader1 != class_loader2) { 2398 return false; 2399 } else if (class_name1 == class_name2) { 2400 return true; // skip painful bytewise comparison 2401 } else { 2402 ResourceMark rm; 2403 2404 // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly 2405 // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding. 2406 // Otherwise, we just compare jbyte values between the strings. 2407 const jbyte *name1 = class_name1->base(); 2408 const jbyte *name2 = class_name2->base(); 2409 2410 const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/'); 2411 const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/'); 2412 2413 if ((last_slash1 == NULL) || (last_slash2 == NULL)) { 2414 // One of the two doesn't have a package. Only return true 2415 // if the other one also doesn't have a package. 2416 return last_slash1 == last_slash2; 2417 } else { 2418 // Skip over '['s 2419 if (*name1 == '[') { 2420 do { 2421 name1++; 2422 } while (*name1 == '['); 2423 if (*name1 != 'L') { 2424 // Something is terribly wrong. Shouldn't be here. 2425 return false; 2426 } 2427 } 2428 if (*name2 == '[') { 2429 do { 2430 name2++; 2431 } while (*name2 == '['); 2432 if (*name2 != 'L') { 2433 // Something is terribly wrong. Shouldn't be here. 2434 return false; 2435 } 2436 } 2437 2438 // Check that package part is identical 2439 int length1 = last_slash1 - name1; 2440 int length2 = last_slash2 - name2; 2441 2442 return UTF8::equal(name1, length1, name2, length2); 2443 } 2444 } 2445 } 2446 2447 // Returns true iff super_method can be overridden by a method in targetclassname 2448 // See JSL 3rd edition 8.4.6.1 2449 // Assumes name-signature match 2450 // "this" is InstanceKlass of super_method which must exist 2451 // note that the InstanceKlass of the method in the targetclassname has not always been created yet 2452 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) { 2453 // Private methods can not be overridden 2454 if (super_method->is_private()) { 2455 return false; 2456 } 2457 // If super method is accessible, then override 2458 if ((super_method->is_protected()) || 2459 (super_method->is_public())) { 2460 return true; 2461 } 2462 // Package-private methods are not inherited outside of package 2463 assert(super_method->is_package_private(), "must be package private"); 2464 return(is_same_class_package(targetclassloader(), targetclassname)); 2465 } 2466 2467 /* defined for now in jvm.cpp, for historical reasons *-- 2468 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self, 2469 Symbol*& simple_name_result, TRAPS) { 2470 ... 2471 } 2472 */ 2473 2474 // tell if two classes have the same enclosing class (at package level) 2475 bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1, 2476 Klass* class2_oop, TRAPS) { 2477 if (class2_oop == class1()) return true; 2478 if (!class2_oop->is_instance_klass()) return false; 2479 instanceKlassHandle class2(THREAD, class2_oop); 2480 2481 // must be in same package before we try anything else 2482 if (!class1->is_same_class_package(class2->class_loader(), class2->name())) 2483 return false; 2484 2485 // As long as there is an outer1.getEnclosingClass, 2486 // shift the search outward. 2487 instanceKlassHandle outer1 = class1; 2488 for (;;) { 2489 // As we walk along, look for equalities between outer1 and class2. 2490 // Eventually, the walks will terminate as outer1 stops 2491 // at the top-level class around the original class. 2492 bool ignore_inner_is_member; 2493 Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member, 2494 CHECK_false); 2495 if (next == NULL) break; 2496 if (next == class2()) return true; 2497 outer1 = instanceKlassHandle(THREAD, next); 2498 } 2499 2500 // Now do the same for class2. 2501 instanceKlassHandle outer2 = class2; 2502 for (;;) { 2503 bool ignore_inner_is_member; 2504 Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member, 2505 CHECK_false); 2506 if (next == NULL) break; 2507 // Might as well check the new outer against all available values. 2508 if (next == class1()) return true; 2509 if (next == outer1()) return true; 2510 outer2 = instanceKlassHandle(THREAD, next); 2511 } 2512 2513 // If by this point we have not found an equality between the 2514 // two classes, we know they are in separate package members. 2515 return false; 2516 } 2517 2518 bool InstanceKlass::find_inner_classes_attr(instanceKlassHandle k, int* ooff, int* noff, TRAPS) { 2519 constantPoolHandle i_cp(THREAD, k->constants()); 2520 for (InnerClassesIterator iter(k); !iter.done(); iter.next()) { 2521 int ioff = iter.inner_class_info_index(); 2522 if (ioff != 0) { 2523 // Check to see if the name matches the class we're looking for 2524 // before attempting to find the class. 2525 if (i_cp->klass_name_at_matches(k, ioff)) { 2526 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false); 2527 if (k() == inner_klass) { 2528 *ooff = iter.outer_class_info_index(); 2529 *noff = iter.inner_name_index(); 2530 return true; 2531 } 2532 } 2533 } 2534 } 2535 return false; 2536 } 2537 2538 Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle k, bool* inner_is_member, TRAPS) { 2539 instanceKlassHandle outer_klass; 2540 *inner_is_member = false; 2541 int ooff = 0, noff = 0; 2542 if (find_inner_classes_attr(k, &ooff, &noff, THREAD)) { 2543 constantPoolHandle i_cp(THREAD, k->constants()); 2544 if (ooff != 0) { 2545 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL); 2546 outer_klass = instanceKlassHandle(THREAD, ok); 2547 *inner_is_member = true; 2548 } 2549 if (outer_klass.is_null()) { 2550 // It may be anonymous; try for that. 2551 int encl_method_class_idx = k->enclosing_method_class_index(); 2552 if (encl_method_class_idx != 0) { 2553 Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL); 2554 outer_klass = instanceKlassHandle(THREAD, ok); 2555 *inner_is_member = false; 2556 } 2557 } 2558 } 2559 2560 // If no inner class attribute found for this class. 2561 if (outer_klass.is_null()) return NULL; 2562 2563 // Throws an exception if outer klass has not declared k as an inner klass 2564 // We need evidence that each klass knows about the other, or else 2565 // the system could allow a spoof of an inner class to gain access rights. 2566 Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL); 2567 return outer_klass(); 2568 } 2569 2570 jint InstanceKlass::compute_modifier_flags(TRAPS) const { 2571 jint access = access_flags().as_int(); 2572 2573 // But check if it happens to be member class. 2574 instanceKlassHandle ik(THREAD, this); 2575 InnerClassesIterator iter(ik); 2576 for (; !iter.done(); iter.next()) { 2577 int ioff = iter.inner_class_info_index(); 2578 // Inner class attribute can be zero, skip it. 2579 // Strange but true: JVM spec. allows null inner class refs. 2580 if (ioff == 0) continue; 2581 2582 // only look at classes that are already loaded 2583 // since we are looking for the flags for our self. 2584 Symbol* inner_name = ik->constants()->klass_name_at(ioff); 2585 if ((ik->name() == inner_name)) { 2586 // This is really a member class. 2587 access = iter.inner_access_flags(); 2588 break; 2589 } 2590 } 2591 // Remember to strip ACC_SUPER bit 2592 return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS; 2593 } 2594 2595 jint InstanceKlass::jvmti_class_status() const { 2596 jint result = 0; 2597 2598 if (is_linked()) { 2599 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED; 2600 } 2601 2602 if (is_initialized()) { 2603 assert(is_linked(), "Class status is not consistent"); 2604 result |= JVMTI_CLASS_STATUS_INITIALIZED; 2605 } 2606 if (is_in_error_state()) { 2607 result |= JVMTI_CLASS_STATUS_ERROR; 2608 } 2609 return result; 2610 } 2611 2612 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) { 2613 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable(); 2614 int method_table_offset_in_words = ioe->offset()/wordSize; 2615 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words()) 2616 / itableOffsetEntry::size(); 2617 2618 for (int cnt = 0 ; ; cnt ++, ioe ++) { 2619 // If the interface isn't implemented by the receiver class, 2620 // the VM should throw IncompatibleClassChangeError. 2621 if (cnt >= nof_interfaces) { 2622 THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError()); 2623 } 2624 2625 Klass* ik = ioe->interface_klass(); 2626 if (ik == holder) break; 2627 } 2628 2629 itableMethodEntry* ime = ioe->first_method_entry(this); 2630 Method* m = ime[index].method(); 2631 if (m == NULL) { 2632 THROW_NULL(vmSymbols::java_lang_AbstractMethodError()); 2633 } 2634 return m; 2635 } 2636 2637 2638 #if INCLUDE_JVMTI 2639 // update default_methods for redefineclasses for methods that are 2640 // not yet in the vtable due to concurrent subclass define and superinterface 2641 // redefinition 2642 // Note: those in the vtable, should have been updated via adjust_method_entries 2643 void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) { 2644 // search the default_methods for uses of either obsolete or EMCP methods 2645 if (default_methods() != NULL) { 2646 for (int index = 0; index < default_methods()->length(); index ++) { 2647 Method* old_method = default_methods()->at(index); 2648 if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) { 2649 continue; // skip uninteresting entries 2650 } 2651 assert(!old_method->is_deleted(), "default methods may not be deleted"); 2652 2653 Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum()); 2654 2655 assert(new_method != NULL, "method_with_idnum() should not be NULL"); 2656 assert(old_method != new_method, "sanity check"); 2657 2658 default_methods()->at_put(index, new_method); 2659 if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) { 2660 if (!(*trace_name_printed)) { 2661 // RC_TRACE_MESG macro has an embedded ResourceMark 2662 RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s", 2663 external_name(), 2664 old_method->method_holder()->external_name())); 2665 *trace_name_printed = true; 2666 } 2667 RC_TRACE(0x00100000, ("default method update: %s(%s) ", 2668 new_method->name()->as_C_string(), 2669 new_method->signature()->as_C_string())); 2670 } 2671 } 2672 } 2673 } 2674 #endif // INCLUDE_JVMTI 2675 2676 // On-stack replacement stuff 2677 void InstanceKlass::add_osr_nmethod(nmethod* n) { 2678 // only one compilation can be active 2679 { 2680 // This is a short non-blocking critical region, so the no safepoint check is ok. 2681 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 2682 assert(n->is_osr_method(), "wrong kind of nmethod"); 2683 n->set_osr_link(osr_nmethods_head()); 2684 set_osr_nmethods_head(n); 2685 // Raise the highest osr level if necessary 2686 if (TieredCompilation) { 2687 Method* m = n->method(); 2688 m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level())); 2689 } 2690 } 2691 2692 // Get rid of the osr methods for the same bci that have lower levels. 2693 if (TieredCompilation) { 2694 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) { 2695 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true); 2696 if (inv != NULL && inv->is_in_use()) { 2697 inv->make_not_entrant(); 2698 } 2699 } 2700 } 2701 } 2702 2703 2704 void InstanceKlass::remove_osr_nmethod(nmethod* n) { 2705 // This is a short non-blocking critical region, so the no safepoint check is ok. 2706 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 2707 assert(n->is_osr_method(), "wrong kind of nmethod"); 2708 nmethod* last = NULL; 2709 nmethod* cur = osr_nmethods_head(); 2710 int max_level = CompLevel_none; // Find the max comp level excluding n 2711 Method* m = n->method(); 2712 // Search for match 2713 while(cur != NULL && cur != n) { 2714 if (TieredCompilation && m == cur->method()) { 2715 // Find max level before n 2716 max_level = MAX2(max_level, cur->comp_level()); 2717 } 2718 last = cur; 2719 cur = cur->osr_link(); 2720 } 2721 nmethod* next = NULL; 2722 if (cur == n) { 2723 next = cur->osr_link(); 2724 if (last == NULL) { 2725 // Remove first element 2726 set_osr_nmethods_head(next); 2727 } else { 2728 last->set_osr_link(next); 2729 } 2730 } 2731 n->set_osr_link(NULL); 2732 if (TieredCompilation) { 2733 cur = next; 2734 while (cur != NULL) { 2735 // Find max level after n 2736 if (m == cur->method()) { 2737 max_level = MAX2(max_level, cur->comp_level()); 2738 } 2739 cur = cur->osr_link(); 2740 } 2741 m->set_highest_osr_comp_level(max_level); 2742 } 2743 } 2744 2745 int InstanceKlass::mark_osr_nmethods(const Method* m) { 2746 // This is a short non-blocking critical region, so the no safepoint check is ok. 2747 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 2748 nmethod* osr = osr_nmethods_head(); 2749 int found = 0; 2750 while (osr != NULL) { 2751 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 2752 if (osr->method() == m) { 2753 osr->mark_for_deoptimization(); 2754 found++; 2755 } 2756 osr = osr->osr_link(); 2757 } 2758 return found; 2759 } 2760 2761 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const { 2762 // This is a short non-blocking critical region, so the no safepoint check is ok. 2763 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 2764 nmethod* osr = osr_nmethods_head(); 2765 nmethod* best = NULL; 2766 while (osr != NULL) { 2767 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 2768 // There can be a time when a c1 osr method exists but we are waiting 2769 // for a c2 version. When c2 completes its osr nmethod we will trash 2770 // the c1 version and only be able to find the c2 version. However 2771 // while we overflow in the c1 code at back branches we don't want to 2772 // try and switch to the same code as we are already running 2773 2774 if (osr->method() == m && 2775 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) { 2776 if (match_level) { 2777 if (osr->comp_level() == comp_level) { 2778 // Found a match - return it. 2779 return osr; 2780 } 2781 } else { 2782 if (best == NULL || (osr->comp_level() > best->comp_level())) { 2783 if (osr->comp_level() == CompLevel_highest_tier) { 2784 // Found the best possible - return it. 2785 return osr; 2786 } 2787 best = osr; 2788 } 2789 } 2790 } 2791 osr = osr->osr_link(); 2792 } 2793 if (best != NULL && best->comp_level() >= comp_level && match_level == false) { 2794 return best; 2795 } 2796 return NULL; 2797 } 2798 2799 bool InstanceKlass::add_member_name(Handle mem_name) { 2800 jweak mem_name_wref = JNIHandles::make_weak_global(mem_name); 2801 MutexLocker ml(MemberNameTable_lock); 2802 DEBUG_ONLY(No_Safepoint_Verifier nsv); 2803 2804 // Check if method has been redefined while taking out MemberNameTable_lock, if so 2805 // return false. We cannot cache obsolete methods. They will crash when the function 2806 // is called! 2807 Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name()); 2808 if (method->is_obsolete()) { 2809 return false; 2810 } else if (method->is_old()) { 2811 // Replace method with redefined version 2812 java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum())); 2813 } 2814 2815 if (_member_names == NULL) { 2816 _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count()); 2817 } 2818 _member_names->add_member_name(mem_name_wref); 2819 return true; 2820 } 2821 2822 // ----------------------------------------------------------------------------------------------------- 2823 // Printing 2824 2825 #ifndef PRODUCT 2826 2827 #define BULLET " - " 2828 2829 static const char* state_names[] = { 2830 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error" 2831 }; 2832 2833 static void print_vtable(intptr_t* start, int len, outputStream* st) { 2834 for (int i = 0; i < len; i++) { 2835 intptr_t e = start[i]; 2836 st->print("%d : " INTPTR_FORMAT, i, e); 2837 if (e != 0 && ((Metadata*)e)->is_metaspace_object()) { 2838 st->print(" "); 2839 ((Metadata*)e)->print_value_on(st); 2840 } 2841 st->cr(); 2842 } 2843 } 2844 2845 void InstanceKlass::print_on(outputStream* st) const { 2846 assert(is_klass(), "must be klass"); 2847 Klass::print_on(st); 2848 2849 st->print(BULLET"instance size: %d", size_helper()); st->cr(); 2850 st->print(BULLET"klass size: %d", size()); st->cr(); 2851 st->print(BULLET"access: "); access_flags().print_on(st); st->cr(); 2852 st->print(BULLET"state: "); st->print_cr("%s", state_names[_init_state]); 2853 st->print(BULLET"name: "); name()->print_value_on(st); st->cr(); 2854 st->print(BULLET"super: "); super()->print_value_on_maybe_null(st); st->cr(); 2855 st->print(BULLET"sub: "); 2856 Klass* sub = subklass(); 2857 int n; 2858 for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) { 2859 if (n < MaxSubklassPrintSize) { 2860 sub->print_value_on(st); 2861 st->print(" "); 2862 } 2863 } 2864 if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize); 2865 st->cr(); 2866 2867 if (is_interface()) { 2868 st->print_cr(BULLET"nof implementors: %d", nof_implementors()); 2869 if (nof_implementors() == 1) { 2870 st->print_cr(BULLET"implementor: "); 2871 st->print(" "); 2872 implementor()->print_value_on(st); 2873 st->cr(); 2874 } 2875 } 2876 2877 st->print(BULLET"arrays: "); array_klasses()->print_value_on_maybe_null(st); st->cr(); 2878 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr(); 2879 if (Verbose || WizardMode) { 2880 Array<Method*>* method_array = methods(); 2881 for (int i = 0; i < method_array->length(); i++) { 2882 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr(); 2883 } 2884 } 2885 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr(); 2886 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr(); 2887 if (Verbose && default_methods() != NULL) { 2888 Array<Method*>* method_array = default_methods(); 2889 for (int i = 0; i < method_array->length(); i++) { 2890 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr(); 2891 } 2892 } 2893 if (default_vtable_indices() != NULL) { 2894 st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr(); 2895 } 2896 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr(); 2897 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr(); 2898 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr(); 2899 if (class_loader_data() != NULL) { 2900 st->print(BULLET"class loader data: "); 2901 class_loader_data()->print_value_on(st); 2902 st->cr(); 2903 } 2904 st->print(BULLET"host class: "); host_klass()->print_value_on_maybe_null(st); st->cr(); 2905 if (source_file_name() != NULL) { 2906 st->print(BULLET"source file: "); 2907 source_file_name()->print_value_on(st); 2908 st->cr(); 2909 } 2910 if (source_debug_extension() != NULL) { 2911 st->print(BULLET"source debug extension: "); 2912 st->print("%s", source_debug_extension()); 2913 st->cr(); 2914 } 2915 st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr(); 2916 st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr(); 2917 st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr(); 2918 st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr(); 2919 { 2920 bool have_pv = false; 2921 // previous versions are linked together through the InstanceKlass 2922 for (InstanceKlass* pv_node = _previous_versions; 2923 pv_node != NULL; 2924 pv_node = pv_node->previous_versions()) { 2925 if (!have_pv) 2926 st->print(BULLET"previous version: "); 2927 have_pv = true; 2928 pv_node->constants()->print_value_on(st); 2929 } 2930 if (have_pv) st->cr(); 2931 } 2932 2933 if (generic_signature() != NULL) { 2934 st->print(BULLET"generic signature: "); 2935 generic_signature()->print_value_on(st); 2936 st->cr(); 2937 } 2938 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr(); 2939 st->print(BULLET"java mirror: "); java_mirror()->print_value_on(st); st->cr(); 2940 st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr(); 2941 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st); 2942 st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr(); 2943 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st); 2944 st->print_cr(BULLET"---- static fields (%d words):", static_field_size()); 2945 FieldPrinter print_static_field(st); 2946 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field); 2947 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size()); 2948 FieldPrinter print_nonstatic_field(st); 2949 InstanceKlass* ik = const_cast<InstanceKlass*>(this); 2950 ik->do_nonstatic_fields(&print_nonstatic_field); 2951 2952 st->print(BULLET"non-static oop maps: "); 2953 OopMapBlock* map = start_of_nonstatic_oop_maps(); 2954 OopMapBlock* end_map = map + nonstatic_oop_map_count(); 2955 while (map < end_map) { 2956 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1)); 2957 map++; 2958 } 2959 st->cr(); 2960 } 2961 2962 #endif //PRODUCT 2963 2964 void InstanceKlass::print_value_on(outputStream* st) const { 2965 assert(is_klass(), "must be klass"); 2966 if (Verbose || WizardMode) access_flags().print_on(st); 2967 name()->print_value_on(st); 2968 } 2969 2970 #ifndef PRODUCT 2971 2972 void FieldPrinter::do_field(fieldDescriptor* fd) { 2973 _st->print(BULLET); 2974 if (_obj == NULL) { 2975 fd->print_on(_st); 2976 _st->cr(); 2977 } else { 2978 fd->print_on_for(_st, _obj); 2979 _st->cr(); 2980 } 2981 } 2982 2983 2984 void InstanceKlass::oop_print_on(oop obj, outputStream* st) { 2985 Klass::oop_print_on(obj, st); 2986 2987 if (this == SystemDictionary::String_klass()) { 2988 typeArrayOop value = java_lang_String::value(obj); 2989 juint length = java_lang_String::length(obj); 2990 if (value != NULL && 2991 value->is_typeArray() && 2992 length <= (juint) value->length()) { 2993 st->print(BULLET"string: "); 2994 java_lang_String::print(obj, st); 2995 st->cr(); 2996 if (!WizardMode) return; // that is enough 2997 } 2998 } 2999 3000 st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj)); 3001 FieldPrinter print_field(st, obj); 3002 do_nonstatic_fields(&print_field); 3003 3004 if (this == SystemDictionary::Class_klass()) { 3005 st->print(BULLET"signature: "); 3006 java_lang_Class::print_signature(obj, st); 3007 st->cr(); 3008 Klass* mirrored_klass = java_lang_Class::as_Klass(obj); 3009 st->print(BULLET"fake entry for mirror: "); 3010 mirrored_klass->print_value_on_maybe_null(st); 3011 st->cr(); 3012 Klass* array_klass = java_lang_Class::array_klass(obj); 3013 st->print(BULLET"fake entry for array: "); 3014 array_klass->print_value_on_maybe_null(st); 3015 st->cr(); 3016 st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj)); 3017 st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj)); 3018 Klass* real_klass = java_lang_Class::as_Klass(obj); 3019 if (real_klass != NULL && real_klass->is_instance_klass()) { 3020 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field); 3021 } 3022 } else if (this == SystemDictionary::MethodType_klass()) { 3023 st->print(BULLET"signature: "); 3024 java_lang_invoke_MethodType::print_signature(obj, st); 3025 st->cr(); 3026 } 3027 } 3028 3029 #endif //PRODUCT 3030 3031 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) { 3032 st->print("a "); 3033 name()->print_value_on(st); 3034 obj->print_address_on(st); 3035 if (this == SystemDictionary::String_klass() 3036 && java_lang_String::value(obj) != NULL) { 3037 ResourceMark rm; 3038 int len = java_lang_String::length(obj); 3039 int plen = (len < 24 ? len : 12); 3040 char* str = java_lang_String::as_utf8_string(obj, 0, plen); 3041 st->print(" = \"%s\"", str); 3042 if (len > plen) 3043 st->print("...[%d]", len); 3044 } else if (this == SystemDictionary::Class_klass()) { 3045 Klass* k = java_lang_Class::as_Klass(obj); 3046 st->print(" = "); 3047 if (k != NULL) { 3048 k->print_value_on(st); 3049 } else { 3050 const char* tname = type2name(java_lang_Class::primitive_type(obj)); 3051 st->print("%s", tname ? tname : "type?"); 3052 } 3053 } else if (this == SystemDictionary::MethodType_klass()) { 3054 st->print(" = "); 3055 java_lang_invoke_MethodType::print_signature(obj, st); 3056 } else if (java_lang_boxing_object::is_instance(obj)) { 3057 st->print(" = "); 3058 java_lang_boxing_object::print(obj, st); 3059 } else if (this == SystemDictionary::LambdaForm_klass()) { 3060 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj); 3061 if (vmentry != NULL) { 3062 st->print(" => "); 3063 vmentry->print_value_on(st); 3064 } 3065 } else if (this == SystemDictionary::MemberName_klass()) { 3066 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj); 3067 if (vmtarget != NULL) { 3068 st->print(" = "); 3069 vmtarget->print_value_on(st); 3070 } else { 3071 java_lang_invoke_MemberName::clazz(obj)->print_value_on(st); 3072 st->print("."); 3073 java_lang_invoke_MemberName::name(obj)->print_value_on(st); 3074 } 3075 } 3076 } 3077 3078 const char* InstanceKlass::internal_name() const { 3079 return external_name(); 3080 } 3081 3082 #if INCLUDE_SERVICES 3083 // Size Statistics 3084 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const { 3085 Klass::collect_statistics(sz); 3086 3087 sz->_inst_size = HeapWordSize * size_helper(); 3088 sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length()); 3089 sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length()); 3090 sz->_nonstatic_oopmap_bytes = HeapWordSize * 3091 ((is_interface() || is_anonymous()) ? 3092 align_object_offset(nonstatic_oop_map_size()) : 3093 nonstatic_oop_map_size()); 3094 3095 int n = 0; 3096 n += (sz->_methods_array_bytes = sz->count_array(methods())); 3097 n += (sz->_method_ordering_bytes = sz->count_array(method_ordering())); 3098 n += (sz->_local_interfaces_bytes = sz->count_array(local_interfaces())); 3099 n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces())); 3100 n += (sz->_fields_bytes = sz->count_array(fields())); 3101 n += (sz->_inner_classes_bytes = sz->count_array(inner_classes())); 3102 sz->_ro_bytes += n; 3103 3104 const ConstantPool* cp = constants(); 3105 if (cp) { 3106 cp->collect_statistics(sz); 3107 } 3108 3109 const Annotations* anno = annotations(); 3110 if (anno) { 3111 anno->collect_statistics(sz); 3112 } 3113 3114 const Array<Method*>* methods_array = methods(); 3115 if (methods()) { 3116 for (int i = 0; i < methods_array->length(); i++) { 3117 Method* method = methods_array->at(i); 3118 if (method) { 3119 sz->_method_count ++; 3120 method->collect_statistics(sz); 3121 } 3122 } 3123 } 3124 } 3125 #endif // INCLUDE_SERVICES 3126 3127 // Verification 3128 3129 class VerifyFieldClosure: public OopClosure { 3130 protected: 3131 template <class T> void do_oop_work(T* p) { 3132 oop obj = oopDesc::load_decode_heap_oop(p); 3133 if (!obj->is_oop_or_null()) { 3134 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj)); 3135 Universe::print(); 3136 guarantee(false, "boom"); 3137 } 3138 } 3139 public: 3140 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); } 3141 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); } 3142 }; 3143 3144 void InstanceKlass::verify_on(outputStream* st) { 3145 #ifndef PRODUCT 3146 // Avoid redundant verifies, this really should be in product. 3147 if (_verify_count == Universe::verify_count()) return; 3148 _verify_count = Universe::verify_count(); 3149 #endif 3150 3151 // Verify Klass 3152 Klass::verify_on(st); 3153 3154 // Verify that klass is present in ClassLoaderData 3155 guarantee(class_loader_data()->contains_klass(this), 3156 "this class isn't found in class loader data"); 3157 3158 // Verify vtables 3159 if (is_linked()) { 3160 ResourceMark rm; 3161 // $$$ This used to be done only for m/s collections. Doing it 3162 // always seemed a valid generalization. (DLD -- 6/00) 3163 vtable()->verify(st); 3164 } 3165 3166 // Verify first subklass 3167 if (subklass() != NULL) { 3168 guarantee(subklass()->is_klass(), "should be klass"); 3169 } 3170 3171 // Verify siblings 3172 Klass* super = this->super(); 3173 Klass* sib = next_sibling(); 3174 if (sib != NULL) { 3175 if (sib == this) { 3176 fatal("subclass points to itself " PTR_FORMAT, p2i(sib)); 3177 } 3178 3179 guarantee(sib->is_klass(), "should be klass"); 3180 guarantee(sib->super() == super, "siblings should have same superklass"); 3181 } 3182 3183 // Verify implementor fields 3184 Klass* im = implementor(); 3185 if (im != NULL) { 3186 guarantee(is_interface(), "only interfaces should have implementor set"); 3187 guarantee(im->is_klass(), "should be klass"); 3188 guarantee(!im->is_interface() || im == this, 3189 "implementors cannot be interfaces"); 3190 } 3191 3192 // Verify local interfaces 3193 if (local_interfaces()) { 3194 Array<Klass*>* local_interfaces = this->local_interfaces(); 3195 for (int j = 0; j < local_interfaces->length(); j++) { 3196 Klass* e = local_interfaces->at(j); 3197 guarantee(e->is_klass() && e->is_interface(), "invalid local interface"); 3198 } 3199 } 3200 3201 // Verify transitive interfaces 3202 if (transitive_interfaces() != NULL) { 3203 Array<Klass*>* transitive_interfaces = this->transitive_interfaces(); 3204 for (int j = 0; j < transitive_interfaces->length(); j++) { 3205 Klass* e = transitive_interfaces->at(j); 3206 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface"); 3207 } 3208 } 3209 3210 // Verify methods 3211 if (methods() != NULL) { 3212 Array<Method*>* methods = this->methods(); 3213 for (int j = 0; j < methods->length(); j++) { 3214 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 3215 } 3216 for (int j = 0; j < methods->length() - 1; j++) { 3217 Method* m1 = methods->at(j); 3218 Method* m2 = methods->at(j + 1); 3219 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 3220 } 3221 } 3222 3223 // Verify method ordering 3224 if (method_ordering() != NULL) { 3225 Array<int>* method_ordering = this->method_ordering(); 3226 int length = method_ordering->length(); 3227 if (JvmtiExport::can_maintain_original_method_order() || 3228 ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) { 3229 guarantee(length == methods()->length(), "invalid method ordering length"); 3230 jlong sum = 0; 3231 for (int j = 0; j < length; j++) { 3232 int original_index = method_ordering->at(j); 3233 guarantee(original_index >= 0, "invalid method ordering index"); 3234 guarantee(original_index < length, "invalid method ordering index"); 3235 sum += original_index; 3236 } 3237 // Verify sum of indices 0,1,...,length-1 3238 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum"); 3239 } else { 3240 guarantee(length == 0, "invalid method ordering length"); 3241 } 3242 } 3243 3244 // Verify default methods 3245 if (default_methods() != NULL) { 3246 Array<Method*>* methods = this->default_methods(); 3247 for (int j = 0; j < methods->length(); j++) { 3248 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 3249 } 3250 for (int j = 0; j < methods->length() - 1; j++) { 3251 Method* m1 = methods->at(j); 3252 Method* m2 = methods->at(j + 1); 3253 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 3254 } 3255 } 3256 3257 // Verify JNI static field identifiers 3258 if (jni_ids() != NULL) { 3259 jni_ids()->verify(this); 3260 } 3261 3262 // Verify other fields 3263 if (array_klasses() != NULL) { 3264 guarantee(array_klasses()->is_klass(), "should be klass"); 3265 } 3266 if (constants() != NULL) { 3267 guarantee(constants()->is_constantPool(), "should be constant pool"); 3268 } 3269 const Klass* host = host_klass(); 3270 if (host != NULL) { 3271 guarantee(host->is_klass(), "should be klass"); 3272 } 3273 } 3274 3275 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) { 3276 Klass::oop_verify_on(obj, st); 3277 VerifyFieldClosure blk; 3278 obj->oop_iterate_no_header(&blk); 3279 } 3280 3281 3282 // JNIid class for jfieldIDs only 3283 // Note to reviewers: 3284 // These JNI functions are just moved over to column 1 and not changed 3285 // in the compressed oops workspace. 3286 JNIid::JNIid(Klass* holder, int offset, JNIid* next) { 3287 _holder = holder; 3288 _offset = offset; 3289 _next = next; 3290 debug_only(_is_static_field_id = false;) 3291 } 3292 3293 3294 JNIid* JNIid::find(int offset) { 3295 JNIid* current = this; 3296 while (current != NULL) { 3297 if (current->offset() == offset) return current; 3298 current = current->next(); 3299 } 3300 return NULL; 3301 } 3302 3303 void JNIid::deallocate(JNIid* current) { 3304 while (current != NULL) { 3305 JNIid* next = current->next(); 3306 delete current; 3307 current = next; 3308 } 3309 } 3310 3311 3312 void JNIid::verify(Klass* holder) { 3313 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields(); 3314 int end_field_offset; 3315 end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize); 3316 3317 JNIid* current = this; 3318 while (current != NULL) { 3319 guarantee(current->holder() == holder, "Invalid klass in JNIid"); 3320 #ifdef ASSERT 3321 int o = current->offset(); 3322 if (current->is_static_field_id()) { 3323 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid"); 3324 } 3325 #endif 3326 current = current->next(); 3327 } 3328 } 3329 3330 3331 #ifdef ASSERT 3332 void InstanceKlass::set_init_state(ClassState state) { 3333 bool good_state = is_shared() ? (_init_state <= state) 3334 : (_init_state < state); 3335 assert(good_state || state == allocated, "illegal state transition"); 3336 _init_state = (u1)state; 3337 } 3338 #endif 3339 3340 3341 3342 // RedefineClasses() support for previous versions: 3343 int InstanceKlass::_previous_version_count = 0; 3344 3345 // Purge previous versions before adding new previous versions of the class. 3346 void InstanceKlass::purge_previous_versions(InstanceKlass* ik) { 3347 if (ik->previous_versions() != NULL) { 3348 // This klass has previous versions so see what we can cleanup 3349 // while it is safe to do so. 3350 3351 int deleted_count = 0; // leave debugging breadcrumbs 3352 int live_count = 0; 3353 ClassLoaderData* loader_data = ik->class_loader_data(); 3354 assert(loader_data != NULL, "should never be null"); 3355 3356 // RC_TRACE macro has an embedded ResourceMark 3357 RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name())); 3358 3359 // previous versions are linked together through the InstanceKlass 3360 InstanceKlass* pv_node = ik->previous_versions(); 3361 InstanceKlass* last = ik; 3362 int version = 0; 3363 3364 // check the previous versions list 3365 for (; pv_node != NULL; ) { 3366 3367 ConstantPool* pvcp = pv_node->constants(); 3368 assert(pvcp != NULL, "cp ref was unexpectedly cleared"); 3369 3370 if (!pvcp->on_stack()) { 3371 // If the constant pool isn't on stack, none of the methods 3372 // are executing. Unlink this previous_version. 3373 // The previous version InstanceKlass is on the ClassLoaderData deallocate list 3374 // so will be deallocated during the next phase of class unloading. 3375 RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is dead", 3376 p2i(pv_node))); 3377 // For debugging purposes. 3378 pv_node->set_is_scratch_class(); 3379 pv_node->class_loader_data()->add_to_deallocate_list(pv_node); 3380 pv_node = pv_node->previous_versions(); 3381 last->link_previous_versions(pv_node); 3382 deleted_count++; 3383 version++; 3384 continue; 3385 } else { 3386 RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive", 3387 p2i(pv_node))); 3388 assert(pvcp->pool_holder() != NULL, "Constant pool with no holder"); 3389 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack"); 3390 live_count++; 3391 } 3392 3393 // At least one method is live in this previous version. 3394 // Reset dead EMCP methods not to get breakpoints. 3395 // All methods are deallocated when all of the methods for this class are no 3396 // longer running. 3397 Array<Method*>* method_refs = pv_node->methods(); 3398 if (method_refs != NULL) { 3399 RC_TRACE(0x00000200, ("purge: previous methods length=%d", 3400 method_refs->length())); 3401 for (int j = 0; j < method_refs->length(); j++) { 3402 Method* method = method_refs->at(j); 3403 3404 if (!method->on_stack()) { 3405 // no breakpoints for non-running methods 3406 if (method->is_running_emcp()) { 3407 method->set_running_emcp(false); 3408 } 3409 } else { 3410 assert (method->is_obsolete() || method->is_running_emcp(), 3411 "emcp method cannot run after emcp bit is cleared"); 3412 // RC_TRACE macro has an embedded ResourceMark 3413 RC_TRACE(0x00000200, 3414 ("purge: %s(%s): prev method @%d in version @%d is alive", 3415 method->name()->as_C_string(), 3416 method->signature()->as_C_string(), j, version)); 3417 } 3418 } 3419 } 3420 // next previous version 3421 last = pv_node; 3422 pv_node = pv_node->previous_versions(); 3423 version++; 3424 } 3425 RC_TRACE(0x00000200, 3426 ("purge: previous version stats: live=%d, deleted=%d", live_count, 3427 deleted_count)); 3428 } 3429 } 3430 3431 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods, 3432 int emcp_method_count) { 3433 int obsolete_method_count = old_methods->length() - emcp_method_count; 3434 3435 if (emcp_method_count != 0 && obsolete_method_count != 0 && 3436 _previous_versions != NULL) { 3437 // We have a mix of obsolete and EMCP methods so we have to 3438 // clear out any matching EMCP method entries the hard way. 3439 int local_count = 0; 3440 for (int i = 0; i < old_methods->length(); i++) { 3441 Method* old_method = old_methods->at(i); 3442 if (old_method->is_obsolete()) { 3443 // only obsolete methods are interesting 3444 Symbol* m_name = old_method->name(); 3445 Symbol* m_signature = old_method->signature(); 3446 3447 // previous versions are linked together through the InstanceKlass 3448 int j = 0; 3449 for (InstanceKlass* prev_version = _previous_versions; 3450 prev_version != NULL; 3451 prev_version = prev_version->previous_versions(), j++) { 3452 3453 Array<Method*>* method_refs = prev_version->methods(); 3454 for (int k = 0; k < method_refs->length(); k++) { 3455 Method* method = method_refs->at(k); 3456 3457 if (!method->is_obsolete() && 3458 method->name() == m_name && 3459 method->signature() == m_signature) { 3460 // The current RedefineClasses() call has made all EMCP 3461 // versions of this method obsolete so mark it as obsolete 3462 RC_TRACE(0x00000400, 3463 ("add: %s(%s): flush obsolete method @%d in version @%d", 3464 m_name->as_C_string(), m_signature->as_C_string(), k, j)); 3465 3466 method->set_is_obsolete(); 3467 break; 3468 } 3469 } 3470 3471 // The previous loop may not find a matching EMCP method, but 3472 // that doesn't mean that we can optimize and not go any 3473 // further back in the PreviousVersion generations. The EMCP 3474 // method for this generation could have already been made obsolete, 3475 // but there still may be an older EMCP method that has not 3476 // been made obsolete. 3477 } 3478 3479 if (++local_count >= obsolete_method_count) { 3480 // no more obsolete methods so bail out now 3481 break; 3482 } 3483 } 3484 } 3485 } 3486 } 3487 3488 // Save the scratch_class as the previous version if any of the methods are running. 3489 // The previous_versions are used to set breakpoints in EMCP methods and they are 3490 // also used to clean MethodData links to redefined methods that are no longer running. 3491 void InstanceKlass::add_previous_version(instanceKlassHandle scratch_class, 3492 int emcp_method_count) { 3493 assert(Thread::current()->is_VM_thread(), 3494 "only VMThread can add previous versions"); 3495 3496 // RC_TRACE macro has an embedded ResourceMark 3497 RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d", 3498 scratch_class->external_name(), emcp_method_count)); 3499 3500 // Clean out old previous versions 3501 purge_previous_versions(this); 3502 3503 // Mark newly obsolete methods in remaining previous versions. An EMCP method from 3504 // a previous redefinition may be made obsolete by this redefinition. 3505 Array<Method*>* old_methods = scratch_class->methods(); 3506 mark_newly_obsolete_methods(old_methods, emcp_method_count); 3507 3508 // If the constant pool for this previous version of the class 3509 // is not marked as being on the stack, then none of the methods 3510 // in this previous version of the class are on the stack so 3511 // we don't need to add this as a previous version. 3512 ConstantPool* cp_ref = scratch_class->constants(); 3513 if (!cp_ref->on_stack()) { 3514 RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running")); 3515 // For debugging purposes. 3516 scratch_class->set_is_scratch_class(); 3517 scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class()); 3518 // Update count for class unloading. 3519 _previous_version_count--; 3520 return; 3521 } 3522 3523 if (emcp_method_count != 0) { 3524 // At least one method is still running, check for EMCP methods 3525 for (int i = 0; i < old_methods->length(); i++) { 3526 Method* old_method = old_methods->at(i); 3527 if (!old_method->is_obsolete() && old_method->on_stack()) { 3528 // if EMCP method (not obsolete) is on the stack, mark as EMCP so that 3529 // we can add breakpoints for it. 3530 3531 // We set the method->on_stack bit during safepoints for class redefinition 3532 // and use this bit to set the is_running_emcp bit. 3533 // After the safepoint, the on_stack bit is cleared and the running emcp 3534 // method may exit. If so, we would set a breakpoint in a method that 3535 // is never reached, but this won't be noticeable to the programmer. 3536 old_method->set_running_emcp(true); 3537 RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT, 3538 old_method->name_and_sig_as_C_string(), p2i(old_method))); 3539 } else if (!old_method->is_obsolete()) { 3540 RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT, 3541 old_method->name_and_sig_as_C_string(), p2i(old_method))); 3542 } 3543 } 3544 } 3545 3546 // Add previous version if any methods are still running. 3547 RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack")); 3548 assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version"); 3549 scratch_class->link_previous_versions(previous_versions()); 3550 link_previous_versions(scratch_class()); 3551 // Update count for class unloading. 3552 _previous_version_count++; 3553 } // end add_previous_version() 3554 3555 3556 Method* InstanceKlass::method_with_idnum(int idnum) { 3557 Method* m = NULL; 3558 if (idnum < methods()->length()) { 3559 m = methods()->at(idnum); 3560 } 3561 if (m == NULL || m->method_idnum() != idnum) { 3562 for (int index = 0; index < methods()->length(); ++index) { 3563 m = methods()->at(index); 3564 if (m->method_idnum() == idnum) { 3565 return m; 3566 } 3567 } 3568 // None found, return null for the caller to handle. 3569 return NULL; 3570 } 3571 return m; 3572 } 3573 3574 3575 Method* InstanceKlass::method_with_orig_idnum(int idnum) { 3576 if (idnum >= methods()->length()) { 3577 return NULL; 3578 } 3579 Method* m = methods()->at(idnum); 3580 if (m != NULL && m->orig_method_idnum() == idnum) { 3581 return m; 3582 } 3583 // Obsolete method idnum does not match the original idnum 3584 for (int index = 0; index < methods()->length(); ++index) { 3585 m = methods()->at(index); 3586 if (m->orig_method_idnum() == idnum) { 3587 return m; 3588 } 3589 } 3590 // None found, return null for the caller to handle. 3591 return NULL; 3592 } 3593 3594 3595 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) { 3596 InstanceKlass* holder = get_klass_version(version); 3597 if (holder == NULL) { 3598 return NULL; // The version of klass is gone, no method is found 3599 } 3600 Method* method = holder->method_with_orig_idnum(idnum); 3601 return method; 3602 } 3603 3604 3605 jint InstanceKlass::get_cached_class_file_len() { 3606 return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file); 3607 } 3608 3609 unsigned char * InstanceKlass::get_cached_class_file_bytes() { 3610 return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file); 3611 } 3612 3613 3614 /////////////// Unit tests /////////////// 3615 3616 #ifndef PRODUCT 3617 3618 class TestNmethodBucketContext { 3619 public: 3620 nmethod* _nmethodLast; 3621 nmethod* _nmethodMiddle; 3622 nmethod* _nmethodFirst; 3623 3624 nmethodBucket* _bucketLast; 3625 nmethodBucket* _bucketMiddle; 3626 nmethodBucket* _bucketFirst; 3627 3628 nmethodBucket* _bucketList; 3629 3630 TestNmethodBucketContext() { 3631 CodeCache_lock->lock_without_safepoint_check(); 3632 3633 _nmethodLast = reinterpret_cast<nmethod*>(0x8 * 0); 3634 _nmethodMiddle = reinterpret_cast<nmethod*>(0x8 * 1); 3635 _nmethodFirst = reinterpret_cast<nmethod*>(0x8 * 2); 3636 3637 _bucketLast = new nmethodBucket(_nmethodLast, NULL); 3638 _bucketMiddle = new nmethodBucket(_nmethodMiddle, _bucketLast); 3639 _bucketFirst = new nmethodBucket(_nmethodFirst, _bucketMiddle); 3640 3641 _bucketList = _bucketFirst; 3642 } 3643 3644 ~TestNmethodBucketContext() { 3645 delete _bucketLast; 3646 delete _bucketMiddle; 3647 delete _bucketFirst; 3648 3649 CodeCache_lock->unlock(); 3650 } 3651 }; 3652 3653 class TestNmethodBucket { 3654 public: 3655 static void testRemoveDependentNmethodFirstDeleteImmediately() { 3656 TestNmethodBucketContext c; 3657 3658 nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodFirst, true /* delete */); 3659 3660 assert(c._bucketList == c._bucketMiddle, "check"); 3661 assert(c._bucketList->next() == c._bucketLast, "check"); 3662 assert(c._bucketList->next()->next() == NULL, "check"); 3663 3664 // Cleanup before context is deleted. 3665 c._bucketFirst = NULL; 3666 } 3667 3668 static void testRemoveDependentNmethodMiddleDeleteImmediately() { 3669 TestNmethodBucketContext c; 3670 3671 nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodMiddle, true /* delete */); 3672 3673 assert(c._bucketList == c._bucketFirst, "check"); 3674 assert(c._bucketList->next() == c._bucketLast, "check"); 3675 assert(c._bucketList->next()->next() == NULL, "check"); 3676 3677 // Cleanup before context is deleted. 3678 c._bucketMiddle = NULL; 3679 } 3680 3681 static void testRemoveDependentNmethodLastDeleteImmediately() { 3682 TestNmethodBucketContext c; 3683 3684 nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodLast, true /* delete */); 3685 3686 assert(c._bucketList == c._bucketFirst, "check"); 3687 assert(c._bucketList->next() == c._bucketMiddle, "check"); 3688 assert(c._bucketList->next()->next() == NULL, "check"); 3689 3690 // Cleanup before context is deleted. 3691 c._bucketLast = NULL; 3692 } 3693 3694 static void testRemoveDependentNmethodFirstDeleteDeferred() { 3695 TestNmethodBucketContext c; 3696 3697 nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodFirst, false /* delete */); 3698 3699 assert(c._bucketList == c._bucketFirst, "check"); 3700 assert(c._bucketList->next() == c._bucketMiddle, "check"); 3701 assert(c._bucketList->next()->next() == c._bucketLast, "check"); 3702 assert(c._bucketList->next()->next()->next() == NULL, "check"); 3703 3704 assert(c._bucketFirst->count() == 0, "check"); 3705 assert(c._bucketMiddle->count() == 1, "check"); 3706 assert(c._bucketLast->count() == 1, "check"); 3707 } 3708 3709 static void testRemoveDependentNmethodMiddleDeleteDeferred() { 3710 TestNmethodBucketContext c; 3711 3712 nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodMiddle, false /* delete */); 3713 3714 assert(c._bucketList == c._bucketFirst, "check"); 3715 assert(c._bucketList->next() == c._bucketMiddle, "check"); 3716 assert(c._bucketList->next()->next() == c._bucketLast, "check"); 3717 assert(c._bucketList->next()->next()->next() == NULL, "check"); 3718 3719 assert(c._bucketFirst->count() == 1, "check"); 3720 assert(c._bucketMiddle->count() == 0, "check"); 3721 assert(c._bucketLast->count() == 1, "check"); 3722 } 3723 3724 static void testRemoveDependentNmethodLastDeleteDeferred() { 3725 TestNmethodBucketContext c; 3726 3727 nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodLast, false /* delete */); 3728 3729 assert(c._bucketList == c._bucketFirst, "check"); 3730 assert(c._bucketList->next() == c._bucketMiddle, "check"); 3731 assert(c._bucketList->next()->next() == c._bucketLast, "check"); 3732 assert(c._bucketList->next()->next()->next() == NULL, "check"); 3733 3734 assert(c._bucketFirst->count() == 1, "check"); 3735 assert(c._bucketMiddle->count() == 1, "check"); 3736 assert(c._bucketLast->count() == 0, "check"); 3737 } 3738 3739 static void testRemoveDependentNmethodConvenienceFirst() { 3740 TestNmethodBucketContext c; 3741 3742 nmethodBucket::remove_dependent_nmethod(c._bucketList, c._nmethodFirst); 3743 3744 assert(c._bucketList == c._bucketFirst, "check"); 3745 assert(c._bucketList->next() == c._bucketMiddle, "check"); 3746 assert(c._bucketList->next()->next() == c._bucketLast, "check"); 3747 assert(c._bucketList->next()->next()->next() == NULL, "check"); 3748 3749 assert(c._bucketFirst->count() == 0, "check"); 3750 assert(c._bucketMiddle->count() == 1, "check"); 3751 assert(c._bucketLast->count() == 1, "check"); 3752 } 3753 3754 static void testRemoveDependentNmethodConvenienceMiddle() { 3755 TestNmethodBucketContext c; 3756 3757 nmethodBucket::remove_dependent_nmethod(c._bucketList, c._nmethodMiddle); 3758 3759 assert(c._bucketList == c._bucketFirst, "check"); 3760 assert(c._bucketList->next() == c._bucketMiddle, "check"); 3761 assert(c._bucketList->next()->next() == c._bucketLast, "check"); 3762 assert(c._bucketList->next()->next()->next() == NULL, "check"); 3763 3764 assert(c._bucketFirst->count() == 1, "check"); 3765 assert(c._bucketMiddle->count() == 0, "check"); 3766 assert(c._bucketLast->count() == 1, "check"); 3767 } 3768 3769 static void testRemoveDependentNmethodConvenienceLast() { 3770 TestNmethodBucketContext c; 3771 3772 nmethodBucket::remove_dependent_nmethod(c._bucketList, c._nmethodLast); 3773 3774 assert(c._bucketList == c._bucketFirst, "check"); 3775 assert(c._bucketList->next() == c._bucketMiddle, "check"); 3776 assert(c._bucketList->next()->next() == c._bucketLast, "check"); 3777 assert(c._bucketList->next()->next()->next() == NULL, "check"); 3778 3779 assert(c._bucketFirst->count() == 1, "check"); 3780 assert(c._bucketMiddle->count() == 1, "check"); 3781 assert(c._bucketLast->count() == 0, "check"); 3782 } 3783 3784 static void testRemoveDependentNmethod() { 3785 testRemoveDependentNmethodFirstDeleteImmediately(); 3786 testRemoveDependentNmethodMiddleDeleteImmediately(); 3787 testRemoveDependentNmethodLastDeleteImmediately(); 3788 3789 testRemoveDependentNmethodFirstDeleteDeferred(); 3790 testRemoveDependentNmethodMiddleDeleteDeferred(); 3791 testRemoveDependentNmethodLastDeleteDeferred(); 3792 3793 testRemoveDependentNmethodConvenienceFirst(); 3794 testRemoveDependentNmethodConvenienceMiddle(); 3795 testRemoveDependentNmethodConvenienceLast(); 3796 } 3797 3798 static void test() { 3799 testRemoveDependentNmethod(); 3800 } 3801 }; 3802 3803 void TestNmethodBucket_test() { 3804 TestNmethodBucket::test(); 3805 } 3806 3807 #endif