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