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