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