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