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