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