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