1 /* 2 * Copyright (c) 1997, 2024, 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 "cds/archiveUtils.hpp" 27 #include "cds/cdsConfig.hpp" 28 #include "cds/classListWriter.hpp" 29 #include "cds/heapShared.hpp" 30 #include "cds/metaspaceShared.hpp" 31 #include "classfile/classFileParser.hpp" 32 #include "classfile/classFileStream.hpp" 33 #include "classfile/classLoader.hpp" 34 #include "classfile/classLoaderData.inline.hpp" 35 #include "classfile/javaClasses.hpp" 36 #include "classfile/moduleEntry.hpp" 37 #include "classfile/systemDictionary.hpp" 38 #include "classfile/systemDictionaryShared.hpp" 39 #include "classfile/verifier.hpp" 40 #include "classfile/vmClasses.hpp" 41 #include "classfile/vmSymbols.hpp" 42 #include "code/codeCache.hpp" 43 #include "code/dependencyContext.hpp" 44 #include "compiler/compilationPolicy.hpp" 45 #include "compiler/compileBroker.hpp" 46 #include "gc/shared/collectedHeap.inline.hpp" 47 #include "interpreter/bytecodeStream.hpp" 48 #include "interpreter/oopMapCache.hpp" 49 #include "interpreter/rewriter.hpp" 50 #include "jvm.h" 51 #include "jvmtifiles/jvmti.h" 52 #include "logging/log.hpp" 53 #include "logging/logMessage.hpp" 54 #include "logging/logStream.hpp" 55 #include "memory/allocation.inline.hpp" 56 #include "memory/iterator.inline.hpp" 57 #include "memory/metadataFactory.hpp" 58 #include "memory/metaspaceClosure.hpp" 59 #include "memory/oopFactory.hpp" 60 #include "memory/resourceArea.hpp" 61 #include "memory/universe.hpp" 62 #include "oops/fieldStreams.inline.hpp" 63 #include "oops/constantPool.hpp" 64 #include "oops/instanceClassLoaderKlass.hpp" 65 #include "oops/instanceKlass.inline.hpp" 66 #include "oops/instanceMirrorKlass.hpp" 67 #include "oops/instanceOop.hpp" 68 #include "oops/instanceStackChunkKlass.hpp" 69 #include "oops/klass.inline.hpp" 70 #include "oops/method.hpp" 71 #include "oops/oop.inline.hpp" 72 #include "oops/recordComponent.hpp" 73 #include "oops/symbol.hpp" 74 #include "prims/jvmtiExport.hpp" 75 #include "prims/jvmtiRedefineClasses.hpp" 76 #include "prims/jvmtiThreadState.hpp" 77 #include "prims/methodComparator.hpp" 78 #include "runtime/arguments.hpp" 79 #include "runtime/deoptimization.hpp" 80 #include "runtime/atomic.hpp" 81 #include "runtime/fieldDescriptor.inline.hpp" 82 #include "runtime/handles.inline.hpp" 83 #include "runtime/javaCalls.hpp" 84 #include "runtime/javaThread.inline.hpp" 85 #include "runtime/mutexLocker.hpp" 86 #include "runtime/orderAccess.hpp" 87 #include "runtime/os.inline.hpp" 88 #include "runtime/reflection.hpp" 89 #include "runtime/threads.hpp" 90 #include "services/classLoadingService.hpp" 91 #include "services/finalizerService.hpp" 92 #include "services/threadService.hpp" 93 #include "utilities/dtrace.hpp" 94 #include "utilities/events.hpp" 95 #include "utilities/macros.hpp" 96 #include "utilities/stringUtils.hpp" 97 #include "utilities/pair.hpp" 98 #ifdef COMPILER1 99 #include "c1/c1_Compiler.hpp" 100 #endif 101 #if INCLUDE_JFR 102 #include "jfr/jfrEvents.hpp" 103 #endif 104 105 #ifdef DTRACE_ENABLED 106 107 108 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED 109 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE 110 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT 111 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS 112 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED 113 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT 114 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR 115 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END 116 #define DTRACE_CLASSINIT_PROBE(type, thread_type) \ 117 { \ 118 char* data = nullptr; \ 119 int len = 0; \ 120 Symbol* clss_name = name(); \ 121 if (clss_name != nullptr) { \ 122 data = (char*)clss_name->bytes(); \ 123 len = clss_name->utf8_length(); \ 124 } \ 125 HOTSPOT_CLASS_INITIALIZATION_##type( \ 126 data, len, (void*)class_loader(), thread_type); \ 127 } 128 129 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \ 130 { \ 131 char* data = nullptr; \ 132 int len = 0; \ 133 Symbol* clss_name = name(); \ 134 if (clss_name != nullptr) { \ 135 data = (char*)clss_name->bytes(); \ 136 len = clss_name->utf8_length(); \ 137 } \ 138 HOTSPOT_CLASS_INITIALIZATION_##type( \ 139 data, len, (void*)class_loader(), thread_type, wait); \ 140 } 141 142 #else // ndef DTRACE_ENABLED 143 144 #define DTRACE_CLASSINIT_PROBE(type, thread_type) 145 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) 146 147 #endif // ndef DTRACE_ENABLED 148 149 bool InstanceKlass::_finalization_enabled = true; 150 151 static inline bool is_class_loader(const Symbol* class_name, 152 const ClassFileParser& parser) { 153 assert(class_name != nullptr, "invariant"); 154 155 if (class_name == vmSymbols::java_lang_ClassLoader()) { 156 return true; 157 } 158 159 if (vmClasses::ClassLoader_klass_loaded()) { 160 const Klass* const super_klass = parser.super_klass(); 161 if (super_klass != nullptr) { 162 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) { 163 return true; 164 } 165 } 166 } 167 return false; 168 } 169 170 static inline bool is_stack_chunk_class(const Symbol* class_name, 171 const ClassLoaderData* loader_data) { 172 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() && 173 loader_data->is_the_null_class_loader_data()); 174 } 175 176 // private: called to verify that k is a static member of this nest. 177 // We know that k is an instance class in the same package and hence the 178 // same classloader. 179 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const { 180 assert(!is_hidden(), "unexpected hidden class"); 181 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) { 182 if (log_is_enabled(Trace, class, nestmates)) { 183 ResourceMark rm(current); 184 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s", 185 k->external_name(), this->external_name()); 186 } 187 return false; 188 } 189 190 if (log_is_enabled(Trace, class, nestmates)) { 191 ResourceMark rm(current); 192 log_trace(class, nestmates)("Checking nest membership of %s in %s", 193 k->external_name(), this->external_name()); 194 } 195 196 // Check for the named class in _nest_members. 197 // We don't resolve, or load, any classes. 198 for (int i = 0; i < _nest_members->length(); i++) { 199 int cp_index = _nest_members->at(i); 200 Symbol* name = _constants->klass_name_at(cp_index); 201 if (name == k->name()) { 202 log_trace(class, nestmates)("- named class found at nest_members[%d] => cp[%d]", i, cp_index); 203 return true; 204 } 205 } 206 log_trace(class, nestmates)("- class is NOT a nest member!"); 207 return false; 208 } 209 210 // Called to verify that k is a permitted subclass of this class 211 bool InstanceKlass::has_as_permitted_subclass(const InstanceKlass* k) const { 212 Thread* current = Thread::current(); 213 assert(k != nullptr, "sanity check"); 214 assert(_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array(), 215 "unexpected empty _permitted_subclasses array"); 216 217 if (log_is_enabled(Trace, class, sealed)) { 218 ResourceMark rm(current); 219 log_trace(class, sealed)("Checking for permitted subclass of %s in %s", 220 k->external_name(), this->external_name()); 221 } 222 223 // Check that the class and its super are in the same module. 224 if (k->module() != this->module()) { 225 ResourceMark rm(current); 226 log_trace(class, sealed)("Check failed for same module of permitted subclass %s and sealed class %s", 227 k->external_name(), this->external_name()); 228 return false; 229 } 230 231 if (!k->is_public() && !is_same_class_package(k)) { 232 ResourceMark rm(current); 233 log_trace(class, sealed)("Check failed, subclass %s not public and not in the same package as sealed class %s", 234 k->external_name(), this->external_name()); 235 return false; 236 } 237 238 for (int i = 0; i < _permitted_subclasses->length(); i++) { 239 int cp_index = _permitted_subclasses->at(i); 240 Symbol* name = _constants->klass_name_at(cp_index); 241 if (name == k->name()) { 242 log_trace(class, sealed)("- Found it at permitted_subclasses[%d] => cp[%d]", i, cp_index); 243 return true; 244 } 245 } 246 log_trace(class, sealed)("- class is NOT a permitted subclass!"); 247 return false; 248 } 249 250 // Return nest-host class, resolving, validating and saving it if needed. 251 // In cases where this is called from a thread that cannot do classloading 252 // (such as a native JIT thread) then we simply return null, which in turn 253 // causes the access check to return false. Such code will retry the access 254 // from a more suitable environment later. Otherwise the _nest_host is always 255 // set once this method returns. 256 // Any errors from nest-host resolution must be preserved so they can be queried 257 // from higher-level access checking code, and reported as part of access checking 258 // exceptions. 259 // VirtualMachineErrors are propagated with a null return. 260 // Under any conditions where the _nest_host can be set to non-null the resulting 261 // value of it and, if applicable, the nest host resolution/validation error, 262 // are idempotent. 263 InstanceKlass* InstanceKlass::nest_host(TRAPS) { 264 InstanceKlass* nest_host_k = _nest_host; 265 if (nest_host_k != nullptr) { 266 return nest_host_k; 267 } 268 269 ResourceMark rm(THREAD); 270 271 // need to resolve and save our nest-host class. 272 if (_nest_host_index != 0) { // we have a real nest_host 273 // Before trying to resolve check if we're in a suitable context 274 bool can_resolve = THREAD->can_call_java(); 275 if (!can_resolve && !_constants->tag_at(_nest_host_index).is_klass()) { 276 log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread", 277 this->external_name()); 278 return nullptr; // sentinel to say "try again from a different context" 279 } 280 281 log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s", 282 this->external_name(), 283 _constants->klass_name_at(_nest_host_index)->as_C_string()); 284 285 Klass* k = _constants->klass_at(_nest_host_index, THREAD); 286 if (HAS_PENDING_EXCEPTION) { 287 if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) { 288 return nullptr; // propagate VMEs 289 } 290 stringStream ss; 291 char* target_host_class = _constants->klass_name_at(_nest_host_index)->as_C_string(); 292 ss.print("Nest host resolution of %s with host %s failed: ", 293 this->external_name(), target_host_class); 294 java_lang_Throwable::print(PENDING_EXCEPTION, &ss); 295 const char* msg = ss.as_string(true /* on C-heap */); 296 constantPoolHandle cph(THREAD, constants()); 297 SystemDictionary::add_nest_host_error(cph, _nest_host_index, msg); 298 CLEAR_PENDING_EXCEPTION; 299 300 log_trace(class, nestmates)("%s", msg); 301 } else { 302 // A valid nest-host is an instance class in the current package that lists this 303 // class as a nest member. If any of these conditions are not met the class is 304 // its own nest-host. 305 const char* error = nullptr; 306 307 // JVMS 5.4.4 indicates package check comes first 308 if (is_same_class_package(k)) { 309 // Now check actual membership. We can't be a member if our "host" is 310 // not an instance class. 311 if (k->is_instance_klass()) { 312 nest_host_k = InstanceKlass::cast(k); 313 bool is_member = nest_host_k->has_nest_member(THREAD, this); 314 if (is_member) { 315 _nest_host = nest_host_k; // save resolved nest-host value 316 317 log_trace(class, nestmates)("Resolved nest-host of %s to %s", 318 this->external_name(), k->external_name()); 319 return nest_host_k; 320 } else { 321 error = "current type is not listed as a nest member"; 322 } 323 } else { 324 error = "host is not an instance class"; 325 } 326 } else { 327 error = "types are in different packages"; 328 } 329 330 // something went wrong, so record what and log it 331 { 332 stringStream ss; 333 ss.print("Type %s (loader: %s) is not a nest member of type %s (loader: %s): %s", 334 this->external_name(), 335 this->class_loader_data()->loader_name_and_id(), 336 k->external_name(), 337 k->class_loader_data()->loader_name_and_id(), 338 error); 339 const char* msg = ss.as_string(true /* on C-heap */); 340 constantPoolHandle cph(THREAD, constants()); 341 SystemDictionary::add_nest_host_error(cph, _nest_host_index, msg); 342 log_trace(class, nestmates)("%s", msg); 343 } 344 } 345 } else { 346 log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self", 347 this->external_name()); 348 } 349 350 // Either not in an explicit nest, or else an error occurred, so 351 // the nest-host is set to `this`. Any thread that sees this assignment 352 // will also see any setting of nest_host_error(), if applicable. 353 return (_nest_host = this); 354 } 355 356 // Dynamic nest member support: set this class's nest host to the given class. 357 // This occurs as part of the class definition, as soon as the instanceKlass 358 // has been created and doesn't require further resolution. The code: 359 // lookup().defineHiddenClass(bytes_for_X, NESTMATE); 360 // results in: 361 // class_of_X.set_nest_host(lookup().lookupClass().getNestHost()) 362 // If it has an explicit _nest_host_index or _nest_members, these will be ignored. 363 // We also know the "host" is a valid nest-host in the same package so we can 364 // assert some of those facts. 365 void InstanceKlass::set_nest_host(InstanceKlass* host) { 366 assert(is_hidden(), "must be a hidden class"); 367 assert(host != nullptr, "null nest host specified"); 368 assert(_nest_host == nullptr, "current class has resolved nest-host"); 369 assert(nest_host_error() == nullptr, "unexpected nest host resolution error exists: %s", 370 nest_host_error()); 371 assert((host->_nest_host == nullptr && host->_nest_host_index == 0) || 372 (host->_nest_host == host), "proposed host is not a valid nest-host"); 373 // Can't assert this as package is not set yet: 374 // assert(is_same_class_package(host), "proposed host is in wrong package"); 375 376 if (log_is_enabled(Trace, class, nestmates)) { 377 ResourceMark rm; 378 const char* msg = ""; 379 // a hidden class does not expect a statically defined nest-host 380 if (_nest_host_index > 0) { 381 msg = "(the NestHost attribute in the current class is ignored)"; 382 } else if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) { 383 msg = "(the NestMembers attribute in the current class is ignored)"; 384 } 385 log_trace(class, nestmates)("Injected type %s into the nest of %s %s", 386 this->external_name(), 387 host->external_name(), 388 msg); 389 } 390 // set dynamic nest host 391 _nest_host = host; 392 // Record dependency to keep nest host from being unloaded before this class. 393 ClassLoaderData* this_key = class_loader_data(); 394 assert(this_key != nullptr, "sanity"); 395 this_key->record_dependency(host); 396 } 397 398 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host, 399 // or we are k's nest_host - all of which is covered by comparing the two 400 // resolved_nest_hosts. 401 // Any exceptions (i.e. VMEs) are propagated. 402 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) { 403 404 assert(this != k, "this should be handled by higher-level code"); 405 406 // Per JVMS 5.4.4 we first resolve and validate the current class, then 407 // the target class k. 408 409 InstanceKlass* cur_host = nest_host(CHECK_false); 410 if (cur_host == nullptr) { 411 return false; 412 } 413 414 Klass* k_nest_host = k->nest_host(CHECK_false); 415 if (k_nest_host == nullptr) { 416 return false; 417 } 418 419 bool access = (cur_host == k_nest_host); 420 421 ResourceMark rm(THREAD); 422 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s", 423 this->external_name(), 424 access ? "" : "NOT ", 425 k->external_name()); 426 return access; 427 } 428 429 const char* InstanceKlass::nest_host_error() { 430 if (_nest_host_index == 0) { 431 return nullptr; 432 } else { 433 constantPoolHandle cph(Thread::current(), constants()); 434 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index); 435 } 436 } 437 438 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) { 439 const int size = InstanceKlass::size(parser.vtable_size(), 440 parser.itable_size(), 441 nonstatic_oop_map_size(parser.total_oop_map_count()), 442 parser.is_interface()); 443 444 const Symbol* const class_name = parser.class_name(); 445 assert(class_name != nullptr, "invariant"); 446 ClassLoaderData* loader_data = parser.loader_data(); 447 assert(loader_data != nullptr, "invariant"); 448 449 InstanceKlass* ik; 450 451 // Allocation 452 if (parser.is_instance_ref_klass()) { 453 // java.lang.ref.Reference 454 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser); 455 } else if (class_name == vmSymbols::java_lang_Class()) { 456 // mirror - java.lang.Class 457 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser); 458 } else if (is_stack_chunk_class(class_name, loader_data)) { 459 // stack chunk 460 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser); 461 } else if (is_class_loader(class_name, parser)) { 462 // class loader - java.lang.ClassLoader 463 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser); 464 } else { 465 // normal 466 ik = new (loader_data, size, THREAD) InstanceKlass(parser); 467 } 468 469 // Check for pending exception before adding to the loader data and incrementing 470 // class count. Can get OOM here. 471 if (HAS_PENDING_EXCEPTION) { 472 return nullptr; 473 } 474 475 return ik; 476 } 477 478 479 // copy method ordering from resource area to Metaspace 480 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) { 481 if (m != nullptr) { 482 // allocate a new array and copy contents (memcpy?) 483 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK); 484 for (int i = 0; i < m->length(); i++) { 485 _method_ordering->at_put(i, m->at(i)); 486 } 487 } else { 488 _method_ordering = Universe::the_empty_int_array(); 489 } 490 } 491 492 // create a new array of vtable_indices for default methods 493 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) { 494 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL); 495 assert(default_vtable_indices() == nullptr, "only create once"); 496 set_default_vtable_indices(vtable_indices); 497 return vtable_indices; 498 } 499 500 static Monitor* create_init_monitor(const char* name) { 501 return new Monitor(Mutex::safepoint, name); 502 } 503 504 InstanceKlass::InstanceKlass() { 505 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS"); 506 } 507 508 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, ReferenceType reference_type) : 509 Klass(kind), 510 _nest_members(nullptr), 511 _nest_host(nullptr), 512 _permitted_subclasses(nullptr), 513 _record_components(nullptr), 514 _static_field_size(parser.static_field_size()), 515 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())), 516 _itable_len(parser.itable_size()), 517 _nest_host_index(0), 518 _init_state(allocated), 519 _reference_type(reference_type), 520 _init_monitor(create_init_monitor("InstanceKlassInitMonitor_lock")), 521 _init_thread(nullptr) 522 { 523 set_vtable_length(parser.vtable_size()); 524 set_access_flags(parser.access_flags()); 525 if (parser.is_hidden()) set_is_hidden(); 526 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(), 527 false)); 528 529 assert(nullptr == _methods, "underlying memory not zeroed?"); 530 assert(is_instance_klass(), "is layout incorrect?"); 531 assert(size_helper() == parser.layout_size(), "incorrect size_helper?"); 532 } 533 534 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data, 535 Array<Method*>* methods) { 536 if (methods != nullptr && methods != Universe::the_empty_method_array() && 537 !methods->is_shared()) { 538 for (int i = 0; i < methods->length(); i++) { 539 Method* method = methods->at(i); 540 if (method == nullptr) continue; // maybe null if error processing 541 // Only want to delete methods that are not executing for RedefineClasses. 542 // The previous version will point to them so they're not totally dangling 543 assert (!method->on_stack(), "shouldn't be called with methods on stack"); 544 MetadataFactory::free_metadata(loader_data, method); 545 } 546 MetadataFactory::free_array<Method*>(loader_data, methods); 547 } 548 } 549 550 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data, 551 const Klass* super_klass, 552 Array<InstanceKlass*>* local_interfaces, 553 Array<InstanceKlass*>* transitive_interfaces) { 554 // Only deallocate transitive interfaces if not empty, same as super class 555 // or same as local interfaces. See code in parseClassFile. 556 Array<InstanceKlass*>* ti = transitive_interfaces; 557 if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) { 558 // check that the interfaces don't come from super class 559 Array<InstanceKlass*>* sti = (super_klass == nullptr) ? nullptr : 560 InstanceKlass::cast(super_klass)->transitive_interfaces(); 561 if (ti != sti && ti != nullptr && !ti->is_shared()) { 562 MetadataFactory::free_array<InstanceKlass*>(loader_data, ti); 563 } 564 } 565 566 // local interfaces can be empty 567 if (local_interfaces != Universe::the_empty_instance_klass_array() && 568 local_interfaces != nullptr && !local_interfaces->is_shared()) { 569 MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces); 570 } 571 } 572 573 void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data, 574 Array<RecordComponent*>* record_components) { 575 if (record_components != nullptr && !record_components->is_shared()) { 576 for (int i = 0; i < record_components->length(); i++) { 577 RecordComponent* record_component = record_components->at(i); 578 MetadataFactory::free_metadata(loader_data, record_component); 579 } 580 MetadataFactory::free_array<RecordComponent*>(loader_data, record_components); 581 } 582 } 583 584 // This function deallocates the metadata and C heap pointers that the 585 // InstanceKlass points to. 586 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) { 587 // Orphan the mirror first, CMS thinks it's still live. 588 if (java_mirror() != nullptr) { 589 java_lang_Class::set_klass(java_mirror(), nullptr); 590 } 591 592 // Also remove mirror from handles 593 loader_data->remove_handle(_java_mirror); 594 595 // Need to take this class off the class loader data list. 596 loader_data->remove_class(this); 597 598 // The array_klass for this class is created later, after error handling. 599 // For class redefinition, we keep the original class so this scratch class 600 // doesn't have an array class. Either way, assert that there is nothing 601 // to deallocate. 602 assert(array_klasses() == nullptr, "array classes shouldn't be created for this class yet"); 603 604 // Release C heap allocated data that this points to, which includes 605 // reference counting symbol names. 606 // Can't release the constant pool or MethodData C heap data here because the constant 607 // pool can be deallocated separately from the InstanceKlass for default methods and 608 // redefine classes. MethodData can also be released separately. 609 release_C_heap_structures(/* release_sub_metadata */ false); 610 611 deallocate_methods(loader_data, methods()); 612 set_methods(nullptr); 613 614 deallocate_record_components(loader_data, record_components()); 615 set_record_components(nullptr); 616 617 if (method_ordering() != nullptr && 618 method_ordering() != Universe::the_empty_int_array() && 619 !method_ordering()->is_shared()) { 620 MetadataFactory::free_array<int>(loader_data, method_ordering()); 621 } 622 set_method_ordering(nullptr); 623 624 // default methods can be empty 625 if (default_methods() != nullptr && 626 default_methods() != Universe::the_empty_method_array() && 627 !default_methods()->is_shared()) { 628 MetadataFactory::free_array<Method*>(loader_data, default_methods()); 629 } 630 // Do NOT deallocate the default methods, they are owned by superinterfaces. 631 set_default_methods(nullptr); 632 633 // default methods vtable indices can be empty 634 if (default_vtable_indices() != nullptr && 635 !default_vtable_indices()->is_shared()) { 636 MetadataFactory::free_array<int>(loader_data, default_vtable_indices()); 637 } 638 set_default_vtable_indices(nullptr); 639 640 641 // This array is in Klass, but remove it with the InstanceKlass since 642 // this place would be the only caller and it can share memory with transitive 643 // interfaces. 644 if (secondary_supers() != nullptr && 645 secondary_supers() != Universe::the_empty_klass_array() && 646 // see comments in compute_secondary_supers about the following cast 647 (address)(secondary_supers()) != (address)(transitive_interfaces()) && 648 !secondary_supers()->is_shared()) { 649 MetadataFactory::free_array<Klass*>(loader_data, secondary_supers()); 650 } 651 set_secondary_supers(nullptr); 652 653 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces()); 654 set_transitive_interfaces(nullptr); 655 set_local_interfaces(nullptr); 656 657 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->is_shared()) { 658 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream()); 659 } 660 set_fieldinfo_stream(nullptr); 661 662 if (fields_status() != nullptr && !fields_status()->is_shared()) { 663 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status()); 664 } 665 set_fields_status(nullptr); 666 667 // If a method from a redefined class is using this constant pool, don't 668 // delete it, yet. The new class's previous version will point to this. 669 if (constants() != nullptr) { 670 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack"); 671 if (!constants()->is_shared()) { 672 MetadataFactory::free_metadata(loader_data, constants()); 673 } 674 // Delete any cached resolution errors for the constant pool 675 SystemDictionary::delete_resolution_error(constants()); 676 677 set_constants(nullptr); 678 } 679 680 if (inner_classes() != nullptr && 681 inner_classes() != Universe::the_empty_short_array() && 682 !inner_classes()->is_shared()) { 683 MetadataFactory::free_array<jushort>(loader_data, inner_classes()); 684 } 685 set_inner_classes(nullptr); 686 687 if (nest_members() != nullptr && 688 nest_members() != Universe::the_empty_short_array() && 689 !nest_members()->is_shared()) { 690 MetadataFactory::free_array<jushort>(loader_data, nest_members()); 691 } 692 set_nest_members(nullptr); 693 694 if (permitted_subclasses() != nullptr && 695 permitted_subclasses() != Universe::the_empty_short_array() && 696 !permitted_subclasses()->is_shared()) { 697 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses()); 698 } 699 set_permitted_subclasses(nullptr); 700 701 // We should deallocate the Annotations instance if it's not in shared spaces. 702 if (annotations() != nullptr && !annotations()->is_shared()) { 703 MetadataFactory::free_metadata(loader_data, annotations()); 704 } 705 set_annotations(nullptr); 706 707 SystemDictionaryShared::handle_class_unloading(this); 708 709 #if INCLUDE_CDS_JAVA_HEAP 710 if (CDSConfig::is_dumping_heap()) { 711 HeapShared::remove_scratch_objects(this); 712 } 713 #endif 714 } 715 716 bool InstanceKlass::is_record() const { 717 return _record_components != nullptr && 718 is_final() && 719 java_super() == vmClasses::Record_klass(); 720 } 721 722 bool InstanceKlass::is_sealed() const { 723 return _permitted_subclasses != nullptr && 724 _permitted_subclasses != Universe::the_empty_short_array(); 725 } 726 727 bool InstanceKlass::should_be_initialized() const { 728 return !is_initialized(); 729 } 730 731 klassItable InstanceKlass::itable() const { 732 return klassItable(const_cast<InstanceKlass*>(this)); 733 } 734 735 // JVMTI spec thinks there are signers and protection domain in the 736 // instanceKlass. These accessors pretend these fields are there. 737 // The hprof specification also thinks these fields are in InstanceKlass. 738 oop InstanceKlass::protection_domain() const { 739 // return the protection_domain from the mirror 740 return java_lang_Class::protection_domain(java_mirror()); 741 } 742 743 objArrayOop InstanceKlass::signers() const { 744 // return the signers from the mirror 745 return java_lang_Class::signers(java_mirror()); 746 } 747 748 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization 749 // process. The step comments refers to the procedure described in that section. 750 // Note: implementation moved to static method to expose the this pointer. 751 void InstanceKlass::initialize(TRAPS) { 752 if (this->should_be_initialized()) { 753 initialize_impl(CHECK); 754 // Note: at this point the class may be initialized 755 // OR it may be in the state of being initialized 756 // in case of recursive initialization! 757 } else { 758 assert(is_initialized(), "sanity check"); 759 } 760 } 761 762 763 bool InstanceKlass::verify_code(TRAPS) { 764 // 1) Verify the bytecodes 765 return Verifier::verify(this, should_verify_class(), THREAD); 766 } 767 768 void InstanceKlass::link_class(TRAPS) { 769 assert(is_loaded(), "must be loaded"); 770 if (!is_linked()) { 771 link_class_impl(CHECK); 772 } 773 } 774 775 void InstanceKlass::check_link_state_and_wait(JavaThread* current) { 776 MonitorLocker ml(current, _init_monitor); 777 778 bool debug_logging_enabled = log_is_enabled(Debug, class, init); 779 780 // Another thread is linking this class, wait. 781 while (is_being_linked() && !is_init_thread(current)) { 782 if (debug_logging_enabled) { 783 ResourceMark rm(current); 784 log_debug(class, init)("Thread \"%s\" waiting for linking of %s by thread \"%s\"", 785 current->name(), external_name(), init_thread_name()); 786 } 787 ml.wait(); 788 } 789 790 // This thread is recursively linking this class, continue 791 if (is_being_linked() && is_init_thread(current)) { 792 if (debug_logging_enabled) { 793 ResourceMark rm(current); 794 log_debug(class, init)("Thread \"%s\" recursively linking %s", 795 current->name(), external_name()); 796 } 797 return; 798 } 799 800 // If this class wasn't linked already, set state to being_linked 801 if (!is_linked()) { 802 if (debug_logging_enabled) { 803 ResourceMark rm(current); 804 log_debug(class, init)("Thread \"%s\" linking %s", 805 current->name(), external_name()); 806 } 807 set_init_state(being_linked); 808 set_init_thread(current); 809 } else { 810 if (debug_logging_enabled) { 811 ResourceMark rm(current); 812 log_debug(class, init)("Thread \"%s\" found %s already linked", 813 current->name(), external_name()); 814 } 815 } 816 } 817 818 // Called to verify that a class can link during initialization, without 819 // throwing a VerifyError. 820 bool InstanceKlass::link_class_or_fail(TRAPS) { 821 assert(is_loaded(), "must be loaded"); 822 if (!is_linked()) { 823 link_class_impl(CHECK_false); 824 } 825 return is_linked(); 826 } 827 828 bool InstanceKlass::link_class_impl(TRAPS) { 829 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) { 830 // This is for CDS static dump only -- we use the in_error_state to indicate that 831 // the class has failed verification. Throwing the NoClassDefFoundError here is just 832 // a convenient way to stop repeat attempts to verify the same (bad) class. 833 // 834 // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown 835 // if we are executing Java code. This is not a problem for CDS dumping phase since 836 // it doesn't execute any Java code. 837 ResourceMark rm(THREAD); 838 Exceptions::fthrow(THREAD_AND_LOCATION, 839 vmSymbols::java_lang_NoClassDefFoundError(), 840 "Class %s, or one of its supertypes, failed class initialization", 841 external_name()); 842 return false; 843 } 844 // return if already verified 845 if (is_linked()) { 846 return true; 847 } 848 849 // Timing 850 // timer handles recursion 851 JavaThread* jt = THREAD; 852 853 // link super class before linking this class 854 Klass* super_klass = super(); 855 if (super_klass != nullptr) { 856 if (super_klass->is_interface()) { // check if super class is an interface 857 ResourceMark rm(THREAD); 858 Exceptions::fthrow( 859 THREAD_AND_LOCATION, 860 vmSymbols::java_lang_IncompatibleClassChangeError(), 861 "class %s has interface %s as super class", 862 external_name(), 863 super_klass->external_name() 864 ); 865 return false; 866 } 867 868 InstanceKlass* ik_super = InstanceKlass::cast(super_klass); 869 ik_super->link_class_impl(CHECK_false); 870 } 871 872 // link all interfaces implemented by this class before linking this class 873 Array<InstanceKlass*>* interfaces = local_interfaces(); 874 int num_interfaces = interfaces->length(); 875 for (int index = 0; index < num_interfaces; index++) { 876 InstanceKlass* interk = interfaces->at(index); 877 interk->link_class_impl(CHECK_false); 878 } 879 880 // in case the class is linked in the process of linking its superclasses 881 if (is_linked()) { 882 return true; 883 } 884 885 // trace only the link time for this klass that includes 886 // the verification time 887 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(), 888 ClassLoader::perf_class_link_selftime(), 889 ClassLoader::perf_classes_linked(), 890 jt->get_thread_stat()->perf_recursion_counts_addr(), 891 jt->get_thread_stat()->perf_timers_addr(), 892 PerfClassTraceTime::CLASS_LINK); 893 894 // verification & rewriting 895 { 896 LockLinkState init_lock(this, jt); 897 898 // rewritten will have been set if loader constraint error found 899 // on an earlier link attempt 900 // don't verify or rewrite if already rewritten 901 // 902 903 if (!is_linked()) { 904 if (!is_rewritten()) { 905 if (is_shared()) { 906 assert(!verified_at_dump_time(), "must be"); 907 } 908 { 909 bool verify_ok = verify_code(THREAD); 910 if (!verify_ok) { 911 return false; 912 } 913 } 914 915 // Just in case a side-effect of verify linked this class already 916 // (which can sometimes happen since the verifier loads classes 917 // using custom class loaders, which are free to initialize things) 918 if (is_linked()) { 919 return true; 920 } 921 922 // also sets rewritten 923 rewrite_class(CHECK_false); 924 } else if (is_shared()) { 925 SystemDictionaryShared::check_verification_constraints(this, CHECK_false); 926 } 927 928 // relocate jsrs and link methods after they are all rewritten 929 link_methods(CHECK_false); 930 931 // Initialize the vtable and interface table after 932 // methods have been rewritten since rewrite may 933 // fabricate new Method*s. 934 // also does loader constraint checking 935 // 936 // initialize_vtable and initialize_itable need to be rerun 937 // for a shared class if 938 // 1) the class is loaded by custom class loader or 939 // 2) the class is loaded by built-in class loader but failed to add archived loader constraints or 940 // 3) the class was not verified during dump time 941 bool need_init_table = true; 942 if (is_shared() && verified_at_dump_time() && 943 SystemDictionaryShared::check_linking_constraints(THREAD, this)) { 944 need_init_table = false; 945 } 946 if (need_init_table) { 947 vtable().initialize_vtable_and_check_constraints(CHECK_false); 948 itable().initialize_itable_and_check_constraints(CHECK_false); 949 } 950 #ifdef ASSERT 951 vtable().verify(tty, true); 952 // In case itable verification is ever added. 953 // itable().verify(tty, true); 954 #endif 955 set_initialization_state_and_notify(linked, THREAD); 956 if (JvmtiExport::should_post_class_prepare()) { 957 JvmtiExport::post_class_prepare(THREAD, this); 958 } 959 } 960 } 961 return true; 962 } 963 964 // Rewrite the byte codes of all of the methods of a class. 965 // The rewriter must be called exactly once. Rewriting must happen after 966 // verification but before the first method of the class is executed. 967 void InstanceKlass::rewrite_class(TRAPS) { 968 assert(is_loaded(), "must be loaded"); 969 if (is_rewritten()) { 970 assert(is_shared(), "rewriting an unshared class?"); 971 return; 972 } 973 Rewriter::rewrite(this, CHECK); 974 set_rewritten(); 975 } 976 977 // Now relocate and link method entry points after class is rewritten. 978 // This is outside is_rewritten flag. In case of an exception, it can be 979 // executed more than once. 980 void InstanceKlass::link_methods(TRAPS) { 981 int len = methods()->length(); 982 for (int i = len-1; i >= 0; i--) { 983 methodHandle m(THREAD, methods()->at(i)); 984 985 // Set up method entry points for compiler and interpreter . 986 m->link_method(m, CHECK); 987 } 988 } 989 990 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access) 991 void InstanceKlass::initialize_super_interfaces(TRAPS) { 992 assert (has_nonstatic_concrete_methods(), "caller should have checked this"); 993 for (int i = 0; i < local_interfaces()->length(); ++i) { 994 InstanceKlass* ik = local_interfaces()->at(i); 995 996 // Initialization is depth first search ie. we start with top of the inheritance tree 997 // has_nonstatic_concrete_methods drives searching superinterfaces since it 998 // means has_nonstatic_concrete_methods in its superinterface hierarchy 999 if (ik->has_nonstatic_concrete_methods()) { 1000 ik->initialize_super_interfaces(CHECK); 1001 } 1002 1003 // Only initialize() interfaces that "declare" concrete methods. 1004 if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) { 1005 ik->initialize(CHECK); 1006 } 1007 } 1008 } 1009 1010 using InitializationErrorTable = ResourceHashtable<const InstanceKlass*, OopHandle, 107, AnyObj::C_HEAP, mtClass>; 1011 static InitializationErrorTable* _initialization_error_table; 1012 1013 void InstanceKlass::add_initialization_error(JavaThread* current, Handle exception) { 1014 // Create the same exception with a message indicating the thread name, 1015 // and the StackTraceElements. 1016 Handle init_error = java_lang_Throwable::create_initialization_error(current, exception); 1017 ResourceMark rm(current); 1018 if (init_error.is_null()) { 1019 log_trace(class, init)("Unable to create the desired initialization error for class %s", external_name()); 1020 1021 // We failed to create the new exception, most likely due to either out-of-memory or 1022 // a stackoverflow error. If the original exception was either of those then we save 1023 // the shared, pre-allocated, stackless, instance of that exception. 1024 if (exception->klass() == vmClasses::StackOverflowError_klass()) { 1025 log_debug(class, init)("Using shared StackOverflowError as initialization error for class %s", external_name()); 1026 init_error = Handle(current, Universe::class_init_stack_overflow_error()); 1027 } else if (exception->klass() == vmClasses::OutOfMemoryError_klass()) { 1028 log_debug(class, init)("Using shared OutOfMemoryError as initialization error for class %s", external_name()); 1029 init_error = Handle(current, Universe::class_init_out_of_memory_error()); 1030 } else { 1031 return; 1032 } 1033 } 1034 1035 MutexLocker ml(current, ClassInitError_lock); 1036 OopHandle elem = OopHandle(Universe::vm_global(), init_error()); 1037 bool created; 1038 if (_initialization_error_table == nullptr) { 1039 _initialization_error_table = new (mtClass) InitializationErrorTable(); 1040 } 1041 _initialization_error_table->put_if_absent(this, elem, &created); 1042 assert(created, "Initialization is single threaded"); 1043 log_trace(class, init)("Initialization error added for class %s", external_name()); 1044 } 1045 1046 oop InstanceKlass::get_initialization_error(JavaThread* current) { 1047 MutexLocker ml(current, ClassInitError_lock); 1048 if (_initialization_error_table == nullptr) { 1049 return nullptr; 1050 } 1051 OopHandle* h = _initialization_error_table->get(this); 1052 return (h != nullptr) ? h->resolve() : nullptr; 1053 } 1054 1055 // Need to remove entries for unloaded classes. 1056 void InstanceKlass::clean_initialization_error_table() { 1057 struct InitErrorTableCleaner { 1058 bool do_entry(const InstanceKlass* ik, OopHandle h) { 1059 if (!ik->is_loader_alive()) { 1060 h.release(Universe::vm_global()); 1061 return true; 1062 } else { 1063 return false; 1064 } 1065 } 1066 }; 1067 1068 assert_locked_or_safepoint(ClassInitError_lock); 1069 InitErrorTableCleaner cleaner; 1070 if (_initialization_error_table != nullptr) { 1071 _initialization_error_table->unlink(&cleaner); 1072 } 1073 } 1074 1075 void InstanceKlass::initialize_impl(TRAPS) { 1076 HandleMark hm(THREAD); 1077 1078 // Make sure klass is linked (verified) before initialization 1079 // A class could already be verified, since it has been reflected upon. 1080 link_class(CHECK); 1081 1082 DTRACE_CLASSINIT_PROBE(required, -1); 1083 1084 bool wait = false; 1085 bool throw_error = false; 1086 1087 JavaThread* jt = THREAD; 1088 1089 bool debug_logging_enabled = log_is_enabled(Debug, class, init); 1090 1091 // refer to the JVM book page 47 for description of steps 1092 // Step 1 1093 { 1094 MonitorLocker ml(jt, _init_monitor); 1095 1096 // Step 2 1097 while (is_being_initialized() && !is_init_thread(jt)) { 1098 if (debug_logging_enabled) { 1099 ResourceMark rm(jt); 1100 log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"", 1101 jt->name(), external_name(), init_thread_name()); 1102 } 1103 1104 wait = true; 1105 jt->set_class_to_be_initialized(this); 1106 ml.wait(); 1107 jt->set_class_to_be_initialized(nullptr); 1108 } 1109 1110 // Step 3 1111 if (is_being_initialized() && is_init_thread(jt)) { 1112 if (debug_logging_enabled) { 1113 ResourceMark rm(jt); 1114 log_debug(class, init)("Thread \"%s\" recursively initializing %s", 1115 jt->name(), external_name()); 1116 } 1117 DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait); 1118 return; 1119 } 1120 1121 // Step 4 1122 if (is_initialized()) { 1123 if (debug_logging_enabled) { 1124 ResourceMark rm(jt); 1125 log_debug(class, init)("Thread \"%s\" found %s already initialized", 1126 jt->name(), external_name()); 1127 } 1128 DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait); 1129 return; 1130 } 1131 1132 // Step 5 1133 if (is_in_error_state()) { 1134 if (debug_logging_enabled) { 1135 ResourceMark rm(jt); 1136 log_debug(class, init)("Thread \"%s\" found %s is in error state", 1137 jt->name(), external_name()); 1138 } 1139 throw_error = true; 1140 } else { 1141 1142 // Step 6 1143 set_init_state(being_initialized); 1144 set_init_thread(jt); 1145 if (debug_logging_enabled) { 1146 ResourceMark rm(jt); 1147 log_debug(class, init)("Thread \"%s\" is initializing %s", 1148 jt->name(), external_name()); 1149 } 1150 } 1151 } 1152 1153 // Throw error outside lock 1154 if (throw_error) { 1155 DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait); 1156 ResourceMark rm(THREAD); 1157 Handle cause(THREAD, get_initialization_error(THREAD)); 1158 1159 stringStream ss; 1160 ss.print("Could not initialize class %s", external_name()); 1161 if (cause.is_null()) { 1162 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string()); 1163 } else { 1164 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(), 1165 ss.as_string(), cause); 1166 } 1167 } 1168 1169 // Step 7 1170 // Next, if C is a class rather than an interface, initialize it's super class and super 1171 // interfaces. 1172 if (!is_interface()) { 1173 Klass* super_klass = super(); 1174 if (super_klass != nullptr && super_klass->should_be_initialized()) { 1175 super_klass->initialize(THREAD); 1176 } 1177 // If C implements any interface that declares a non-static, concrete method, 1178 // the initialization of C triggers initialization of its super interfaces. 1179 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and 1180 // having a superinterface that declares, non-static, concrete methods 1181 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) { 1182 initialize_super_interfaces(THREAD); 1183 } 1184 1185 // If any exceptions, complete abruptly, throwing the same exception as above. 1186 if (HAS_PENDING_EXCEPTION) { 1187 Handle e(THREAD, PENDING_EXCEPTION); 1188 CLEAR_PENDING_EXCEPTION; 1189 { 1190 EXCEPTION_MARK; 1191 add_initialization_error(THREAD, e); 1192 // Locks object, set state, and notify all waiting threads 1193 set_initialization_state_and_notify(initialization_error, THREAD); 1194 CLEAR_PENDING_EXCEPTION; 1195 } 1196 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait); 1197 THROW_OOP(e()); 1198 } 1199 } 1200 1201 1202 // Step 8 1203 { 1204 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait); 1205 if (class_initializer() != nullptr) { 1206 // Timer includes any side effects of class initialization (resolution, 1207 // etc), but not recursive entry into call_class_initializer(). 1208 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(), 1209 ClassLoader::perf_class_init_selftime(), 1210 ClassLoader::perf_classes_inited(), 1211 jt->get_thread_stat()->perf_recursion_counts_addr(), 1212 jt->get_thread_stat()->perf_timers_addr(), 1213 PerfClassTraceTime::CLASS_CLINIT); 1214 call_class_initializer(THREAD); 1215 } else { 1216 // The elapsed time is so small it's not worth counting. 1217 if (UsePerfData) { 1218 ClassLoader::perf_classes_inited()->inc(); 1219 } 1220 call_class_initializer(THREAD); 1221 } 1222 } 1223 1224 // Step 9 1225 if (!HAS_PENDING_EXCEPTION) { 1226 set_initialization_state_and_notify(fully_initialized, THREAD); 1227 debug_only(vtable().verify(tty, true);) 1228 } 1229 else { 1230 // Step 10 and 11 1231 Handle e(THREAD, PENDING_EXCEPTION); 1232 CLEAR_PENDING_EXCEPTION; 1233 // JVMTI has already reported the pending exception 1234 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError 1235 JvmtiExport::clear_detected_exception(jt); 1236 { 1237 EXCEPTION_MARK; 1238 add_initialization_error(THREAD, e); 1239 set_initialization_state_and_notify(initialization_error, THREAD); 1240 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below 1241 // JVMTI has already reported the pending exception 1242 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError 1243 JvmtiExport::clear_detected_exception(jt); 1244 } 1245 DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait); 1246 if (e->is_a(vmClasses::Error_klass())) { 1247 THROW_OOP(e()); 1248 } else { 1249 JavaCallArguments args(e); 1250 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(), 1251 vmSymbols::throwable_void_signature(), 1252 &args); 1253 } 1254 } 1255 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait); 1256 } 1257 1258 1259 void InstanceKlass::set_initialization_state_and_notify(ClassState state, JavaThread* current) { 1260 MonitorLocker ml(current, _init_monitor); 1261 1262 if (state == linked && UseVtableBasedCHA && Universe::is_fully_initialized()) { 1263 DeoptimizationScope deopt_scope; 1264 { 1265 // Now mark all code that assumes the class is not linked. 1266 // Set state under the Compile_lock also. 1267 MutexLocker ml(current, Compile_lock); 1268 1269 set_init_thread(nullptr); // reset _init_thread before changing _init_state 1270 set_init_state(state); 1271 1272 CodeCache::mark_dependents_on(&deopt_scope, this); 1273 } 1274 // Perform the deopt handshake outside Compile_lock. 1275 deopt_scope.deoptimize_marked(); 1276 } else { 1277 set_init_thread(nullptr); // reset _init_thread before changing _init_state 1278 set_init_state(state); 1279 } 1280 ml.notify_all(); 1281 } 1282 1283 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock 1284 // is grabbed, to ensure that the compiler is not using the class hierarchy. 1285 void InstanceKlass::add_to_hierarchy(JavaThread* current) { 1286 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint"); 1287 1288 // In case we are not using CHA based vtables we need to make sure the loaded 1289 // deopt is completed before anyone links this class. 1290 // Linking is done with _init_monitor held, by loading and deopting with it 1291 // held we make sure the deopt is completed before linking. 1292 if (!UseVtableBasedCHA) { 1293 init_monitor()->lock(); 1294 } 1295 1296 DeoptimizationScope deopt_scope; 1297 { 1298 MutexLocker ml(current, Compile_lock); 1299 1300 set_init_state(InstanceKlass::loaded); 1301 // make sure init_state store is already done. 1302 // The compiler reads the hierarchy outside of the Compile_lock. 1303 // Access ordering is used to add to hierarchy. 1304 1305 // Link into hierarchy. 1306 append_to_sibling_list(); // add to superklass/sibling list 1307 process_interfaces(); // handle all "implements" declarations 1308 1309 // Now mark all code that depended on old class hierarchy. 1310 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97) 1311 if (Universe::is_fully_initialized()) { 1312 CodeCache::mark_dependents_on(&deopt_scope, this); 1313 } 1314 } 1315 // Perform the deopt handshake outside Compile_lock. 1316 deopt_scope.deoptimize_marked(); 1317 1318 if (!UseVtableBasedCHA) { 1319 init_monitor()->unlock(); 1320 } 1321 } 1322 1323 InstanceKlass* InstanceKlass::implementor() const { 1324 InstanceKlass* volatile* ik = adr_implementor(); 1325 if (ik == nullptr) { 1326 return nullptr; 1327 } else { 1328 // This load races with inserts, and therefore needs acquire. 1329 InstanceKlass* ikls = Atomic::load_acquire(ik); 1330 if (ikls != nullptr && !ikls->is_loader_alive()) { 1331 return nullptr; // don't return unloaded class 1332 } else { 1333 return ikls; 1334 } 1335 } 1336 } 1337 1338 1339 void InstanceKlass::set_implementor(InstanceKlass* ik) { 1340 assert_locked_or_safepoint(Compile_lock); 1341 assert(is_interface(), "not interface"); 1342 InstanceKlass* volatile* addr = adr_implementor(); 1343 assert(addr != nullptr, "null addr"); 1344 if (addr != nullptr) { 1345 Atomic::release_store(addr, ik); 1346 } 1347 } 1348 1349 int InstanceKlass::nof_implementors() const { 1350 InstanceKlass* ik = implementor(); 1351 if (ik == nullptr) { 1352 return 0; 1353 } else if (ik != this) { 1354 return 1; 1355 } else { 1356 return 2; 1357 } 1358 } 1359 1360 // The embedded _implementor field can only record one implementor. 1361 // When there are more than one implementors, the _implementor field 1362 // is set to the interface Klass* itself. Following are the possible 1363 // values for the _implementor field: 1364 // null - no implementor 1365 // implementor Klass* - one implementor 1366 // self - more than one implementor 1367 // 1368 // The _implementor field only exists for interfaces. 1369 void InstanceKlass::add_implementor(InstanceKlass* ik) { 1370 if (Universe::is_fully_initialized()) { 1371 assert_lock_strong(Compile_lock); 1372 } 1373 assert(is_interface(), "not interface"); 1374 // Filter out my subinterfaces. 1375 // (Note: Interfaces are never on the subklass list.) 1376 if (ik->is_interface()) return; 1377 1378 // Filter out subclasses whose supers already implement me. 1379 // (Note: CHA must walk subclasses of direct implementors 1380 // in order to locate indirect implementors.) 1381 InstanceKlass* super_ik = ik->java_super(); 1382 if (super_ik != nullptr && super_ik->implements_interface(this)) 1383 // We only need to check one immediate superclass, since the 1384 // implements_interface query looks at transitive_interfaces. 1385 // Any supers of the super have the same (or fewer) transitive_interfaces. 1386 return; 1387 1388 InstanceKlass* iklass = implementor(); 1389 if (iklass == nullptr) { 1390 set_implementor(ik); 1391 } else if (iklass != this && iklass != ik) { 1392 // There is already an implementor. Use itself as an indicator of 1393 // more than one implementors. 1394 set_implementor(this); 1395 } 1396 1397 // The implementor also implements the transitive_interfaces 1398 for (int index = 0; index < local_interfaces()->length(); index++) { 1399 local_interfaces()->at(index)->add_implementor(ik); 1400 } 1401 } 1402 1403 void InstanceKlass::init_implementor() { 1404 if (is_interface()) { 1405 set_implementor(nullptr); 1406 } 1407 } 1408 1409 1410 void InstanceKlass::process_interfaces() { 1411 // link this class into the implementors list of every interface it implements 1412 for (int i = local_interfaces()->length() - 1; i >= 0; i--) { 1413 assert(local_interfaces()->at(i)->is_klass(), "must be a klass"); 1414 InstanceKlass* interf = local_interfaces()->at(i); 1415 assert(interf->is_interface(), "expected interface"); 1416 interf->add_implementor(this); 1417 } 1418 } 1419 1420 bool InstanceKlass::can_be_primary_super_slow() const { 1421 if (is_interface()) 1422 return false; 1423 else 1424 return Klass::can_be_primary_super_slow(); 1425 } 1426 1427 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots, 1428 Array<InstanceKlass*>* transitive_interfaces) { 1429 // The secondaries are the implemented interfaces. 1430 // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>, 1431 // (but it's safe to do here because we won't write into _secondary_supers from this point on). 1432 Array<Klass*>* interfaces = (Array<Klass*>*)(address)transitive_interfaces; 1433 int num_secondaries = num_extra_slots + interfaces->length(); 1434 if (num_secondaries == 0) { 1435 // Must share this for correct bootstrapping! 1436 set_secondary_supers(Universe::the_empty_klass_array(), Universe::the_empty_klass_bitmap()); 1437 return nullptr; 1438 } else if (num_extra_slots == 0) { 1439 // The secondary super list is exactly the same as the transitive interfaces, so 1440 // let's use it instead of making a copy. 1441 // Redefine classes has to be careful not to delete this! 1442 if (!UseSecondarySupersTable) { 1443 set_secondary_supers(interfaces); 1444 return nullptr; 1445 } else if (num_extra_slots == 0 && interfaces->length() <= 1) { 1446 // We will reuse the transitive interfaces list if we're certain 1447 // it's in hash order. 1448 uintx bitmap = compute_secondary_supers_bitmap(interfaces); 1449 set_secondary_supers(interfaces, bitmap); 1450 return nullptr; 1451 } 1452 // ... fall through if that didn't work. 1453 } 1454 // Copy transitive interfaces to a temporary growable array to be constructed 1455 // into the secondary super list with extra slots. 1456 GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length()); 1457 for (int i = 0; i < interfaces->length(); i++) { 1458 secondaries->push(interfaces->at(i)); 1459 } 1460 return secondaries; 1461 } 1462 1463 bool InstanceKlass::implements_interface(Klass* k) const { 1464 if (this == k) return true; 1465 assert(k->is_interface(), "should be an interface class"); 1466 for (int i = 0; i < transitive_interfaces()->length(); i++) { 1467 if (transitive_interfaces()->at(i) == k) { 1468 return true; 1469 } 1470 } 1471 return false; 1472 } 1473 1474 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const { 1475 // Verify direct super interface 1476 if (this == k) return true; 1477 assert(k->is_interface(), "should be an interface class"); 1478 for (int i = 0; i < local_interfaces()->length(); i++) { 1479 if (local_interfaces()->at(i) == k) { 1480 return true; 1481 } 1482 } 1483 return false; 1484 } 1485 1486 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) { 1487 check_array_allocation_length(length, arrayOopDesc::max_array_length(T_OBJECT), CHECK_NULL); 1488 size_t size = objArrayOopDesc::object_size(length); 1489 ArrayKlass* ak = array_klass(n, CHECK_NULL); 1490 objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length, 1491 /* do_zero */ true, CHECK_NULL); 1492 return o; 1493 } 1494 1495 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) { 1496 if (TraceFinalizerRegistration) { 1497 tty->print("Registered "); 1498 i->print_value_on(tty); 1499 tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i)); 1500 } 1501 instanceHandle h_i(THREAD, i); 1502 // Pass the handle as argument, JavaCalls::call expects oop as jobjects 1503 JavaValue result(T_VOID); 1504 JavaCallArguments args(h_i); 1505 methodHandle mh(THREAD, Universe::finalizer_register_method()); 1506 JavaCalls::call(&result, mh, &args, CHECK_NULL); 1507 MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);) 1508 return h_i(); 1509 } 1510 1511 instanceOop InstanceKlass::allocate_instance(TRAPS) { 1512 assert(!is_abstract() && !is_interface(), "Should not create this object"); 1513 size_t size = size_helper(); // Query before forming handle. 1514 return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL); 1515 } 1516 1517 instanceOop InstanceKlass::allocate_instance(oop java_class, TRAPS) { 1518 Klass* k = java_lang_Class::as_Klass(java_class); 1519 if (k == nullptr) { 1520 ResourceMark rm(THREAD); 1521 THROW_(vmSymbols::java_lang_InstantiationException(), nullptr); 1522 } 1523 InstanceKlass* ik = cast(k); 1524 ik->check_valid_for_instantiation(false, CHECK_NULL); 1525 ik->initialize(CHECK_NULL); 1526 return ik->allocate_instance(THREAD); 1527 } 1528 1529 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) { 1530 return instanceHandle(THREAD, allocate_instance(THREAD)); 1531 } 1532 1533 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) { 1534 if (is_interface() || is_abstract()) { 1535 ResourceMark rm(THREAD); 1536 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError() 1537 : vmSymbols::java_lang_InstantiationException(), external_name()); 1538 } 1539 if (this == vmClasses::Class_klass()) { 1540 ResourceMark rm(THREAD); 1541 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError() 1542 : vmSymbols::java_lang_IllegalAccessException(), external_name()); 1543 } 1544 } 1545 1546 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) { 1547 // Need load-acquire for lock-free read 1548 if (array_klasses_acquire() == nullptr) { 1549 1550 // Recursively lock array allocation 1551 RecursiveLocker rl(MultiArray_lock, THREAD); 1552 1553 // Check if another thread created the array klass while we were waiting for the lock. 1554 if (array_klasses() == nullptr) { 1555 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL); 1556 // use 'release' to pair with lock-free load 1557 release_set_array_klasses(k); 1558 } 1559 } 1560 1561 // array_klasses() will always be set at this point 1562 ObjArrayKlass* ak = array_klasses(); 1563 assert(ak != nullptr, "should be set"); 1564 return ak->array_klass(n, THREAD); 1565 } 1566 1567 ArrayKlass* InstanceKlass::array_klass_or_null(int n) { 1568 // Need load-acquire for lock-free read 1569 ObjArrayKlass* oak = array_klasses_acquire(); 1570 if (oak == nullptr) { 1571 return nullptr; 1572 } else { 1573 return oak->array_klass_or_null(n); 1574 } 1575 } 1576 1577 ArrayKlass* InstanceKlass::array_klass(TRAPS) { 1578 return array_klass(1, THREAD); 1579 } 1580 1581 ArrayKlass* InstanceKlass::array_klass_or_null() { 1582 return array_klass_or_null(1); 1583 } 1584 1585 static int call_class_initializer_counter = 0; // for debugging 1586 1587 Method* InstanceKlass::class_initializer() const { 1588 Method* clinit = find_method( 1589 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature()); 1590 if (clinit != nullptr && clinit->has_valid_initializer_flags()) { 1591 return clinit; 1592 } 1593 return nullptr; 1594 } 1595 1596 void InstanceKlass::call_class_initializer(TRAPS) { 1597 if (ReplayCompiles && 1598 (ReplaySuppressInitializers == 1 || 1599 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) { 1600 // Hide the existence of the initializer for the purpose of replaying the compile 1601 return; 1602 } 1603 1604 #if INCLUDE_CDS 1605 // This is needed to ensure the consistency of the archived heap objects. 1606 if (has_archived_enum_objs()) { 1607 assert(is_shared(), "must be"); 1608 bool initialized = HeapShared::initialize_enum_klass(this, CHECK); 1609 if (initialized) { 1610 return; 1611 } 1612 } 1613 #endif 1614 1615 methodHandle h_method(THREAD, class_initializer()); 1616 assert(!is_initialized(), "we cannot initialize twice"); 1617 LogTarget(Info, class, init) lt; 1618 if (lt.is_enabled()) { 1619 ResourceMark rm(THREAD); 1620 LogStream ls(lt); 1621 ls.print("%d Initializing ", call_class_initializer_counter++); 1622 name()->print_value_on(&ls); 1623 ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"", 1624 h_method() == nullptr ? "(no method)" : "", p2i(this), 1625 THREAD->name()); 1626 } 1627 if (h_method() != nullptr) { 1628 JavaCallArguments args; // No arguments 1629 JavaValue result(T_VOID); 1630 JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args) 1631 } 1632 } 1633 1634 1635 void InstanceKlass::mask_for(const methodHandle& method, int bci, 1636 InterpreterOopMap* entry_for) { 1637 // Lazily create the _oop_map_cache at first request. 1638 // Load_acquire is needed to safely get instance published with CAS by another thread. 1639 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache); 1640 if (oop_map_cache == nullptr) { 1641 // Try to install new instance atomically. 1642 oop_map_cache = new OopMapCache(); 1643 OopMapCache* other = Atomic::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache); 1644 if (other != nullptr) { 1645 // Someone else managed to install before us, ditch local copy and use the existing one. 1646 delete oop_map_cache; 1647 oop_map_cache = other; 1648 } 1649 } 1650 // _oop_map_cache is constant after init; lookup below does its own locking. 1651 oop_map_cache->lookup(method, bci, entry_for); 1652 } 1653 1654 bool InstanceKlass::contains_field_offset(int offset) { 1655 fieldDescriptor fd; 1656 return find_field_from_offset(offset, false, &fd); 1657 } 1658 1659 FieldInfo InstanceKlass::field(int index) const { 1660 for (AllFieldStream fs(this); !fs.done(); fs.next()) { 1661 if (fs.index() == index) { 1662 return fs.to_FieldInfo(); 1663 } 1664 } 1665 fatal("Field not found"); 1666 return FieldInfo(); 1667 } 1668 1669 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const { 1670 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1671 Symbol* f_name = fs.name(); 1672 Symbol* f_sig = fs.signature(); 1673 if (f_name == name && f_sig == sig) { 1674 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index()); 1675 return true; 1676 } 1677 } 1678 return false; 1679 } 1680 1681 1682 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const { 1683 const int n = local_interfaces()->length(); 1684 for (int i = 0; i < n; i++) { 1685 Klass* intf1 = local_interfaces()->at(i); 1686 assert(intf1->is_interface(), "just checking type"); 1687 // search for field in current interface 1688 if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) { 1689 assert(fd->is_static(), "interface field must be static"); 1690 return intf1; 1691 } 1692 // search for field in direct superinterfaces 1693 Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd); 1694 if (intf2 != nullptr) return intf2; 1695 } 1696 // otherwise field lookup fails 1697 return nullptr; 1698 } 1699 1700 1701 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const { 1702 // search order according to newest JVM spec (5.4.3.2, p.167). 1703 // 1) search for field in current klass 1704 if (find_local_field(name, sig, fd)) { 1705 return const_cast<InstanceKlass*>(this); 1706 } 1707 // 2) search for field recursively in direct superinterfaces 1708 { Klass* intf = find_interface_field(name, sig, fd); 1709 if (intf != nullptr) return intf; 1710 } 1711 // 3) apply field lookup recursively if superclass exists 1712 { Klass* supr = super(); 1713 if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, fd); 1714 } 1715 // 4) otherwise field lookup fails 1716 return nullptr; 1717 } 1718 1719 1720 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const { 1721 // search order according to newest JVM spec (5.4.3.2, p.167). 1722 // 1) search for field in current klass 1723 if (find_local_field(name, sig, fd)) { 1724 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this); 1725 } 1726 // 2) search for field recursively in direct superinterfaces 1727 if (is_static) { 1728 Klass* intf = find_interface_field(name, sig, fd); 1729 if (intf != nullptr) return intf; 1730 } 1731 // 3) apply field lookup recursively if superclass exists 1732 { Klass* supr = super(); 1733 if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd); 1734 } 1735 // 4) otherwise field lookup fails 1736 return nullptr; 1737 } 1738 1739 1740 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const { 1741 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1742 if (fs.offset() == offset) { 1743 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index()); 1744 if (fd->is_static() == is_static) return true; 1745 } 1746 } 1747 return false; 1748 } 1749 1750 1751 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const { 1752 Klass* klass = const_cast<InstanceKlass*>(this); 1753 while (klass != nullptr) { 1754 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) { 1755 return true; 1756 } 1757 klass = klass->super(); 1758 } 1759 return false; 1760 } 1761 1762 1763 void InstanceKlass::methods_do(void f(Method* method)) { 1764 // Methods aren't stable until they are loaded. This can be read outside 1765 // a lock through the ClassLoaderData for profiling 1766 // Redefined scratch classes are on the list and need to be cleaned 1767 if (!is_loaded() && !is_scratch_class()) { 1768 return; 1769 } 1770 1771 int len = methods()->length(); 1772 for (int index = 0; index < len; index++) { 1773 Method* m = methods()->at(index); 1774 assert(m->is_method(), "must be method"); 1775 f(m); 1776 } 1777 } 1778 1779 1780 void InstanceKlass::do_local_static_fields(FieldClosure* cl) { 1781 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1782 if (fs.access_flags().is_static()) { 1783 fieldDescriptor& fd = fs.field_descriptor(); 1784 cl->do_field(&fd); 1785 } 1786 } 1787 } 1788 1789 1790 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) { 1791 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1792 if (fs.access_flags().is_static()) { 1793 fieldDescriptor& fd = fs.field_descriptor(); 1794 f(&fd, mirror, CHECK); 1795 } 1796 } 1797 } 1798 1799 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) { 1800 InstanceKlass* super = superklass(); 1801 if (super != nullptr) { 1802 super->do_nonstatic_fields(cl); 1803 } 1804 fieldDescriptor fd; 1805 int length = java_fields_count(); 1806 for (int i = 0; i < length; i += 1) { 1807 fd.reinitialize(this, i); 1808 if (!fd.is_static()) { 1809 cl->do_field(&fd); 1810 } 1811 } 1812 } 1813 1814 // first in Pair is offset, second is index. 1815 static int compare_fields_by_offset(Pair<int,int>* a, Pair<int,int>* b) { 1816 return a->first - b->first; 1817 } 1818 1819 void InstanceKlass::print_nonstatic_fields(FieldClosure* cl) { 1820 InstanceKlass* super = superklass(); 1821 if (super != nullptr) { 1822 super->print_nonstatic_fields(cl); 1823 } 1824 ResourceMark rm; 1825 fieldDescriptor fd; 1826 // In DebugInfo nonstatic fields are sorted by offset. 1827 GrowableArray<Pair<int,int> > fields_sorted; 1828 int i = 0; 1829 for (AllFieldStream fs(this); !fs.done(); fs.next()) { 1830 if (!fs.access_flags().is_static()) { 1831 fd = fs.field_descriptor(); 1832 Pair<int,int> f(fs.offset(), fs.index()); 1833 fields_sorted.push(f); 1834 i++; 1835 } 1836 } 1837 if (i > 0) { 1838 int length = i; 1839 assert(length == fields_sorted.length(), "duh"); 1840 fields_sorted.sort(compare_fields_by_offset); 1841 for (int i = 0; i < length; i++) { 1842 fd.reinitialize(this, fields_sorted.at(i).second); 1843 assert(!fd.is_static() && fd.offset() == fields_sorted.at(i).first, "only nonstatic fields"); 1844 cl->do_field(&fd); 1845 } 1846 } 1847 } 1848 1849 #ifdef ASSERT 1850 static int linear_search(const Array<Method*>* methods, 1851 const Symbol* name, 1852 const Symbol* signature) { 1853 const int len = methods->length(); 1854 for (int index = 0; index < len; index++) { 1855 const Method* const m = methods->at(index); 1856 assert(m->is_method(), "must be method"); 1857 if (m->signature() == signature && m->name() == name) { 1858 return index; 1859 } 1860 } 1861 return -1; 1862 } 1863 #endif 1864 1865 bool InstanceKlass::_disable_method_binary_search = false; 1866 1867 NOINLINE int linear_search(const Array<Method*>* methods, const Symbol* name) { 1868 int len = methods->length(); 1869 int l = 0; 1870 int h = len - 1; 1871 while (l <= h) { 1872 Method* m = methods->at(l); 1873 if (m->name() == name) { 1874 return l; 1875 } 1876 l++; 1877 } 1878 return -1; 1879 } 1880 1881 inline int InstanceKlass::quick_search(const Array<Method*>* methods, const Symbol* name) { 1882 if (_disable_method_binary_search) { 1883 assert(CDSConfig::is_dumping_dynamic_archive(), "must be"); 1884 // At the final stage of dynamic dumping, the methods array may not be sorted 1885 // by ascending addresses of their names, so we can't use binary search anymore. 1886 // However, methods with the same name are still laid out consecutively inside the 1887 // methods array, so let's look for the first one that matches. 1888 return linear_search(methods, name); 1889 } 1890 1891 int len = methods->length(); 1892 int l = 0; 1893 int h = len - 1; 1894 1895 // methods are sorted by ascending addresses of their names, so do binary search 1896 while (l <= h) { 1897 int mid = (l + h) >> 1; 1898 Method* m = methods->at(mid); 1899 assert(m->is_method(), "must be method"); 1900 int res = m->name()->fast_compare(name); 1901 if (res == 0) { 1902 return mid; 1903 } else if (res < 0) { 1904 l = mid + 1; 1905 } else { 1906 h = mid - 1; 1907 } 1908 } 1909 return -1; 1910 } 1911 1912 // find_method looks up the name/signature in the local methods array 1913 Method* InstanceKlass::find_method(const Symbol* name, 1914 const Symbol* signature) const { 1915 return find_method_impl(name, signature, 1916 OverpassLookupMode::find, 1917 StaticLookupMode::find, 1918 PrivateLookupMode::find); 1919 } 1920 1921 Method* InstanceKlass::find_method_impl(const Symbol* name, 1922 const Symbol* signature, 1923 OverpassLookupMode overpass_mode, 1924 StaticLookupMode static_mode, 1925 PrivateLookupMode private_mode) const { 1926 return InstanceKlass::find_method_impl(methods(), 1927 name, 1928 signature, 1929 overpass_mode, 1930 static_mode, 1931 private_mode); 1932 } 1933 1934 // find_instance_method looks up the name/signature in the local methods array 1935 // and skips over static methods 1936 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods, 1937 const Symbol* name, 1938 const Symbol* signature, 1939 PrivateLookupMode private_mode) { 1940 Method* const meth = InstanceKlass::find_method_impl(methods, 1941 name, 1942 signature, 1943 OverpassLookupMode::find, 1944 StaticLookupMode::skip, 1945 private_mode); 1946 assert(((meth == nullptr) || !meth->is_static()), 1947 "find_instance_method should have skipped statics"); 1948 return meth; 1949 } 1950 1951 // find_instance_method looks up the name/signature in the local methods array 1952 // and skips over static methods 1953 Method* InstanceKlass::find_instance_method(const Symbol* name, 1954 const Symbol* signature, 1955 PrivateLookupMode private_mode) const { 1956 return InstanceKlass::find_instance_method(methods(), name, signature, private_mode); 1957 } 1958 1959 // Find looks up the name/signature in the local methods array 1960 // and filters on the overpass, static and private flags 1961 // This returns the first one found 1962 // note that the local methods array can have up to one overpass, one static 1963 // and one instance (private or not) with the same name/signature 1964 Method* InstanceKlass::find_local_method(const Symbol* name, 1965 const Symbol* signature, 1966 OverpassLookupMode overpass_mode, 1967 StaticLookupMode static_mode, 1968 PrivateLookupMode private_mode) const { 1969 return InstanceKlass::find_method_impl(methods(), 1970 name, 1971 signature, 1972 overpass_mode, 1973 static_mode, 1974 private_mode); 1975 } 1976 1977 // Find looks up the name/signature in the local methods array 1978 // and filters on the overpass, static and private flags 1979 // This returns the first one found 1980 // note that the local methods array can have up to one overpass, one static 1981 // and one instance (private or not) with the same name/signature 1982 Method* InstanceKlass::find_local_method(const Array<Method*>* methods, 1983 const Symbol* name, 1984 const Symbol* signature, 1985 OverpassLookupMode overpass_mode, 1986 StaticLookupMode static_mode, 1987 PrivateLookupMode private_mode) { 1988 return InstanceKlass::find_method_impl(methods, 1989 name, 1990 signature, 1991 overpass_mode, 1992 static_mode, 1993 private_mode); 1994 } 1995 1996 Method* InstanceKlass::find_method(const Array<Method*>* methods, 1997 const Symbol* name, 1998 const Symbol* signature) { 1999 return InstanceKlass::find_method_impl(methods, 2000 name, 2001 signature, 2002 OverpassLookupMode::find, 2003 StaticLookupMode::find, 2004 PrivateLookupMode::find); 2005 } 2006 2007 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods, 2008 const Symbol* name, 2009 const Symbol* signature, 2010 OverpassLookupMode overpass_mode, 2011 StaticLookupMode static_mode, 2012 PrivateLookupMode private_mode) { 2013 int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode); 2014 return hit >= 0 ? methods->at(hit): nullptr; 2015 } 2016 2017 // true if method matches signature and conforms to skipping_X conditions. 2018 static bool method_matches(const Method* m, 2019 const Symbol* signature, 2020 bool skipping_overpass, 2021 bool skipping_static, 2022 bool skipping_private) { 2023 return ((m->signature() == signature) && 2024 (!skipping_overpass || !m->is_overpass()) && 2025 (!skipping_static || !m->is_static()) && 2026 (!skipping_private || !m->is_private())); 2027 } 2028 2029 // Used directly for default_methods to find the index into the 2030 // default_vtable_indices, and indirectly by find_method 2031 // find_method_index looks in the local methods array to return the index 2032 // of the matching name/signature. If, overpass methods are being ignored, 2033 // the search continues to find a potential non-overpass match. This capability 2034 // is important during method resolution to prefer a static method, for example, 2035 // over an overpass method. 2036 // There is the possibility in any _method's array to have the same name/signature 2037 // for a static method, an overpass method and a local instance method 2038 // To correctly catch a given method, the search criteria may need 2039 // to explicitly skip the other two. For local instance methods, it 2040 // is often necessary to skip private methods 2041 int InstanceKlass::find_method_index(const Array<Method*>* methods, 2042 const Symbol* name, 2043 const Symbol* signature, 2044 OverpassLookupMode overpass_mode, 2045 StaticLookupMode static_mode, 2046 PrivateLookupMode private_mode) { 2047 const bool skipping_overpass = (overpass_mode == OverpassLookupMode::skip); 2048 const bool skipping_static = (static_mode == StaticLookupMode::skip); 2049 const bool skipping_private = (private_mode == PrivateLookupMode::skip); 2050 const int hit = quick_search(methods, name); 2051 if (hit != -1) { 2052 const Method* const m = methods->at(hit); 2053 2054 // Do linear search to find matching signature. First, quick check 2055 // for common case, ignoring overpasses if requested. 2056 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) { 2057 return hit; 2058 } 2059 2060 // search downwards through overloaded methods 2061 int i; 2062 for (i = hit - 1; i >= 0; --i) { 2063 const Method* const m = methods->at(i); 2064 assert(m->is_method(), "must be method"); 2065 if (m->name() != name) { 2066 break; 2067 } 2068 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) { 2069 return i; 2070 } 2071 } 2072 // search upwards 2073 for (i = hit + 1; i < methods->length(); ++i) { 2074 const Method* const m = methods->at(i); 2075 assert(m->is_method(), "must be method"); 2076 if (m->name() != name) { 2077 break; 2078 } 2079 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) { 2080 return i; 2081 } 2082 } 2083 // not found 2084 #ifdef ASSERT 2085 const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : 2086 linear_search(methods, name, signature); 2087 assert(-1 == index, "binary search should have found entry %d", index); 2088 #endif 2089 } 2090 return -1; 2091 } 2092 2093 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const { 2094 return find_method_by_name(methods(), name, end); 2095 } 2096 2097 int InstanceKlass::find_method_by_name(const Array<Method*>* methods, 2098 const Symbol* name, 2099 int* end_ptr) { 2100 assert(end_ptr != nullptr, "just checking"); 2101 int start = quick_search(methods, name); 2102 int end = start + 1; 2103 if (start != -1) { 2104 while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start; 2105 while (end < methods->length() && (methods->at(end))->name() == name) ++end; 2106 *end_ptr = end; 2107 return start; 2108 } 2109 return -1; 2110 } 2111 2112 // uncached_lookup_method searches both the local class methods array and all 2113 // superclasses methods arrays, skipping any overpass methods in superclasses, 2114 // and possibly skipping private methods. 2115 Method* InstanceKlass::uncached_lookup_method(const Symbol* name, 2116 const Symbol* signature, 2117 OverpassLookupMode overpass_mode, 2118 PrivateLookupMode private_mode) const { 2119 OverpassLookupMode overpass_local_mode = overpass_mode; 2120 const Klass* klass = this; 2121 while (klass != nullptr) { 2122 Method* const method = InstanceKlass::cast(klass)->find_method_impl(name, 2123 signature, 2124 overpass_local_mode, 2125 StaticLookupMode::find, 2126 private_mode); 2127 if (method != nullptr) { 2128 return method; 2129 } 2130 klass = klass->super(); 2131 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses 2132 } 2133 return nullptr; 2134 } 2135 2136 #ifdef ASSERT 2137 // search through class hierarchy and return true if this class or 2138 // one of the superclasses was redefined 2139 bool InstanceKlass::has_redefined_this_or_super() const { 2140 const Klass* klass = this; 2141 while (klass != nullptr) { 2142 if (InstanceKlass::cast(klass)->has_been_redefined()) { 2143 return true; 2144 } 2145 klass = klass->super(); 2146 } 2147 return false; 2148 } 2149 #endif 2150 2151 // lookup a method in the default methods list then in all transitive interfaces 2152 // Do NOT return private or static methods 2153 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name, 2154 Symbol* signature) const { 2155 Method* m = nullptr; 2156 if (default_methods() != nullptr) { 2157 m = find_method(default_methods(), name, signature); 2158 } 2159 // Look up interfaces 2160 if (m == nullptr) { 2161 m = lookup_method_in_all_interfaces(name, signature, DefaultsLookupMode::find); 2162 } 2163 return m; 2164 } 2165 2166 // lookup a method in all the interfaces that this class implements 2167 // Do NOT return private or static methods, new in JDK8 which are not externally visible 2168 // They should only be found in the initial InterfaceMethodRef 2169 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name, 2170 Symbol* signature, 2171 DefaultsLookupMode defaults_mode) const { 2172 Array<InstanceKlass*>* all_ifs = transitive_interfaces(); 2173 int num_ifs = all_ifs->length(); 2174 InstanceKlass *ik = nullptr; 2175 for (int i = 0; i < num_ifs; i++) { 2176 ik = all_ifs->at(i); 2177 Method* m = ik->lookup_method(name, signature); 2178 if (m != nullptr && m->is_public() && !m->is_static() && 2179 ((defaults_mode != DefaultsLookupMode::skip) || !m->is_default_method())) { 2180 return m; 2181 } 2182 } 2183 return nullptr; 2184 } 2185 2186 PrintClassClosure::PrintClassClosure(outputStream* st, bool verbose) 2187 :_st(st), _verbose(verbose) { 2188 ResourceMark rm; 2189 _st->print("%-18s ", "KlassAddr"); 2190 _st->print("%-4s ", "Size"); 2191 _st->print("%-20s ", "State"); 2192 _st->print("%-7s ", "Flags"); 2193 _st->print("%-5s ", "ClassName"); 2194 _st->cr(); 2195 } 2196 2197 void PrintClassClosure::do_klass(Klass* k) { 2198 ResourceMark rm; 2199 // klass pointer 2200 _st->print(PTR_FORMAT " ", p2i(k)); 2201 // klass size 2202 _st->print("%4d ", k->size()); 2203 // initialization state 2204 if (k->is_instance_klass()) { 2205 _st->print("%-20s ",InstanceKlass::cast(k)->init_state_name()); 2206 } else { 2207 _st->print("%-20s ",""); 2208 } 2209 // misc flags(Changes should synced with ClassesDCmd::ClassesDCmd help doc) 2210 char buf[10]; 2211 int i = 0; 2212 if (k->has_finalizer()) buf[i++] = 'F'; 2213 if (k->is_instance_klass()) { 2214 InstanceKlass* ik = InstanceKlass::cast(k); 2215 if (ik->has_final_method()) buf[i++] = 'f'; 2216 if (ik->is_rewritten()) buf[i++] = 'W'; 2217 if (ik->is_contended()) buf[i++] = 'C'; 2218 if (ik->has_been_redefined()) buf[i++] = 'R'; 2219 if (ik->is_shared()) buf[i++] = 'S'; 2220 } 2221 buf[i++] = '\0'; 2222 _st->print("%-7s ", buf); 2223 // klass name 2224 _st->print("%-5s ", k->external_name()); 2225 // end 2226 _st->cr(); 2227 if (_verbose) { 2228 k->print_on(_st); 2229 } 2230 } 2231 2232 /* jni_id_for for jfieldIds only */ 2233 JNIid* InstanceKlass::jni_id_for(int offset) { 2234 MutexLocker ml(JfieldIdCreation_lock); 2235 JNIid* probe = jni_ids() == nullptr ? nullptr : jni_ids()->find(offset); 2236 if (probe == nullptr) { 2237 // Allocate new static field identifier 2238 probe = new JNIid(this, offset, jni_ids()); 2239 set_jni_ids(probe); 2240 } 2241 return probe; 2242 } 2243 2244 u2 InstanceKlass::enclosing_method_data(int offset) const { 2245 const Array<jushort>* const inner_class_list = inner_classes(); 2246 if (inner_class_list == nullptr) { 2247 return 0; 2248 } 2249 const int length = inner_class_list->length(); 2250 if (length % inner_class_next_offset == 0) { 2251 return 0; 2252 } 2253 const int index = length - enclosing_method_attribute_size; 2254 assert(offset < enclosing_method_attribute_size, "invalid offset"); 2255 return inner_class_list->at(index + offset); 2256 } 2257 2258 void InstanceKlass::set_enclosing_method_indices(u2 class_index, 2259 u2 method_index) { 2260 Array<jushort>* inner_class_list = inner_classes(); 2261 assert (inner_class_list != nullptr, "_inner_classes list is not set up"); 2262 int length = inner_class_list->length(); 2263 if (length % inner_class_next_offset == enclosing_method_attribute_size) { 2264 int index = length - enclosing_method_attribute_size; 2265 inner_class_list->at_put( 2266 index + enclosing_method_class_index_offset, class_index); 2267 inner_class_list->at_put( 2268 index + enclosing_method_method_index_offset, method_index); 2269 } 2270 } 2271 2272 jmethodID InstanceKlass::update_jmethod_id(jmethodID* jmeths, Method* method, int idnum) { 2273 if (method->is_old() && !method->is_obsolete()) { 2274 // If the method passed in is old (but not obsolete), use the current version. 2275 method = method_with_idnum((int)idnum); 2276 assert(method != nullptr, "old and but not obsolete, so should exist"); 2277 } 2278 jmethodID new_id = Method::make_jmethod_id(class_loader_data(), method); 2279 Atomic::release_store(&jmeths[idnum + 1], new_id); 2280 return new_id; 2281 } 2282 2283 // Lookup or create a jmethodID. 2284 // This code is called by the VMThread and JavaThreads so the 2285 // locking has to be done very carefully to avoid deadlocks 2286 // and/or other cache consistency problems. 2287 // 2288 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) { 2289 Method* method = method_h(); 2290 int idnum = method->method_idnum(); 2291 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2292 2293 // We use a double-check locking idiom here because this cache is 2294 // performance sensitive. In the normal system, this cache only 2295 // transitions from null to non-null which is safe because we use 2296 // release_set_methods_jmethod_ids() to advertise the new cache. 2297 // A partially constructed cache should never be seen by a racing 2298 // thread. We also use release_store() to save a new jmethodID 2299 // in the cache so a partially constructed jmethodID should never be 2300 // seen either. Cache reads of existing jmethodIDs proceed without a 2301 // lock, but cache writes of a new jmethodID requires uniqueness and 2302 // creation of the cache itself requires no leaks so a lock is 2303 // acquired in those two cases. 2304 // 2305 // If the RedefineClasses() API has been used, then this cache grows 2306 // in the redefinition safepoint. 2307 2308 if (jmeths == nullptr) { 2309 MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag); 2310 jmeths = methods_jmethod_ids_acquire(); 2311 // Still null? 2312 if (jmeths == nullptr) { 2313 size_t size = idnum_allocated_count(); 2314 assert(size > (size_t)idnum, "should already have space"); 2315 jmeths = NEW_C_HEAP_ARRAY(jmethodID, size + 1, mtClass); 2316 memset(jmeths, 0, (size + 1) * sizeof(jmethodID)); 2317 // cache size is stored in element[0], other elements offset by one 2318 jmeths[0] = (jmethodID)size; 2319 jmethodID new_id = update_jmethod_id(jmeths, method, idnum); 2320 2321 // publish jmeths 2322 release_set_methods_jmethod_ids(jmeths); 2323 return new_id; 2324 } 2325 } 2326 2327 jmethodID id = Atomic::load_acquire(&jmeths[idnum + 1]); 2328 if (id == nullptr) { 2329 MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag); 2330 id = jmeths[idnum + 1]; 2331 // Still null? 2332 if (id == nullptr) { 2333 return update_jmethod_id(jmeths, method, idnum); 2334 } 2335 } 2336 return id; 2337 } 2338 2339 void InstanceKlass::update_methods_jmethod_cache() { 2340 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 2341 jmethodID* cache = _methods_jmethod_ids; 2342 if (cache != nullptr) { 2343 size_t size = idnum_allocated_count(); 2344 size_t old_size = (size_t)cache[0]; 2345 if (old_size < size + 1) { 2346 // Allocate a larger one and copy entries to the new one. 2347 // They've already been updated to point to new methods where applicable (i.e., not obsolete). 2348 jmethodID* new_cache = NEW_C_HEAP_ARRAY(jmethodID, size + 1, mtClass); 2349 memset(new_cache, 0, (size + 1) * sizeof(jmethodID)); 2350 // The cache size is stored in element[0]; the other elements are offset by one. 2351 new_cache[0] = (jmethodID)size; 2352 2353 for (int i = 1; i <= (int)old_size; i++) { 2354 new_cache[i] = cache[i]; 2355 } 2356 _methods_jmethod_ids = new_cache; 2357 FREE_C_HEAP_ARRAY(jmethodID, cache); 2358 } 2359 } 2360 } 2361 2362 // Figure out how many jmethodIDs haven't been allocated, and make 2363 // sure space for them is pre-allocated. This makes getting all 2364 // method ids much, much faster with classes with more than 8 2365 // methods, and has a *substantial* effect on performance with jvmti 2366 // code that loads all jmethodIDs for all classes. 2367 void InstanceKlass::ensure_space_for_methodids(int start_offset) { 2368 int new_jmeths = 0; 2369 int length = methods()->length(); 2370 for (int index = start_offset; index < length; index++) { 2371 Method* m = methods()->at(index); 2372 jmethodID id = m->find_jmethod_id_or_null(); 2373 if (id == nullptr) { 2374 new_jmeths++; 2375 } 2376 } 2377 if (new_jmeths != 0) { 2378 Method::ensure_jmethod_ids(class_loader_data(), new_jmeths); 2379 } 2380 } 2381 2382 // Lookup a jmethodID, null if not found. Do no blocking, no allocations, no handles 2383 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) { 2384 int idnum = method->method_idnum(); 2385 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2386 return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr; 2387 } 2388 2389 inline DependencyContext InstanceKlass::dependencies() { 2390 DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned); 2391 return dep_context; 2392 } 2393 2394 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) { 2395 dependencies().mark_dependent_nmethods(deopt_scope, changes); 2396 } 2397 2398 void InstanceKlass::add_dependent_nmethod(nmethod* nm) { 2399 dependencies().add_dependent_nmethod(nm); 2400 } 2401 2402 void InstanceKlass::clean_dependency_context() { 2403 dependencies().clean_unloading_dependents(); 2404 } 2405 2406 #ifndef PRODUCT 2407 void InstanceKlass::print_dependent_nmethods(bool verbose) { 2408 dependencies().print_dependent_nmethods(verbose); 2409 } 2410 2411 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) { 2412 return dependencies().is_dependent_nmethod(nm); 2413 } 2414 #endif //PRODUCT 2415 2416 void InstanceKlass::clean_weak_instanceklass_links() { 2417 clean_implementors_list(); 2418 clean_method_data(); 2419 } 2420 2421 void InstanceKlass::clean_implementors_list() { 2422 assert(is_loader_alive(), "this klass should be live"); 2423 if (is_interface()) { 2424 assert (ClassUnloading, "only called for ClassUnloading"); 2425 for (;;) { 2426 // Use load_acquire due to competing with inserts 2427 InstanceKlass* volatile* iklass = adr_implementor(); 2428 assert(iklass != nullptr, "Klass must not be null"); 2429 InstanceKlass* impl = Atomic::load_acquire(iklass); 2430 if (impl != nullptr && !impl->is_loader_alive()) { 2431 // null this field, might be an unloaded instance klass or null 2432 if (Atomic::cmpxchg(iklass, impl, (InstanceKlass*)nullptr) == impl) { 2433 // Successfully unlinking implementor. 2434 if (log_is_enabled(Trace, class, unload)) { 2435 ResourceMark rm; 2436 log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name()); 2437 } 2438 return; 2439 } 2440 } else { 2441 return; 2442 } 2443 } 2444 } 2445 } 2446 2447 void InstanceKlass::clean_method_data() { 2448 for (int m = 0; m < methods()->length(); m++) { 2449 MethodData* mdo = methods()->at(m)->method_data(); 2450 if (mdo != nullptr) { 2451 mdo->clean_method_data(/*always_clean*/false); 2452 } 2453 } 2454 } 2455 2456 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) { 2457 Klass::metaspace_pointers_do(it); 2458 2459 if (log_is_enabled(Trace, cds)) { 2460 ResourceMark rm; 2461 log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name()); 2462 } 2463 2464 it->push(&_annotations); 2465 it->push((Klass**)&_array_klasses); 2466 if (!is_rewritten()) { 2467 it->push(&_constants, MetaspaceClosure::_writable); 2468 } else { 2469 it->push(&_constants); 2470 } 2471 it->push(&_inner_classes); 2472 #if INCLUDE_JVMTI 2473 it->push(&_previous_versions); 2474 #endif 2475 #if INCLUDE_CDS 2476 // For "old" classes with methods containing the jsr bytecode, the _methods array will 2477 // be rewritten during runtime (see Rewriter::rewrite_jsrs()). So setting the _methods to 2478 // be writable. The length check on the _methods is necessary because classes which 2479 // don't have any methods share the Universe::_the_empty_method_array which is in the RO region. 2480 if (_methods != nullptr && _methods->length() > 0 && 2481 !can_be_verified_at_dumptime() && methods_contain_jsr_bytecode()) { 2482 // To handle jsr bytecode, new Method* maybe stored into _methods 2483 it->push(&_methods, MetaspaceClosure::_writable); 2484 } else { 2485 #endif 2486 it->push(&_methods); 2487 #if INCLUDE_CDS 2488 } 2489 #endif 2490 it->push(&_default_methods); 2491 it->push(&_local_interfaces); 2492 it->push(&_transitive_interfaces); 2493 it->push(&_method_ordering); 2494 if (!is_rewritten()) { 2495 it->push(&_default_vtable_indices, MetaspaceClosure::_writable); 2496 } else { 2497 it->push(&_default_vtable_indices); 2498 } 2499 2500 it->push(&_fieldinfo_stream); 2501 // _fields_status might be written into by Rewriter::scan_method() -> fd.set_has_initialized_final_update() 2502 it->push(&_fields_status, MetaspaceClosure::_writable); 2503 2504 if (itable_length() > 0) { 2505 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable(); 2506 int method_table_offset_in_words = ioe->offset()/wordSize; 2507 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this); 2508 2509 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words) 2510 / itableOffsetEntry::size(); 2511 2512 for (int i = 0; i < nof_interfaces; i ++, ioe ++) { 2513 if (ioe->interface_klass() != nullptr) { 2514 it->push(ioe->interface_klass_addr()); 2515 itableMethodEntry* ime = ioe->first_method_entry(this); 2516 int n = klassItable::method_count_for_interface(ioe->interface_klass()); 2517 for (int index = 0; index < n; index ++) { 2518 it->push(ime[index].method_addr()); 2519 } 2520 } 2521 } 2522 } 2523 2524 it->push(&_nest_members); 2525 it->push(&_permitted_subclasses); 2526 it->push(&_record_components); 2527 } 2528 2529 #if INCLUDE_CDS 2530 void InstanceKlass::remove_unshareable_info() { 2531 2532 if (is_linked()) { 2533 assert(can_be_verified_at_dumptime(), "must be"); 2534 // Remember this so we can avoid walking the hierarchy at runtime. 2535 set_verified_at_dump_time(); 2536 } 2537 2538 Klass::remove_unshareable_info(); 2539 2540 if (SystemDictionaryShared::has_class_failed_verification(this)) { 2541 // Classes are attempted to link during dumping and may fail, 2542 // but these classes are still in the dictionary and class list in CLD. 2543 // If the class has failed verification, there is nothing else to remove. 2544 return; 2545 } 2546 2547 // Reset to the 'allocated' state to prevent any premature accessing to 2548 // a shared class at runtime while the class is still being loaded and 2549 // restored. A class' init_state is set to 'loaded' at runtime when it's 2550 // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()). 2551 _init_state = allocated; 2552 2553 { // Otherwise this needs to take out the Compile_lock. 2554 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 2555 init_implementor(); 2556 } 2557 2558 constants()->remove_unshareable_info(); 2559 2560 for (int i = 0; i < methods()->length(); i++) { 2561 Method* m = methods()->at(i); 2562 m->remove_unshareable_info(); 2563 } 2564 2565 // do array classes also. 2566 if (array_klasses() != nullptr) { 2567 array_klasses()->remove_unshareable_info(); 2568 } 2569 2570 // These are not allocated from metaspace. They are safe to set to null. 2571 _source_debug_extension = nullptr; 2572 _dep_context = nullptr; 2573 _osr_nmethods_head = nullptr; 2574 #if INCLUDE_JVMTI 2575 _breakpoints = nullptr; 2576 _previous_versions = nullptr; 2577 _cached_class_file = nullptr; 2578 _jvmti_cached_class_field_map = nullptr; 2579 #endif 2580 2581 _init_thread = nullptr; 2582 _methods_jmethod_ids = nullptr; 2583 _jni_ids = nullptr; 2584 _oop_map_cache = nullptr; 2585 // clear _nest_host to ensure re-load at runtime 2586 _nest_host = nullptr; 2587 init_shared_package_entry(); 2588 _dep_context_last_cleaned = 0; 2589 _init_monitor = nullptr; 2590 2591 remove_unshareable_flags(); 2592 } 2593 2594 void InstanceKlass::remove_unshareable_flags() { 2595 // clear all the flags/stats that shouldn't be in the archived version 2596 assert(!is_scratch_class(), "must be"); 2597 assert(!has_been_redefined(), "must be"); 2598 #if INCLUDE_JVMTI 2599 set_is_being_redefined(false); 2600 #endif 2601 set_has_resolved_methods(false); 2602 } 2603 2604 void InstanceKlass::remove_java_mirror() { 2605 Klass::remove_java_mirror(); 2606 2607 // do array classes also. 2608 if (array_klasses() != nullptr) { 2609 array_klasses()->remove_java_mirror(); 2610 } 2611 } 2612 2613 void InstanceKlass::init_shared_package_entry() { 2614 assert(CDSConfig::is_dumping_archive(), "must be"); 2615 #if !INCLUDE_CDS_JAVA_HEAP 2616 _package_entry = nullptr; 2617 #else 2618 if (CDSConfig::is_dumping_full_module_graph()) { 2619 if (is_shared_unregistered_class()) { 2620 _package_entry = nullptr; 2621 } else { 2622 _package_entry = PackageEntry::get_archived_entry(_package_entry); 2623 } 2624 } else if (CDSConfig::is_dumping_dynamic_archive() && 2625 CDSConfig::is_using_full_module_graph() && 2626 MetaspaceShared::is_in_shared_metaspace(_package_entry)) { 2627 // _package_entry is an archived package in the base archive. Leave it as is. 2628 } else { 2629 _package_entry = nullptr; 2630 } 2631 ArchivePtrMarker::mark_pointer((address**)&_package_entry); 2632 #endif 2633 } 2634 2635 void InstanceKlass::compute_has_loops_flag_for_methods() { 2636 Array<Method*>* methods = this->methods(); 2637 for (int index = 0; index < methods->length(); ++index) { 2638 Method* m = methods->at(index); 2639 if (!m->is_overpass()) { // work around JDK-8305771 2640 m->compute_has_loops_flag(); 2641 } 2642 } 2643 } 2644 2645 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, 2646 PackageEntry* pkg_entry, TRAPS) { 2647 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded 2648 // before the InstanceKlass is added to the SystemDictionary. Make 2649 // sure the current state is <loaded. 2650 assert(!is_loaded(), "invalid init state"); 2651 assert(!shared_loading_failed(), "Must not try to load failed class again"); 2652 set_package(loader_data, pkg_entry, CHECK); 2653 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK); 2654 2655 Array<Method*>* methods = this->methods(); 2656 int num_methods = methods->length(); 2657 for (int index = 0; index < num_methods; ++index) { 2658 methods->at(index)->restore_unshareable_info(CHECK); 2659 } 2660 #if INCLUDE_JVMTI 2661 if (JvmtiExport::has_redefined_a_class()) { 2662 // Reinitialize vtable because RedefineClasses may have changed some 2663 // entries in this vtable for super classes so the CDS vtable might 2664 // point to old or obsolete entries. RedefineClasses doesn't fix up 2665 // vtables in the shared system dictionary, only the main one. 2666 // It also redefines the itable too so fix that too. 2667 // First fix any default methods that point to a super class that may 2668 // have been redefined. 2669 bool trace_name_printed = false; 2670 adjust_default_methods(&trace_name_printed); 2671 vtable().initialize_vtable(); 2672 itable().initialize_itable(); 2673 } 2674 #endif 2675 2676 // restore constant pool resolved references 2677 constants()->restore_unshareable_info(CHECK); 2678 2679 if (array_klasses() != nullptr) { 2680 // To get a consistent list of classes we need MultiArray_lock to ensure 2681 // array classes aren't observed while they are being restored. 2682 RecursiveLocker rl(MultiArray_lock, THREAD); 2683 assert(this == array_klasses()->bottom_klass(), "sanity"); 2684 // Array classes have null protection domain. 2685 // --> see ArrayKlass::complete_create_array_klass() 2686 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK); 2687 } 2688 2689 // Initialize @ValueBased class annotation 2690 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) { 2691 set_is_value_based(); 2692 } 2693 2694 // restore the monitor 2695 _init_monitor = create_init_monitor("InstanceKlassInitMonitorRestored_lock"); 2696 } 2697 2698 // Check if a class or any of its supertypes has a version older than 50. 2699 // CDS will not perform verification of old classes during dump time because 2700 // without changing the old verifier, the verification constraint cannot be 2701 // retrieved during dump time. 2702 // Verification of archived old classes will be performed during run time. 2703 bool InstanceKlass::can_be_verified_at_dumptime() const { 2704 if (MetaspaceShared::is_in_shared_metaspace(this)) { 2705 // This is a class that was dumped into the base archive, so we know 2706 // it was verified at dump time. 2707 return true; 2708 } 2709 if (major_version() < 50 /*JAVA_6_VERSION*/) { 2710 return false; 2711 } 2712 if (java_super() != nullptr && !java_super()->can_be_verified_at_dumptime()) { 2713 return false; 2714 } 2715 Array<InstanceKlass*>* interfaces = local_interfaces(); 2716 int len = interfaces->length(); 2717 for (int i = 0; i < len; i++) { 2718 if (!interfaces->at(i)->can_be_verified_at_dumptime()) { 2719 return false; 2720 } 2721 } 2722 return true; 2723 } 2724 2725 bool InstanceKlass::methods_contain_jsr_bytecode() const { 2726 Thread* thread = Thread::current(); 2727 for (int i = 0; i < _methods->length(); i++) { 2728 methodHandle m(thread, _methods->at(i)); 2729 BytecodeStream bcs(m); 2730 while (!bcs.is_last_bytecode()) { 2731 Bytecodes::Code opcode = bcs.next(); 2732 if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) { 2733 return true; 2734 } 2735 } 2736 } 2737 return false; 2738 } 2739 #endif // INCLUDE_CDS 2740 2741 #if INCLUDE_JVMTI 2742 static void clear_all_breakpoints(Method* m) { 2743 m->clear_all_breakpoints(); 2744 } 2745 #endif 2746 2747 void InstanceKlass::unload_class(InstanceKlass* ik) { 2748 // Release dependencies. 2749 ik->dependencies().remove_all_dependents(); 2750 2751 // notify the debugger 2752 if (JvmtiExport::should_post_class_unload()) { 2753 JvmtiExport::post_class_unload(ik); 2754 } 2755 2756 // notify ClassLoadingService of class unload 2757 ClassLoadingService::notify_class_unloaded(ik); 2758 2759 SystemDictionaryShared::handle_class_unloading(ik); 2760 2761 if (log_is_enabled(Info, class, unload)) { 2762 ResourceMark rm; 2763 log_info(class, unload)("unloading class %s " PTR_FORMAT, ik->external_name(), p2i(ik)); 2764 } 2765 2766 Events::log_class_unloading(Thread::current(), ik); 2767 2768 #if INCLUDE_JFR 2769 assert(ik != nullptr, "invariant"); 2770 EventClassUnload event; 2771 event.set_unloadedClass(ik); 2772 event.set_definingClassLoader(ik->class_loader_data()); 2773 event.commit(); 2774 #endif 2775 } 2776 2777 static void method_release_C_heap_structures(Method* m) { 2778 m->release_C_heap_structures(); 2779 } 2780 2781 // Called also by InstanceKlass::deallocate_contents, with false for release_sub_metadata. 2782 void InstanceKlass::release_C_heap_structures(bool release_sub_metadata) { 2783 // Clean up C heap 2784 Klass::release_C_heap_structures(); 2785 2786 // Deallocate and call destructors for MDO mutexes 2787 if (release_sub_metadata) { 2788 methods_do(method_release_C_heap_structures); 2789 } 2790 2791 // Destroy the init_monitor 2792 delete _init_monitor; 2793 2794 // Deallocate oop map cache 2795 if (_oop_map_cache != nullptr) { 2796 delete _oop_map_cache; 2797 _oop_map_cache = nullptr; 2798 } 2799 2800 // Deallocate JNI identifiers for jfieldIDs 2801 JNIid::deallocate(jni_ids()); 2802 set_jni_ids(nullptr); 2803 2804 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2805 if (jmeths != nullptr) { 2806 release_set_methods_jmethod_ids(nullptr); 2807 FreeHeap(jmeths); 2808 } 2809 2810 assert(_dep_context == nullptr, 2811 "dependencies should already be cleaned"); 2812 2813 #if INCLUDE_JVMTI 2814 // Deallocate breakpoint records 2815 if (breakpoints() != 0x0) { 2816 methods_do(clear_all_breakpoints); 2817 assert(breakpoints() == 0x0, "should have cleared breakpoints"); 2818 } 2819 2820 // deallocate the cached class file 2821 if (_cached_class_file != nullptr) { 2822 os::free(_cached_class_file); 2823 _cached_class_file = nullptr; 2824 } 2825 #endif 2826 2827 FREE_C_HEAP_ARRAY(char, _source_debug_extension); 2828 2829 if (release_sub_metadata) { 2830 constants()->release_C_heap_structures(); 2831 } 2832 } 2833 2834 // The constant pool is on stack if any of the methods are executing or 2835 // referenced by handles. 2836 bool InstanceKlass::on_stack() const { 2837 return _constants->on_stack(); 2838 } 2839 2840 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); } 2841 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); } 2842 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); } 2843 2844 // minor and major version numbers of class file 2845 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); } 2846 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); } 2847 u2 InstanceKlass::major_version() const { return _constants->major_version(); } 2848 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); } 2849 2850 InstanceKlass* InstanceKlass::get_klass_version(int version) { 2851 for (InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) { 2852 if (ik->constants()->version() == version) { 2853 return ik; 2854 } 2855 } 2856 return nullptr; 2857 } 2858 2859 void InstanceKlass::set_source_debug_extension(const char* array, int length) { 2860 if (array == nullptr) { 2861 _source_debug_extension = nullptr; 2862 } else { 2863 // Adding one to the attribute length in order to store a null terminator 2864 // character could cause an overflow because the attribute length is 2865 // already coded with an u4 in the classfile, but in practice, it's 2866 // unlikely to happen. 2867 assert((length+1) > length, "Overflow checking"); 2868 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass); 2869 for (int i = 0; i < length; i++) { 2870 sde[i] = array[i]; 2871 } 2872 sde[length] = '\0'; 2873 _source_debug_extension = sde; 2874 } 2875 } 2876 2877 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); } 2878 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); } 2879 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); } 2880 2881 const char* InstanceKlass::signature_name() const { 2882 2883 // Get the internal name as a c string 2884 const char* src = (const char*) (name()->as_C_string()); 2885 const int src_length = (int)strlen(src); 2886 2887 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3); 2888 2889 // Add L as type indicator 2890 int dest_index = 0; 2891 dest[dest_index++] = JVM_SIGNATURE_CLASS; 2892 2893 // Add the actual class name 2894 for (int src_index = 0; src_index < src_length; ) { 2895 dest[dest_index++] = src[src_index++]; 2896 } 2897 2898 if (is_hidden()) { // Replace the last '+' with a '.'. 2899 for (int index = (int)src_length; index > 0; index--) { 2900 if (dest[index] == '+') { 2901 dest[index] = JVM_SIGNATURE_DOT; 2902 break; 2903 } 2904 } 2905 } 2906 2907 // Add the semicolon and the null 2908 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS; 2909 dest[dest_index] = '\0'; 2910 return dest; 2911 } 2912 2913 ModuleEntry* InstanceKlass::module() const { 2914 if (is_hidden() && 2915 in_unnamed_package() && 2916 class_loader_data()->has_class_mirror_holder()) { 2917 // For a non-strong hidden class defined to an unnamed package, 2918 // its (class held) CLD will not have an unnamed module created for it. 2919 // Two choices to find the correct ModuleEntry: 2920 // 1. If hidden class is within a nest, use nest host's module 2921 // 2. Find the unnamed module off from the class loader 2922 // For now option #2 is used since a nest host is not set until 2923 // after the instance class is created in jvm_lookup_define_class(). 2924 if (class_loader_data()->is_boot_class_loader_data()) { 2925 return ClassLoaderData::the_null_class_loader_data()->unnamed_module(); 2926 } else { 2927 oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader()); 2928 assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module"); 2929 return java_lang_Module::module_entry(module); 2930 } 2931 } 2932 2933 // Class is in a named package 2934 if (!in_unnamed_package()) { 2935 return _package_entry->module(); 2936 } 2937 2938 // Class is in an unnamed package, return its loader's unnamed module 2939 return class_loader_data()->unnamed_module(); 2940 } 2941 2942 void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) { 2943 2944 // ensure java/ packages only loaded by boot or platform builtin loaders 2945 // not needed for shared class since CDS does not archive prohibited classes. 2946 if (!is_shared()) { 2947 check_prohibited_package(name(), loader_data, CHECK); 2948 } 2949 2950 if (is_shared() && _package_entry != nullptr) { 2951 if (CDSConfig::is_using_full_module_graph() && _package_entry == pkg_entry) { 2952 // we can use the saved package 2953 assert(MetaspaceShared::is_in_shared_metaspace(_package_entry), "must be"); 2954 return; 2955 } else { 2956 _package_entry = nullptr; 2957 } 2958 } 2959 2960 // ClassLoader::package_from_class_name has already incremented the refcount of the symbol 2961 // it returns, so we need to decrement it when the current function exits. 2962 TempNewSymbol from_class_name = 2963 (pkg_entry != nullptr) ? nullptr : ClassLoader::package_from_class_name(name()); 2964 2965 Symbol* pkg_name; 2966 if (pkg_entry != nullptr) { 2967 pkg_name = pkg_entry->name(); 2968 } else { 2969 pkg_name = from_class_name; 2970 } 2971 2972 if (pkg_name != nullptr && loader_data != nullptr) { 2973 2974 // Find in class loader's package entry table. 2975 _package_entry = pkg_entry != nullptr ? pkg_entry : loader_data->packages()->lookup_only(pkg_name); 2976 2977 // If the package name is not found in the loader's package 2978 // entry table, it is an indication that the package has not 2979 // been defined. Consider it defined within the unnamed module. 2980 if (_package_entry == nullptr) { 2981 2982 if (!ModuleEntryTable::javabase_defined()) { 2983 // Before java.base is defined during bootstrapping, define all packages in 2984 // the java.base module. If a non-java.base package is erroneously placed 2985 // in the java.base module it will be caught later when java.base 2986 // is defined by ModuleEntryTable::verify_javabase_packages check. 2987 assert(ModuleEntryTable::javabase_moduleEntry() != nullptr, JAVA_BASE_NAME " module is null"); 2988 _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, ModuleEntryTable::javabase_moduleEntry()); 2989 } else { 2990 assert(loader_data->unnamed_module() != nullptr, "unnamed module is null"); 2991 _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, loader_data->unnamed_module()); 2992 } 2993 2994 // A package should have been successfully created 2995 DEBUG_ONLY(ResourceMark rm(THREAD)); 2996 assert(_package_entry != nullptr, "Package entry for class %s not found, loader %s", 2997 name()->as_C_string(), loader_data->loader_name_and_id()); 2998 } 2999 3000 if (log_is_enabled(Debug, module)) { 3001 ResourceMark rm(THREAD); 3002 ModuleEntry* m = _package_entry->module(); 3003 log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s", 3004 external_name(), 3005 pkg_name->as_C_string(), 3006 loader_data->loader_name_and_id(), 3007 (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE)); 3008 } 3009 } else { 3010 ResourceMark rm(THREAD); 3011 log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s", 3012 external_name(), 3013 (loader_data != nullptr) ? loader_data->loader_name_and_id() : "null", 3014 UNNAMED_MODULE); 3015 } 3016 } 3017 3018 // Function set_classpath_index ensures that for a non-null _package_entry 3019 // of the InstanceKlass, the entry is in the boot loader's package entry table. 3020 // It then sets the classpath_index in the package entry record. 3021 // 3022 // The classpath_index field is used to find the entry on the boot loader class 3023 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a 3024 // in an unnamed module. It is also used to indicate (for all packages whose 3025 // classes are loaded by the boot loader) that at least one of the package's 3026 // classes has been loaded. 3027 void InstanceKlass::set_classpath_index(s2 path_index) { 3028 if (_package_entry != nullptr) { 3029 DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();) 3030 assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same"); 3031 assert(path_index != -1, "Unexpected classpath_index"); 3032 _package_entry->set_classpath_index(path_index); 3033 } 3034 } 3035 3036 // different versions of is_same_class_package 3037 3038 bool InstanceKlass::is_same_class_package(const Klass* class2) const { 3039 oop classloader1 = this->class_loader(); 3040 PackageEntry* classpkg1 = this->package(); 3041 if (class2->is_objArray_klass()) { 3042 class2 = ObjArrayKlass::cast(class2)->bottom_klass(); 3043 } 3044 3045 oop classloader2; 3046 PackageEntry* classpkg2; 3047 if (class2->is_instance_klass()) { 3048 classloader2 = class2->class_loader(); 3049 classpkg2 = class2->package(); 3050 } else { 3051 assert(class2->is_typeArray_klass(), "should be type array"); 3052 classloader2 = nullptr; 3053 classpkg2 = nullptr; 3054 } 3055 3056 // Same package is determined by comparing class loader 3057 // and package entries. Both must be the same. This rule 3058 // applies even to classes that are defined in the unnamed 3059 // package, they still must have the same class loader. 3060 if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) { 3061 return true; 3062 } 3063 3064 return false; 3065 } 3066 3067 // return true if this class and other_class are in the same package. Classloader 3068 // and classname information is enough to determine a class's package 3069 bool InstanceKlass::is_same_class_package(oop other_class_loader, 3070 const Symbol* other_class_name) const { 3071 if (class_loader() != other_class_loader) { 3072 return false; 3073 } 3074 if (name()->fast_compare(other_class_name) == 0) { 3075 return true; 3076 } 3077 3078 { 3079 ResourceMark rm; 3080 3081 bool bad_class_name = false; 3082 TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name); 3083 if (bad_class_name) { 3084 return false; 3085 } 3086 // Check that package_from_class_name() returns null, not "", if there is no package. 3087 assert(other_pkg == nullptr || other_pkg->utf8_length() > 0, "package name is empty string"); 3088 3089 const Symbol* const this_package_name = 3090 this->package() != nullptr ? this->package()->name() : nullptr; 3091 3092 if (this_package_name == nullptr || other_pkg == nullptr) { 3093 // One of the two doesn't have a package. Only return true if the other 3094 // one also doesn't have a package. 3095 return this_package_name == other_pkg; 3096 } 3097 3098 // Check if package is identical 3099 return this_package_name->fast_compare(other_pkg) == 0; 3100 } 3101 } 3102 3103 static bool is_prohibited_package_slow(Symbol* class_name) { 3104 // Caller has ResourceMark 3105 int length; 3106 jchar* unicode = class_name->as_unicode(length); 3107 return (length >= 5 && 3108 unicode[0] == 'j' && 3109 unicode[1] == 'a' && 3110 unicode[2] == 'v' && 3111 unicode[3] == 'a' && 3112 unicode[4] == '/'); 3113 } 3114 3115 // Only boot and platform class loaders can define classes in "java/" packages. 3116 void InstanceKlass::check_prohibited_package(Symbol* class_name, 3117 ClassLoaderData* loader_data, 3118 TRAPS) { 3119 if (!loader_data->is_boot_class_loader_data() && 3120 !loader_data->is_platform_class_loader_data() && 3121 class_name != nullptr && class_name->utf8_length() >= 5) { 3122 ResourceMark rm(THREAD); 3123 bool prohibited; 3124 const u1* base = class_name->base(); 3125 if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) { 3126 prohibited = is_prohibited_package_slow(class_name); 3127 } else { 3128 char* name = class_name->as_C_string(); 3129 prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/'); 3130 } 3131 if (prohibited) { 3132 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name); 3133 assert(pkg_name != nullptr, "Error in parsing package name starting with 'java/'"); 3134 char* name = pkg_name->as_C_string(); 3135 const char* class_loader_name = loader_data->loader_name_and_id(); 3136 StringUtils::replace_no_expand(name, "/", "."); 3137 const char* msg_text1 = "Class loader (instance of): "; 3138 const char* msg_text2 = " tried to load prohibited package name: "; 3139 size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1; 3140 char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len); 3141 jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name); 3142 THROW_MSG(vmSymbols::java_lang_SecurityException(), message); 3143 } 3144 } 3145 return; 3146 } 3147 3148 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const { 3149 constantPoolHandle i_cp(THREAD, constants()); 3150 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) { 3151 int ioff = iter.inner_class_info_index(); 3152 if (ioff != 0) { 3153 // Check to see if the name matches the class we're looking for 3154 // before attempting to find the class. 3155 if (i_cp->klass_name_at_matches(this, ioff)) { 3156 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false); 3157 if (this == inner_klass) { 3158 *ooff = iter.outer_class_info_index(); 3159 *noff = iter.inner_name_index(); 3160 return true; 3161 } 3162 } 3163 } 3164 } 3165 return false; 3166 } 3167 3168 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const { 3169 InstanceKlass* outer_klass = nullptr; 3170 *inner_is_member = false; 3171 int ooff = 0, noff = 0; 3172 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD); 3173 if (has_inner_classes_attr) { 3174 constantPoolHandle i_cp(THREAD, constants()); 3175 if (ooff != 0) { 3176 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL); 3177 if (!ok->is_instance_klass()) { 3178 // If the outer class is not an instance klass then it cannot have 3179 // declared any inner classes. 3180 ResourceMark rm(THREAD); 3181 Exceptions::fthrow( 3182 THREAD_AND_LOCATION, 3183 vmSymbols::java_lang_IncompatibleClassChangeError(), 3184 "%s and %s disagree on InnerClasses attribute", 3185 ok->external_name(), 3186 external_name()); 3187 return nullptr; 3188 } 3189 outer_klass = InstanceKlass::cast(ok); 3190 *inner_is_member = true; 3191 } 3192 if (nullptr == outer_klass) { 3193 // It may be a local class; try for that. 3194 int encl_method_class_idx = enclosing_method_class_index(); 3195 if (encl_method_class_idx != 0) { 3196 Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL); 3197 outer_klass = InstanceKlass::cast(ok); 3198 *inner_is_member = false; 3199 } 3200 } 3201 } 3202 3203 // If no inner class attribute found for this class. 3204 if (nullptr == outer_klass) return nullptr; 3205 3206 // Throws an exception if outer klass has not declared k as an inner klass 3207 // We need evidence that each klass knows about the other, or else 3208 // the system could allow a spoof of an inner class to gain access rights. 3209 Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL); 3210 return outer_klass; 3211 } 3212 3213 jint InstanceKlass::compute_modifier_flags() const { 3214 jint access = access_flags().as_int(); 3215 3216 // But check if it happens to be member class. 3217 InnerClassesIterator iter(this); 3218 for (; !iter.done(); iter.next()) { 3219 int ioff = iter.inner_class_info_index(); 3220 // Inner class attribute can be zero, skip it. 3221 // Strange but true: JVM spec. allows null inner class refs. 3222 if (ioff == 0) continue; 3223 3224 // only look at classes that are already loaded 3225 // since we are looking for the flags for our self. 3226 Symbol* inner_name = constants()->klass_name_at(ioff); 3227 if (name() == inner_name) { 3228 // This is really a member class. 3229 access = iter.inner_access_flags(); 3230 break; 3231 } 3232 } 3233 // Remember to strip ACC_SUPER bit 3234 return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS; 3235 } 3236 3237 jint InstanceKlass::jvmti_class_status() const { 3238 jint result = 0; 3239 3240 if (is_linked()) { 3241 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED; 3242 } 3243 3244 if (is_initialized()) { 3245 assert(is_linked(), "Class status is not consistent"); 3246 result |= JVMTI_CLASS_STATUS_INITIALIZED; 3247 } 3248 if (is_in_error_state()) { 3249 result |= JVMTI_CLASS_STATUS_ERROR; 3250 } 3251 return result; 3252 } 3253 3254 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) { 3255 bool implements_interface; // initialized by method_at_itable_or_null 3256 Method* m = method_at_itable_or_null(holder, index, 3257 implements_interface); // out parameter 3258 if (m != nullptr) { 3259 assert(implements_interface, "sanity"); 3260 return m; 3261 } else if (implements_interface) { 3262 // Throw AbstractMethodError since corresponding itable slot is empty. 3263 THROW_NULL(vmSymbols::java_lang_AbstractMethodError()); 3264 } else { 3265 // If the interface isn't implemented by the receiver class, 3266 // the VM should throw IncompatibleClassChangeError. 3267 ResourceMark rm(THREAD); 3268 stringStream ss; 3269 bool same_module = (module() == holder->module()); 3270 ss.print("Receiver class %s does not implement " 3271 "the interface %s defining the method to be called " 3272 "(%s%s%s)", 3273 external_name(), holder->external_name(), 3274 (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(), 3275 (same_module) ? "" : "; ", 3276 (same_module) ? "" : holder->class_in_module_of_loader()); 3277 THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string()); 3278 } 3279 } 3280 3281 Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) { 3282 klassItable itable(this); 3283 for (int i = 0; i < itable.size_offset_table(); i++) { 3284 itableOffsetEntry* offset_entry = itable.offset_entry(i); 3285 if (offset_entry->interface_klass() == holder) { 3286 implements_interface = true; 3287 itableMethodEntry* ime = offset_entry->first_method_entry(this); 3288 Method* m = ime[index].method(); 3289 return m; 3290 } 3291 } 3292 implements_interface = false; 3293 return nullptr; // offset entry not found 3294 } 3295 3296 int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) { 3297 assert(is_linked(), "required"); 3298 assert(intf_method->method_holder()->is_interface(), "not an interface method"); 3299 assert(is_subtype_of(intf_method->method_holder()), "interface not implemented"); 3300 3301 int vtable_index = Method::invalid_vtable_index; 3302 Symbol* name = intf_method->name(); 3303 Symbol* signature = intf_method->signature(); 3304 3305 // First check in default method array 3306 if (!intf_method->is_abstract() && default_methods() != nullptr) { 3307 int index = find_method_index(default_methods(), 3308 name, signature, 3309 Klass::OverpassLookupMode::find, 3310 Klass::StaticLookupMode::find, 3311 Klass::PrivateLookupMode::find); 3312 if (index >= 0) { 3313 vtable_index = default_vtable_indices()->at(index); 3314 } 3315 } 3316 if (vtable_index == Method::invalid_vtable_index) { 3317 // get vtable_index for miranda methods 3318 klassVtable vt = vtable(); 3319 vtable_index = vt.index_of_miranda(name, signature); 3320 } 3321 return vtable_index; 3322 } 3323 3324 #if INCLUDE_JVMTI 3325 // update default_methods for redefineclasses for methods that are 3326 // not yet in the vtable due to concurrent subclass define and superinterface 3327 // redefinition 3328 // Note: those in the vtable, should have been updated via adjust_method_entries 3329 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) { 3330 // search the default_methods for uses of either obsolete or EMCP methods 3331 if (default_methods() != nullptr) { 3332 for (int index = 0; index < default_methods()->length(); index ++) { 3333 Method* old_method = default_methods()->at(index); 3334 if (old_method == nullptr || !old_method->is_old()) { 3335 continue; // skip uninteresting entries 3336 } 3337 assert(!old_method->is_deleted(), "default methods may not be deleted"); 3338 Method* new_method = old_method->get_new_method(); 3339 default_methods()->at_put(index, new_method); 3340 3341 if (log_is_enabled(Info, redefine, class, update)) { 3342 ResourceMark rm; 3343 if (!(*trace_name_printed)) { 3344 log_info(redefine, class, update) 3345 ("adjust: klassname=%s default methods from name=%s", 3346 external_name(), old_method->method_holder()->external_name()); 3347 *trace_name_printed = true; 3348 } 3349 log_debug(redefine, class, update, vtables) 3350 ("default method update: %s(%s) ", 3351 new_method->name()->as_C_string(), new_method->signature()->as_C_string()); 3352 } 3353 } 3354 } 3355 } 3356 #endif // INCLUDE_JVMTI 3357 3358 // On-stack replacement stuff 3359 void InstanceKlass::add_osr_nmethod(nmethod* n) { 3360 assert_lock_strong(NMethodState_lock); 3361 #ifndef PRODUCT 3362 nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true); 3363 assert(prev == nullptr || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation), 3364 "redundant OSR recompilation detected. memory leak in CodeCache!"); 3365 #endif 3366 // only one compilation can be active 3367 assert(n->is_osr_method(), "wrong kind of nmethod"); 3368 n->set_osr_link(osr_nmethods_head()); 3369 set_osr_nmethods_head(n); 3370 // Raise the highest osr level if necessary 3371 n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level())); 3372 3373 // Get rid of the osr methods for the same bci that have lower levels. 3374 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) { 3375 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true); 3376 if (inv != nullptr && inv->is_in_use()) { 3377 inv->make_not_entrant(); 3378 } 3379 } 3380 } 3381 3382 // Remove osr nmethod from the list. Return true if found and removed. 3383 bool InstanceKlass::remove_osr_nmethod(nmethod* n) { 3384 // This is a short non-blocking critical region, so the no safepoint check is ok. 3385 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3386 assert(n->is_osr_method(), "wrong kind of nmethod"); 3387 nmethod* last = nullptr; 3388 nmethod* cur = osr_nmethods_head(); 3389 int max_level = CompLevel_none; // Find the max comp level excluding n 3390 Method* m = n->method(); 3391 // Search for match 3392 bool found = false; 3393 while(cur != nullptr && cur != n) { 3394 if (m == cur->method()) { 3395 // Find max level before n 3396 max_level = MAX2(max_level, cur->comp_level()); 3397 } 3398 last = cur; 3399 cur = cur->osr_link(); 3400 } 3401 nmethod* next = nullptr; 3402 if (cur == n) { 3403 found = true; 3404 next = cur->osr_link(); 3405 if (last == nullptr) { 3406 // Remove first element 3407 set_osr_nmethods_head(next); 3408 } else { 3409 last->set_osr_link(next); 3410 } 3411 } 3412 n->set_osr_link(nullptr); 3413 cur = next; 3414 while (cur != nullptr) { 3415 // Find max level after n 3416 if (m == cur->method()) { 3417 max_level = MAX2(max_level, cur->comp_level()); 3418 } 3419 cur = cur->osr_link(); 3420 } 3421 m->set_highest_osr_comp_level(max_level); 3422 return found; 3423 } 3424 3425 int InstanceKlass::mark_osr_nmethods(DeoptimizationScope* deopt_scope, const Method* m) { 3426 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3427 nmethod* osr = osr_nmethods_head(); 3428 int found = 0; 3429 while (osr != nullptr) { 3430 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3431 if (osr->method() == m) { 3432 deopt_scope->mark(osr); 3433 found++; 3434 } 3435 osr = osr->osr_link(); 3436 } 3437 return found; 3438 } 3439 3440 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const { 3441 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3442 nmethod* osr = osr_nmethods_head(); 3443 nmethod* best = nullptr; 3444 while (osr != nullptr) { 3445 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3446 // There can be a time when a c1 osr method exists but we are waiting 3447 // for a c2 version. When c2 completes its osr nmethod we will trash 3448 // the c1 version and only be able to find the c2 version. However 3449 // while we overflow in the c1 code at back branches we don't want to 3450 // try and switch to the same code as we are already running 3451 3452 if (osr->method() == m && 3453 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) { 3454 if (match_level) { 3455 if (osr->comp_level() == comp_level) { 3456 // Found a match - return it. 3457 return osr; 3458 } 3459 } else { 3460 if (best == nullptr || (osr->comp_level() > best->comp_level())) { 3461 if (osr->comp_level() == CompilationPolicy::highest_compile_level()) { 3462 // Found the best possible - return it. 3463 return osr; 3464 } 3465 best = osr; 3466 } 3467 } 3468 } 3469 osr = osr->osr_link(); 3470 } 3471 3472 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set"); 3473 if (best != nullptr && best->comp_level() >= comp_level) { 3474 return best; 3475 } 3476 return nullptr; 3477 } 3478 3479 // ----------------------------------------------------------------------------------------------------- 3480 // Printing 3481 3482 #define BULLET " - " 3483 3484 static const char* state_names[] = { 3485 "allocated", "loaded", "being_linked", "linked", "being_initialized", "fully_initialized", "initialization_error" 3486 }; 3487 3488 static void print_vtable(intptr_t* start, int len, outputStream* st) { 3489 for (int i = 0; i < len; i++) { 3490 intptr_t e = start[i]; 3491 st->print("%d : " INTPTR_FORMAT, i, e); 3492 if (MetaspaceObj::is_valid((Metadata*)e)) { 3493 st->print(" "); 3494 ((Metadata*)e)->print_value_on(st); 3495 } 3496 st->cr(); 3497 } 3498 } 3499 3500 static void print_vtable(vtableEntry* start, int len, outputStream* st) { 3501 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st); 3502 } 3503 3504 const char* InstanceKlass::init_state_name() const { 3505 return state_names[init_state()]; 3506 } 3507 3508 void InstanceKlass::print_on(outputStream* st) const { 3509 assert(is_klass(), "must be klass"); 3510 Klass::print_on(st); 3511 3512 st->print(BULLET"instance size: %d", size_helper()); st->cr(); 3513 st->print(BULLET"klass size: %d", size()); st->cr(); 3514 st->print(BULLET"access: "); access_flags().print_on(st); st->cr(); 3515 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr(); 3516 st->print(BULLET"state: "); st->print_cr("%s", init_state_name()); 3517 st->print(BULLET"name: "); name()->print_value_on(st); st->cr(); 3518 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr(); 3519 st->print(BULLET"sub: "); 3520 Klass* sub = subklass(); 3521 int n; 3522 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) { 3523 if (n < MaxSubklassPrintSize) { 3524 sub->print_value_on(st); 3525 st->print(" "); 3526 } 3527 } 3528 if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize); 3529 st->cr(); 3530 3531 if (is_interface()) { 3532 st->print_cr(BULLET"nof implementors: %d", nof_implementors()); 3533 if (nof_implementors() == 1) { 3534 st->print_cr(BULLET"implementor: "); 3535 st->print(" "); 3536 implementor()->print_value_on(st); 3537 st->cr(); 3538 } 3539 } 3540 3541 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr(); 3542 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr(); 3543 if (Verbose || WizardMode) { 3544 Array<Method*>* method_array = methods(); 3545 for (int i = 0; i < method_array->length(); i++) { 3546 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr(); 3547 } 3548 } 3549 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr(); 3550 if (default_methods() != nullptr) { 3551 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr(); 3552 if (Verbose) { 3553 Array<Method*>* method_array = default_methods(); 3554 for (int i = 0; i < method_array->length(); i++) { 3555 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr(); 3556 } 3557 } 3558 } 3559 if (default_vtable_indices() != nullptr) { 3560 st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr(); 3561 } 3562 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr(); 3563 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr(); 3564 3565 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr(); 3566 if (UseSecondarySupersTable) { 3567 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr(); 3568 st->print(BULLET"bitmap: " UINTX_FORMAT_X_0, _bitmap); st->cr(); 3569 } 3570 if (secondary_supers() != nullptr) { 3571 if (Verbose) { 3572 bool is_hashed = UseSecondarySupersTable && (_bitmap != SECONDARY_SUPERS_BITMAP_FULL); 3573 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length()); 3574 for (int i = 0; i < _secondary_supers->length(); i++) { 3575 ResourceMark rm; // for external_name() 3576 Klass* secondary_super = _secondary_supers->at(i); 3577 st->print(BULLET"%2d:", i); 3578 if (is_hashed) { 3579 int home_slot = compute_home_slot(secondary_super, _bitmap); 3580 int distance = (i - home_slot) & SECONDARY_SUPERS_TABLE_MASK; 3581 st->print(" dist:%02d:", distance); 3582 } 3583 st->print_cr(" %p %s", secondary_super, secondary_super->external_name()); 3584 } 3585 } 3586 } 3587 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr(); 3588 if (class_loader_data() != nullptr) { 3589 st->print(BULLET"class loader data: "); 3590 class_loader_data()->print_value_on(st); 3591 st->cr(); 3592 } 3593 if (source_file_name() != nullptr) { 3594 st->print(BULLET"source file: "); 3595 source_file_name()->print_value_on(st); 3596 st->cr(); 3597 } 3598 if (source_debug_extension() != nullptr) { 3599 st->print(BULLET"source debug extension: "); 3600 st->print("%s", source_debug_extension()); 3601 st->cr(); 3602 } 3603 st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr(); 3604 st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr(); 3605 st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr(); 3606 st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr(); 3607 { 3608 bool have_pv = false; 3609 // previous versions are linked together through the InstanceKlass 3610 for (InstanceKlass* pv_node = previous_versions(); 3611 pv_node != nullptr; 3612 pv_node = pv_node->previous_versions()) { 3613 if (!have_pv) 3614 st->print(BULLET"previous version: "); 3615 have_pv = true; 3616 pv_node->constants()->print_value_on(st); 3617 } 3618 if (have_pv) st->cr(); 3619 } 3620 3621 if (generic_signature() != nullptr) { 3622 st->print(BULLET"generic signature: "); 3623 generic_signature()->print_value_on(st); 3624 st->cr(); 3625 } 3626 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr(); 3627 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr(); 3628 if (record_components() != nullptr) { 3629 st->print(BULLET"record components: "); record_components()->print_value_on(st); st->cr(); 3630 } 3631 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr(); 3632 if (java_mirror() != nullptr) { 3633 st->print(BULLET"java mirror: "); 3634 java_mirror()->print_value_on(st); 3635 st->cr(); 3636 } else { 3637 st->print_cr(BULLET"java mirror: null"); 3638 } 3639 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr(); 3640 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st); 3641 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr(); 3642 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st); 3643 st->print_cr(BULLET"---- static fields (%d words):", static_field_size()); 3644 3645 FieldPrinter print_static_field(st); 3646 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field); 3647 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size()); 3648 FieldPrinter print_nonstatic_field(st); 3649 InstanceKlass* ik = const_cast<InstanceKlass*>(this); 3650 ik->print_nonstatic_fields(&print_nonstatic_field); 3651 3652 st->print(BULLET"non-static oop maps: "); 3653 OopMapBlock* map = start_of_nonstatic_oop_maps(); 3654 OopMapBlock* end_map = map + nonstatic_oop_map_count(); 3655 while (map < end_map) { 3656 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1)); 3657 map++; 3658 } 3659 st->cr(); 3660 } 3661 3662 void InstanceKlass::print_value_on(outputStream* st) const { 3663 assert(is_klass(), "must be klass"); 3664 if (Verbose || WizardMode) access_flags().print_on(st); 3665 name()->print_value_on(st); 3666 } 3667 3668 void FieldPrinter::do_field(fieldDescriptor* fd) { 3669 _st->print(BULLET); 3670 if (_obj == nullptr) { 3671 fd->print_on(_st); 3672 _st->cr(); 3673 } else { 3674 fd->print_on_for(_st, _obj); 3675 _st->cr(); 3676 } 3677 } 3678 3679 3680 void InstanceKlass::oop_print_on(oop obj, outputStream* st) { 3681 Klass::oop_print_on(obj, st); 3682 3683 if (this == vmClasses::String_klass()) { 3684 typeArrayOop value = java_lang_String::value(obj); 3685 juint length = java_lang_String::length(obj); 3686 if (value != nullptr && 3687 value->is_typeArray() && 3688 length <= (juint) value->length()) { 3689 st->print(BULLET"string: "); 3690 java_lang_String::print(obj, st); 3691 st->cr(); 3692 } 3693 } 3694 3695 st->print_cr(BULLET"---- fields (total size " SIZE_FORMAT " words):", oop_size(obj)); 3696 FieldPrinter print_field(st, obj); 3697 print_nonstatic_fields(&print_field); 3698 3699 if (this == vmClasses::Class_klass()) { 3700 st->print(BULLET"signature: "); 3701 java_lang_Class::print_signature(obj, st); 3702 st->cr(); 3703 Klass* real_klass = java_lang_Class::as_Klass(obj); 3704 if (real_klass != nullptr && real_klass->is_instance_klass()) { 3705 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj)); 3706 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field); 3707 } 3708 } else if (this == vmClasses::MethodType_klass()) { 3709 st->print(BULLET"signature: "); 3710 java_lang_invoke_MethodType::print_signature(obj, st); 3711 st->cr(); 3712 } 3713 } 3714 3715 #ifndef PRODUCT 3716 3717 bool InstanceKlass::verify_itable_index(int i) { 3718 int method_count = klassItable::method_count_for_interface(this); 3719 assert(i >= 0 && i < method_count, "index out of bounds"); 3720 return true; 3721 } 3722 3723 #endif //PRODUCT 3724 3725 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) { 3726 st->print("a "); 3727 name()->print_value_on(st); 3728 obj->print_address_on(st); 3729 if (this == vmClasses::String_klass() 3730 && java_lang_String::value(obj) != nullptr) { 3731 ResourceMark rm; 3732 int len = java_lang_String::length(obj); 3733 int plen = (len < 24 ? len : 12); 3734 char* str = java_lang_String::as_utf8_string(obj, 0, plen); 3735 st->print(" = \"%s\"", str); 3736 if (len > plen) 3737 st->print("...[%d]", len); 3738 } else if (this == vmClasses::Class_klass()) { 3739 Klass* k = java_lang_Class::as_Klass(obj); 3740 st->print(" = "); 3741 if (k != nullptr) { 3742 k->print_value_on(st); 3743 } else { 3744 const char* tname = type2name(java_lang_Class::primitive_type(obj)); 3745 st->print("%s", tname ? tname : "type?"); 3746 } 3747 } else if (this == vmClasses::MethodType_klass()) { 3748 st->print(" = "); 3749 java_lang_invoke_MethodType::print_signature(obj, st); 3750 } else if (java_lang_boxing_object::is_instance(obj)) { 3751 st->print(" = "); 3752 java_lang_boxing_object::print(obj, st); 3753 } else if (this == vmClasses::LambdaForm_klass()) { 3754 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj); 3755 if (vmentry != nullptr) { 3756 st->print(" => "); 3757 vmentry->print_value_on(st); 3758 } 3759 } else if (this == vmClasses::MemberName_klass()) { 3760 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj); 3761 if (vmtarget != nullptr) { 3762 st->print(" = "); 3763 vmtarget->print_value_on(st); 3764 } else { 3765 oop clazz = java_lang_invoke_MemberName::clazz(obj); 3766 oop name = java_lang_invoke_MemberName::name(obj); 3767 if (clazz != nullptr) { 3768 clazz->print_value_on(st); 3769 } else { 3770 st->print("null"); 3771 } 3772 st->print("."); 3773 if (name != nullptr) { 3774 name->print_value_on(st); 3775 } else { 3776 st->print("null"); 3777 } 3778 } 3779 } 3780 } 3781 3782 const char* InstanceKlass::internal_name() const { 3783 return external_name(); 3784 } 3785 3786 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data, 3787 const ModuleEntry* module_entry, 3788 const ClassFileStream* cfs) const { 3789 3790 if (ClassListWriter::is_enabled()) { 3791 ClassListWriter::write(this, cfs); 3792 } 3793 3794 print_class_load_helper(loader_data, module_entry, cfs); 3795 print_class_load_cause_logging(); 3796 } 3797 3798 void InstanceKlass::print_class_load_helper(ClassLoaderData* loader_data, 3799 const ModuleEntry* module_entry, 3800 const ClassFileStream* cfs) const { 3801 3802 if (!log_is_enabled(Info, class, load)) { 3803 return; 3804 } 3805 3806 ResourceMark rm; 3807 LogMessage(class, load) msg; 3808 stringStream info_stream; 3809 3810 // Name and class hierarchy info 3811 info_stream.print("%s", external_name()); 3812 3813 // Source 3814 if (cfs != nullptr) { 3815 if (cfs->source() != nullptr) { 3816 const char* module_name = (module_entry->name() == nullptr) ? UNNAMED_MODULE : module_entry->name()->as_C_string(); 3817 if (module_name != nullptr) { 3818 // When the boot loader created the stream, it didn't know the module name 3819 // yet. Let's format it now. 3820 if (cfs->from_boot_loader_modules_image()) { 3821 info_stream.print(" source: jrt:/%s", module_name); 3822 } else { 3823 info_stream.print(" source: %s", cfs->source()); 3824 } 3825 } else { 3826 info_stream.print(" source: %s", cfs->source()); 3827 } 3828 } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) { 3829 Thread* current = Thread::current(); 3830 Klass* caller = current->is_Java_thread() ? 3831 JavaThread::cast(current)->security_get_caller_class(1): 3832 nullptr; 3833 // caller can be null, for example, during a JVMTI VM_Init hook 3834 if (caller != nullptr) { 3835 info_stream.print(" source: instance of %s", caller->external_name()); 3836 } else { 3837 // source is unknown 3838 } 3839 } else { 3840 oop class_loader = loader_data->class_loader(); 3841 info_stream.print(" source: %s", class_loader->klass()->external_name()); 3842 } 3843 } else { 3844 assert(this->is_shared(), "must be"); 3845 if (MetaspaceShared::is_shared_dynamic((void*)this)) { 3846 info_stream.print(" source: shared objects file (top)"); 3847 } else { 3848 info_stream.print(" source: shared objects file"); 3849 } 3850 } 3851 3852 msg.info("%s", info_stream.as_string()); 3853 3854 if (log_is_enabled(Debug, class, load)) { 3855 stringStream debug_stream; 3856 3857 // Class hierarchy info 3858 debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT, 3859 p2i(this), p2i(superklass())); 3860 3861 // Interfaces 3862 if (local_interfaces() != nullptr && local_interfaces()->length() > 0) { 3863 debug_stream.print(" interfaces:"); 3864 int length = local_interfaces()->length(); 3865 for (int i = 0; i < length; i++) { 3866 debug_stream.print(" " PTR_FORMAT, 3867 p2i(InstanceKlass::cast(local_interfaces()->at(i)))); 3868 } 3869 } 3870 3871 // Class loader 3872 debug_stream.print(" loader: ["); 3873 loader_data->print_value_on(&debug_stream); 3874 debug_stream.print("]"); 3875 3876 // Classfile checksum 3877 if (cfs) { 3878 debug_stream.print(" bytes: %d checksum: %08x", 3879 cfs->length(), 3880 ClassLoader::crc32(0, (const char*)cfs->buffer(), 3881 cfs->length())); 3882 } 3883 3884 msg.debug("%s", debug_stream.as_string()); 3885 } 3886 } 3887 3888 void InstanceKlass::print_class_load_cause_logging() const { 3889 bool log_cause_native = log_is_enabled(Info, class, load, cause, native); 3890 if (log_cause_native || log_is_enabled(Info, class, load, cause)) { 3891 JavaThread* current = JavaThread::current(); 3892 ResourceMark rm(current); 3893 const char* name = external_name(); 3894 3895 if (LogClassLoadingCauseFor == nullptr || 3896 (strcmp("*", LogClassLoadingCauseFor) != 0 && 3897 strstr(name, LogClassLoadingCauseFor) == nullptr)) { 3898 return; 3899 } 3900 3901 // Log Java stack first 3902 { 3903 LogMessage(class, load, cause) msg; 3904 NonInterleavingLogStream info_stream{LogLevelType::Info, msg}; 3905 3906 info_stream.print_cr("Java stack when loading %s:", name); 3907 current->print_stack_on(&info_stream); 3908 } 3909 3910 // Log native stack second 3911 if (log_cause_native) { 3912 // Log to string first so that lines can be indented 3913 stringStream stack_stream; 3914 char buf[O_BUFLEN]; 3915 address lastpc = nullptr; 3916 if (os::platform_print_native_stack(&stack_stream, nullptr, buf, O_BUFLEN, lastpc)) { 3917 // We have printed the native stack in platform-specific code, 3918 // so nothing else to do in this case. 3919 } else { 3920 frame f = os::current_frame(); 3921 VMError::print_native_stack(&stack_stream, f, current, true /*print_source_info */, 3922 -1 /* max stack_stream */, buf, O_BUFLEN); 3923 } 3924 3925 LogMessage(class, load, cause, native) msg; 3926 NonInterleavingLogStream info_stream{LogLevelType::Info, msg}; 3927 info_stream.print_cr("Native stack when loading %s:", name); 3928 3929 // Print each native stack line to the log 3930 int size = (int) stack_stream.size(); 3931 char* stack = stack_stream.as_string(); 3932 char* stack_end = stack + size; 3933 char* line_start = stack; 3934 for (char* p = stack; p < stack_end; p++) { 3935 if (*p == '\n') { 3936 *p = '\0'; 3937 info_stream.print_cr("\t%s", line_start); 3938 line_start = p + 1; 3939 } 3940 } 3941 if (line_start < stack_end) { 3942 info_stream.print_cr("\t%s", line_start); 3943 } 3944 } 3945 } 3946 } 3947 3948 // Verification 3949 3950 class VerifyFieldClosure: public BasicOopIterateClosure { 3951 protected: 3952 template <class T> void do_oop_work(T* p) { 3953 oop obj = RawAccess<>::oop_load(p); 3954 if (!oopDesc::is_oop_or_null(obj)) { 3955 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj)); 3956 Universe::print_on(tty); 3957 guarantee(false, "boom"); 3958 } 3959 } 3960 public: 3961 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); } 3962 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); } 3963 }; 3964 3965 void InstanceKlass::verify_on(outputStream* st) { 3966 #ifndef PRODUCT 3967 // Avoid redundant verifies, this really should be in product. 3968 if (_verify_count == Universe::verify_count()) return; 3969 _verify_count = Universe::verify_count(); 3970 #endif 3971 3972 // Verify Klass 3973 Klass::verify_on(st); 3974 3975 // Verify that klass is present in ClassLoaderData 3976 guarantee(class_loader_data()->contains_klass(this), 3977 "this class isn't found in class loader data"); 3978 3979 // Verify vtables 3980 if (is_linked()) { 3981 // $$$ This used to be done only for m/s collections. Doing it 3982 // always seemed a valid generalization. (DLD -- 6/00) 3983 vtable().verify(st); 3984 } 3985 3986 // Verify first subklass 3987 if (subklass() != nullptr) { 3988 guarantee(subklass()->is_klass(), "should be klass"); 3989 } 3990 3991 // Verify siblings 3992 Klass* super = this->super(); 3993 Klass* sib = next_sibling(); 3994 if (sib != nullptr) { 3995 if (sib == this) { 3996 fatal("subclass points to itself " PTR_FORMAT, p2i(sib)); 3997 } 3998 3999 guarantee(sib->is_klass(), "should be klass"); 4000 guarantee(sib->super() == super, "siblings should have same superklass"); 4001 } 4002 4003 // Verify local interfaces 4004 if (local_interfaces()) { 4005 Array<InstanceKlass*>* local_interfaces = this->local_interfaces(); 4006 for (int j = 0; j < local_interfaces->length(); j++) { 4007 InstanceKlass* e = local_interfaces->at(j); 4008 guarantee(e->is_klass() && e->is_interface(), "invalid local interface"); 4009 } 4010 } 4011 4012 // Verify transitive interfaces 4013 if (transitive_interfaces() != nullptr) { 4014 Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces(); 4015 for (int j = 0; j < transitive_interfaces->length(); j++) { 4016 InstanceKlass* e = transitive_interfaces->at(j); 4017 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface"); 4018 } 4019 } 4020 4021 // Verify methods 4022 if (methods() != nullptr) { 4023 Array<Method*>* methods = this->methods(); 4024 for (int j = 0; j < methods->length(); j++) { 4025 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 4026 } 4027 for (int j = 0; j < methods->length() - 1; j++) { 4028 Method* m1 = methods->at(j); 4029 Method* m2 = methods->at(j + 1); 4030 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 4031 } 4032 } 4033 4034 // Verify method ordering 4035 if (method_ordering() != nullptr) { 4036 Array<int>* method_ordering = this->method_ordering(); 4037 int length = method_ordering->length(); 4038 if (JvmtiExport::can_maintain_original_method_order() || 4039 ((CDSConfig::is_using_archive() || CDSConfig::is_dumping_archive()) && length != 0)) { 4040 guarantee(length == methods()->length(), "invalid method ordering length"); 4041 jlong sum = 0; 4042 for (int j = 0; j < length; j++) { 4043 int original_index = method_ordering->at(j); 4044 guarantee(original_index >= 0, "invalid method ordering index"); 4045 guarantee(original_index < length, "invalid method ordering index"); 4046 sum += original_index; 4047 } 4048 // Verify sum of indices 0,1,...,length-1 4049 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum"); 4050 } else { 4051 guarantee(length == 0, "invalid method ordering length"); 4052 } 4053 } 4054 4055 // Verify default methods 4056 if (default_methods() != nullptr) { 4057 Array<Method*>* methods = this->default_methods(); 4058 for (int j = 0; j < methods->length(); j++) { 4059 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 4060 } 4061 for (int j = 0; j < methods->length() - 1; j++) { 4062 Method* m1 = methods->at(j); 4063 Method* m2 = methods->at(j + 1); 4064 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 4065 } 4066 } 4067 4068 // Verify JNI static field identifiers 4069 if (jni_ids() != nullptr) { 4070 jni_ids()->verify(this); 4071 } 4072 4073 // Verify other fields 4074 if (constants() != nullptr) { 4075 guarantee(constants()->is_constantPool(), "should be constant pool"); 4076 } 4077 } 4078 4079 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) { 4080 Klass::oop_verify_on(obj, st); 4081 VerifyFieldClosure blk; 4082 obj->oop_iterate(&blk); 4083 } 4084 4085 4086 // JNIid class for jfieldIDs only 4087 // Note to reviewers: 4088 // These JNI functions are just moved over to column 1 and not changed 4089 // in the compressed oops workspace. 4090 JNIid::JNIid(Klass* holder, int offset, JNIid* next) { 4091 _holder = holder; 4092 _offset = offset; 4093 _next = next; 4094 debug_only(_is_static_field_id = false;) 4095 } 4096 4097 4098 JNIid* JNIid::find(int offset) { 4099 JNIid* current = this; 4100 while (current != nullptr) { 4101 if (current->offset() == offset) return current; 4102 current = current->next(); 4103 } 4104 return nullptr; 4105 } 4106 4107 void JNIid::deallocate(JNIid* current) { 4108 while (current != nullptr) { 4109 JNIid* next = current->next(); 4110 delete current; 4111 current = next; 4112 } 4113 } 4114 4115 4116 void JNIid::verify(Klass* holder) { 4117 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields(); 4118 int end_field_offset; 4119 end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize); 4120 4121 JNIid* current = this; 4122 while (current != nullptr) { 4123 guarantee(current->holder() == holder, "Invalid klass in JNIid"); 4124 #ifdef ASSERT 4125 int o = current->offset(); 4126 if (current->is_static_field_id()) { 4127 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid"); 4128 } 4129 #endif 4130 current = current->next(); 4131 } 4132 } 4133 4134 void InstanceKlass::set_init_state(ClassState state) { 4135 if (state > loaded) { 4136 assert_lock_strong(_init_monitor); 4137 } 4138 #ifdef ASSERT 4139 bool good_state = is_shared() ? (_init_state <= state) 4140 : (_init_state < state); 4141 bool link_failed = _init_state == being_linked && state == loaded; 4142 assert(good_state || state == allocated || link_failed, "illegal state transition"); 4143 #endif 4144 assert(_init_thread == nullptr, "should be cleared before state change"); 4145 Atomic::store(&_init_state, state); 4146 } 4147 4148 #if INCLUDE_JVMTI 4149 4150 // RedefineClasses() support for previous versions 4151 4152 // Globally, there is at least one previous version of a class to walk 4153 // during class unloading, which is saved because old methods in the class 4154 // are still running. Otherwise the previous version list is cleaned up. 4155 bool InstanceKlass::_should_clean_previous_versions = false; 4156 4157 // Returns true if there are previous versions of a class for class 4158 // unloading only. Also resets the flag to false. purge_previous_version 4159 // will set the flag to true if there are any left, i.e., if there's any 4160 // work to do for next time. This is to avoid the expensive code cache 4161 // walk in CLDG::clean_deallocate_lists(). 4162 bool InstanceKlass::should_clean_previous_versions_and_reset() { 4163 bool ret = _should_clean_previous_versions; 4164 log_trace(redefine, class, iklass, purge)("Class unloading: should_clean_previous_versions = %s", 4165 ret ? "true" : "false"); 4166 _should_clean_previous_versions = false; 4167 return ret; 4168 } 4169 4170 // This nulls out jmethodIDs for all methods in 'klass' 4171 // It needs to be called explicitly for all previous versions of a class because these may not be cleaned up 4172 // during class unloading. 4173 // We can not use the jmethodID cache associated with klass directly because the 'previous' versions 4174 // do not have the jmethodID cache filled in. Instead, we need to lookup jmethodID for each method and this 4175 // is expensive - O(n) for one jmethodID lookup. For all contained methods it is O(n^2). 4176 // The reason for expensive jmethodID lookup for each method is that there is no direct link between method and jmethodID. 4177 void InstanceKlass::clear_jmethod_ids(InstanceKlass* klass) { 4178 Array<Method*>* method_refs = klass->methods(); 4179 for (int k = 0; k < method_refs->length(); k++) { 4180 Method* method = method_refs->at(k); 4181 if (method != nullptr && method->is_obsolete()) { 4182 method->clear_jmethod_id(); 4183 } 4184 } 4185 } 4186 4187 // Purge previous versions before adding new previous versions of the class and 4188 // during class unloading. 4189 void InstanceKlass::purge_previous_version_list() { 4190 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 4191 assert(has_been_redefined(), "Should only be called for main class"); 4192 4193 // Quick exit. 4194 if (previous_versions() == nullptr) { 4195 return; 4196 } 4197 4198 // This klass has previous versions so see what we can cleanup 4199 // while it is safe to do so. 4200 4201 int deleted_count = 0; // leave debugging breadcrumbs 4202 int live_count = 0; 4203 ClassLoaderData* loader_data = class_loader_data(); 4204 assert(loader_data != nullptr, "should never be null"); 4205 4206 ResourceMark rm; 4207 log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name()); 4208 4209 // previous versions are linked together through the InstanceKlass 4210 InstanceKlass* pv_node = previous_versions(); 4211 InstanceKlass* last = this; 4212 int version = 0; 4213 4214 // check the previous versions list 4215 for (; pv_node != nullptr; ) { 4216 4217 ConstantPool* pvcp = pv_node->constants(); 4218 assert(pvcp != nullptr, "cp ref was unexpectedly cleared"); 4219 4220 if (!pvcp->on_stack()) { 4221 // If the constant pool isn't on stack, none of the methods 4222 // are executing. Unlink this previous_version. 4223 // The previous version InstanceKlass is on the ClassLoaderData deallocate list 4224 // so will be deallocated during the next phase of class unloading. 4225 log_trace(redefine, class, iklass, purge) 4226 ("previous version " PTR_FORMAT " is dead.", p2i(pv_node)); 4227 // Unlink from previous version list. 4228 assert(pv_node->class_loader_data() == loader_data, "wrong loader_data"); 4229 InstanceKlass* next = pv_node->previous_versions(); 4230 clear_jmethod_ids(pv_node); // jmethodID maintenance for the unloaded class 4231 pv_node->link_previous_versions(nullptr); // point next to null 4232 last->link_previous_versions(next); 4233 // Delete this node directly. Nothing is referring to it and we don't 4234 // want it to increase the counter for metadata to delete in CLDG. 4235 MetadataFactory::free_metadata(loader_data, pv_node); 4236 pv_node = next; 4237 deleted_count++; 4238 version++; 4239 continue; 4240 } else { 4241 assert(pvcp->pool_holder() != nullptr, "Constant pool with no holder"); 4242 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack"); 4243 live_count++; 4244 if (pvcp->is_shared()) { 4245 // Shared previous versions can never be removed so no cleaning is needed. 4246 log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is shared", p2i(pv_node)); 4247 } else { 4248 // Previous version alive, set that clean is needed for next time. 4249 _should_clean_previous_versions = true; 4250 log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is alive", p2i(pv_node)); 4251 } 4252 } 4253 4254 // next previous version 4255 last = pv_node; 4256 pv_node = pv_node->previous_versions(); 4257 version++; 4258 } 4259 log_trace(redefine, class, iklass, purge) 4260 ("previous version stats: live=%d, deleted=%d", live_count, deleted_count); 4261 } 4262 4263 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods, 4264 int emcp_method_count) { 4265 int obsolete_method_count = old_methods->length() - emcp_method_count; 4266 4267 if (emcp_method_count != 0 && obsolete_method_count != 0 && 4268 _previous_versions != nullptr) { 4269 // We have a mix of obsolete and EMCP methods so we have to 4270 // clear out any matching EMCP method entries the hard way. 4271 int local_count = 0; 4272 for (int i = 0; i < old_methods->length(); i++) { 4273 Method* old_method = old_methods->at(i); 4274 if (old_method->is_obsolete()) { 4275 // only obsolete methods are interesting 4276 Symbol* m_name = old_method->name(); 4277 Symbol* m_signature = old_method->signature(); 4278 4279 // previous versions are linked together through the InstanceKlass 4280 int j = 0; 4281 for (InstanceKlass* prev_version = _previous_versions; 4282 prev_version != nullptr; 4283 prev_version = prev_version->previous_versions(), j++) { 4284 4285 Array<Method*>* method_refs = prev_version->methods(); 4286 for (int k = 0; k < method_refs->length(); k++) { 4287 Method* method = method_refs->at(k); 4288 4289 if (!method->is_obsolete() && 4290 method->name() == m_name && 4291 method->signature() == m_signature) { 4292 // The current RedefineClasses() call has made all EMCP 4293 // versions of this method obsolete so mark it as obsolete 4294 log_trace(redefine, class, iklass, add) 4295 ("%s(%s): flush obsolete method @%d in version @%d", 4296 m_name->as_C_string(), m_signature->as_C_string(), k, j); 4297 4298 method->set_is_obsolete(); 4299 break; 4300 } 4301 } 4302 4303 // The previous loop may not find a matching EMCP method, but 4304 // that doesn't mean that we can optimize and not go any 4305 // further back in the PreviousVersion generations. The EMCP 4306 // method for this generation could have already been made obsolete, 4307 // but there still may be an older EMCP method that has not 4308 // been made obsolete. 4309 } 4310 4311 if (++local_count >= obsolete_method_count) { 4312 // no more obsolete methods so bail out now 4313 break; 4314 } 4315 } 4316 } 4317 } 4318 } 4319 4320 // Save the scratch_class as the previous version if any of the methods are running. 4321 // The previous_versions are used to set breakpoints in EMCP methods and they are 4322 // also used to clean MethodData links to redefined methods that are no longer running. 4323 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class, 4324 int emcp_method_count) { 4325 assert(Thread::current()->is_VM_thread(), 4326 "only VMThread can add previous versions"); 4327 4328 ResourceMark rm; 4329 log_trace(redefine, class, iklass, add) 4330 ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count); 4331 4332 // Clean out old previous versions for this class 4333 purge_previous_version_list(); 4334 4335 // Mark newly obsolete methods in remaining previous versions. An EMCP method from 4336 // a previous redefinition may be made obsolete by this redefinition. 4337 Array<Method*>* old_methods = scratch_class->methods(); 4338 mark_newly_obsolete_methods(old_methods, emcp_method_count); 4339 4340 // If the constant pool for this previous version of the class 4341 // is not marked as being on the stack, then none of the methods 4342 // in this previous version of the class are on the stack so 4343 // we don't need to add this as a previous version. 4344 ConstantPool* cp_ref = scratch_class->constants(); 4345 if (!cp_ref->on_stack()) { 4346 log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running"); 4347 scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class); 4348 return; 4349 } 4350 4351 // Add previous version if any methods are still running or if this is 4352 // a shared class which should never be removed. 4353 assert(scratch_class->previous_versions() == nullptr, "shouldn't have a previous version"); 4354 scratch_class->link_previous_versions(previous_versions()); 4355 link_previous_versions(scratch_class); 4356 if (cp_ref->is_shared()) { 4357 log_trace(redefine, class, iklass, add) ("scratch class added; class is shared"); 4358 } else { 4359 // We only set clean_previous_versions flag for processing during class 4360 // unloading for non-shared classes. 4361 _should_clean_previous_versions = true; 4362 log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack."); 4363 } 4364 } // end add_previous_version() 4365 4366 #endif // INCLUDE_JVMTI 4367 4368 Method* InstanceKlass::method_with_idnum(int idnum) { 4369 Method* m = nullptr; 4370 if (idnum < methods()->length()) { 4371 m = methods()->at(idnum); 4372 } 4373 if (m == nullptr || m->method_idnum() != idnum) { 4374 for (int index = 0; index < methods()->length(); ++index) { 4375 m = methods()->at(index); 4376 if (m->method_idnum() == idnum) { 4377 return m; 4378 } 4379 } 4380 // None found, return null for the caller to handle. 4381 return nullptr; 4382 } 4383 return m; 4384 } 4385 4386 4387 Method* InstanceKlass::method_with_orig_idnum(int idnum) { 4388 if (idnum >= methods()->length()) { 4389 return nullptr; 4390 } 4391 Method* m = methods()->at(idnum); 4392 if (m != nullptr && m->orig_method_idnum() == idnum) { 4393 return m; 4394 } 4395 // Obsolete method idnum does not match the original idnum 4396 for (int index = 0; index < methods()->length(); ++index) { 4397 m = methods()->at(index); 4398 if (m->orig_method_idnum() == idnum) { 4399 return m; 4400 } 4401 } 4402 // None found, return null for the caller to handle. 4403 return nullptr; 4404 } 4405 4406 4407 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) { 4408 InstanceKlass* holder = get_klass_version(version); 4409 if (holder == nullptr) { 4410 return nullptr; // The version of klass is gone, no method is found 4411 } 4412 Method* method = holder->method_with_orig_idnum(idnum); 4413 return method; 4414 } 4415 4416 #if INCLUDE_JVMTI 4417 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() { 4418 return _cached_class_file; 4419 } 4420 4421 jint InstanceKlass::get_cached_class_file_len() { 4422 return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file); 4423 } 4424 4425 unsigned char * InstanceKlass::get_cached_class_file_bytes() { 4426 return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file); 4427 } 4428 #endif 4429 4430 // Make a step iterating over the class hierarchy under the root class. 4431 // Skips subclasses if requested. 4432 void ClassHierarchyIterator::next() { 4433 assert(_current != nullptr, "required"); 4434 if (_visit_subclasses && _current->subklass() != nullptr) { 4435 _current = _current->subklass(); 4436 return; // visit next subclass 4437 } 4438 _visit_subclasses = true; // reset 4439 while (_current->next_sibling() == nullptr && _current != _root) { 4440 _current = _current->superklass(); // backtrack; no more sibling subclasses left 4441 } 4442 if (_current == _root) { 4443 // Iteration is over (back at root after backtracking). Invalidate the iterator. 4444 _current = nullptr; 4445 return; 4446 } 4447 _current = _current->next_sibling(); 4448 return; // visit next sibling subclass 4449 }