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