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