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