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