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