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