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