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