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