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