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