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