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