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