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