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