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