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