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