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