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