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