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