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