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