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