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