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()). So setting the _methods to 2707 // be writable. The length check on the _methods is necessary because classes which 2708 // don't have any methods share the Universe::_the_empty_method_array which is in the RO region. 2709 if (_methods != nullptr && _methods->length() > 0 && 2710 !can_be_verified_at_dumptime() && methods_contain_jsr_bytecode()) { 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 2958 bool InstanceKlass::methods_contain_jsr_bytecode() const { 2959 Thread* thread = Thread::current(); 2960 for (int i = 0; i < _methods->length(); i++) { 2961 methodHandle m(thread, _methods->at(i)); 2962 BytecodeStream bcs(m); 2963 while (!bcs.is_last_bytecode()) { 2964 Bytecodes::Code opcode = bcs.next(); 2965 if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) { 2966 return true; 2967 } 2968 } 2969 } 2970 return false; 2971 } 2972 #endif // INCLUDE_CDS 2973 2974 #if INCLUDE_JVMTI 2975 static void clear_all_breakpoints(Method* m) { 2976 m->clear_all_breakpoints(); 2977 } 2978 #endif 2979 2980 void InstanceKlass::unload_class(InstanceKlass* ik) { 2981 2982 if (ik->is_scratch_class()) { 2983 assert(ik->dependencies().is_empty(), "dependencies should be empty for scratch classes"); 2984 return; 2985 } 2986 assert(ik->is_loaded(), "class should be loaded " PTR_FORMAT, p2i(ik)); 2987 2988 // Release dependencies. 2989 ik->dependencies().remove_all_dependents(); 2990 2991 // notify the debugger 2992 if (JvmtiExport::should_post_class_unload()) { 2993 JvmtiExport::post_class_unload(ik); 2994 } 2995 2996 // notify ClassLoadingService of class unload 2997 ClassLoadingService::notify_class_unloaded(ik); 2998 2999 SystemDictionaryShared::handle_class_unloading(ik); 3000 3001 if (log_is_enabled(Info, class, unload)) { 3002 ResourceMark rm; 3003 log_info(class, unload)("unloading class %s " PTR_FORMAT, ik->external_name(), p2i(ik)); 3004 } 3005 3006 Events::log_class_unloading(Thread::current(), ik); 3007 3008 #if INCLUDE_JFR 3009 assert(ik != nullptr, "invariant"); 3010 EventClassUnload event; 3011 event.set_unloadedClass(ik); 3012 event.set_definingClassLoader(ik->class_loader_data()); 3013 event.commit(); 3014 #endif 3015 } 3016 3017 static void method_release_C_heap_structures(Method* m) { 3018 m->release_C_heap_structures(); 3019 } 3020 3021 // Called also by InstanceKlass::deallocate_contents, with false for release_sub_metadata. 3022 void InstanceKlass::release_C_heap_structures(bool release_sub_metadata) { 3023 // Clean up C heap 3024 Klass::release_C_heap_structures(); 3025 3026 // Deallocate and call destructors for MDO mutexes 3027 if (release_sub_metadata) { 3028 methods_do(method_release_C_heap_structures); 3029 } 3030 3031 // Deallocate oop map cache 3032 if (_oop_map_cache != nullptr) { 3033 delete _oop_map_cache; 3034 _oop_map_cache = nullptr; 3035 } 3036 3037 // Deallocate JNI identifiers for jfieldIDs 3038 JNIid::deallocate(jni_ids()); 3039 set_jni_ids(nullptr); 3040 3041 jmethodID* jmeths = methods_jmethod_ids_acquire(); 3042 if (jmeths != nullptr) { 3043 release_set_methods_jmethod_ids(nullptr); 3044 FreeHeap(jmeths); 3045 } 3046 3047 assert(_dep_context == nullptr, 3048 "dependencies should already be cleaned"); 3049 3050 #if INCLUDE_JVMTI 3051 // Deallocate breakpoint records 3052 if (breakpoints() != nullptr) { 3053 methods_do(clear_all_breakpoints); 3054 assert(breakpoints() == nullptr, "should have cleared breakpoints"); 3055 } 3056 3057 // deallocate the cached class file 3058 if (_cached_class_file != nullptr) { 3059 os::free(_cached_class_file); 3060 _cached_class_file = nullptr; 3061 } 3062 #endif 3063 3064 FREE_C_HEAP_ARRAY(char, _source_debug_extension); 3065 3066 if (release_sub_metadata) { 3067 constants()->release_C_heap_structures(); 3068 } 3069 } 3070 3071 // The constant pool is on stack if any of the methods are executing or 3072 // referenced by handles. 3073 bool InstanceKlass::on_stack() const { 3074 return _constants->on_stack(); 3075 } 3076 3077 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); } 3078 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); } 3079 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); } 3080 3081 // minor and major version numbers of class file 3082 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); } 3083 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); } 3084 u2 InstanceKlass::major_version() const { return _constants->major_version(); } 3085 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); } 3086 3087 InstanceKlass* InstanceKlass::get_klass_version(int version) { 3088 for (InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) { 3089 if (ik->constants()->version() == version) { 3090 return ik; 3091 } 3092 } 3093 return nullptr; 3094 } 3095 3096 void InstanceKlass::set_source_debug_extension(const char* array, int length) { 3097 if (array == nullptr) { 3098 _source_debug_extension = nullptr; 3099 } else { 3100 // Adding one to the attribute length in order to store a null terminator 3101 // character could cause an overflow because the attribute length is 3102 // already coded with an u4 in the classfile, but in practice, it's 3103 // unlikely to happen. 3104 assert((length+1) > length, "Overflow checking"); 3105 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass); 3106 for (int i = 0; i < length; i++) { 3107 sde[i] = array[i]; 3108 } 3109 sde[length] = '\0'; 3110 _source_debug_extension = sde; 3111 } 3112 } 3113 3114 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); } 3115 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); } 3116 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); } 3117 3118 const char* InstanceKlass::signature_name() const { 3119 return signature_name_of_carrier(JVM_SIGNATURE_CLASS); 3120 } 3121 3122 const char* InstanceKlass::signature_name_of_carrier(char c) const { 3123 // Get the internal name as a c string 3124 const char* src = (const char*) (name()->as_C_string()); 3125 const int src_length = (int)strlen(src); 3126 3127 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3); 3128 3129 // Add L or Q as type indicator 3130 int dest_index = 0; 3131 dest[dest_index++] = c; 3132 3133 // Add the actual class name 3134 for (int src_index = 0; src_index < src_length; ) { 3135 dest[dest_index++] = src[src_index++]; 3136 } 3137 3138 if (is_hidden()) { // Replace the last '+' with a '.'. 3139 for (int index = (int)src_length; index > 0; index--) { 3140 if (dest[index] == '+') { 3141 dest[index] = JVM_SIGNATURE_DOT; 3142 break; 3143 } 3144 } 3145 } 3146 3147 // Add the semicolon and the null 3148 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS; 3149 dest[dest_index] = '\0'; 3150 return dest; 3151 } 3152 3153 ModuleEntry* InstanceKlass::module() const { 3154 if (is_hidden() && 3155 in_unnamed_package() && 3156 class_loader_data()->has_class_mirror_holder()) { 3157 // For a non-strong hidden class defined to an unnamed package, 3158 // its (class held) CLD will not have an unnamed module created for it. 3159 // Two choices to find the correct ModuleEntry: 3160 // 1. If hidden class is within a nest, use nest host's module 3161 // 2. Find the unnamed module off from the class loader 3162 // For now option #2 is used since a nest host is not set until 3163 // after the instance class is created in jvm_lookup_define_class(). 3164 if (class_loader_data()->is_boot_class_loader_data()) { 3165 return ClassLoaderData::the_null_class_loader_data()->unnamed_module(); 3166 } else { 3167 oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader()); 3168 assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module"); 3169 return java_lang_Module::module_entry(module); 3170 } 3171 } 3172 3173 // Class is in a named package 3174 if (!in_unnamed_package()) { 3175 return _package_entry->module(); 3176 } 3177 3178 // Class is in an unnamed package, return its loader's unnamed module 3179 return class_loader_data()->unnamed_module(); 3180 } 3181 3182 void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) { 3183 3184 // ensure java/ packages only loaded by boot or platform builtin loaders 3185 // not needed for shared class since CDS does not archive prohibited classes. 3186 if (!is_shared()) { 3187 check_prohibited_package(name(), loader_data, CHECK); 3188 } 3189 3190 if (is_shared() && _package_entry != nullptr) { 3191 if (CDSConfig::is_using_full_module_graph() && _package_entry == pkg_entry) { 3192 // we can use the saved package 3193 assert(MetaspaceShared::is_in_shared_metaspace(_package_entry), "must be"); 3194 return; 3195 } else { 3196 _package_entry = nullptr; 3197 } 3198 } 3199 3200 // ClassLoader::package_from_class_name has already incremented the refcount of the symbol 3201 // it returns, so we need to decrement it when the current function exits. 3202 TempNewSymbol from_class_name = 3203 (pkg_entry != nullptr) ? nullptr : ClassLoader::package_from_class_name(name()); 3204 3205 Symbol* pkg_name; 3206 if (pkg_entry != nullptr) { 3207 pkg_name = pkg_entry->name(); 3208 } else { 3209 pkg_name = from_class_name; 3210 } 3211 3212 if (pkg_name != nullptr && loader_data != nullptr) { 3213 3214 // Find in class loader's package entry table. 3215 _package_entry = pkg_entry != nullptr ? pkg_entry : loader_data->packages()->lookup_only(pkg_name); 3216 3217 // If the package name is not found in the loader's package 3218 // entry table, it is an indication that the package has not 3219 // been defined. Consider it defined within the unnamed module. 3220 if (_package_entry == nullptr) { 3221 3222 if (!ModuleEntryTable::javabase_defined()) { 3223 // Before java.base is defined during bootstrapping, define all packages in 3224 // the java.base module. If a non-java.base package is erroneously placed 3225 // in the java.base module it will be caught later when java.base 3226 // is defined by ModuleEntryTable::verify_javabase_packages check. 3227 assert(ModuleEntryTable::javabase_moduleEntry() != nullptr, JAVA_BASE_NAME " module is null"); 3228 _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, ModuleEntryTable::javabase_moduleEntry()); 3229 } else { 3230 assert(loader_data->unnamed_module() != nullptr, "unnamed module is null"); 3231 _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, loader_data->unnamed_module()); 3232 } 3233 3234 // A package should have been successfully created 3235 DEBUG_ONLY(ResourceMark rm(THREAD)); 3236 assert(_package_entry != nullptr, "Package entry for class %s not found, loader %s", 3237 name()->as_C_string(), loader_data->loader_name_and_id()); 3238 } 3239 3240 if (log_is_enabled(Debug, module)) { 3241 ResourceMark rm(THREAD); 3242 ModuleEntry* m = _package_entry->module(); 3243 log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s", 3244 external_name(), 3245 pkg_name->as_C_string(), 3246 loader_data->loader_name_and_id(), 3247 (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE)); 3248 } 3249 } else { 3250 ResourceMark rm(THREAD); 3251 log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s", 3252 external_name(), 3253 (loader_data != nullptr) ? loader_data->loader_name_and_id() : "null", 3254 UNNAMED_MODULE); 3255 } 3256 } 3257 3258 // Function set_classpath_index ensures that for a non-null _package_entry 3259 // of the InstanceKlass, the entry is in the boot loader's package entry table. 3260 // It then sets the classpath_index in the package entry record. 3261 // 3262 // The classpath_index field is used to find the entry on the boot loader class 3263 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a 3264 // in an unnamed module. It is also used to indicate (for all packages whose 3265 // classes are loaded by the boot loader) that at least one of the package's 3266 // classes has been loaded. 3267 void InstanceKlass::set_classpath_index(s2 path_index) { 3268 if (_package_entry != nullptr) { 3269 DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();) 3270 assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same"); 3271 assert(path_index != -1, "Unexpected classpath_index"); 3272 _package_entry->set_classpath_index(path_index); 3273 } 3274 } 3275 3276 // different versions of is_same_class_package 3277 3278 bool InstanceKlass::is_same_class_package(const Klass* class2) const { 3279 oop classloader1 = this->class_loader(); 3280 PackageEntry* classpkg1 = this->package(); 3281 if (class2->is_objArray_klass()) { 3282 class2 = ObjArrayKlass::cast(class2)->bottom_klass(); 3283 } 3284 3285 oop classloader2; 3286 PackageEntry* classpkg2; 3287 if (class2->is_instance_klass()) { 3288 classloader2 = class2->class_loader(); 3289 classpkg2 = class2->package(); 3290 } else { 3291 assert(class2->is_typeArray_klass(), "should be type array"); 3292 classloader2 = nullptr; 3293 classpkg2 = nullptr; 3294 } 3295 3296 // Same package is determined by comparing class loader 3297 // and package entries. Both must be the same. This rule 3298 // applies even to classes that are defined in the unnamed 3299 // package, they still must have the same class loader. 3300 if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) { 3301 return true; 3302 } 3303 3304 return false; 3305 } 3306 3307 // return true if this class and other_class are in the same package. Classloader 3308 // and classname information is enough to determine a class's package 3309 bool InstanceKlass::is_same_class_package(oop other_class_loader, 3310 const Symbol* other_class_name) const { 3311 if (class_loader() != other_class_loader) { 3312 return false; 3313 } 3314 if (name()->fast_compare(other_class_name) == 0) { 3315 return true; 3316 } 3317 3318 { 3319 ResourceMark rm; 3320 3321 bool bad_class_name = false; 3322 TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name); 3323 if (bad_class_name) { 3324 return false; 3325 } 3326 // Check that package_from_class_name() returns null, not "", if there is no package. 3327 assert(other_pkg == nullptr || other_pkg->utf8_length() > 0, "package name is empty string"); 3328 3329 const Symbol* const this_package_name = 3330 this->package() != nullptr ? this->package()->name() : nullptr; 3331 3332 if (this_package_name == nullptr || other_pkg == nullptr) { 3333 // One of the two doesn't have a package. Only return true if the other 3334 // one also doesn't have a package. 3335 return this_package_name == other_pkg; 3336 } 3337 3338 // Check if package is identical 3339 return this_package_name->fast_compare(other_pkg) == 0; 3340 } 3341 } 3342 3343 static bool is_prohibited_package_slow(Symbol* class_name) { 3344 // Caller has ResourceMark 3345 int length; 3346 jchar* unicode = class_name->as_unicode(length); 3347 return (length >= 5 && 3348 unicode[0] == 'j' && 3349 unicode[1] == 'a' && 3350 unicode[2] == 'v' && 3351 unicode[3] == 'a' && 3352 unicode[4] == '/'); 3353 } 3354 3355 // Only boot and platform class loaders can define classes in "java/" packages. 3356 void InstanceKlass::check_prohibited_package(Symbol* class_name, 3357 ClassLoaderData* loader_data, 3358 TRAPS) { 3359 if (!loader_data->is_boot_class_loader_data() && 3360 !loader_data->is_platform_class_loader_data() && 3361 class_name != nullptr && class_name->utf8_length() >= 5) { 3362 ResourceMark rm(THREAD); 3363 bool prohibited; 3364 const u1* base = class_name->base(); 3365 if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) { 3366 prohibited = is_prohibited_package_slow(class_name); 3367 } else { 3368 char* name = class_name->as_C_string(); 3369 prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/'); 3370 } 3371 if (prohibited) { 3372 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name); 3373 assert(pkg_name != nullptr, "Error in parsing package name starting with 'java/'"); 3374 char* name = pkg_name->as_C_string(); 3375 const char* class_loader_name = loader_data->loader_name_and_id(); 3376 StringUtils::replace_no_expand(name, "/", "."); 3377 const char* msg_text1 = "Class loader (instance of): "; 3378 const char* msg_text2 = " tried to load prohibited package name: "; 3379 size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1; 3380 char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len); 3381 jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name); 3382 THROW_MSG(vmSymbols::java_lang_SecurityException(), message); 3383 } 3384 } 3385 return; 3386 } 3387 3388 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const { 3389 constantPoolHandle i_cp(THREAD, constants()); 3390 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) { 3391 int ioff = iter.inner_class_info_index(); 3392 if (ioff != 0) { 3393 // Check to see if the name matches the class we're looking for 3394 // before attempting to find the class. 3395 if (i_cp->klass_name_at_matches(this, ioff)) { 3396 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false); 3397 if (this == inner_klass) { 3398 *ooff = iter.outer_class_info_index(); 3399 *noff = iter.inner_name_index(); 3400 return true; 3401 } 3402 } 3403 } 3404 } 3405 return false; 3406 } 3407 3408 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const { 3409 InstanceKlass* outer_klass = nullptr; 3410 *inner_is_member = false; 3411 int ooff = 0, noff = 0; 3412 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD); 3413 if (has_inner_classes_attr) { 3414 constantPoolHandle i_cp(THREAD, constants()); 3415 if (ooff != 0) { 3416 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL); 3417 if (!ok->is_instance_klass()) { 3418 // If the outer class is not an instance klass then it cannot have 3419 // declared any inner classes. 3420 ResourceMark rm(THREAD); 3421 Exceptions::fthrow( 3422 THREAD_AND_LOCATION, 3423 vmSymbols::java_lang_IncompatibleClassChangeError(), 3424 "%s and %s disagree on InnerClasses attribute", 3425 ok->external_name(), 3426 external_name()); 3427 return nullptr; 3428 } 3429 outer_klass = InstanceKlass::cast(ok); 3430 *inner_is_member = true; 3431 } 3432 if (nullptr == outer_klass) { 3433 // It may be a local class; try for that. 3434 int encl_method_class_idx = enclosing_method_class_index(); 3435 if (encl_method_class_idx != 0) { 3436 Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL); 3437 outer_klass = InstanceKlass::cast(ok); 3438 *inner_is_member = false; 3439 } 3440 } 3441 } 3442 3443 // If no inner class attribute found for this class. 3444 if (nullptr == outer_klass) return nullptr; 3445 3446 // Throws an exception if outer klass has not declared k as an inner klass 3447 // We need evidence that each klass knows about the other, or else 3448 // the system could allow a spoof of an inner class to gain access rights. 3449 Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL); 3450 return outer_klass; 3451 } 3452 3453 jint InstanceKlass::compute_modifier_flags() const { 3454 jint access = access_flags().as_int(); 3455 3456 // But check if it happens to be member class. 3457 InnerClassesIterator iter(this); 3458 for (; !iter.done(); iter.next()) { 3459 int ioff = iter.inner_class_info_index(); 3460 // Inner class attribute can be zero, skip it. 3461 // Strange but true: JVM spec. allows null inner class refs. 3462 if (ioff == 0) continue; 3463 3464 // only look at classes that are already loaded 3465 // since we are looking for the flags for our self. 3466 Symbol* inner_name = constants()->klass_name_at(ioff); 3467 if (name() == inner_name) { 3468 // This is really a member class. 3469 access = iter.inner_access_flags(); 3470 break; 3471 } 3472 } 3473 return (access & JVM_ACC_WRITTEN_FLAGS); 3474 } 3475 3476 jint InstanceKlass::jvmti_class_status() const { 3477 jint result = 0; 3478 3479 if (is_linked()) { 3480 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED; 3481 } 3482 3483 if (is_initialized()) { 3484 assert(is_linked(), "Class status is not consistent"); 3485 result |= JVMTI_CLASS_STATUS_INITIALIZED; 3486 } 3487 if (is_in_error_state()) { 3488 result |= JVMTI_CLASS_STATUS_ERROR; 3489 } 3490 return result; 3491 } 3492 3493 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) { 3494 bool implements_interface; // initialized by method_at_itable_or_null 3495 Method* m = method_at_itable_or_null(holder, index, 3496 implements_interface); // out parameter 3497 if (m != nullptr) { 3498 assert(implements_interface, "sanity"); 3499 return m; 3500 } else if (implements_interface) { 3501 // Throw AbstractMethodError since corresponding itable slot is empty. 3502 THROW_NULL(vmSymbols::java_lang_AbstractMethodError()); 3503 } else { 3504 // If the interface isn't implemented by the receiver class, 3505 // the VM should throw IncompatibleClassChangeError. 3506 ResourceMark rm(THREAD); 3507 stringStream ss; 3508 bool same_module = (module() == holder->module()); 3509 ss.print("Receiver class %s does not implement " 3510 "the interface %s defining the method to be called " 3511 "(%s%s%s)", 3512 external_name(), holder->external_name(), 3513 (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(), 3514 (same_module) ? "" : "; ", 3515 (same_module) ? "" : holder->class_in_module_of_loader()); 3516 THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string()); 3517 } 3518 } 3519 3520 Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) { 3521 klassItable itable(this); 3522 for (int i = 0; i < itable.size_offset_table(); i++) { 3523 itableOffsetEntry* offset_entry = itable.offset_entry(i); 3524 if (offset_entry->interface_klass() == holder) { 3525 implements_interface = true; 3526 itableMethodEntry* ime = offset_entry->first_method_entry(this); 3527 Method* m = ime[index].method(); 3528 return m; 3529 } 3530 } 3531 implements_interface = false; 3532 return nullptr; // offset entry not found 3533 } 3534 3535 int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) { 3536 assert(is_linked(), "required"); 3537 assert(intf_method->method_holder()->is_interface(), "not an interface method"); 3538 assert(is_subtype_of(intf_method->method_holder()), "interface not implemented"); 3539 3540 int vtable_index = Method::invalid_vtable_index; 3541 Symbol* name = intf_method->name(); 3542 Symbol* signature = intf_method->signature(); 3543 3544 // First check in default method array 3545 if (!intf_method->is_abstract() && default_methods() != nullptr) { 3546 int index = find_method_index(default_methods(), 3547 name, signature, 3548 Klass::OverpassLookupMode::find, 3549 Klass::StaticLookupMode::find, 3550 Klass::PrivateLookupMode::find); 3551 if (index >= 0) { 3552 vtable_index = default_vtable_indices()->at(index); 3553 } 3554 } 3555 if (vtable_index == Method::invalid_vtable_index) { 3556 // get vtable_index for miranda methods 3557 klassVtable vt = vtable(); 3558 vtable_index = vt.index_of_miranda(name, signature); 3559 } 3560 return vtable_index; 3561 } 3562 3563 #if INCLUDE_JVMTI 3564 // update default_methods for redefineclasses for methods that are 3565 // not yet in the vtable due to concurrent subclass define and superinterface 3566 // redefinition 3567 // Note: those in the vtable, should have been updated via adjust_method_entries 3568 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) { 3569 // search the default_methods for uses of either obsolete or EMCP methods 3570 if (default_methods() != nullptr) { 3571 for (int index = 0; index < default_methods()->length(); index ++) { 3572 Method* old_method = default_methods()->at(index); 3573 if (old_method == nullptr || !old_method->is_old()) { 3574 continue; // skip uninteresting entries 3575 } 3576 assert(!old_method->is_deleted(), "default methods may not be deleted"); 3577 Method* new_method = old_method->get_new_method(); 3578 default_methods()->at_put(index, new_method); 3579 3580 if (log_is_enabled(Info, redefine, class, update)) { 3581 ResourceMark rm; 3582 if (!(*trace_name_printed)) { 3583 log_info(redefine, class, update) 3584 ("adjust: klassname=%s default methods from name=%s", 3585 external_name(), old_method->method_holder()->external_name()); 3586 *trace_name_printed = true; 3587 } 3588 log_debug(redefine, class, update, vtables) 3589 ("default method update: %s(%s) ", 3590 new_method->name()->as_C_string(), new_method->signature()->as_C_string()); 3591 } 3592 } 3593 } 3594 } 3595 #endif // INCLUDE_JVMTI 3596 3597 // On-stack replacement stuff 3598 void InstanceKlass::add_osr_nmethod(nmethod* n) { 3599 assert_lock_strong(NMethodState_lock); 3600 #ifndef PRODUCT 3601 nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true); 3602 assert(prev == nullptr || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation), 3603 "redundant OSR recompilation detected. memory leak in CodeCache!"); 3604 #endif 3605 // only one compilation can be active 3606 assert(n->is_osr_method(), "wrong kind of nmethod"); 3607 n->set_osr_link(osr_nmethods_head()); 3608 set_osr_nmethods_head(n); 3609 // Raise the highest osr level if necessary 3610 n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level())); 3611 3612 // Get rid of the osr methods for the same bci that have lower levels. 3613 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) { 3614 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true); 3615 if (inv != nullptr && inv->is_in_use()) { 3616 inv->make_not_entrant(); 3617 } 3618 } 3619 } 3620 3621 // Remove osr nmethod from the list. Return true if found and removed. 3622 bool InstanceKlass::remove_osr_nmethod(nmethod* n) { 3623 // This is a short non-blocking critical region, so the no safepoint check is ok. 3624 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3625 assert(n->is_osr_method(), "wrong kind of nmethod"); 3626 nmethod* last = nullptr; 3627 nmethod* cur = osr_nmethods_head(); 3628 int max_level = CompLevel_none; // Find the max comp level excluding n 3629 Method* m = n->method(); 3630 // Search for match 3631 bool found = false; 3632 while(cur != nullptr && cur != n) { 3633 if (m == cur->method()) { 3634 // Find max level before n 3635 max_level = MAX2(max_level, cur->comp_level()); 3636 } 3637 last = cur; 3638 cur = cur->osr_link(); 3639 } 3640 nmethod* next = nullptr; 3641 if (cur == n) { 3642 found = true; 3643 next = cur->osr_link(); 3644 if (last == nullptr) { 3645 // Remove first element 3646 set_osr_nmethods_head(next); 3647 } else { 3648 last->set_osr_link(next); 3649 } 3650 } 3651 n->set_osr_link(nullptr); 3652 cur = next; 3653 while (cur != nullptr) { 3654 // Find max level after n 3655 if (m == cur->method()) { 3656 max_level = MAX2(max_level, cur->comp_level()); 3657 } 3658 cur = cur->osr_link(); 3659 } 3660 m->set_highest_osr_comp_level(max_level); 3661 return found; 3662 } 3663 3664 int InstanceKlass::mark_osr_nmethods(DeoptimizationScope* deopt_scope, const Method* m) { 3665 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3666 nmethod* osr = osr_nmethods_head(); 3667 int found = 0; 3668 while (osr != nullptr) { 3669 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3670 if (osr->method() == m) { 3671 deopt_scope->mark(osr); 3672 found++; 3673 } 3674 osr = osr->osr_link(); 3675 } 3676 return found; 3677 } 3678 3679 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const { 3680 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3681 nmethod* osr = osr_nmethods_head(); 3682 nmethod* best = nullptr; 3683 while (osr != nullptr) { 3684 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3685 // There can be a time when a c1 osr method exists but we are waiting 3686 // for a c2 version. When c2 completes its osr nmethod we will trash 3687 // the c1 version and only be able to find the c2 version. However 3688 // while we overflow in the c1 code at back branches we don't want to 3689 // try and switch to the same code as we are already running 3690 3691 if (osr->method() == m && 3692 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) { 3693 if (match_level) { 3694 if (osr->comp_level() == comp_level) { 3695 // Found a match - return it. 3696 return osr; 3697 } 3698 } else { 3699 if (best == nullptr || (osr->comp_level() > best->comp_level())) { 3700 if (osr->comp_level() == CompilationPolicy::highest_compile_level()) { 3701 // Found the best possible - return it. 3702 return osr; 3703 } 3704 best = osr; 3705 } 3706 } 3707 } 3708 osr = osr->osr_link(); 3709 } 3710 3711 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set"); 3712 if (best != nullptr && best->comp_level() >= comp_level) { 3713 return best; 3714 } 3715 return nullptr; 3716 } 3717 3718 // ----------------------------------------------------------------------------------------------------- 3719 // Printing 3720 3721 #define BULLET " - " 3722 3723 static const char* state_names[] = { 3724 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error" 3725 }; 3726 3727 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) { 3728 ResourceMark rm; 3729 int* forward_refs = NEW_RESOURCE_ARRAY(int, len); 3730 for (int i = 0; i < len; i++) forward_refs[i] = 0; 3731 for (int i = 0; i < len; i++) { 3732 intptr_t e = start[i]; 3733 st->print("%d : " INTPTR_FORMAT, i, e); 3734 if (forward_refs[i] != 0) { 3735 int from = forward_refs[i]; 3736 int off = (int) start[from]; 3737 st->print(" (offset %d <= [%d])", off, from); 3738 } 3739 if (MetaspaceObj::is_valid((Metadata*)e)) { 3740 st->print(" "); 3741 ((Metadata*)e)->print_value_on(st); 3742 } else if (self != nullptr && e > 0 && e < 0x10000) { 3743 address location = self + e; 3744 int index = (int)((intptr_t*)location - start); 3745 st->print(" (offset %d => [%d])", (int)e, index); 3746 if (index >= 0 && index < len) 3747 forward_refs[index] = i; 3748 } 3749 st->cr(); 3750 } 3751 } 3752 3753 static void print_vtable(vtableEntry* start, int len, outputStream* st) { 3754 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st); 3755 } 3756 3757 template<typename T> 3758 static void print_array_on(outputStream* st, Array<T>* array) { 3759 if (array == nullptr) { st->print_cr("nullptr"); return; } 3760 array->print_value_on(st); st->cr(); 3761 if (Verbose || WizardMode) { 3762 for (int i = 0; i < array->length(); i++) { 3763 st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr(); 3764 } 3765 } 3766 } 3767 3768 static void print_array_on(outputStream* st, Array<int>* array) { 3769 if (array == nullptr) { st->print_cr("nullptr"); return; } 3770 array->print_value_on(st); st->cr(); 3771 if (Verbose || WizardMode) { 3772 for (int i = 0; i < array->length(); i++) { 3773 st->print("%d : %d", i, array->at(i)); st->cr(); 3774 } 3775 } 3776 } 3777 3778 const char* InstanceKlass::init_state_name() const { 3779 return state_names[init_state()]; 3780 } 3781 3782 void InstanceKlass::print_on(outputStream* st) const { 3783 assert(is_klass(), "must be klass"); 3784 Klass::print_on(st); 3785 3786 st->print(BULLET"instance size: %d", size_helper()); st->cr(); 3787 st->print(BULLET"klass size: %d", size()); st->cr(); 3788 st->print(BULLET"access: "); access_flags().print_on(st); st->cr(); 3789 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr(); 3790 st->print(BULLET"state: "); st->print_cr("%s", init_state_name()); 3791 st->print(BULLET"name: "); name()->print_value_on(st); st->cr(); 3792 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr(); 3793 st->print(BULLET"sub: "); 3794 Klass* sub = subklass(); 3795 int n; 3796 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) { 3797 if (n < MaxSubklassPrintSize) { 3798 sub->print_value_on(st); 3799 st->print(" "); 3800 } 3801 } 3802 if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize); 3803 st->cr(); 3804 3805 if (is_interface()) { 3806 st->print_cr(BULLET"nof implementors: %d", nof_implementors()); 3807 if (nof_implementors() == 1) { 3808 st->print_cr(BULLET"implementor: "); 3809 st->print(" "); 3810 implementor()->print_value_on(st); 3811 st->cr(); 3812 } 3813 } 3814 3815 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr(); 3816 st->print(BULLET"methods: "); print_array_on(st, methods()); 3817 st->print(BULLET"method ordering: "); print_array_on(st, method_ordering()); 3818 if (default_methods() != nullptr) { 3819 st->print(BULLET"default_methods: "); print_array_on(st, default_methods()); 3820 } 3821 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices()); 3822 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr(); 3823 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr(); 3824 3825 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr(); 3826 if (UseSecondarySupersTable) { 3827 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr(); 3828 st->print(BULLET"bitmap: " UINTX_FORMAT_X_0, _bitmap); st->cr(); 3829 } 3830 if (secondary_supers() != nullptr) { 3831 if (Verbose) { 3832 bool is_hashed = UseSecondarySupersTable && (_bitmap != SECONDARY_SUPERS_BITMAP_FULL); 3833 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length()); 3834 for (int i = 0; i < _secondary_supers->length(); i++) { 3835 ResourceMark rm; // for external_name() 3836 Klass* secondary_super = _secondary_supers->at(i); 3837 st->print(BULLET"%2d:", i); 3838 if (is_hashed) { 3839 int home_slot = compute_home_slot(secondary_super, _bitmap); 3840 int distance = (i - home_slot) & SECONDARY_SUPERS_TABLE_MASK; 3841 st->print(" dist:%02d:", distance); 3842 } 3843 st->print_cr(" %p %s", secondary_super, secondary_super->external_name()); 3844 } 3845 } 3846 } 3847 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr(); 3848 3849 print_on_maybe_null(st, BULLET"class loader data: ", class_loader_data()); 3850 print_on_maybe_null(st, BULLET"source file: ", source_file_name()); 3851 if (source_debug_extension() != nullptr) { 3852 st->print(BULLET"source debug extension: "); 3853 st->print("%s", source_debug_extension()); 3854 st->cr(); 3855 } 3856 print_on_maybe_null(st, BULLET"class annotations: ", class_annotations()); 3857 print_on_maybe_null(st, BULLET"class type annotations: ", class_type_annotations()); 3858 print_on_maybe_null(st, BULLET"field annotations: ", fields_annotations()); 3859 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations()); 3860 { 3861 bool have_pv = false; 3862 // previous versions are linked together through the InstanceKlass 3863 for (InstanceKlass* pv_node = previous_versions(); 3864 pv_node != nullptr; 3865 pv_node = pv_node->previous_versions()) { 3866 if (!have_pv) 3867 st->print(BULLET"previous version: "); 3868 have_pv = true; 3869 pv_node->constants()->print_value_on(st); 3870 } 3871 if (have_pv) st->cr(); 3872 } 3873 3874 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature()); 3875 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr(); 3876 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr(); 3877 print_on_maybe_null(st, BULLET"record components: ", record_components()); 3878 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr(); 3879 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr(); 3880 if (java_mirror() != nullptr) { 3881 st->print(BULLET"java mirror: "); 3882 java_mirror()->print_value_on(st); 3883 st->cr(); 3884 } else { 3885 st->print_cr(BULLET"java mirror: null"); 3886 } 3887 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr(); 3888 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st); 3889 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr(); 3890 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st); 3891 st->print_cr(BULLET"---- static fields (%d words):", static_field_size()); 3892 3893 FieldPrinter print_static_field(st); 3894 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field); 3895 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size()); 3896 FieldPrinter print_nonstatic_field(st); 3897 InstanceKlass* ik = const_cast<InstanceKlass*>(this); 3898 ik->print_nonstatic_fields(&print_nonstatic_field); 3899 3900 st->print(BULLET"non-static oop maps: "); 3901 OopMapBlock* map = start_of_nonstatic_oop_maps(); 3902 OopMapBlock* end_map = map + nonstatic_oop_map_count(); 3903 while (map < end_map) { 3904 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1)); 3905 map++; 3906 } 3907 st->cr(); 3908 } 3909 3910 void InstanceKlass::print_value_on(outputStream* st) const { 3911 assert(is_klass(), "must be klass"); 3912 if (Verbose || WizardMode) access_flags().print_on(st); 3913 name()->print_value_on(st); 3914 } 3915 3916 void FieldPrinter::do_field(fieldDescriptor* fd) { 3917 _st->print(BULLET); 3918 if (_obj == nullptr) { 3919 fd->print_on(_st); 3920 _st->cr(); 3921 } else { 3922 fd->print_on_for(_st, _obj); 3923 _st->cr(); 3924 } 3925 } 3926 3927 3928 void InstanceKlass::oop_print_on(oop obj, outputStream* st) { 3929 Klass::oop_print_on(obj, st); 3930 3931 if (this == vmClasses::String_klass()) { 3932 typeArrayOop value = java_lang_String::value(obj); 3933 juint length = java_lang_String::length(obj); 3934 if (value != nullptr && 3935 value->is_typeArray() && 3936 length <= (juint) value->length()) { 3937 st->print(BULLET"string: "); 3938 java_lang_String::print(obj, st); 3939 st->cr(); 3940 } 3941 } 3942 3943 st->print_cr(BULLET"---- fields (total size " SIZE_FORMAT " words):", oop_size(obj)); 3944 FieldPrinter print_field(st, obj); 3945 print_nonstatic_fields(&print_field); 3946 3947 if (this == vmClasses::Class_klass()) { 3948 st->print(BULLET"signature: "); 3949 java_lang_Class::print_signature(obj, st); 3950 st->cr(); 3951 Klass* real_klass = java_lang_Class::as_Klass(obj); 3952 if (real_klass != nullptr && real_klass->is_instance_klass()) { 3953 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj)); 3954 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field); 3955 } 3956 } else if (this == vmClasses::MethodType_klass()) { 3957 st->print(BULLET"signature: "); 3958 java_lang_invoke_MethodType::print_signature(obj, st); 3959 st->cr(); 3960 } 3961 } 3962 3963 #ifndef PRODUCT 3964 3965 bool InstanceKlass::verify_itable_index(int i) { 3966 int method_count = klassItable::method_count_for_interface(this); 3967 assert(i >= 0 && i < method_count, "index out of bounds"); 3968 return true; 3969 } 3970 3971 #endif //PRODUCT 3972 3973 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) { 3974 st->print("a "); 3975 name()->print_value_on(st); 3976 obj->print_address_on(st); 3977 if (this == vmClasses::String_klass() 3978 && java_lang_String::value(obj) != nullptr) { 3979 ResourceMark rm; 3980 int len = java_lang_String::length(obj); 3981 int plen = (len < 24 ? len : 12); 3982 char* str = java_lang_String::as_utf8_string(obj, 0, plen); 3983 st->print(" = \"%s\"", str); 3984 if (len > plen) 3985 st->print("...[%d]", len); 3986 } else if (this == vmClasses::Class_klass()) { 3987 Klass* k = java_lang_Class::as_Klass(obj); 3988 st->print(" = "); 3989 if (k != nullptr) { 3990 k->print_value_on(st); 3991 } else { 3992 const char* tname = type2name(java_lang_Class::primitive_type(obj)); 3993 st->print("%s", tname ? tname : "type?"); 3994 } 3995 } else if (this == vmClasses::MethodType_klass()) { 3996 st->print(" = "); 3997 java_lang_invoke_MethodType::print_signature(obj, st); 3998 } else if (java_lang_boxing_object::is_instance(obj)) { 3999 st->print(" = "); 4000 java_lang_boxing_object::print(obj, st); 4001 } else if (this == vmClasses::LambdaForm_klass()) { 4002 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj); 4003 if (vmentry != nullptr) { 4004 st->print(" => "); 4005 vmentry->print_value_on(st); 4006 } 4007 } else if (this == vmClasses::MemberName_klass()) { 4008 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj); 4009 if (vmtarget != nullptr) { 4010 st->print(" = "); 4011 vmtarget->print_value_on(st); 4012 } else { 4013 oop clazz = java_lang_invoke_MemberName::clazz(obj); 4014 oop name = java_lang_invoke_MemberName::name(obj); 4015 if (clazz != nullptr) { 4016 clazz->print_value_on(st); 4017 } else { 4018 st->print("null"); 4019 } 4020 st->print("."); 4021 if (name != nullptr) { 4022 name->print_value_on(st); 4023 } else { 4024 st->print("null"); 4025 } 4026 } 4027 } 4028 } 4029 4030 const char* InstanceKlass::internal_name() const { 4031 return external_name(); 4032 } 4033 4034 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data, 4035 const ModuleEntry* module_entry, 4036 const ClassFileStream* cfs) const { 4037 4038 if (ClassListWriter::is_enabled()) { 4039 ClassListWriter::write(this, cfs); 4040 } 4041 4042 print_class_load_helper(loader_data, module_entry, cfs); 4043 print_class_load_cause_logging(); 4044 } 4045 4046 void InstanceKlass::print_class_load_helper(ClassLoaderData* loader_data, 4047 const ModuleEntry* module_entry, 4048 const ClassFileStream* cfs) const { 4049 4050 if (!log_is_enabled(Info, class, load)) { 4051 return; 4052 } 4053 4054 ResourceMark rm; 4055 LogMessage(class, load) msg; 4056 stringStream info_stream; 4057 4058 // Name and class hierarchy info 4059 info_stream.print("%s", external_name()); 4060 4061 // Source 4062 if (cfs != nullptr) { 4063 if (cfs->source() != nullptr) { 4064 const char* module_name = (module_entry->name() == nullptr) ? UNNAMED_MODULE : module_entry->name()->as_C_string(); 4065 if (module_name != nullptr) { 4066 // When the boot loader created the stream, it didn't know the module name 4067 // yet. Let's format it now. 4068 if (cfs->from_boot_loader_modules_image()) { 4069 info_stream.print(" source: jrt:/%s", module_name); 4070 } else { 4071 info_stream.print(" source: %s", cfs->source()); 4072 } 4073 } else { 4074 info_stream.print(" source: %s", cfs->source()); 4075 } 4076 } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) { 4077 Thread* current = Thread::current(); 4078 Klass* caller = current->is_Java_thread() ? 4079 JavaThread::cast(current)->security_get_caller_class(1): 4080 nullptr; 4081 // caller can be null, for example, during a JVMTI VM_Init hook 4082 if (caller != nullptr) { 4083 info_stream.print(" source: instance of %s", caller->external_name()); 4084 } else { 4085 // source is unknown 4086 } 4087 } else { 4088 oop class_loader = loader_data->class_loader(); 4089 info_stream.print(" source: %s", class_loader->klass()->external_name()); 4090 } 4091 } else { 4092 assert(this->is_shared(), "must be"); 4093 if (MetaspaceShared::is_shared_dynamic((void*)this)) { 4094 info_stream.print(" source: shared objects file (top)"); 4095 } else { 4096 info_stream.print(" source: shared objects file"); 4097 } 4098 } 4099 4100 msg.info("%s", info_stream.as_string()); 4101 4102 if (log_is_enabled(Debug, class, load)) { 4103 stringStream debug_stream; 4104 4105 // Class hierarchy info 4106 debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT, 4107 p2i(this), p2i(superklass())); 4108 4109 // Interfaces 4110 if (local_interfaces() != nullptr && local_interfaces()->length() > 0) { 4111 debug_stream.print(" interfaces:"); 4112 int length = local_interfaces()->length(); 4113 for (int i = 0; i < length; i++) { 4114 debug_stream.print(" " PTR_FORMAT, 4115 p2i(InstanceKlass::cast(local_interfaces()->at(i)))); 4116 } 4117 } 4118 4119 // Class loader 4120 debug_stream.print(" loader: ["); 4121 loader_data->print_value_on(&debug_stream); 4122 debug_stream.print("]"); 4123 4124 // Classfile checksum 4125 if (cfs) { 4126 debug_stream.print(" bytes: %d checksum: %08x", 4127 cfs->length(), 4128 ClassLoader::crc32(0, (const char*)cfs->buffer(), 4129 cfs->length())); 4130 } 4131 4132 msg.debug("%s", debug_stream.as_string()); 4133 } 4134 } 4135 4136 void InstanceKlass::print_class_load_cause_logging() const { 4137 bool log_cause_native = log_is_enabled(Info, class, load, cause, native); 4138 if (log_cause_native || log_is_enabled(Info, class, load, cause)) { 4139 JavaThread* current = JavaThread::current(); 4140 ResourceMark rm(current); 4141 const char* name = external_name(); 4142 4143 if (LogClassLoadingCauseFor == nullptr || 4144 (strcmp("*", LogClassLoadingCauseFor) != 0 && 4145 strstr(name, LogClassLoadingCauseFor) == nullptr)) { 4146 return; 4147 } 4148 4149 // Log Java stack first 4150 { 4151 LogMessage(class, load, cause) msg; 4152 NonInterleavingLogStream info_stream{LogLevelType::Info, msg}; 4153 4154 info_stream.print_cr("Java stack when loading %s:", name); 4155 current->print_stack_on(&info_stream); 4156 } 4157 4158 // Log native stack second 4159 if (log_cause_native) { 4160 // Log to string first so that lines can be indented 4161 stringStream stack_stream; 4162 char buf[O_BUFLEN]; 4163 address lastpc = nullptr; 4164 if (os::platform_print_native_stack(&stack_stream, nullptr, buf, O_BUFLEN, lastpc)) { 4165 // We have printed the native stack in platform-specific code, 4166 // so nothing else to do in this case. 4167 } else { 4168 frame f = os::current_frame(); 4169 VMError::print_native_stack(&stack_stream, f, current, true /*print_source_info */, 4170 -1 /* max stack_stream */, buf, O_BUFLEN); 4171 } 4172 4173 LogMessage(class, load, cause, native) msg; 4174 NonInterleavingLogStream info_stream{LogLevelType::Info, msg}; 4175 info_stream.print_cr("Native stack when loading %s:", name); 4176 4177 // Print each native stack line to the log 4178 int size = (int) stack_stream.size(); 4179 char* stack = stack_stream.as_string(); 4180 char* stack_end = stack + size; 4181 char* line_start = stack; 4182 for (char* p = stack; p < stack_end; p++) { 4183 if (*p == '\n') { 4184 *p = '\0'; 4185 info_stream.print_cr("\t%s", line_start); 4186 line_start = p + 1; 4187 } 4188 } 4189 if (line_start < stack_end) { 4190 info_stream.print_cr("\t%s", line_start); 4191 } 4192 } 4193 } 4194 } 4195 4196 // Verification 4197 4198 class VerifyFieldClosure: public BasicOopIterateClosure { 4199 protected: 4200 template <class T> void do_oop_work(T* p) { 4201 oop obj = RawAccess<>::oop_load(p); 4202 if (!oopDesc::is_oop_or_null(obj)) { 4203 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj)); 4204 Universe::print_on(tty); 4205 guarantee(false, "boom"); 4206 } 4207 } 4208 public: 4209 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); } 4210 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); } 4211 }; 4212 4213 void InstanceKlass::verify_on(outputStream* st) { 4214 #ifndef PRODUCT 4215 // Avoid redundant verifies, this really should be in product. 4216 if (_verify_count == Universe::verify_count()) return; 4217 _verify_count = Universe::verify_count(); 4218 #endif 4219 4220 // Verify Klass 4221 Klass::verify_on(st); 4222 4223 // Verify that klass is present in ClassLoaderData 4224 guarantee(class_loader_data()->contains_klass(this), 4225 "this class isn't found in class loader data"); 4226 4227 // Verify vtables 4228 if (is_linked()) { 4229 // $$$ This used to be done only for m/s collections. Doing it 4230 // always seemed a valid generalization. (DLD -- 6/00) 4231 vtable().verify(st); 4232 } 4233 4234 // Verify first subklass 4235 if (subklass() != nullptr) { 4236 guarantee(subklass()->is_klass(), "should be klass"); 4237 } 4238 4239 // Verify siblings 4240 Klass* super = this->super(); 4241 Klass* sib = next_sibling(); 4242 if (sib != nullptr) { 4243 if (sib == this) { 4244 fatal("subclass points to itself " PTR_FORMAT, p2i(sib)); 4245 } 4246 4247 guarantee(sib->is_klass(), "should be klass"); 4248 guarantee(sib->super() == super, "siblings should have same superklass"); 4249 } 4250 4251 // Verify local interfaces 4252 if (local_interfaces()) { 4253 Array<InstanceKlass*>* local_interfaces = this->local_interfaces(); 4254 for (int j = 0; j < local_interfaces->length(); j++) { 4255 InstanceKlass* e = local_interfaces->at(j); 4256 guarantee(e->is_klass() && e->is_interface(), "invalid local interface"); 4257 } 4258 } 4259 4260 // Verify transitive interfaces 4261 if (transitive_interfaces() != nullptr) { 4262 Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces(); 4263 for (int j = 0; j < transitive_interfaces->length(); j++) { 4264 InstanceKlass* e = transitive_interfaces->at(j); 4265 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface"); 4266 } 4267 } 4268 4269 // Verify methods 4270 if (methods() != nullptr) { 4271 Array<Method*>* methods = this->methods(); 4272 for (int j = 0; j < methods->length(); j++) { 4273 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 4274 } 4275 for (int j = 0; j < methods->length() - 1; j++) { 4276 Method* m1 = methods->at(j); 4277 Method* m2 = methods->at(j + 1); 4278 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 4279 } 4280 } 4281 4282 // Verify method ordering 4283 if (method_ordering() != nullptr) { 4284 Array<int>* method_ordering = this->method_ordering(); 4285 int length = method_ordering->length(); 4286 if (JvmtiExport::can_maintain_original_method_order() || 4287 ((CDSConfig::is_using_archive() || CDSConfig::is_dumping_archive()) && length != 0)) { 4288 guarantee(length == methods()->length(), "invalid method ordering length"); 4289 jlong sum = 0; 4290 for (int j = 0; j < length; j++) { 4291 int original_index = method_ordering->at(j); 4292 guarantee(original_index >= 0, "invalid method ordering index"); 4293 guarantee(original_index < length, "invalid method ordering index"); 4294 sum += original_index; 4295 } 4296 // Verify sum of indices 0,1,...,length-1 4297 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum"); 4298 } else { 4299 guarantee(length == 0, "invalid method ordering length"); 4300 } 4301 } 4302 4303 // Verify default methods 4304 if (default_methods() != nullptr) { 4305 Array<Method*>* methods = this->default_methods(); 4306 for (int j = 0; j < methods->length(); j++) { 4307 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 4308 } 4309 for (int j = 0; j < methods->length() - 1; j++) { 4310 Method* m1 = methods->at(j); 4311 Method* m2 = methods->at(j + 1); 4312 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 4313 } 4314 } 4315 4316 // Verify JNI static field identifiers 4317 if (jni_ids() != nullptr) { 4318 jni_ids()->verify(this); 4319 } 4320 4321 // Verify other fields 4322 if (constants() != nullptr) { 4323 guarantee(constants()->is_constantPool(), "should be constant pool"); 4324 } 4325 } 4326 4327 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) { 4328 Klass::oop_verify_on(obj, st); 4329 VerifyFieldClosure blk; 4330 obj->oop_iterate(&blk); 4331 } 4332 4333 4334 // JNIid class for jfieldIDs only 4335 // Note to reviewers: 4336 // These JNI functions are just moved over to column 1 and not changed 4337 // in the compressed oops workspace. 4338 JNIid::JNIid(Klass* holder, int offset, JNIid* next) { 4339 _holder = holder; 4340 _offset = offset; 4341 _next = next; 4342 debug_only(_is_static_field_id = false;) 4343 } 4344 4345 4346 JNIid* JNIid::find(int offset) { 4347 JNIid* current = this; 4348 while (current != nullptr) { 4349 if (current->offset() == offset) return current; 4350 current = current->next(); 4351 } 4352 return nullptr; 4353 } 4354 4355 void JNIid::deallocate(JNIid* current) { 4356 while (current != nullptr) { 4357 JNIid* next = current->next(); 4358 delete current; 4359 current = next; 4360 } 4361 } 4362 4363 4364 void JNIid::verify(Klass* holder) { 4365 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields(); 4366 int end_field_offset; 4367 end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize); 4368 4369 JNIid* current = this; 4370 while (current != nullptr) { 4371 guarantee(current->holder() == holder, "Invalid klass in JNIid"); 4372 #ifdef ASSERT 4373 int o = current->offset(); 4374 if (current->is_static_field_id()) { 4375 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid"); 4376 } 4377 #endif 4378 current = current->next(); 4379 } 4380 } 4381 4382 void InstanceKlass::set_init_state(ClassState state) { 4383 #ifdef ASSERT 4384 bool good_state = is_shared() ? (_init_state <= state) 4385 : (_init_state < state); 4386 assert(good_state || state == allocated, "illegal state transition"); 4387 #endif 4388 assert(_init_thread == nullptr, "should be cleared before state change"); 4389 Atomic::release_store(&_init_state, state); 4390 } 4391 4392 #if INCLUDE_JVMTI 4393 4394 // RedefineClasses() support for previous versions 4395 4396 // Globally, there is at least one previous version of a class to walk 4397 // during class unloading, which is saved because old methods in the class 4398 // are still running. Otherwise the previous version list is cleaned up. 4399 bool InstanceKlass::_should_clean_previous_versions = false; 4400 4401 // Returns true if there are previous versions of a class for class 4402 // unloading only. Also resets the flag to false. purge_previous_version 4403 // will set the flag to true if there are any left, i.e., if there's any 4404 // work to do for next time. This is to avoid the expensive code cache 4405 // walk in CLDG::clean_deallocate_lists(). 4406 bool InstanceKlass::should_clean_previous_versions_and_reset() { 4407 bool ret = _should_clean_previous_versions; 4408 log_trace(redefine, class, iklass, purge)("Class unloading: should_clean_previous_versions = %s", 4409 ret ? "true" : "false"); 4410 _should_clean_previous_versions = false; 4411 return ret; 4412 } 4413 4414 // This nulls out jmethodIDs for all methods in 'klass' 4415 // It needs to be called explicitly for all previous versions of a class because these may not be cleaned up 4416 // during class unloading. 4417 // We can not use the jmethodID cache associated with klass directly because the 'previous' versions 4418 // do not have the jmethodID cache filled in. Instead, we need to lookup jmethodID for each method and this 4419 // is expensive - O(n) for one jmethodID lookup. For all contained methods it is O(n^2). 4420 // The reason for expensive jmethodID lookup for each method is that there is no direct link between method and jmethodID. 4421 void InstanceKlass::clear_jmethod_ids(InstanceKlass* klass) { 4422 Array<Method*>* method_refs = klass->methods(); 4423 for (int k = 0; k < method_refs->length(); k++) { 4424 Method* method = method_refs->at(k); 4425 if (method != nullptr && method->is_obsolete()) { 4426 method->clear_jmethod_id(); 4427 } 4428 } 4429 } 4430 4431 // Purge previous versions before adding new previous versions of the class and 4432 // during class unloading. 4433 void InstanceKlass::purge_previous_version_list() { 4434 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 4435 assert(has_been_redefined(), "Should only be called for main class"); 4436 4437 // Quick exit. 4438 if (previous_versions() == nullptr) { 4439 return; 4440 } 4441 4442 // This klass has previous versions so see what we can cleanup 4443 // while it is safe to do so. 4444 4445 int deleted_count = 0; // leave debugging breadcrumbs 4446 int live_count = 0; 4447 ClassLoaderData* loader_data = class_loader_data(); 4448 assert(loader_data != nullptr, "should never be null"); 4449 4450 ResourceMark rm; 4451 log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name()); 4452 4453 // previous versions are linked together through the InstanceKlass 4454 InstanceKlass* pv_node = previous_versions(); 4455 InstanceKlass* last = this; 4456 int version = 0; 4457 4458 // check the previous versions list 4459 for (; pv_node != nullptr; ) { 4460 4461 ConstantPool* pvcp = pv_node->constants(); 4462 assert(pvcp != nullptr, "cp ref was unexpectedly cleared"); 4463 4464 if (!pvcp->on_stack()) { 4465 // If the constant pool isn't on stack, none of the methods 4466 // are executing. Unlink this previous_version. 4467 // The previous version InstanceKlass is on the ClassLoaderData deallocate list 4468 // so will be deallocated during the next phase of class unloading. 4469 log_trace(redefine, class, iklass, purge) 4470 ("previous version " PTR_FORMAT " is dead.", p2i(pv_node)); 4471 // Unlink from previous version list. 4472 assert(pv_node->class_loader_data() == loader_data, "wrong loader_data"); 4473 InstanceKlass* next = pv_node->previous_versions(); 4474 clear_jmethod_ids(pv_node); // jmethodID maintenance for the unloaded class 4475 pv_node->link_previous_versions(nullptr); // point next to null 4476 last->link_previous_versions(next); 4477 // Delete this node directly. Nothing is referring to it and we don't 4478 // want it to increase the counter for metadata to delete in CLDG. 4479 MetadataFactory::free_metadata(loader_data, pv_node); 4480 pv_node = next; 4481 deleted_count++; 4482 version++; 4483 continue; 4484 } else { 4485 assert(pvcp->pool_holder() != nullptr, "Constant pool with no holder"); 4486 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack"); 4487 live_count++; 4488 if (pvcp->is_shared()) { 4489 // Shared previous versions can never be removed so no cleaning is needed. 4490 log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is shared", p2i(pv_node)); 4491 } else { 4492 // Previous version alive, set that clean is needed for next time. 4493 _should_clean_previous_versions = true; 4494 log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is alive", p2i(pv_node)); 4495 } 4496 } 4497 4498 // next previous version 4499 last = pv_node; 4500 pv_node = pv_node->previous_versions(); 4501 version++; 4502 } 4503 log_trace(redefine, class, iklass, purge) 4504 ("previous version stats: live=%d, deleted=%d", live_count, deleted_count); 4505 } 4506 4507 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods, 4508 int emcp_method_count) { 4509 int obsolete_method_count = old_methods->length() - emcp_method_count; 4510 4511 if (emcp_method_count != 0 && obsolete_method_count != 0 && 4512 _previous_versions != nullptr) { 4513 // We have a mix of obsolete and EMCP methods so we have to 4514 // clear out any matching EMCP method entries the hard way. 4515 int local_count = 0; 4516 for (int i = 0; i < old_methods->length(); i++) { 4517 Method* old_method = old_methods->at(i); 4518 if (old_method->is_obsolete()) { 4519 // only obsolete methods are interesting 4520 Symbol* m_name = old_method->name(); 4521 Symbol* m_signature = old_method->signature(); 4522 4523 // previous versions are linked together through the InstanceKlass 4524 int j = 0; 4525 for (InstanceKlass* prev_version = _previous_versions; 4526 prev_version != nullptr; 4527 prev_version = prev_version->previous_versions(), j++) { 4528 4529 Array<Method*>* method_refs = prev_version->methods(); 4530 for (int k = 0; k < method_refs->length(); k++) { 4531 Method* method = method_refs->at(k); 4532 4533 if (!method->is_obsolete() && 4534 method->name() == m_name && 4535 method->signature() == m_signature) { 4536 // The current RedefineClasses() call has made all EMCP 4537 // versions of this method obsolete so mark it as obsolete 4538 log_trace(redefine, class, iklass, add) 4539 ("%s(%s): flush obsolete method @%d in version @%d", 4540 m_name->as_C_string(), m_signature->as_C_string(), k, j); 4541 4542 method->set_is_obsolete(); 4543 break; 4544 } 4545 } 4546 4547 // The previous loop may not find a matching EMCP method, but 4548 // that doesn't mean that we can optimize and not go any 4549 // further back in the PreviousVersion generations. The EMCP 4550 // method for this generation could have already been made obsolete, 4551 // but there still may be an older EMCP method that has not 4552 // been made obsolete. 4553 } 4554 4555 if (++local_count >= obsolete_method_count) { 4556 // no more obsolete methods so bail out now 4557 break; 4558 } 4559 } 4560 } 4561 } 4562 } 4563 4564 // Save the scratch_class as the previous version if any of the methods are running. 4565 // The previous_versions are used to set breakpoints in EMCP methods and they are 4566 // also used to clean MethodData links to redefined methods that are no longer running. 4567 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class, 4568 int emcp_method_count) { 4569 assert(Thread::current()->is_VM_thread(), 4570 "only VMThread can add previous versions"); 4571 4572 ResourceMark rm; 4573 log_trace(redefine, class, iklass, add) 4574 ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count); 4575 4576 // Clean out old previous versions for this class 4577 purge_previous_version_list(); 4578 4579 // Mark newly obsolete methods in remaining previous versions. An EMCP method from 4580 // a previous redefinition may be made obsolete by this redefinition. 4581 Array<Method*>* old_methods = scratch_class->methods(); 4582 mark_newly_obsolete_methods(old_methods, emcp_method_count); 4583 4584 // If the constant pool for this previous version of the class 4585 // is not marked as being on the stack, then none of the methods 4586 // in this previous version of the class are on the stack so 4587 // we don't need to add this as a previous version. 4588 ConstantPool* cp_ref = scratch_class->constants(); 4589 if (!cp_ref->on_stack()) { 4590 log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running"); 4591 scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class); 4592 return; 4593 } 4594 4595 // Add previous version if any methods are still running or if this is 4596 // a shared class which should never be removed. 4597 assert(scratch_class->previous_versions() == nullptr, "shouldn't have a previous version"); 4598 scratch_class->link_previous_versions(previous_versions()); 4599 link_previous_versions(scratch_class); 4600 if (cp_ref->is_shared()) { 4601 log_trace(redefine, class, iklass, add) ("scratch class added; class is shared"); 4602 } else { 4603 // We only set clean_previous_versions flag for processing during class 4604 // unloading for non-shared classes. 4605 _should_clean_previous_versions = true; 4606 log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack."); 4607 } 4608 } // end add_previous_version() 4609 4610 #endif // INCLUDE_JVMTI 4611 4612 Method* InstanceKlass::method_with_idnum(int idnum) { 4613 Method* m = nullptr; 4614 if (idnum < methods()->length()) { 4615 m = methods()->at(idnum); 4616 } 4617 if (m == nullptr || m->method_idnum() != idnum) { 4618 for (int index = 0; index < methods()->length(); ++index) { 4619 m = methods()->at(index); 4620 if (m->method_idnum() == idnum) { 4621 return m; 4622 } 4623 } 4624 // None found, return null for the caller to handle. 4625 return nullptr; 4626 } 4627 return m; 4628 } 4629 4630 4631 Method* InstanceKlass::method_with_orig_idnum(int idnum) { 4632 if (idnum >= methods()->length()) { 4633 return nullptr; 4634 } 4635 Method* m = methods()->at(idnum); 4636 if (m != nullptr && m->orig_method_idnum() == idnum) { 4637 return m; 4638 } 4639 // Obsolete method idnum does not match the original idnum 4640 for (int index = 0; index < methods()->length(); ++index) { 4641 m = methods()->at(index); 4642 if (m->orig_method_idnum() == idnum) { 4643 return m; 4644 } 4645 } 4646 // None found, return null for the caller to handle. 4647 return nullptr; 4648 } 4649 4650 4651 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) { 4652 InstanceKlass* holder = get_klass_version(version); 4653 if (holder == nullptr) { 4654 return nullptr; // The version of klass is gone, no method is found 4655 } 4656 Method* method = holder->method_with_orig_idnum(idnum); 4657 return method; 4658 } 4659 4660 #if INCLUDE_JVMTI 4661 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() { 4662 return _cached_class_file; 4663 } 4664 4665 jint InstanceKlass::get_cached_class_file_len() { 4666 return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file); 4667 } 4668 4669 unsigned char * InstanceKlass::get_cached_class_file_bytes() { 4670 return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file); 4671 } 4672 #endif 4673 4674 // Make a step iterating over the class hierarchy under the root class. 4675 // Skips subclasses if requested. 4676 void ClassHierarchyIterator::next() { 4677 assert(_current != nullptr, "required"); 4678 if (_visit_subclasses && _current->subklass() != nullptr) { 4679 _current = _current->subklass(); 4680 return; // visit next subclass 4681 } 4682 _visit_subclasses = true; // reset 4683 while (_current->next_sibling() == nullptr && _current != _root) { 4684 _current = _current->superklass(); // backtrack; no more sibling subclasses left 4685 } 4686 if (_current == _root) { 4687 // Iteration is over (back at root after backtracking). Invalidate the iterator. 4688 _current = nullptr; 4689 return; 4690 } 4691 _current = _current->next_sibling(); 4692 return; // visit next sibling subclass 4693 }