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