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