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 ResourceMark rm(THREAD); 1549 JavaThread *jt = THREAD; 1550 { 1551 // Atomic creation of array_klasses 1552 MutexLocker ma(THREAD, MultiArray_lock); 1553 1554 // Check if update has already taken place 1555 if (array_klasses() == nullptr) { 1556 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL); 1557 // use 'release' to pair with lock-free load 1558 release_set_array_klasses(k); 1559 } 1560 } 1561 } 1562 // array_klasses() will always be set at this point 1563 ObjArrayKlass* oak = array_klasses(); 1564 return oak->array_klass(n, THREAD); 1565 } 1566 1567 ArrayKlass* InstanceKlass::array_klass_or_null(int n) { 1568 // Need load-acquire for lock-free read 1569 ObjArrayKlass* oak = array_klasses_acquire(); 1570 if (oak == nullptr) { 1571 return nullptr; 1572 } else { 1573 return oak->array_klass_or_null(n); 1574 } 1575 } 1576 1577 ArrayKlass* InstanceKlass::array_klass(TRAPS) { 1578 return array_klass(1, THREAD); 1579 } 1580 1581 ArrayKlass* InstanceKlass::array_klass_or_null() { 1582 return array_klass_or_null(1); 1583 } 1584 1585 static int call_class_initializer_counter = 0; // for debugging 1586 1587 Method* InstanceKlass::class_initializer() const { 1588 Method* clinit = find_method( 1589 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature()); 1590 if (clinit != nullptr && clinit->has_valid_initializer_flags()) { 1591 return clinit; 1592 } 1593 return nullptr; 1594 } 1595 1596 void InstanceKlass::call_class_initializer(TRAPS) { 1597 if (ReplayCompiles && 1598 (ReplaySuppressInitializers == 1 || 1599 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) { 1600 // Hide the existence of the initializer for the purpose of replaying the compile 1601 return; 1602 } 1603 1604 #if INCLUDE_CDS 1605 // This is needed to ensure the consistency of the archived heap objects. 1606 if (has_archived_enum_objs()) { 1607 assert(is_shared(), "must be"); 1608 bool initialized = HeapShared::initialize_enum_klass(this, CHECK); 1609 if (initialized) { 1610 return; 1611 } 1612 } 1613 #endif 1614 1615 methodHandle h_method(THREAD, class_initializer()); 1616 assert(!is_initialized(), "we cannot initialize twice"); 1617 LogTarget(Info, class, init) lt; 1618 if (lt.is_enabled()) { 1619 ResourceMark rm(THREAD); 1620 LogStream ls(lt); 1621 ls.print("%d Initializing ", call_class_initializer_counter++); 1622 name()->print_value_on(&ls); 1623 ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"", 1624 h_method() == nullptr ? "(no method)" : "", p2i(this), 1625 THREAD->name()); 1626 } 1627 if (h_method() != nullptr) { 1628 JavaCallArguments args; // No arguments 1629 JavaValue result(T_VOID); 1630 JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args) 1631 } 1632 } 1633 1634 1635 void InstanceKlass::mask_for(const methodHandle& method, int bci, 1636 InterpreterOopMap* entry_for) { 1637 // Lazily create the _oop_map_cache at first request 1638 // Lock-free access requires load_acquire. 1639 OopMapCache* oop_map_cache = Atomic::load_acquire(&_oop_map_cache); 1640 if (oop_map_cache == nullptr) { 1641 MutexLocker x(OopMapCacheAlloc_lock); 1642 // Check if _oop_map_cache was allocated while we were waiting for this lock 1643 if ((oop_map_cache = _oop_map_cache) == nullptr) { 1644 oop_map_cache = new OopMapCache(); 1645 // Ensure _oop_map_cache is stable, since it is examined without a lock 1646 Atomic::release_store(&_oop_map_cache, oop_map_cache); 1647 } 1648 } 1649 // _oop_map_cache is constant after init; lookup below does its own locking. 1650 oop_map_cache->lookup(method, bci, entry_for); 1651 } 1652 1653 bool InstanceKlass::contains_field_offset(int offset) { 1654 fieldDescriptor fd; 1655 return find_field_from_offset(offset, false, &fd); 1656 } 1657 1658 FieldInfo InstanceKlass::field(int index) const { 1659 for (AllFieldStream fs(this); !fs.done(); fs.next()) { 1660 if (fs.index() == index) { 1661 return fs.to_FieldInfo(); 1662 } 1663 } 1664 fatal("Field not found"); 1665 return FieldInfo(); 1666 } 1667 1668 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const { 1669 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1670 Symbol* f_name = fs.name(); 1671 Symbol* f_sig = fs.signature(); 1672 if (f_name == name && f_sig == sig) { 1673 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index()); 1674 return true; 1675 } 1676 } 1677 return false; 1678 } 1679 1680 1681 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const { 1682 const int n = local_interfaces()->length(); 1683 for (int i = 0; i < n; i++) { 1684 Klass* intf1 = local_interfaces()->at(i); 1685 assert(intf1->is_interface(), "just checking type"); 1686 // search for field in current interface 1687 if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) { 1688 assert(fd->is_static(), "interface field must be static"); 1689 return intf1; 1690 } 1691 // search for field in direct superinterfaces 1692 Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd); 1693 if (intf2 != nullptr) return intf2; 1694 } 1695 // otherwise field lookup fails 1696 return nullptr; 1697 } 1698 1699 1700 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const { 1701 // search order according to newest JVM spec (5.4.3.2, p.167). 1702 // 1) search for field in current klass 1703 if (find_local_field(name, sig, fd)) { 1704 return const_cast<InstanceKlass*>(this); 1705 } 1706 // 2) search for field recursively in direct superinterfaces 1707 { Klass* intf = find_interface_field(name, sig, fd); 1708 if (intf != nullptr) return intf; 1709 } 1710 // 3) apply field lookup recursively if superclass exists 1711 { Klass* supr = super(); 1712 if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, fd); 1713 } 1714 // 4) otherwise field lookup fails 1715 return nullptr; 1716 } 1717 1718 1719 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const { 1720 // search order according to newest JVM spec (5.4.3.2, p.167). 1721 // 1) search for field in current klass 1722 if (find_local_field(name, sig, fd)) { 1723 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this); 1724 } 1725 // 2) search for field recursively in direct superinterfaces 1726 if (is_static) { 1727 Klass* intf = find_interface_field(name, sig, fd); 1728 if (intf != nullptr) return intf; 1729 } 1730 // 3) apply field lookup recursively if superclass exists 1731 { Klass* supr = super(); 1732 if (supr != nullptr) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd); 1733 } 1734 // 4) otherwise field lookup fails 1735 return nullptr; 1736 } 1737 1738 1739 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const { 1740 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1741 if (fs.offset() == offset) { 1742 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index()); 1743 if (fd->is_static() == is_static) return true; 1744 } 1745 } 1746 return false; 1747 } 1748 1749 1750 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const { 1751 Klass* klass = const_cast<InstanceKlass*>(this); 1752 while (klass != nullptr) { 1753 if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) { 1754 return true; 1755 } 1756 klass = klass->super(); 1757 } 1758 return false; 1759 } 1760 1761 1762 void InstanceKlass::methods_do(void f(Method* method)) { 1763 // Methods aren't stable until they are loaded. This can be read outside 1764 // a lock through the ClassLoaderData for profiling 1765 // Redefined scratch classes are on the list and need to be cleaned 1766 if (!is_loaded() && !is_scratch_class()) { 1767 return; 1768 } 1769 1770 int len = methods()->length(); 1771 for (int index = 0; index < len; index++) { 1772 Method* m = methods()->at(index); 1773 assert(m->is_method(), "must be method"); 1774 f(m); 1775 } 1776 } 1777 1778 1779 void InstanceKlass::do_local_static_fields(FieldClosure* cl) { 1780 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1781 if (fs.access_flags().is_static()) { 1782 fieldDescriptor& fd = fs.field_descriptor(); 1783 cl->do_field(&fd); 1784 } 1785 } 1786 } 1787 1788 1789 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) { 1790 for (JavaFieldStream fs(this); !fs.done(); fs.next()) { 1791 if (fs.access_flags().is_static()) { 1792 fieldDescriptor& fd = fs.field_descriptor(); 1793 f(&fd, mirror, CHECK); 1794 } 1795 } 1796 } 1797 1798 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) { 1799 InstanceKlass* super = superklass(); 1800 if (super != nullptr) { 1801 super->do_nonstatic_fields(cl); 1802 } 1803 fieldDescriptor fd; 1804 int length = java_fields_count(); 1805 for (int i = 0; i < length; i += 1) { 1806 fd.reinitialize(this, i); 1807 if (!fd.is_static()) { 1808 cl->do_field(&fd); 1809 } 1810 } 1811 } 1812 1813 // first in Pair is offset, second is index. 1814 static int compare_fields_by_offset(Pair<int,int>* a, Pair<int,int>* b) { 1815 return a->first - b->first; 1816 } 1817 1818 void InstanceKlass::print_nonstatic_fields(FieldClosure* cl) { 1819 InstanceKlass* super = superklass(); 1820 if (super != nullptr) { 1821 super->print_nonstatic_fields(cl); 1822 } 1823 ResourceMark rm; 1824 fieldDescriptor fd; 1825 // In DebugInfo nonstatic fields are sorted by offset. 1826 GrowableArray<Pair<int,int> > fields_sorted; 1827 int i = 0; 1828 for (AllFieldStream fs(this); !fs.done(); fs.next()) { 1829 if (!fs.access_flags().is_static()) { 1830 fd = fs.field_descriptor(); 1831 Pair<int,int> f(fs.offset(), fs.index()); 1832 fields_sorted.push(f); 1833 i++; 1834 } 1835 } 1836 if (i > 0) { 1837 int length = i; 1838 assert(length == fields_sorted.length(), "duh"); 1839 fields_sorted.sort(compare_fields_by_offset); 1840 for (int i = 0; i < length; i++) { 1841 fd.reinitialize(this, fields_sorted.at(i).second); 1842 assert(!fd.is_static() && fd.offset() == fields_sorted.at(i).first, "only nonstatic fields"); 1843 cl->do_field(&fd); 1844 } 1845 } 1846 } 1847 1848 #ifdef ASSERT 1849 static int linear_search(const Array<Method*>* methods, 1850 const Symbol* name, 1851 const Symbol* signature) { 1852 const int len = methods->length(); 1853 for (int index = 0; index < len; index++) { 1854 const Method* const m = methods->at(index); 1855 assert(m->is_method(), "must be method"); 1856 if (m->signature() == signature && m->name() == name) { 1857 return index; 1858 } 1859 } 1860 return -1; 1861 } 1862 #endif 1863 1864 bool InstanceKlass::_disable_method_binary_search = false; 1865 1866 NOINLINE int linear_search(const Array<Method*>* methods, const Symbol* name) { 1867 int len = methods->length(); 1868 int l = 0; 1869 int h = len - 1; 1870 while (l <= h) { 1871 Method* m = methods->at(l); 1872 if (m->name() == name) { 1873 return l; 1874 } 1875 l++; 1876 } 1877 return -1; 1878 } 1879 1880 inline int InstanceKlass::quick_search(const Array<Method*>* methods, const Symbol* name) { 1881 if (_disable_method_binary_search) { 1882 assert(CDSConfig::is_dumping_dynamic_archive(), "must be"); 1883 // At the final stage of dynamic dumping, the methods array may not be sorted 1884 // by ascending addresses of their names, so we can't use binary search anymore. 1885 // However, methods with the same name are still laid out consecutively inside the 1886 // methods array, so let's look for the first one that matches. 1887 return linear_search(methods, name); 1888 } 1889 1890 int len = methods->length(); 1891 int l = 0; 1892 int h = len - 1; 1893 1894 // methods are sorted by ascending addresses of their names, so do binary search 1895 while (l <= h) { 1896 int mid = (l + h) >> 1; 1897 Method* m = methods->at(mid); 1898 assert(m->is_method(), "must be method"); 1899 int res = m->name()->fast_compare(name); 1900 if (res == 0) { 1901 return mid; 1902 } else if (res < 0) { 1903 l = mid + 1; 1904 } else { 1905 h = mid - 1; 1906 } 1907 } 1908 return -1; 1909 } 1910 1911 // find_method looks up the name/signature in the local methods array 1912 Method* InstanceKlass::find_method(const Symbol* name, 1913 const Symbol* signature) const { 1914 return find_method_impl(name, signature, 1915 OverpassLookupMode::find, 1916 StaticLookupMode::find, 1917 PrivateLookupMode::find); 1918 } 1919 1920 Method* InstanceKlass::find_method_impl(const Symbol* name, 1921 const Symbol* signature, 1922 OverpassLookupMode overpass_mode, 1923 StaticLookupMode static_mode, 1924 PrivateLookupMode private_mode) const { 1925 return InstanceKlass::find_method_impl(methods(), 1926 name, 1927 signature, 1928 overpass_mode, 1929 static_mode, 1930 private_mode); 1931 } 1932 1933 // find_instance_method looks up the name/signature in the local methods array 1934 // and skips over static methods 1935 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods, 1936 const Symbol* name, 1937 const Symbol* signature, 1938 PrivateLookupMode private_mode) { 1939 Method* const meth = InstanceKlass::find_method_impl(methods, 1940 name, 1941 signature, 1942 OverpassLookupMode::find, 1943 StaticLookupMode::skip, 1944 private_mode); 1945 assert(((meth == nullptr) || !meth->is_static()), 1946 "find_instance_method should have skipped statics"); 1947 return meth; 1948 } 1949 1950 // find_instance_method looks up the name/signature in the local methods array 1951 // and skips over static methods 1952 Method* InstanceKlass::find_instance_method(const Symbol* name, 1953 const Symbol* signature, 1954 PrivateLookupMode private_mode) const { 1955 return InstanceKlass::find_instance_method(methods(), name, signature, private_mode); 1956 } 1957 1958 // Find looks up the name/signature in the local methods array 1959 // and filters on the overpass, static and private flags 1960 // This returns the first one found 1961 // note that the local methods array can have up to one overpass, one static 1962 // and one instance (private or not) with the same name/signature 1963 Method* InstanceKlass::find_local_method(const Symbol* name, 1964 const Symbol* signature, 1965 OverpassLookupMode overpass_mode, 1966 StaticLookupMode static_mode, 1967 PrivateLookupMode private_mode) const { 1968 return InstanceKlass::find_method_impl(methods(), 1969 name, 1970 signature, 1971 overpass_mode, 1972 static_mode, 1973 private_mode); 1974 } 1975 1976 // Find looks up the name/signature in the local methods array 1977 // and filters on the overpass, static and private flags 1978 // This returns the first one found 1979 // note that the local methods array can have up to one overpass, one static 1980 // and one instance (private or not) with the same name/signature 1981 Method* InstanceKlass::find_local_method(const Array<Method*>* methods, 1982 const Symbol* name, 1983 const Symbol* signature, 1984 OverpassLookupMode overpass_mode, 1985 StaticLookupMode static_mode, 1986 PrivateLookupMode private_mode) { 1987 return InstanceKlass::find_method_impl(methods, 1988 name, 1989 signature, 1990 overpass_mode, 1991 static_mode, 1992 private_mode); 1993 } 1994 1995 Method* InstanceKlass::find_method(const Array<Method*>* methods, 1996 const Symbol* name, 1997 const Symbol* signature) { 1998 return InstanceKlass::find_method_impl(methods, 1999 name, 2000 signature, 2001 OverpassLookupMode::find, 2002 StaticLookupMode::find, 2003 PrivateLookupMode::find); 2004 } 2005 2006 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods, 2007 const Symbol* name, 2008 const Symbol* signature, 2009 OverpassLookupMode overpass_mode, 2010 StaticLookupMode static_mode, 2011 PrivateLookupMode private_mode) { 2012 int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode); 2013 return hit >= 0 ? methods->at(hit): nullptr; 2014 } 2015 2016 // true if method matches signature and conforms to skipping_X conditions. 2017 static bool method_matches(const Method* m, 2018 const Symbol* signature, 2019 bool skipping_overpass, 2020 bool skipping_static, 2021 bool skipping_private) { 2022 return ((m->signature() == signature) && 2023 (!skipping_overpass || !m->is_overpass()) && 2024 (!skipping_static || !m->is_static()) && 2025 (!skipping_private || !m->is_private())); 2026 } 2027 2028 // Used directly for default_methods to find the index into the 2029 // default_vtable_indices, and indirectly by find_method 2030 // find_method_index looks in the local methods array to return the index 2031 // of the matching name/signature. If, overpass methods are being ignored, 2032 // the search continues to find a potential non-overpass match. This capability 2033 // is important during method resolution to prefer a static method, for example, 2034 // over an overpass method. 2035 // There is the possibility in any _method's array to have the same name/signature 2036 // for a static method, an overpass method and a local instance method 2037 // To correctly catch a given method, the search criteria may need 2038 // to explicitly skip the other two. For local instance methods, it 2039 // is often necessary to skip private methods 2040 int InstanceKlass::find_method_index(const Array<Method*>* methods, 2041 const Symbol* name, 2042 const Symbol* signature, 2043 OverpassLookupMode overpass_mode, 2044 StaticLookupMode static_mode, 2045 PrivateLookupMode private_mode) { 2046 const bool skipping_overpass = (overpass_mode == OverpassLookupMode::skip); 2047 const bool skipping_static = (static_mode == StaticLookupMode::skip); 2048 const bool skipping_private = (private_mode == PrivateLookupMode::skip); 2049 const int hit = quick_search(methods, name); 2050 if (hit != -1) { 2051 const Method* const m = methods->at(hit); 2052 2053 // Do linear search to find matching signature. First, quick check 2054 // for common case, ignoring overpasses if requested. 2055 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) { 2056 return hit; 2057 } 2058 2059 // search downwards through overloaded methods 2060 int i; 2061 for (i = hit - 1; i >= 0; --i) { 2062 const Method* const m = methods->at(i); 2063 assert(m->is_method(), "must be method"); 2064 if (m->name() != name) { 2065 break; 2066 } 2067 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) { 2068 return i; 2069 } 2070 } 2071 // search upwards 2072 for (i = hit + 1; i < methods->length(); ++i) { 2073 const Method* const m = methods->at(i); 2074 assert(m->is_method(), "must be method"); 2075 if (m->name() != name) { 2076 break; 2077 } 2078 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) { 2079 return i; 2080 } 2081 } 2082 // not found 2083 #ifdef ASSERT 2084 const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : 2085 linear_search(methods, name, signature); 2086 assert(-1 == index, "binary search should have found entry %d", index); 2087 #endif 2088 } 2089 return -1; 2090 } 2091 2092 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const { 2093 return find_method_by_name(methods(), name, end); 2094 } 2095 2096 int InstanceKlass::find_method_by_name(const Array<Method*>* methods, 2097 const Symbol* name, 2098 int* end_ptr) { 2099 assert(end_ptr != nullptr, "just checking"); 2100 int start = quick_search(methods, name); 2101 int end = start + 1; 2102 if (start != -1) { 2103 while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start; 2104 while (end < methods->length() && (methods->at(end))->name() == name) ++end; 2105 *end_ptr = end; 2106 return start; 2107 } 2108 return -1; 2109 } 2110 2111 // uncached_lookup_method searches both the local class methods array and all 2112 // superclasses methods arrays, skipping any overpass methods in superclasses, 2113 // and possibly skipping private methods. 2114 Method* InstanceKlass::uncached_lookup_method(const Symbol* name, 2115 const Symbol* signature, 2116 OverpassLookupMode overpass_mode, 2117 PrivateLookupMode private_mode) const { 2118 OverpassLookupMode overpass_local_mode = overpass_mode; 2119 const Klass* klass = this; 2120 while (klass != nullptr) { 2121 Method* const method = InstanceKlass::cast(klass)->find_method_impl(name, 2122 signature, 2123 overpass_local_mode, 2124 StaticLookupMode::find, 2125 private_mode); 2126 if (method != nullptr) { 2127 return method; 2128 } 2129 klass = klass->super(); 2130 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses 2131 } 2132 return nullptr; 2133 } 2134 2135 #ifdef ASSERT 2136 // search through class hierarchy and return true if this class or 2137 // one of the superclasses was redefined 2138 bool InstanceKlass::has_redefined_this_or_super() const { 2139 const Klass* klass = this; 2140 while (klass != nullptr) { 2141 if (InstanceKlass::cast(klass)->has_been_redefined()) { 2142 return true; 2143 } 2144 klass = klass->super(); 2145 } 2146 return false; 2147 } 2148 #endif 2149 2150 // lookup a method in the default methods list then in all transitive interfaces 2151 // Do NOT return private or static methods 2152 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name, 2153 Symbol* signature) const { 2154 Method* m = nullptr; 2155 if (default_methods() != nullptr) { 2156 m = find_method(default_methods(), name, signature); 2157 } 2158 // Look up interfaces 2159 if (m == nullptr) { 2160 m = lookup_method_in_all_interfaces(name, signature, DefaultsLookupMode::find); 2161 } 2162 return m; 2163 } 2164 2165 // lookup a method in all the interfaces that this class implements 2166 // Do NOT return private or static methods, new in JDK8 which are not externally visible 2167 // They should only be found in the initial InterfaceMethodRef 2168 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name, 2169 Symbol* signature, 2170 DefaultsLookupMode defaults_mode) const { 2171 Array<InstanceKlass*>* all_ifs = transitive_interfaces(); 2172 int num_ifs = all_ifs->length(); 2173 InstanceKlass *ik = nullptr; 2174 for (int i = 0; i < num_ifs; i++) { 2175 ik = all_ifs->at(i); 2176 Method* m = ik->lookup_method(name, signature); 2177 if (m != nullptr && m->is_public() && !m->is_static() && 2178 ((defaults_mode != DefaultsLookupMode::skip) || !m->is_default_method())) { 2179 return m; 2180 } 2181 } 2182 return nullptr; 2183 } 2184 2185 PrintClassClosure::PrintClassClosure(outputStream* st, bool verbose) 2186 :_st(st), _verbose(verbose) { 2187 ResourceMark rm; 2188 _st->print("%-18s ", "KlassAddr"); 2189 _st->print("%-4s ", "Size"); 2190 _st->print("%-20s ", "State"); 2191 _st->print("%-7s ", "Flags"); 2192 _st->print("%-5s ", "ClassName"); 2193 _st->cr(); 2194 } 2195 2196 void PrintClassClosure::do_klass(Klass* k) { 2197 ResourceMark rm; 2198 // klass pointer 2199 _st->print(PTR_FORMAT " ", p2i(k)); 2200 // klass size 2201 _st->print("%4d ", k->size()); 2202 // initialization state 2203 if (k->is_instance_klass()) { 2204 _st->print("%-20s ",InstanceKlass::cast(k)->init_state_name()); 2205 } else { 2206 _st->print("%-20s ",""); 2207 } 2208 // misc flags(Changes should synced with ClassesDCmd::ClassesDCmd help doc) 2209 char buf[10]; 2210 int i = 0; 2211 if (k->has_finalizer()) buf[i++] = 'F'; 2212 if (k->is_instance_klass()) { 2213 InstanceKlass* ik = InstanceKlass::cast(k); 2214 if (ik->has_final_method()) buf[i++] = 'f'; 2215 if (ik->is_rewritten()) buf[i++] = 'W'; 2216 if (ik->is_contended()) buf[i++] = 'C'; 2217 if (ik->has_been_redefined()) buf[i++] = 'R'; 2218 if (ik->is_shared()) buf[i++] = 'S'; 2219 } 2220 buf[i++] = '\0'; 2221 _st->print("%-7s ", buf); 2222 // klass name 2223 _st->print("%-5s ", k->external_name()); 2224 // end 2225 _st->cr(); 2226 if (_verbose) { 2227 k->print_on(_st); 2228 } 2229 } 2230 2231 /* jni_id_for for jfieldIds only */ 2232 JNIid* InstanceKlass::jni_id_for(int offset) { 2233 MutexLocker ml(JfieldIdCreation_lock); 2234 JNIid* probe = jni_ids() == nullptr ? nullptr : jni_ids()->find(offset); 2235 if (probe == nullptr) { 2236 // Allocate new static field identifier 2237 probe = new JNIid(this, offset, jni_ids()); 2238 set_jni_ids(probe); 2239 } 2240 return probe; 2241 } 2242 2243 u2 InstanceKlass::enclosing_method_data(int offset) const { 2244 const Array<jushort>* const inner_class_list = inner_classes(); 2245 if (inner_class_list == nullptr) { 2246 return 0; 2247 } 2248 const int length = inner_class_list->length(); 2249 if (length % inner_class_next_offset == 0) { 2250 return 0; 2251 } 2252 const int index = length - enclosing_method_attribute_size; 2253 assert(offset < enclosing_method_attribute_size, "invalid offset"); 2254 return inner_class_list->at(index + offset); 2255 } 2256 2257 void InstanceKlass::set_enclosing_method_indices(u2 class_index, 2258 u2 method_index) { 2259 Array<jushort>* inner_class_list = inner_classes(); 2260 assert (inner_class_list != nullptr, "_inner_classes list is not set up"); 2261 int length = inner_class_list->length(); 2262 if (length % inner_class_next_offset == enclosing_method_attribute_size) { 2263 int index = length - enclosing_method_attribute_size; 2264 inner_class_list->at_put( 2265 index + enclosing_method_class_index_offset, class_index); 2266 inner_class_list->at_put( 2267 index + enclosing_method_method_index_offset, method_index); 2268 } 2269 } 2270 2271 // Lookup or create a jmethodID. 2272 // This code is called by the VMThread and JavaThreads so the 2273 // locking has to be done very carefully to avoid deadlocks 2274 // and/or other cache consistency problems. 2275 // 2276 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) { 2277 size_t idnum = (size_t)method_h->method_idnum(); 2278 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2279 size_t length = 0; 2280 jmethodID id = nullptr; 2281 2282 // We use a double-check locking idiom here because this cache is 2283 // performance sensitive. In the normal system, this cache only 2284 // transitions from null to non-null which is safe because we use 2285 // release_set_methods_jmethod_ids() to advertise the new cache. 2286 // A partially constructed cache should never be seen by a racing 2287 // thread. We also use release_store() to save a new jmethodID 2288 // in the cache so a partially constructed jmethodID should never be 2289 // seen either. Cache reads of existing jmethodIDs proceed without a 2290 // lock, but cache writes of a new jmethodID requires uniqueness and 2291 // creation of the cache itself requires no leaks so a lock is 2292 // generally acquired in those two cases. 2293 // 2294 // If the RedefineClasses() API has been used, then this cache can 2295 // grow and we'll have transitions from non-null to bigger non-null. 2296 // Cache creation requires no leaks and we require safety between all 2297 // cache accesses and freeing of the old cache so a lock is generally 2298 // acquired when the RedefineClasses() API has been used. 2299 2300 if (jmeths != nullptr) { 2301 // the cache already exists 2302 if (!idnum_can_increment()) { 2303 // the cache can't grow so we can just get the current values 2304 get_jmethod_id_length_value(jmeths, idnum, &length, &id); 2305 } else { 2306 MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag); 2307 get_jmethod_id_length_value(jmeths, idnum, &length, &id); 2308 } 2309 } 2310 // implied else: 2311 // we need to allocate a cache so default length and id values are good 2312 2313 if (jmeths == nullptr || // no cache yet 2314 length <= idnum || // cache is too short 2315 id == nullptr) { // cache doesn't contain entry 2316 2317 // This function can be called by the VMThread or GC worker threads so we 2318 // have to do all things that might block on a safepoint before grabbing the lock. 2319 // Otherwise, we can deadlock with the VMThread or have a cache 2320 // consistency issue. These vars keep track of what we might have 2321 // to free after the lock is dropped. 2322 jmethodID to_dealloc_id = nullptr; 2323 jmethodID* to_dealloc_jmeths = nullptr; 2324 2325 // may not allocate new_jmeths or use it if we allocate it 2326 jmethodID* new_jmeths = nullptr; 2327 if (length <= idnum) { 2328 // allocate a new cache that might be used 2329 size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count()); 2330 new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass); 2331 memset(new_jmeths, 0, (size+1)*sizeof(jmethodID)); 2332 // cache size is stored in element[0], other elements offset by one 2333 new_jmeths[0] = (jmethodID)size; 2334 } 2335 2336 // allocate a new jmethodID that might be used 2337 { 2338 MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag); 2339 jmethodID new_id = nullptr; 2340 if (method_h->is_old() && !method_h->is_obsolete()) { 2341 // The method passed in is old (but not obsolete), we need to use the current version 2342 Method* current_method = method_with_idnum((int)idnum); 2343 assert(current_method != nullptr, "old and but not obsolete, so should exist"); 2344 new_id = Method::make_jmethod_id(class_loader_data(), current_method); 2345 } else { 2346 // It is the current version of the method or an obsolete method, 2347 // use the version passed in 2348 new_id = Method::make_jmethod_id(class_loader_data(), method_h()); 2349 } 2350 2351 id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths, 2352 &to_dealloc_id, &to_dealloc_jmeths); 2353 } 2354 2355 // The lock has been dropped so we can free resources. 2356 // Free up either the old cache or the new cache if we allocated one. 2357 if (to_dealloc_jmeths != nullptr) { 2358 FreeHeap(to_dealloc_jmeths); 2359 } 2360 // free up the new ID since it wasn't needed 2361 if (to_dealloc_id != nullptr) { 2362 Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id); 2363 } 2364 } 2365 return id; 2366 } 2367 2368 // Figure out how many jmethodIDs haven't been allocated, and make 2369 // sure space for them is pre-allocated. This makes getting all 2370 // method ids much, much faster with classes with more than 8 2371 // methods, and has a *substantial* effect on performance with jvmti 2372 // code that loads all jmethodIDs for all classes. 2373 void InstanceKlass::ensure_space_for_methodids(int start_offset) { 2374 int new_jmeths = 0; 2375 int length = methods()->length(); 2376 for (int index = start_offset; index < length; index++) { 2377 Method* m = methods()->at(index); 2378 jmethodID id = m->find_jmethod_id_or_null(); 2379 if (id == nullptr) { 2380 new_jmeths++; 2381 } 2382 } 2383 if (new_jmeths != 0) { 2384 Method::ensure_jmethod_ids(class_loader_data(), new_jmeths); 2385 } 2386 } 2387 2388 // Common code to fetch the jmethodID from the cache or update the 2389 // cache with the new jmethodID. This function should never do anything 2390 // that causes the caller to go to a safepoint or we can deadlock with 2391 // the VMThread or have cache consistency issues. 2392 // 2393 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update( 2394 size_t idnum, jmethodID new_id, 2395 jmethodID* new_jmeths, jmethodID* to_dealloc_id_p, 2396 jmethodID** to_dealloc_jmeths_p) { 2397 assert(new_id != nullptr, "sanity check"); 2398 assert(to_dealloc_id_p != nullptr, "sanity check"); 2399 assert(to_dealloc_jmeths_p != nullptr, "sanity check"); 2400 assert(JmethodIdCreation_lock->owned_by_self(), "sanity check"); 2401 2402 // reacquire the cache - we are locked, single threaded or at a safepoint 2403 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2404 jmethodID id = nullptr; 2405 size_t length = 0; 2406 2407 if (jmeths == nullptr || // no cache yet 2408 (length = (size_t)jmeths[0]) <= idnum) { // cache is too short 2409 if (jmeths != nullptr) { 2410 // copy any existing entries from the old cache 2411 for (size_t index = 0; index < length; index++) { 2412 new_jmeths[index+1] = jmeths[index+1]; 2413 } 2414 *to_dealloc_jmeths_p = jmeths; // save old cache for later delete 2415 } 2416 release_set_methods_jmethod_ids(jmeths = new_jmeths); 2417 } else { 2418 // fetch jmethodID (if any) from the existing cache 2419 id = jmeths[idnum+1]; 2420 *to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete 2421 } 2422 if (id == nullptr) { 2423 // No matching jmethodID in the existing cache or we have a new 2424 // cache or we just grew the cache. This cache write is done here 2425 // by the first thread to win the foot race because a jmethodID 2426 // needs to be unique once it is generally available. 2427 id = new_id; 2428 2429 // The jmethodID cache can be read while unlocked so we have to 2430 // make sure the new jmethodID is complete before installing it 2431 // in the cache. 2432 Atomic::release_store(&jmeths[idnum+1], id); 2433 } else { 2434 *to_dealloc_id_p = new_id; // save new id for later delete 2435 } 2436 return id; 2437 } 2438 2439 2440 // Common code to get the jmethodID cache length and the jmethodID 2441 // value at index idnum if there is one. 2442 // 2443 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache, 2444 size_t idnum, size_t *length_p, jmethodID* id_p) { 2445 assert(cache != nullptr, "sanity check"); 2446 assert(length_p != nullptr, "sanity check"); 2447 assert(id_p != nullptr, "sanity check"); 2448 2449 // cache size is stored in element[0], other elements offset by one 2450 *length_p = (size_t)cache[0]; 2451 if (*length_p <= idnum) { // cache is too short 2452 *id_p = nullptr; 2453 } else { 2454 *id_p = cache[idnum+1]; // fetch jmethodID (if any) 2455 } 2456 } 2457 2458 2459 // Lookup a jmethodID, null if not found. Do no blocking, no allocations, no handles 2460 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) { 2461 size_t idnum = (size_t)method->method_idnum(); 2462 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2463 size_t length; // length assigned as debugging crumb 2464 jmethodID id = nullptr; 2465 if (jmeths != nullptr && // If there is a cache 2466 (length = (size_t)jmeths[0]) > idnum) { // and if it is long enough, 2467 id = jmeths[idnum+1]; // Look up the id (may be null) 2468 } 2469 return id; 2470 } 2471 2472 inline DependencyContext InstanceKlass::dependencies() { 2473 DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned); 2474 return dep_context; 2475 } 2476 2477 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) { 2478 dependencies().mark_dependent_nmethods(deopt_scope, changes); 2479 } 2480 2481 void InstanceKlass::add_dependent_nmethod(nmethod* nm) { 2482 dependencies().add_dependent_nmethod(nm); 2483 } 2484 2485 void InstanceKlass::clean_dependency_context() { 2486 dependencies().clean_unloading_dependents(); 2487 } 2488 2489 #ifndef PRODUCT 2490 void InstanceKlass::print_dependent_nmethods(bool verbose) { 2491 dependencies().print_dependent_nmethods(verbose); 2492 } 2493 2494 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) { 2495 return dependencies().is_dependent_nmethod(nm); 2496 } 2497 #endif //PRODUCT 2498 2499 void InstanceKlass::clean_weak_instanceklass_links() { 2500 clean_implementors_list(); 2501 clean_method_data(); 2502 } 2503 2504 void InstanceKlass::clean_implementors_list() { 2505 assert(is_loader_alive(), "this klass should be live"); 2506 if (is_interface()) { 2507 assert (ClassUnloading, "only called for ClassUnloading"); 2508 for (;;) { 2509 // Use load_acquire due to competing with inserts 2510 InstanceKlass* volatile* iklass = adr_implementor(); 2511 assert(iklass != nullptr, "Klass must not be null"); 2512 InstanceKlass* impl = Atomic::load_acquire(iklass); 2513 if (impl != nullptr && !impl->is_loader_alive()) { 2514 // null this field, might be an unloaded instance klass or null 2515 if (Atomic::cmpxchg(iklass, impl, (InstanceKlass*)nullptr) == impl) { 2516 // Successfully unlinking implementor. 2517 if (log_is_enabled(Trace, class, unload)) { 2518 ResourceMark rm; 2519 log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name()); 2520 } 2521 return; 2522 } 2523 } else { 2524 return; 2525 } 2526 } 2527 } 2528 } 2529 2530 void InstanceKlass::clean_method_data() { 2531 for (int m = 0; m < methods()->length(); m++) { 2532 MethodData* mdo = methods()->at(m)->method_data(); 2533 if (mdo != nullptr) { 2534 mdo->clean_method_data(/*always_clean*/false); 2535 } 2536 } 2537 } 2538 2539 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) { 2540 Klass::metaspace_pointers_do(it); 2541 2542 if (log_is_enabled(Trace, cds)) { 2543 ResourceMark rm; 2544 log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name()); 2545 } 2546 2547 it->push(&_annotations); 2548 it->push((Klass**)&_array_klasses); 2549 if (!is_rewritten()) { 2550 it->push(&_constants, MetaspaceClosure::_writable); 2551 } else { 2552 it->push(&_constants); 2553 } 2554 it->push(&_inner_classes); 2555 #if INCLUDE_JVMTI 2556 it->push(&_previous_versions); 2557 #endif 2558 #if INCLUDE_CDS 2559 // For "old" classes with methods containing the jsr bytecode, the _methods array will 2560 // be rewritten during runtime (see Rewriter::rewrite_jsrs()). So setting the _methods to 2561 // be writable. The length check on the _methods is necessary because classes which 2562 // don't have any methods share the Universe::_the_empty_method_array which is in the RO region. 2563 if (_methods != nullptr && _methods->length() > 0 && 2564 !can_be_verified_at_dumptime() && methods_contain_jsr_bytecode()) { 2565 // To handle jsr bytecode, new Method* maybe stored into _methods 2566 it->push(&_methods, MetaspaceClosure::_writable); 2567 } else { 2568 #endif 2569 it->push(&_methods); 2570 #if INCLUDE_CDS 2571 } 2572 #endif 2573 it->push(&_default_methods); 2574 it->push(&_local_interfaces); 2575 it->push(&_transitive_interfaces); 2576 it->push(&_method_ordering); 2577 if (!is_rewritten()) { 2578 it->push(&_default_vtable_indices, MetaspaceClosure::_writable); 2579 } else { 2580 it->push(&_default_vtable_indices); 2581 } 2582 2583 it->push(&_fieldinfo_stream); 2584 // _fields_status might be written into by Rewriter::scan_method() -> fd.set_has_initialized_final_update() 2585 it->push(&_fields_status, MetaspaceClosure::_writable); 2586 2587 if (itable_length() > 0) { 2588 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable(); 2589 int method_table_offset_in_words = ioe->offset()/wordSize; 2590 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this); 2591 2592 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words) 2593 / itableOffsetEntry::size(); 2594 2595 for (int i = 0; i < nof_interfaces; i ++, ioe ++) { 2596 if (ioe->interface_klass() != nullptr) { 2597 it->push(ioe->interface_klass_addr()); 2598 itableMethodEntry* ime = ioe->first_method_entry(this); 2599 int n = klassItable::method_count_for_interface(ioe->interface_klass()); 2600 for (int index = 0; index < n; index ++) { 2601 it->push(ime[index].method_addr()); 2602 } 2603 } 2604 } 2605 } 2606 2607 it->push(&_nest_members); 2608 it->push(&_permitted_subclasses); 2609 it->push(&_record_components); 2610 } 2611 2612 #if INCLUDE_CDS 2613 void InstanceKlass::remove_unshareable_info() { 2614 2615 if (is_linked()) { 2616 assert(can_be_verified_at_dumptime(), "must be"); 2617 // Remember this so we can avoid walking the hierarchy at runtime. 2618 set_verified_at_dump_time(); 2619 } 2620 2621 Klass::remove_unshareable_info(); 2622 2623 if (SystemDictionaryShared::has_class_failed_verification(this)) { 2624 // Classes are attempted to link during dumping and may fail, 2625 // but these classes are still in the dictionary and class list in CLD. 2626 // If the class has failed verification, there is nothing else to remove. 2627 return; 2628 } 2629 2630 // Reset to the 'allocated' state to prevent any premature accessing to 2631 // a shared class at runtime while the class is still being loaded and 2632 // restored. A class' init_state is set to 'loaded' at runtime when it's 2633 // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()). 2634 _init_state = allocated; 2635 2636 { // Otherwise this needs to take out the Compile_lock. 2637 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 2638 init_implementor(); 2639 } 2640 2641 constants()->remove_unshareable_info(); 2642 2643 for (int i = 0; i < methods()->length(); i++) { 2644 Method* m = methods()->at(i); 2645 m->remove_unshareable_info(); 2646 } 2647 2648 // do array classes also. 2649 if (array_klasses() != nullptr) { 2650 array_klasses()->remove_unshareable_info(); 2651 } 2652 2653 // These are not allocated from metaspace. They are safe to set to null. 2654 _source_debug_extension = nullptr; 2655 _dep_context = nullptr; 2656 _osr_nmethods_head = nullptr; 2657 #if INCLUDE_JVMTI 2658 _breakpoints = nullptr; 2659 _previous_versions = nullptr; 2660 _cached_class_file = nullptr; 2661 _jvmti_cached_class_field_map = nullptr; 2662 #endif 2663 2664 _init_thread = nullptr; 2665 _methods_jmethod_ids = nullptr; 2666 _jni_ids = nullptr; 2667 _oop_map_cache = nullptr; 2668 // clear _nest_host to ensure re-load at runtime 2669 _nest_host = nullptr; 2670 init_shared_package_entry(); 2671 _dep_context_last_cleaned = 0; 2672 _init_monitor = nullptr; 2673 2674 remove_unshareable_flags(); 2675 } 2676 2677 void InstanceKlass::remove_unshareable_flags() { 2678 // clear all the flags/stats that shouldn't be in the archived version 2679 assert(!is_scratch_class(), "must be"); 2680 assert(!has_been_redefined(), "must be"); 2681 #if INCLUDE_JVMTI 2682 set_is_being_redefined(false); 2683 #endif 2684 set_has_resolved_methods(false); 2685 } 2686 2687 void InstanceKlass::remove_java_mirror() { 2688 Klass::remove_java_mirror(); 2689 2690 // do array classes also. 2691 if (array_klasses() != nullptr) { 2692 array_klasses()->remove_java_mirror(); 2693 } 2694 } 2695 2696 void InstanceKlass::init_shared_package_entry() { 2697 assert(CDSConfig::is_dumping_archive(), "must be"); 2698 #if !INCLUDE_CDS_JAVA_HEAP 2699 _package_entry = nullptr; 2700 #else 2701 if (CDSConfig::is_dumping_full_module_graph()) { 2702 if (is_shared_unregistered_class()) { 2703 _package_entry = nullptr; 2704 } else { 2705 _package_entry = PackageEntry::get_archived_entry(_package_entry); 2706 } 2707 } else if (CDSConfig::is_dumping_dynamic_archive() && 2708 CDSConfig::is_loading_full_module_graph() && 2709 MetaspaceShared::is_in_shared_metaspace(_package_entry)) { 2710 // _package_entry is an archived package in the base archive. Leave it as is. 2711 } else { 2712 _package_entry = nullptr; 2713 } 2714 ArchivePtrMarker::mark_pointer((address**)&_package_entry); 2715 #endif 2716 } 2717 2718 void InstanceKlass::compute_has_loops_flag_for_methods() { 2719 Array<Method*>* methods = this->methods(); 2720 for (int index = 0; index < methods->length(); ++index) { 2721 Method* m = methods->at(index); 2722 if (!m->is_overpass()) { // work around JDK-8305771 2723 m->compute_has_loops_flag(); 2724 } 2725 } 2726 } 2727 2728 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, 2729 PackageEntry* pkg_entry, TRAPS) { 2730 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded 2731 // before the InstanceKlass is added to the SystemDictionary. Make 2732 // sure the current state is <loaded. 2733 assert(!is_loaded(), "invalid init state"); 2734 assert(!shared_loading_failed(), "Must not try to load failed class again"); 2735 set_package(loader_data, pkg_entry, CHECK); 2736 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK); 2737 2738 Array<Method*>* methods = this->methods(); 2739 int num_methods = methods->length(); 2740 for (int index = 0; index < num_methods; ++index) { 2741 methods->at(index)->restore_unshareable_info(CHECK); 2742 } 2743 #if INCLUDE_JVMTI 2744 if (JvmtiExport::has_redefined_a_class()) { 2745 // Reinitialize vtable because RedefineClasses may have changed some 2746 // entries in this vtable for super classes so the CDS vtable might 2747 // point to old or obsolete entries. RedefineClasses doesn't fix up 2748 // vtables in the shared system dictionary, only the main one. 2749 // It also redefines the itable too so fix that too. 2750 // First fix any default methods that point to a super class that may 2751 // have been redefined. 2752 bool trace_name_printed = false; 2753 adjust_default_methods(&trace_name_printed); 2754 vtable().initialize_vtable(); 2755 itable().initialize_itable(); 2756 } 2757 #endif 2758 2759 // restore constant pool resolved references 2760 constants()->restore_unshareable_info(CHECK); 2761 2762 if (array_klasses() != nullptr) { 2763 // To get a consistent list of classes we need MultiArray_lock to ensure 2764 // array classes aren't observed while they are being restored. 2765 MutexLocker ml(MultiArray_lock); 2766 assert(this == array_klasses()->bottom_klass(), "sanity"); 2767 // Array classes have null protection domain. 2768 // --> see ArrayKlass::complete_create_array_klass() 2769 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK); 2770 } 2771 2772 // Initialize @ValueBased class annotation 2773 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation()) { 2774 set_is_value_based(); 2775 } 2776 2777 // restore the monitor 2778 _init_monitor = create_init_monitor("InstanceKlassInitMonitorRestored_lock"); 2779 } 2780 2781 // Check if a class or any of its supertypes has a version older than 50. 2782 // CDS will not perform verification of old classes during dump time because 2783 // without changing the old verifier, the verification constraint cannot be 2784 // retrieved during dump time. 2785 // Verification of archived old classes will be performed during run time. 2786 bool InstanceKlass::can_be_verified_at_dumptime() const { 2787 if (MetaspaceShared::is_in_shared_metaspace(this)) { 2788 // This is a class that was dumped into the base archive, so we know 2789 // it was verified at dump time. 2790 return true; 2791 } 2792 if (major_version() < 50 /*JAVA_6_VERSION*/) { 2793 return false; 2794 } 2795 if (java_super() != nullptr && !java_super()->can_be_verified_at_dumptime()) { 2796 return false; 2797 } 2798 Array<InstanceKlass*>* interfaces = local_interfaces(); 2799 int len = interfaces->length(); 2800 for (int i = 0; i < len; i++) { 2801 if (!interfaces->at(i)->can_be_verified_at_dumptime()) { 2802 return false; 2803 } 2804 } 2805 return true; 2806 } 2807 2808 bool InstanceKlass::methods_contain_jsr_bytecode() const { 2809 Thread* thread = Thread::current(); 2810 for (int i = 0; i < _methods->length(); i++) { 2811 methodHandle m(thread, _methods->at(i)); 2812 BytecodeStream bcs(m); 2813 while (!bcs.is_last_bytecode()) { 2814 Bytecodes::Code opcode = bcs.next(); 2815 if (opcode == Bytecodes::_jsr || opcode == Bytecodes::_jsr_w) { 2816 return true; 2817 } 2818 } 2819 } 2820 return false; 2821 } 2822 #endif // INCLUDE_CDS 2823 2824 #if INCLUDE_JVMTI 2825 static void clear_all_breakpoints(Method* m) { 2826 m->clear_all_breakpoints(); 2827 } 2828 #endif 2829 2830 void InstanceKlass::unload_class(InstanceKlass* ik) { 2831 // Release dependencies. 2832 ik->dependencies().remove_all_dependents(); 2833 2834 // notify the debugger 2835 if (JvmtiExport::should_post_class_unload()) { 2836 JvmtiExport::post_class_unload(ik); 2837 } 2838 2839 // notify ClassLoadingService of class unload 2840 ClassLoadingService::notify_class_unloaded(ik); 2841 2842 SystemDictionaryShared::handle_class_unloading(ik); 2843 2844 if (log_is_enabled(Info, class, unload)) { 2845 ResourceMark rm; 2846 log_info(class, unload)("unloading class %s " PTR_FORMAT, ik->external_name(), p2i(ik)); 2847 } 2848 2849 Events::log_class_unloading(Thread::current(), ik); 2850 2851 #if INCLUDE_JFR 2852 assert(ik != nullptr, "invariant"); 2853 EventClassUnload event; 2854 event.set_unloadedClass(ik); 2855 event.set_definingClassLoader(ik->class_loader_data()); 2856 event.commit(); 2857 #endif 2858 } 2859 2860 static void method_release_C_heap_structures(Method* m) { 2861 m->release_C_heap_structures(); 2862 } 2863 2864 // Called also by InstanceKlass::deallocate_contents, with false for release_sub_metadata. 2865 void InstanceKlass::release_C_heap_structures(bool release_sub_metadata) { 2866 // Clean up C heap 2867 Klass::release_C_heap_structures(); 2868 2869 // Deallocate and call destructors for MDO mutexes 2870 if (release_sub_metadata) { 2871 methods_do(method_release_C_heap_structures); 2872 } 2873 2874 // Destroy the init_monitor 2875 delete _init_monitor; 2876 2877 // Deallocate oop map cache 2878 if (_oop_map_cache != nullptr) { 2879 delete _oop_map_cache; 2880 _oop_map_cache = nullptr; 2881 } 2882 2883 // Deallocate JNI identifiers for jfieldIDs 2884 JNIid::deallocate(jni_ids()); 2885 set_jni_ids(nullptr); 2886 2887 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2888 if (jmeths != (jmethodID*)nullptr) { 2889 release_set_methods_jmethod_ids(nullptr); 2890 FreeHeap(jmeths); 2891 } 2892 2893 assert(_dep_context == nullptr, 2894 "dependencies should already be cleaned"); 2895 2896 #if INCLUDE_JVMTI 2897 // Deallocate breakpoint records 2898 if (breakpoints() != 0x0) { 2899 methods_do(clear_all_breakpoints); 2900 assert(breakpoints() == 0x0, "should have cleared breakpoints"); 2901 } 2902 2903 // deallocate the cached class file 2904 if (_cached_class_file != nullptr) { 2905 os::free(_cached_class_file); 2906 _cached_class_file = nullptr; 2907 } 2908 #endif 2909 2910 FREE_C_HEAP_ARRAY(char, _source_debug_extension); 2911 2912 if (release_sub_metadata) { 2913 constants()->release_C_heap_structures(); 2914 } 2915 } 2916 2917 // The constant pool is on stack if any of the methods are executing or 2918 // referenced by handles. 2919 bool InstanceKlass::on_stack() const { 2920 return _constants->on_stack(); 2921 } 2922 2923 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); } 2924 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); } 2925 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); } 2926 2927 // minor and major version numbers of class file 2928 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); } 2929 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); } 2930 u2 InstanceKlass::major_version() const { return _constants->major_version(); } 2931 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); } 2932 2933 InstanceKlass* InstanceKlass::get_klass_version(int version) { 2934 for (InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) { 2935 if (ik->constants()->version() == version) { 2936 return ik; 2937 } 2938 } 2939 return nullptr; 2940 } 2941 2942 void InstanceKlass::set_source_debug_extension(const char* array, int length) { 2943 if (array == nullptr) { 2944 _source_debug_extension = nullptr; 2945 } else { 2946 // Adding one to the attribute length in order to store a null terminator 2947 // character could cause an overflow because the attribute length is 2948 // already coded with an u4 in the classfile, but in practice, it's 2949 // unlikely to happen. 2950 assert((length+1) > length, "Overflow checking"); 2951 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass); 2952 for (int i = 0; i < length; i++) { 2953 sde[i] = array[i]; 2954 } 2955 sde[length] = '\0'; 2956 _source_debug_extension = sde; 2957 } 2958 } 2959 2960 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); } 2961 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); } 2962 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); } 2963 2964 const char* InstanceKlass::signature_name() const { 2965 2966 // Get the internal name as a c string 2967 const char* src = (const char*) (name()->as_C_string()); 2968 const int src_length = (int)strlen(src); 2969 2970 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3); 2971 2972 // Add L as type indicator 2973 int dest_index = 0; 2974 dest[dest_index++] = JVM_SIGNATURE_CLASS; 2975 2976 // Add the actual class name 2977 for (int src_index = 0; src_index < src_length; ) { 2978 dest[dest_index++] = src[src_index++]; 2979 } 2980 2981 if (is_hidden()) { // Replace the last '+' with a '.'. 2982 for (int index = (int)src_length; index > 0; index--) { 2983 if (dest[index] == '+') { 2984 dest[index] = JVM_SIGNATURE_DOT; 2985 break; 2986 } 2987 } 2988 } 2989 2990 // Add the semicolon and the null 2991 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS; 2992 dest[dest_index] = '\0'; 2993 return dest; 2994 } 2995 2996 ModuleEntry* InstanceKlass::module() const { 2997 if (is_hidden() && 2998 in_unnamed_package() && 2999 class_loader_data()->has_class_mirror_holder()) { 3000 // For a non-strong hidden class defined to an unnamed package, 3001 // its (class held) CLD will not have an unnamed module created for it. 3002 // Two choices to find the correct ModuleEntry: 3003 // 1. If hidden class is within a nest, use nest host's module 3004 // 2. Find the unnamed module off from the class loader 3005 // For now option #2 is used since a nest host is not set until 3006 // after the instance class is created in jvm_lookup_define_class(). 3007 if (class_loader_data()->is_boot_class_loader_data()) { 3008 return ClassLoaderData::the_null_class_loader_data()->unnamed_module(); 3009 } else { 3010 oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader()); 3011 assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module"); 3012 return java_lang_Module::module_entry(module); 3013 } 3014 } 3015 3016 // Class is in a named package 3017 if (!in_unnamed_package()) { 3018 return _package_entry->module(); 3019 } 3020 3021 // Class is in an unnamed package, return its loader's unnamed module 3022 return class_loader_data()->unnamed_module(); 3023 } 3024 3025 void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) { 3026 3027 // ensure java/ packages only loaded by boot or platform builtin loaders 3028 // not needed for shared class since CDS does not archive prohibited classes. 3029 if (!is_shared()) { 3030 check_prohibited_package(name(), loader_data, CHECK); 3031 } 3032 3033 if (is_shared() && _package_entry != nullptr) { 3034 if (CDSConfig::is_loading_full_module_graph() && _package_entry == pkg_entry) { 3035 // we can use the saved package 3036 assert(MetaspaceShared::is_in_shared_metaspace(_package_entry), "must be"); 3037 return; 3038 } else { 3039 _package_entry = nullptr; 3040 } 3041 } 3042 3043 // ClassLoader::package_from_class_name has already incremented the refcount of the symbol 3044 // it returns, so we need to decrement it when the current function exits. 3045 TempNewSymbol from_class_name = 3046 (pkg_entry != nullptr) ? nullptr : ClassLoader::package_from_class_name(name()); 3047 3048 Symbol* pkg_name; 3049 if (pkg_entry != nullptr) { 3050 pkg_name = pkg_entry->name(); 3051 } else { 3052 pkg_name = from_class_name; 3053 } 3054 3055 if (pkg_name != nullptr && loader_data != nullptr) { 3056 3057 // Find in class loader's package entry table. 3058 _package_entry = pkg_entry != nullptr ? pkg_entry : loader_data->packages()->lookup_only(pkg_name); 3059 3060 // If the package name is not found in the loader's package 3061 // entry table, it is an indication that the package has not 3062 // been defined. Consider it defined within the unnamed module. 3063 if (_package_entry == nullptr) { 3064 3065 if (!ModuleEntryTable::javabase_defined()) { 3066 // Before java.base is defined during bootstrapping, define all packages in 3067 // the java.base module. If a non-java.base package is erroneously placed 3068 // in the java.base module it will be caught later when java.base 3069 // is defined by ModuleEntryTable::verify_javabase_packages check. 3070 assert(ModuleEntryTable::javabase_moduleEntry() != nullptr, JAVA_BASE_NAME " module is null"); 3071 _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, ModuleEntryTable::javabase_moduleEntry()); 3072 } else { 3073 assert(loader_data->unnamed_module() != nullptr, "unnamed module is null"); 3074 _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, loader_data->unnamed_module()); 3075 } 3076 3077 // A package should have been successfully created 3078 DEBUG_ONLY(ResourceMark rm(THREAD)); 3079 assert(_package_entry != nullptr, "Package entry for class %s not found, loader %s", 3080 name()->as_C_string(), loader_data->loader_name_and_id()); 3081 } 3082 3083 if (log_is_enabled(Debug, module)) { 3084 ResourceMark rm(THREAD); 3085 ModuleEntry* m = _package_entry->module(); 3086 log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s", 3087 external_name(), 3088 pkg_name->as_C_string(), 3089 loader_data->loader_name_and_id(), 3090 (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE)); 3091 } 3092 } else { 3093 ResourceMark rm(THREAD); 3094 log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s", 3095 external_name(), 3096 (loader_data != nullptr) ? loader_data->loader_name_and_id() : "null", 3097 UNNAMED_MODULE); 3098 } 3099 } 3100 3101 // Function set_classpath_index ensures that for a non-null _package_entry 3102 // of the InstanceKlass, the entry is in the boot loader's package entry table. 3103 // It then sets the classpath_index in the package entry record. 3104 // 3105 // The classpath_index field is used to find the entry on the boot loader class 3106 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a 3107 // in an unnamed module. It is also used to indicate (for all packages whose 3108 // classes are loaded by the boot loader) that at least one of the package's 3109 // classes has been loaded. 3110 void InstanceKlass::set_classpath_index(s2 path_index) { 3111 if (_package_entry != nullptr) { 3112 DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();) 3113 assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same"); 3114 assert(path_index != -1, "Unexpected classpath_index"); 3115 _package_entry->set_classpath_index(path_index); 3116 } 3117 } 3118 3119 // different versions of is_same_class_package 3120 3121 bool InstanceKlass::is_same_class_package(const Klass* class2) const { 3122 oop classloader1 = this->class_loader(); 3123 PackageEntry* classpkg1 = this->package(); 3124 if (class2->is_objArray_klass()) { 3125 class2 = ObjArrayKlass::cast(class2)->bottom_klass(); 3126 } 3127 3128 oop classloader2; 3129 PackageEntry* classpkg2; 3130 if (class2->is_instance_klass()) { 3131 classloader2 = class2->class_loader(); 3132 classpkg2 = class2->package(); 3133 } else { 3134 assert(class2->is_typeArray_klass(), "should be type array"); 3135 classloader2 = nullptr; 3136 classpkg2 = nullptr; 3137 } 3138 3139 // Same package is determined by comparing class loader 3140 // and package entries. Both must be the same. This rule 3141 // applies even to classes that are defined in the unnamed 3142 // package, they still must have the same class loader. 3143 if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) { 3144 return true; 3145 } 3146 3147 return false; 3148 } 3149 3150 // return true if this class and other_class are in the same package. Classloader 3151 // and classname information is enough to determine a class's package 3152 bool InstanceKlass::is_same_class_package(oop other_class_loader, 3153 const Symbol* other_class_name) const { 3154 if (class_loader() != other_class_loader) { 3155 return false; 3156 } 3157 if (name()->fast_compare(other_class_name) == 0) { 3158 return true; 3159 } 3160 3161 { 3162 ResourceMark rm; 3163 3164 bool bad_class_name = false; 3165 TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name); 3166 if (bad_class_name) { 3167 return false; 3168 } 3169 // Check that package_from_class_name() returns null, not "", if there is no package. 3170 assert(other_pkg == nullptr || other_pkg->utf8_length() > 0, "package name is empty string"); 3171 3172 const Symbol* const this_package_name = 3173 this->package() != nullptr ? this->package()->name() : nullptr; 3174 3175 if (this_package_name == nullptr || other_pkg == nullptr) { 3176 // One of the two doesn't have a package. Only return true if the other 3177 // one also doesn't have a package. 3178 return this_package_name == other_pkg; 3179 } 3180 3181 // Check if package is identical 3182 return this_package_name->fast_compare(other_pkg) == 0; 3183 } 3184 } 3185 3186 static bool is_prohibited_package_slow(Symbol* class_name) { 3187 // Caller has ResourceMark 3188 int length; 3189 jchar* unicode = class_name->as_unicode(length); 3190 return (length >= 5 && 3191 unicode[0] == 'j' && 3192 unicode[1] == 'a' && 3193 unicode[2] == 'v' && 3194 unicode[3] == 'a' && 3195 unicode[4] == '/'); 3196 } 3197 3198 // Only boot and platform class loaders can define classes in "java/" packages. 3199 void InstanceKlass::check_prohibited_package(Symbol* class_name, 3200 ClassLoaderData* loader_data, 3201 TRAPS) { 3202 if (!loader_data->is_boot_class_loader_data() && 3203 !loader_data->is_platform_class_loader_data() && 3204 class_name != nullptr && class_name->utf8_length() >= 5) { 3205 ResourceMark rm(THREAD); 3206 bool prohibited; 3207 const u1* base = class_name->base(); 3208 if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) { 3209 prohibited = is_prohibited_package_slow(class_name); 3210 } else { 3211 char* name = class_name->as_C_string(); 3212 prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/'); 3213 } 3214 if (prohibited) { 3215 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name); 3216 assert(pkg_name != nullptr, "Error in parsing package name starting with 'java/'"); 3217 char* name = pkg_name->as_C_string(); 3218 const char* class_loader_name = loader_data->loader_name_and_id(); 3219 StringUtils::replace_no_expand(name, "/", "."); 3220 const char* msg_text1 = "Class loader (instance of): "; 3221 const char* msg_text2 = " tried to load prohibited package name: "; 3222 size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1; 3223 char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len); 3224 jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name); 3225 THROW_MSG(vmSymbols::java_lang_SecurityException(), message); 3226 } 3227 } 3228 return; 3229 } 3230 3231 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const { 3232 constantPoolHandle i_cp(THREAD, constants()); 3233 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) { 3234 int ioff = iter.inner_class_info_index(); 3235 if (ioff != 0) { 3236 // Check to see if the name matches the class we're looking for 3237 // before attempting to find the class. 3238 if (i_cp->klass_name_at_matches(this, ioff)) { 3239 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false); 3240 if (this == inner_klass) { 3241 *ooff = iter.outer_class_info_index(); 3242 *noff = iter.inner_name_index(); 3243 return true; 3244 } 3245 } 3246 } 3247 } 3248 return false; 3249 } 3250 3251 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const { 3252 InstanceKlass* outer_klass = nullptr; 3253 *inner_is_member = false; 3254 int ooff = 0, noff = 0; 3255 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD); 3256 if (has_inner_classes_attr) { 3257 constantPoolHandle i_cp(THREAD, constants()); 3258 if (ooff != 0) { 3259 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL); 3260 if (!ok->is_instance_klass()) { 3261 // If the outer class is not an instance klass then it cannot have 3262 // declared any inner classes. 3263 ResourceMark rm(THREAD); 3264 Exceptions::fthrow( 3265 THREAD_AND_LOCATION, 3266 vmSymbols::java_lang_IncompatibleClassChangeError(), 3267 "%s and %s disagree on InnerClasses attribute", 3268 ok->external_name(), 3269 external_name()); 3270 return nullptr; 3271 } 3272 outer_klass = InstanceKlass::cast(ok); 3273 *inner_is_member = true; 3274 } 3275 if (nullptr == outer_klass) { 3276 // It may be a local class; try for that. 3277 int encl_method_class_idx = enclosing_method_class_index(); 3278 if (encl_method_class_idx != 0) { 3279 Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL); 3280 outer_klass = InstanceKlass::cast(ok); 3281 *inner_is_member = false; 3282 } 3283 } 3284 } 3285 3286 // If no inner class attribute found for this class. 3287 if (nullptr == outer_klass) return nullptr; 3288 3289 // Throws an exception if outer klass has not declared k as an inner klass 3290 // We need evidence that each klass knows about the other, or else 3291 // the system could allow a spoof of an inner class to gain access rights. 3292 Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL); 3293 return outer_klass; 3294 } 3295 3296 jint InstanceKlass::compute_modifier_flags() const { 3297 jint access = access_flags().as_int(); 3298 3299 // But check if it happens to be member class. 3300 InnerClassesIterator iter(this); 3301 for (; !iter.done(); iter.next()) { 3302 int ioff = iter.inner_class_info_index(); 3303 // Inner class attribute can be zero, skip it. 3304 // Strange but true: JVM spec. allows null inner class refs. 3305 if (ioff == 0) continue; 3306 3307 // only look at classes that are already loaded 3308 // since we are looking for the flags for our self. 3309 Symbol* inner_name = constants()->klass_name_at(ioff); 3310 if (name() == inner_name) { 3311 // This is really a member class. 3312 access = iter.inner_access_flags(); 3313 break; 3314 } 3315 } 3316 // Remember to strip ACC_SUPER bit 3317 return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS; 3318 } 3319 3320 jint InstanceKlass::jvmti_class_status() const { 3321 jint result = 0; 3322 3323 if (is_linked()) { 3324 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED; 3325 } 3326 3327 if (is_initialized()) { 3328 assert(is_linked(), "Class status is not consistent"); 3329 result |= JVMTI_CLASS_STATUS_INITIALIZED; 3330 } 3331 if (is_in_error_state()) { 3332 result |= JVMTI_CLASS_STATUS_ERROR; 3333 } 3334 return result; 3335 } 3336 3337 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) { 3338 bool implements_interface; // initialized by method_at_itable_or_null 3339 Method* m = method_at_itable_or_null(holder, index, 3340 implements_interface); // out parameter 3341 if (m != nullptr) { 3342 assert(implements_interface, "sanity"); 3343 return m; 3344 } else if (implements_interface) { 3345 // Throw AbstractMethodError since corresponding itable slot is empty. 3346 THROW_NULL(vmSymbols::java_lang_AbstractMethodError()); 3347 } else { 3348 // If the interface isn't implemented by the receiver class, 3349 // the VM should throw IncompatibleClassChangeError. 3350 ResourceMark rm(THREAD); 3351 stringStream ss; 3352 bool same_module = (module() == holder->module()); 3353 ss.print("Receiver class %s does not implement " 3354 "the interface %s defining the method to be called " 3355 "(%s%s%s)", 3356 external_name(), holder->external_name(), 3357 (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(), 3358 (same_module) ? "" : "; ", 3359 (same_module) ? "" : holder->class_in_module_of_loader()); 3360 THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string()); 3361 } 3362 } 3363 3364 Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) { 3365 klassItable itable(this); 3366 for (int i = 0; i < itable.size_offset_table(); i++) { 3367 itableOffsetEntry* offset_entry = itable.offset_entry(i); 3368 if (offset_entry->interface_klass() == holder) { 3369 implements_interface = true; 3370 itableMethodEntry* ime = offset_entry->first_method_entry(this); 3371 Method* m = ime[index].method(); 3372 return m; 3373 } 3374 } 3375 implements_interface = false; 3376 return nullptr; // offset entry not found 3377 } 3378 3379 int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) { 3380 assert(is_linked(), "required"); 3381 assert(intf_method->method_holder()->is_interface(), "not an interface method"); 3382 assert(is_subtype_of(intf_method->method_holder()), "interface not implemented"); 3383 3384 int vtable_index = Method::invalid_vtable_index; 3385 Symbol* name = intf_method->name(); 3386 Symbol* signature = intf_method->signature(); 3387 3388 // First check in default method array 3389 if (!intf_method->is_abstract() && default_methods() != nullptr) { 3390 int index = find_method_index(default_methods(), 3391 name, signature, 3392 Klass::OverpassLookupMode::find, 3393 Klass::StaticLookupMode::find, 3394 Klass::PrivateLookupMode::find); 3395 if (index >= 0) { 3396 vtable_index = default_vtable_indices()->at(index); 3397 } 3398 } 3399 if (vtable_index == Method::invalid_vtable_index) { 3400 // get vtable_index for miranda methods 3401 klassVtable vt = vtable(); 3402 vtable_index = vt.index_of_miranda(name, signature); 3403 } 3404 return vtable_index; 3405 } 3406 3407 #if INCLUDE_JVMTI 3408 // update default_methods for redefineclasses for methods that are 3409 // not yet in the vtable due to concurrent subclass define and superinterface 3410 // redefinition 3411 // Note: those in the vtable, should have been updated via adjust_method_entries 3412 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) { 3413 // search the default_methods for uses of either obsolete or EMCP methods 3414 if (default_methods() != nullptr) { 3415 for (int index = 0; index < default_methods()->length(); index ++) { 3416 Method* old_method = default_methods()->at(index); 3417 if (old_method == nullptr || !old_method->is_old()) { 3418 continue; // skip uninteresting entries 3419 } 3420 assert(!old_method->is_deleted(), "default methods may not be deleted"); 3421 Method* new_method = old_method->get_new_method(); 3422 default_methods()->at_put(index, new_method); 3423 3424 if (log_is_enabled(Info, redefine, class, update)) { 3425 ResourceMark rm; 3426 if (!(*trace_name_printed)) { 3427 log_info(redefine, class, update) 3428 ("adjust: klassname=%s default methods from name=%s", 3429 external_name(), old_method->method_holder()->external_name()); 3430 *trace_name_printed = true; 3431 } 3432 log_debug(redefine, class, update, vtables) 3433 ("default method update: %s(%s) ", 3434 new_method->name()->as_C_string(), new_method->signature()->as_C_string()); 3435 } 3436 } 3437 } 3438 } 3439 #endif // INCLUDE_JVMTI 3440 3441 // On-stack replacement stuff 3442 void InstanceKlass::add_osr_nmethod(nmethod* n) { 3443 assert_lock_strong(CompiledMethod_lock); 3444 #ifndef PRODUCT 3445 nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true); 3446 assert(prev == nullptr || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation), 3447 "redundant OSR recompilation detected. memory leak in CodeCache!"); 3448 #endif 3449 // only one compilation can be active 3450 assert(n->is_osr_method(), "wrong kind of nmethod"); 3451 n->set_osr_link(osr_nmethods_head()); 3452 set_osr_nmethods_head(n); 3453 // Raise the highest osr level if necessary 3454 n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level())); 3455 3456 // Get rid of the osr methods for the same bci that have lower levels. 3457 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) { 3458 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true); 3459 if (inv != nullptr && inv->is_in_use()) { 3460 inv->make_not_entrant(); 3461 } 3462 } 3463 } 3464 3465 // Remove osr nmethod from the list. Return true if found and removed. 3466 bool InstanceKlass::remove_osr_nmethod(nmethod* n) { 3467 // This is a short non-blocking critical region, so the no safepoint check is ok. 3468 ConditionalMutexLocker ml(CompiledMethod_lock, !CompiledMethod_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3469 assert(n->is_osr_method(), "wrong kind of nmethod"); 3470 nmethod* last = nullptr; 3471 nmethod* cur = osr_nmethods_head(); 3472 int max_level = CompLevel_none; // Find the max comp level excluding n 3473 Method* m = n->method(); 3474 // Search for match 3475 bool found = false; 3476 while(cur != nullptr && cur != n) { 3477 if (m == cur->method()) { 3478 // Find max level before n 3479 max_level = MAX2(max_level, cur->comp_level()); 3480 } 3481 last = cur; 3482 cur = cur->osr_link(); 3483 } 3484 nmethod* next = nullptr; 3485 if (cur == n) { 3486 found = true; 3487 next = cur->osr_link(); 3488 if (last == nullptr) { 3489 // Remove first element 3490 set_osr_nmethods_head(next); 3491 } else { 3492 last->set_osr_link(next); 3493 } 3494 } 3495 n->set_osr_link(nullptr); 3496 cur = next; 3497 while (cur != nullptr) { 3498 // Find max level after n 3499 if (m == cur->method()) { 3500 max_level = MAX2(max_level, cur->comp_level()); 3501 } 3502 cur = cur->osr_link(); 3503 } 3504 m->set_highest_osr_comp_level(max_level); 3505 return found; 3506 } 3507 3508 int InstanceKlass::mark_osr_nmethods(DeoptimizationScope* deopt_scope, const Method* m) { 3509 ConditionalMutexLocker ml(CompiledMethod_lock, !CompiledMethod_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3510 nmethod* osr = osr_nmethods_head(); 3511 int found = 0; 3512 while (osr != nullptr) { 3513 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3514 if (osr->method() == m) { 3515 deopt_scope->mark(osr); 3516 found++; 3517 } 3518 osr = osr->osr_link(); 3519 } 3520 return found; 3521 } 3522 3523 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const { 3524 ConditionalMutexLocker ml(CompiledMethod_lock, !CompiledMethod_lock->owned_by_self(), Mutex::_no_safepoint_check_flag); 3525 nmethod* osr = osr_nmethods_head(); 3526 nmethod* best = nullptr; 3527 while (osr != nullptr) { 3528 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3529 // There can be a time when a c1 osr method exists but we are waiting 3530 // for a c2 version. When c2 completes its osr nmethod we will trash 3531 // the c1 version and only be able to find the c2 version. However 3532 // while we overflow in the c1 code at back branches we don't want to 3533 // try and switch to the same code as we are already running 3534 3535 if (osr->method() == m && 3536 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) { 3537 if (match_level) { 3538 if (osr->comp_level() == comp_level) { 3539 // Found a match - return it. 3540 return osr; 3541 } 3542 } else { 3543 if (best == nullptr || (osr->comp_level() > best->comp_level())) { 3544 if (osr->comp_level() == CompilationPolicy::highest_compile_level()) { 3545 // Found the best possible - return it. 3546 return osr; 3547 } 3548 best = osr; 3549 } 3550 } 3551 } 3552 osr = osr->osr_link(); 3553 } 3554 3555 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set"); 3556 if (best != nullptr && best->comp_level() >= comp_level) { 3557 return best; 3558 } 3559 return nullptr; 3560 } 3561 3562 // ----------------------------------------------------------------------------------------------------- 3563 // Printing 3564 3565 #define BULLET " - " 3566 3567 static const char* state_names[] = { 3568 "allocated", "loaded", "being_linked", "linked", "being_initialized", "fully_initialized", "initialization_error" 3569 }; 3570 3571 static void print_vtable(intptr_t* start, int len, outputStream* st) { 3572 for (int i = 0; i < len; i++) { 3573 intptr_t e = start[i]; 3574 st->print("%d : " INTPTR_FORMAT, i, e); 3575 if (MetaspaceObj::is_valid((Metadata*)e)) { 3576 st->print(" "); 3577 ((Metadata*)e)->print_value_on(st); 3578 } 3579 st->cr(); 3580 } 3581 } 3582 3583 static void print_vtable(vtableEntry* start, int len, outputStream* st) { 3584 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st); 3585 } 3586 3587 const char* InstanceKlass::init_state_name() const { 3588 return state_names[init_state()]; 3589 } 3590 3591 void InstanceKlass::print_on(outputStream* st) const { 3592 assert(is_klass(), "must be klass"); 3593 Klass::print_on(st); 3594 3595 st->print(BULLET"instance size: %d", size_helper()); st->cr(); 3596 st->print(BULLET"klass size: %d", size()); st->cr(); 3597 st->print(BULLET"access: "); access_flags().print_on(st); st->cr(); 3598 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr(); 3599 st->print(BULLET"state: "); st->print_cr("%s", init_state_name()); 3600 st->print(BULLET"name: "); name()->print_value_on(st); st->cr(); 3601 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr(); 3602 st->print(BULLET"sub: "); 3603 Klass* sub = subklass(); 3604 int n; 3605 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) { 3606 if (n < MaxSubklassPrintSize) { 3607 sub->print_value_on(st); 3608 st->print(" "); 3609 } 3610 } 3611 if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize); 3612 st->cr(); 3613 3614 if (is_interface()) { 3615 st->print_cr(BULLET"nof implementors: %d", nof_implementors()); 3616 if (nof_implementors() == 1) { 3617 st->print_cr(BULLET"implementor: "); 3618 st->print(" "); 3619 implementor()->print_value_on(st); 3620 st->cr(); 3621 } 3622 } 3623 3624 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr(); 3625 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr(); 3626 if (Verbose || WizardMode) { 3627 Array<Method*>* method_array = methods(); 3628 for (int i = 0; i < method_array->length(); i++) { 3629 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr(); 3630 } 3631 } 3632 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr(); 3633 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr(); 3634 if (Verbose && default_methods() != nullptr) { 3635 Array<Method*>* method_array = default_methods(); 3636 for (int i = 0; i < method_array->length(); i++) { 3637 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr(); 3638 } 3639 } 3640 if (default_vtable_indices() != nullptr) { 3641 st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr(); 3642 } 3643 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr(); 3644 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr(); 3645 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr(); 3646 if (class_loader_data() != nullptr) { 3647 st->print(BULLET"class loader data: "); 3648 class_loader_data()->print_value_on(st); 3649 st->cr(); 3650 } 3651 if (source_file_name() != nullptr) { 3652 st->print(BULLET"source file: "); 3653 source_file_name()->print_value_on(st); 3654 st->cr(); 3655 } 3656 if (source_debug_extension() != nullptr) { 3657 st->print(BULLET"source debug extension: "); 3658 st->print("%s", source_debug_extension()); 3659 st->cr(); 3660 } 3661 st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr(); 3662 st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr(); 3663 st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr(); 3664 st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr(); 3665 { 3666 bool have_pv = false; 3667 // previous versions are linked together through the InstanceKlass 3668 for (InstanceKlass* pv_node = previous_versions(); 3669 pv_node != nullptr; 3670 pv_node = pv_node->previous_versions()) { 3671 if (!have_pv) 3672 st->print(BULLET"previous version: "); 3673 have_pv = true; 3674 pv_node->constants()->print_value_on(st); 3675 } 3676 if (have_pv) st->cr(); 3677 } 3678 3679 if (generic_signature() != nullptr) { 3680 st->print(BULLET"generic signature: "); 3681 generic_signature()->print_value_on(st); 3682 st->cr(); 3683 } 3684 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr(); 3685 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr(); 3686 if (record_components() != nullptr) { 3687 st->print(BULLET"record components: "); record_components()->print_value_on(st); st->cr(); 3688 } 3689 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr(); 3690 if (java_mirror() != nullptr) { 3691 st->print(BULLET"java mirror: "); 3692 java_mirror()->print_value_on(st); 3693 st->cr(); 3694 } else { 3695 st->print_cr(BULLET"java mirror: null"); 3696 } 3697 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr(); 3698 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st); 3699 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr(); 3700 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st); 3701 st->print_cr(BULLET"---- static fields (%d words):", static_field_size()); 3702 FieldPrinter print_static_field(st); 3703 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field); 3704 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size()); 3705 FieldPrinter print_nonstatic_field(st); 3706 InstanceKlass* ik = const_cast<InstanceKlass*>(this); 3707 ik->print_nonstatic_fields(&print_nonstatic_field); 3708 3709 st->print(BULLET"non-static oop maps: "); 3710 OopMapBlock* map = start_of_nonstatic_oop_maps(); 3711 OopMapBlock* end_map = map + nonstatic_oop_map_count(); 3712 while (map < end_map) { 3713 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1)); 3714 map++; 3715 } 3716 st->cr(); 3717 } 3718 3719 void InstanceKlass::print_value_on(outputStream* st) const { 3720 assert(is_klass(), "must be klass"); 3721 if (Verbose || WizardMode) access_flags().print_on(st); 3722 name()->print_value_on(st); 3723 } 3724 3725 void FieldPrinter::do_field(fieldDescriptor* fd) { 3726 _st->print(BULLET); 3727 if (_obj == nullptr) { 3728 fd->print_on(_st); 3729 _st->cr(); 3730 } else { 3731 fd->print_on_for(_st, _obj); 3732 _st->cr(); 3733 } 3734 } 3735 3736 3737 void InstanceKlass::oop_print_on(oop obj, outputStream* st) { 3738 Klass::oop_print_on(obj, st); 3739 3740 if (this == vmClasses::String_klass()) { 3741 typeArrayOop value = java_lang_String::value(obj); 3742 juint length = java_lang_String::length(obj); 3743 if (value != nullptr && 3744 value->is_typeArray() && 3745 length <= (juint) value->length()) { 3746 st->print(BULLET"string: "); 3747 java_lang_String::print(obj, st); 3748 st->cr(); 3749 } 3750 } 3751 3752 st->print_cr(BULLET"---- fields (total size " SIZE_FORMAT " words):", oop_size(obj)); 3753 FieldPrinter print_field(st, obj); 3754 print_nonstatic_fields(&print_field); 3755 3756 if (this == vmClasses::Class_klass()) { 3757 st->print(BULLET"signature: "); 3758 java_lang_Class::print_signature(obj, st); 3759 st->cr(); 3760 Klass* real_klass = java_lang_Class::as_Klass(obj); 3761 if (real_klass != nullptr && real_klass->is_instance_klass()) { 3762 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj)); 3763 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field); 3764 } 3765 } else if (this == vmClasses::MethodType_klass()) { 3766 st->print(BULLET"signature: "); 3767 java_lang_invoke_MethodType::print_signature(obj, st); 3768 st->cr(); 3769 } 3770 } 3771 3772 #ifndef PRODUCT 3773 3774 bool InstanceKlass::verify_itable_index(int i) { 3775 int method_count = klassItable::method_count_for_interface(this); 3776 assert(i >= 0 && i < method_count, "index out of bounds"); 3777 return true; 3778 } 3779 3780 #endif //PRODUCT 3781 3782 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) { 3783 st->print("a "); 3784 name()->print_value_on(st); 3785 obj->print_address_on(st); 3786 if (this == vmClasses::String_klass() 3787 && java_lang_String::value(obj) != nullptr) { 3788 ResourceMark rm; 3789 int len = java_lang_String::length(obj); 3790 int plen = (len < 24 ? len : 12); 3791 char* str = java_lang_String::as_utf8_string(obj, 0, plen); 3792 st->print(" = \"%s\"", str); 3793 if (len > plen) 3794 st->print("...[%d]", len); 3795 } else if (this == vmClasses::Class_klass()) { 3796 Klass* k = java_lang_Class::as_Klass(obj); 3797 st->print(" = "); 3798 if (k != nullptr) { 3799 k->print_value_on(st); 3800 } else { 3801 const char* tname = type2name(java_lang_Class::primitive_type(obj)); 3802 st->print("%s", tname ? tname : "type?"); 3803 } 3804 } else if (this == vmClasses::MethodType_klass()) { 3805 st->print(" = "); 3806 java_lang_invoke_MethodType::print_signature(obj, st); 3807 } else if (java_lang_boxing_object::is_instance(obj)) { 3808 st->print(" = "); 3809 java_lang_boxing_object::print(obj, st); 3810 } else if (this == vmClasses::LambdaForm_klass()) { 3811 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj); 3812 if (vmentry != nullptr) { 3813 st->print(" => "); 3814 vmentry->print_value_on(st); 3815 } 3816 } else if (this == vmClasses::MemberName_klass()) { 3817 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj); 3818 if (vmtarget != nullptr) { 3819 st->print(" = "); 3820 vmtarget->print_value_on(st); 3821 } else { 3822 oop clazz = java_lang_invoke_MemberName::clazz(obj); 3823 oop name = java_lang_invoke_MemberName::name(obj); 3824 if (clazz != nullptr) { 3825 clazz->print_value_on(st); 3826 } else { 3827 st->print("null"); 3828 } 3829 st->print("."); 3830 if (name != nullptr) { 3831 name->print_value_on(st); 3832 } else { 3833 st->print("null"); 3834 } 3835 } 3836 } 3837 } 3838 3839 const char* InstanceKlass::internal_name() const { 3840 return external_name(); 3841 } 3842 3843 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data, 3844 const ModuleEntry* module_entry, 3845 const ClassFileStream* cfs) const { 3846 3847 if (ClassListWriter::is_enabled()) { 3848 ClassListWriter::write(this, cfs); 3849 } 3850 3851 print_class_load_helper(loader_data, module_entry, cfs); 3852 print_class_load_cause_logging(); 3853 } 3854 3855 void InstanceKlass::print_class_load_helper(ClassLoaderData* loader_data, 3856 const ModuleEntry* module_entry, 3857 const ClassFileStream* cfs) const { 3858 3859 if (!log_is_enabled(Info, class, load)) { 3860 return; 3861 } 3862 3863 ResourceMark rm; 3864 LogMessage(class, load) msg; 3865 stringStream info_stream; 3866 3867 // Name and class hierarchy info 3868 info_stream.print("%s", external_name()); 3869 3870 // Source 3871 if (cfs != nullptr) { 3872 if (cfs->source() != nullptr) { 3873 const char* module_name = (module_entry->name() == nullptr) ? UNNAMED_MODULE : module_entry->name()->as_C_string(); 3874 if (module_name != nullptr) { 3875 // When the boot loader created the stream, it didn't know the module name 3876 // yet. Let's format it now. 3877 if (cfs->from_boot_loader_modules_image()) { 3878 info_stream.print(" source: jrt:/%s", module_name); 3879 } else { 3880 info_stream.print(" source: %s", cfs->source()); 3881 } 3882 } else { 3883 info_stream.print(" source: %s", cfs->source()); 3884 } 3885 } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) { 3886 Thread* current = Thread::current(); 3887 Klass* caller = current->is_Java_thread() ? 3888 JavaThread::cast(current)->security_get_caller_class(1): 3889 nullptr; 3890 // caller can be null, for example, during a JVMTI VM_Init hook 3891 if (caller != nullptr) { 3892 info_stream.print(" source: instance of %s", caller->external_name()); 3893 } else { 3894 // source is unknown 3895 } 3896 } else { 3897 oop class_loader = loader_data->class_loader(); 3898 info_stream.print(" source: %s", class_loader->klass()->external_name()); 3899 } 3900 } else { 3901 assert(this->is_shared(), "must be"); 3902 if (MetaspaceShared::is_shared_dynamic((void*)this)) { 3903 info_stream.print(" source: shared objects file (top)"); 3904 } else { 3905 info_stream.print(" source: shared objects file"); 3906 } 3907 } 3908 3909 msg.info("%s", info_stream.as_string()); 3910 3911 if (log_is_enabled(Debug, class, load)) { 3912 stringStream debug_stream; 3913 3914 // Class hierarchy info 3915 debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT, 3916 p2i(this), p2i(superklass())); 3917 3918 // Interfaces 3919 if (local_interfaces() != nullptr && local_interfaces()->length() > 0) { 3920 debug_stream.print(" interfaces:"); 3921 int length = local_interfaces()->length(); 3922 for (int i = 0; i < length; i++) { 3923 debug_stream.print(" " PTR_FORMAT, 3924 p2i(InstanceKlass::cast(local_interfaces()->at(i)))); 3925 } 3926 } 3927 3928 // Class loader 3929 debug_stream.print(" loader: ["); 3930 loader_data->print_value_on(&debug_stream); 3931 debug_stream.print("]"); 3932 3933 // Classfile checksum 3934 if (cfs) { 3935 debug_stream.print(" bytes: %d checksum: %08x", 3936 cfs->length(), 3937 ClassLoader::crc32(0, (const char*)cfs->buffer(), 3938 cfs->length())); 3939 } 3940 3941 msg.debug("%s", debug_stream.as_string()); 3942 } 3943 } 3944 3945 void InstanceKlass::print_class_load_cause_logging() const { 3946 bool log_cause_native = log_is_enabled(Info, class, load, cause, native); 3947 if (log_cause_native || log_is_enabled(Info, class, load, cause)) { 3948 JavaThread* current = JavaThread::current(); 3949 ResourceMark rm(current); 3950 const char* name = external_name(); 3951 3952 if (LogClassLoadingCauseFor == nullptr || 3953 (strcmp("*", LogClassLoadingCauseFor) != 0 && 3954 strstr(name, LogClassLoadingCauseFor) == nullptr)) { 3955 return; 3956 } 3957 3958 // Log Java stack first 3959 { 3960 LogMessage(class, load, cause) msg; 3961 NonInterleavingLogStream info_stream{LogLevelType::Info, msg}; 3962 3963 info_stream.print_cr("Java stack when loading %s:", name); 3964 current->print_stack_on(&info_stream); 3965 } 3966 3967 // Log native stack second 3968 if (log_cause_native) { 3969 // Log to string first so that lines can be indented 3970 stringStream stack_stream; 3971 char buf[O_BUFLEN]; 3972 address lastpc = nullptr; 3973 if (os::platform_print_native_stack(&stack_stream, nullptr, buf, O_BUFLEN, lastpc)) { 3974 // We have printed the native stack in platform-specific code, 3975 // so nothing else to do in this case. 3976 } else { 3977 frame f = os::current_frame(); 3978 VMError::print_native_stack(&stack_stream, f, current, true /*print_source_info */, 3979 -1 /* max stack_stream */, buf, O_BUFLEN); 3980 } 3981 3982 LogMessage(class, load, cause, native) msg; 3983 NonInterleavingLogStream info_stream{LogLevelType::Info, msg}; 3984 info_stream.print_cr("Native stack when loading %s:", name); 3985 3986 // Print each native stack line to the log 3987 int size = (int) stack_stream.size(); 3988 char* stack = stack_stream.as_string(); 3989 char* stack_end = stack + size; 3990 char* line_start = stack; 3991 for (char* p = stack; p < stack_end; p++) { 3992 if (*p == '\n') { 3993 *p = '\0'; 3994 info_stream.print_cr("\t%s", line_start); 3995 line_start = p + 1; 3996 } 3997 } 3998 if (line_start < stack_end) { 3999 info_stream.print_cr("\t%s", line_start); 4000 } 4001 } 4002 } 4003 } 4004 4005 // Verification 4006 4007 class VerifyFieldClosure: public BasicOopIterateClosure { 4008 protected: 4009 template <class T> void do_oop_work(T* p) { 4010 oop obj = RawAccess<>::oop_load(p); 4011 if (!oopDesc::is_oop_or_null(obj)) { 4012 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj)); 4013 Universe::print_on(tty); 4014 guarantee(false, "boom"); 4015 } 4016 } 4017 public: 4018 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); } 4019 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); } 4020 }; 4021 4022 void InstanceKlass::verify_on(outputStream* st) { 4023 #ifndef PRODUCT 4024 // Avoid redundant verifies, this really should be in product. 4025 if (_verify_count == Universe::verify_count()) return; 4026 _verify_count = Universe::verify_count(); 4027 #endif 4028 4029 // Verify Klass 4030 Klass::verify_on(st); 4031 4032 // Verify that klass is present in ClassLoaderData 4033 guarantee(class_loader_data()->contains_klass(this), 4034 "this class isn't found in class loader data"); 4035 4036 // Verify vtables 4037 if (is_linked()) { 4038 // $$$ This used to be done only for m/s collections. Doing it 4039 // always seemed a valid generalization. (DLD -- 6/00) 4040 vtable().verify(st); 4041 } 4042 4043 // Verify first subklass 4044 if (subklass() != nullptr) { 4045 guarantee(subklass()->is_klass(), "should be klass"); 4046 } 4047 4048 // Verify siblings 4049 Klass* super = this->super(); 4050 Klass* sib = next_sibling(); 4051 if (sib != nullptr) { 4052 if (sib == this) { 4053 fatal("subclass points to itself " PTR_FORMAT, p2i(sib)); 4054 } 4055 4056 guarantee(sib->is_klass(), "should be klass"); 4057 guarantee(sib->super() == super, "siblings should have same superklass"); 4058 } 4059 4060 // Verify local interfaces 4061 if (local_interfaces()) { 4062 Array<InstanceKlass*>* local_interfaces = this->local_interfaces(); 4063 for (int j = 0; j < local_interfaces->length(); j++) { 4064 InstanceKlass* e = local_interfaces->at(j); 4065 guarantee(e->is_klass() && e->is_interface(), "invalid local interface"); 4066 } 4067 } 4068 4069 // Verify transitive interfaces 4070 if (transitive_interfaces() != nullptr) { 4071 Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces(); 4072 for (int j = 0; j < transitive_interfaces->length(); j++) { 4073 InstanceKlass* e = transitive_interfaces->at(j); 4074 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface"); 4075 } 4076 } 4077 4078 // Verify methods 4079 if (methods() != nullptr) { 4080 Array<Method*>* methods = this->methods(); 4081 for (int j = 0; j < methods->length(); j++) { 4082 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 4083 } 4084 for (int j = 0; j < methods->length() - 1; j++) { 4085 Method* m1 = methods->at(j); 4086 Method* m2 = methods->at(j + 1); 4087 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 4088 } 4089 } 4090 4091 // Verify method ordering 4092 if (method_ordering() != nullptr) { 4093 Array<int>* method_ordering = this->method_ordering(); 4094 int length = method_ordering->length(); 4095 if (JvmtiExport::can_maintain_original_method_order() || 4096 ((UseSharedSpaces || CDSConfig::is_dumping_archive()) && length != 0)) { 4097 guarantee(length == methods()->length(), "invalid method ordering length"); 4098 jlong sum = 0; 4099 for (int j = 0; j < length; j++) { 4100 int original_index = method_ordering->at(j); 4101 guarantee(original_index >= 0, "invalid method ordering index"); 4102 guarantee(original_index < length, "invalid method ordering index"); 4103 sum += original_index; 4104 } 4105 // Verify sum of indices 0,1,...,length-1 4106 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum"); 4107 } else { 4108 guarantee(length == 0, "invalid method ordering length"); 4109 } 4110 } 4111 4112 // Verify default methods 4113 if (default_methods() != nullptr) { 4114 Array<Method*>* methods = this->default_methods(); 4115 for (int j = 0; j < methods->length(); j++) { 4116 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 4117 } 4118 for (int j = 0; j < methods->length() - 1; j++) { 4119 Method* m1 = methods->at(j); 4120 Method* m2 = methods->at(j + 1); 4121 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 4122 } 4123 } 4124 4125 // Verify JNI static field identifiers 4126 if (jni_ids() != nullptr) { 4127 jni_ids()->verify(this); 4128 } 4129 4130 // Verify other fields 4131 if (constants() != nullptr) { 4132 guarantee(constants()->is_constantPool(), "should be constant pool"); 4133 } 4134 } 4135 4136 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) { 4137 Klass::oop_verify_on(obj, st); 4138 VerifyFieldClosure blk; 4139 obj->oop_iterate(&blk); 4140 } 4141 4142 4143 // JNIid class for jfieldIDs only 4144 // Note to reviewers: 4145 // These JNI functions are just moved over to column 1 and not changed 4146 // in the compressed oops workspace. 4147 JNIid::JNIid(Klass* holder, int offset, JNIid* next) { 4148 _holder = holder; 4149 _offset = offset; 4150 _next = next; 4151 debug_only(_is_static_field_id = false;) 4152 } 4153 4154 4155 JNIid* JNIid::find(int offset) { 4156 JNIid* current = this; 4157 while (current != nullptr) { 4158 if (current->offset() == offset) return current; 4159 current = current->next(); 4160 } 4161 return nullptr; 4162 } 4163 4164 void JNIid::deallocate(JNIid* current) { 4165 while (current != nullptr) { 4166 JNIid* next = current->next(); 4167 delete current; 4168 current = next; 4169 } 4170 } 4171 4172 4173 void JNIid::verify(Klass* holder) { 4174 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields(); 4175 int end_field_offset; 4176 end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize); 4177 4178 JNIid* current = this; 4179 while (current != nullptr) { 4180 guarantee(current->holder() == holder, "Invalid klass in JNIid"); 4181 #ifdef ASSERT 4182 int o = current->offset(); 4183 if (current->is_static_field_id()) { 4184 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid"); 4185 } 4186 #endif 4187 current = current->next(); 4188 } 4189 } 4190 4191 void InstanceKlass::set_init_state(ClassState state) { 4192 if (state > loaded) { 4193 assert_lock_strong(_init_monitor); 4194 } 4195 #ifdef ASSERT 4196 bool good_state = is_shared() ? (_init_state <= state) 4197 : (_init_state < state); 4198 bool link_failed = _init_state == being_linked && state == loaded; 4199 assert(good_state || state == allocated || link_failed, "illegal state transition"); 4200 #endif 4201 assert(_init_thread == nullptr, "should be cleared before state change"); 4202 Atomic::store(&_init_state, state); 4203 } 4204 4205 #if INCLUDE_JVMTI 4206 4207 // RedefineClasses() support for previous versions 4208 4209 // Globally, there is at least one previous version of a class to walk 4210 // during class unloading, which is saved because old methods in the class 4211 // are still running. Otherwise the previous version list is cleaned up. 4212 bool InstanceKlass::_should_clean_previous_versions = false; 4213 4214 // Returns true if there are previous versions of a class for class 4215 // unloading only. Also resets the flag to false. purge_previous_version 4216 // will set the flag to true if there are any left, i.e., if there's any 4217 // work to do for next time. This is to avoid the expensive code cache 4218 // walk in CLDG::clean_deallocate_lists(). 4219 bool InstanceKlass::should_clean_previous_versions_and_reset() { 4220 bool ret = _should_clean_previous_versions; 4221 log_trace(redefine, class, iklass, purge)("Class unloading: should_clean_previous_versions = %s", 4222 ret ? "true" : "false"); 4223 _should_clean_previous_versions = false; 4224 return ret; 4225 } 4226 4227 // This nulls out jmethodIDs for all methods in 'klass' 4228 // It needs to be called explicitly for all previous versions of a class because these may not be cleaned up 4229 // during class unloading. 4230 // We can not use the jmethodID cache associated with klass directly because the 'previous' versions 4231 // do not have the jmethodID cache filled in. Instead, we need to lookup jmethodID for each method and this 4232 // is expensive - O(n) for one jmethodID lookup. For all contained methods it is O(n^2). 4233 // The reason for expensive jmethodID lookup for each method is that there is no direct link between method and jmethodID. 4234 void InstanceKlass::clear_jmethod_ids(InstanceKlass* klass) { 4235 Array<Method*>* method_refs = klass->methods(); 4236 for (int k = 0; k < method_refs->length(); k++) { 4237 Method* method = method_refs->at(k); 4238 if (method != nullptr && method->is_obsolete()) { 4239 method->clear_jmethod_id(); 4240 } 4241 } 4242 } 4243 4244 // Purge previous versions before adding new previous versions of the class and 4245 // during class unloading. 4246 void InstanceKlass::purge_previous_version_list() { 4247 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 4248 assert(has_been_redefined(), "Should only be called for main class"); 4249 4250 // Quick exit. 4251 if (previous_versions() == nullptr) { 4252 return; 4253 } 4254 4255 // This klass has previous versions so see what we can cleanup 4256 // while it is safe to do so. 4257 4258 int deleted_count = 0; // leave debugging breadcrumbs 4259 int live_count = 0; 4260 ClassLoaderData* loader_data = class_loader_data(); 4261 assert(loader_data != nullptr, "should never be null"); 4262 4263 ResourceMark rm; 4264 log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name()); 4265 4266 // previous versions are linked together through the InstanceKlass 4267 InstanceKlass* pv_node = previous_versions(); 4268 InstanceKlass* last = this; 4269 int version = 0; 4270 4271 // check the previous versions list 4272 for (; pv_node != nullptr; ) { 4273 4274 ConstantPool* pvcp = pv_node->constants(); 4275 assert(pvcp != nullptr, "cp ref was unexpectedly cleared"); 4276 4277 if (!pvcp->on_stack()) { 4278 // If the constant pool isn't on stack, none of the methods 4279 // are executing. Unlink this previous_version. 4280 // The previous version InstanceKlass is on the ClassLoaderData deallocate list 4281 // so will be deallocated during the next phase of class unloading. 4282 log_trace(redefine, class, iklass, purge) 4283 ("previous version " PTR_FORMAT " is dead.", p2i(pv_node)); 4284 // Unlink from previous version list. 4285 assert(pv_node->class_loader_data() == loader_data, "wrong loader_data"); 4286 InstanceKlass* next = pv_node->previous_versions(); 4287 clear_jmethod_ids(pv_node); // jmethodID maintenance for the unloaded class 4288 pv_node->link_previous_versions(nullptr); // point next to null 4289 last->link_previous_versions(next); 4290 // Delete this node directly. Nothing is referring to it and we don't 4291 // want it to increase the counter for metadata to delete in CLDG. 4292 MetadataFactory::free_metadata(loader_data, pv_node); 4293 pv_node = next; 4294 deleted_count++; 4295 version++; 4296 continue; 4297 } else { 4298 assert(pvcp->pool_holder() != nullptr, "Constant pool with no holder"); 4299 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack"); 4300 live_count++; 4301 if (pvcp->is_shared()) { 4302 // Shared previous versions can never be removed so no cleaning is needed. 4303 log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is shared", p2i(pv_node)); 4304 } else { 4305 // Previous version alive, set that clean is needed for next time. 4306 _should_clean_previous_versions = true; 4307 log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is alive", p2i(pv_node)); 4308 } 4309 } 4310 4311 // next previous version 4312 last = pv_node; 4313 pv_node = pv_node->previous_versions(); 4314 version++; 4315 } 4316 log_trace(redefine, class, iklass, purge) 4317 ("previous version stats: live=%d, deleted=%d", live_count, deleted_count); 4318 } 4319 4320 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods, 4321 int emcp_method_count) { 4322 int obsolete_method_count = old_methods->length() - emcp_method_count; 4323 4324 if (emcp_method_count != 0 && obsolete_method_count != 0 && 4325 _previous_versions != nullptr) { 4326 // We have a mix of obsolete and EMCP methods so we have to 4327 // clear out any matching EMCP method entries the hard way. 4328 int local_count = 0; 4329 for (int i = 0; i < old_methods->length(); i++) { 4330 Method* old_method = old_methods->at(i); 4331 if (old_method->is_obsolete()) { 4332 // only obsolete methods are interesting 4333 Symbol* m_name = old_method->name(); 4334 Symbol* m_signature = old_method->signature(); 4335 4336 // previous versions are linked together through the InstanceKlass 4337 int j = 0; 4338 for (InstanceKlass* prev_version = _previous_versions; 4339 prev_version != nullptr; 4340 prev_version = prev_version->previous_versions(), j++) { 4341 4342 Array<Method*>* method_refs = prev_version->methods(); 4343 for (int k = 0; k < method_refs->length(); k++) { 4344 Method* method = method_refs->at(k); 4345 4346 if (!method->is_obsolete() && 4347 method->name() == m_name && 4348 method->signature() == m_signature) { 4349 // The current RedefineClasses() call has made all EMCP 4350 // versions of this method obsolete so mark it as obsolete 4351 log_trace(redefine, class, iklass, add) 4352 ("%s(%s): flush obsolete method @%d in version @%d", 4353 m_name->as_C_string(), m_signature->as_C_string(), k, j); 4354 4355 method->set_is_obsolete(); 4356 break; 4357 } 4358 } 4359 4360 // The previous loop may not find a matching EMCP method, but 4361 // that doesn't mean that we can optimize and not go any 4362 // further back in the PreviousVersion generations. The EMCP 4363 // method for this generation could have already been made obsolete, 4364 // but there still may be an older EMCP method that has not 4365 // been made obsolete. 4366 } 4367 4368 if (++local_count >= obsolete_method_count) { 4369 // no more obsolete methods so bail out now 4370 break; 4371 } 4372 } 4373 } 4374 } 4375 } 4376 4377 // Save the scratch_class as the previous version if any of the methods are running. 4378 // The previous_versions are used to set breakpoints in EMCP methods and they are 4379 // also used to clean MethodData links to redefined methods that are no longer running. 4380 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class, 4381 int emcp_method_count) { 4382 assert(Thread::current()->is_VM_thread(), 4383 "only VMThread can add previous versions"); 4384 4385 ResourceMark rm; 4386 log_trace(redefine, class, iklass, add) 4387 ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count); 4388 4389 // Clean out old previous versions for this class 4390 purge_previous_version_list(); 4391 4392 // Mark newly obsolete methods in remaining previous versions. An EMCP method from 4393 // a previous redefinition may be made obsolete by this redefinition. 4394 Array<Method*>* old_methods = scratch_class->methods(); 4395 mark_newly_obsolete_methods(old_methods, emcp_method_count); 4396 4397 // If the constant pool for this previous version of the class 4398 // is not marked as being on the stack, then none of the methods 4399 // in this previous version of the class are on the stack so 4400 // we don't need to add this as a previous version. 4401 ConstantPool* cp_ref = scratch_class->constants(); 4402 if (!cp_ref->on_stack()) { 4403 log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running"); 4404 scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class); 4405 return; 4406 } 4407 4408 // Add previous version if any methods are still running or if this is 4409 // a shared class which should never be removed. 4410 assert(scratch_class->previous_versions() == nullptr, "shouldn't have a previous version"); 4411 scratch_class->link_previous_versions(previous_versions()); 4412 link_previous_versions(scratch_class); 4413 if (cp_ref->is_shared()) { 4414 log_trace(redefine, class, iklass, add) ("scratch class added; class is shared"); 4415 } else { 4416 // We only set clean_previous_versions flag for processing during class 4417 // unloading for non-shared classes. 4418 _should_clean_previous_versions = true; 4419 log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack."); 4420 } 4421 } // end add_previous_version() 4422 4423 #endif // INCLUDE_JVMTI 4424 4425 Method* InstanceKlass::method_with_idnum(int idnum) { 4426 Method* m = nullptr; 4427 if (idnum < methods()->length()) { 4428 m = methods()->at(idnum); 4429 } 4430 if (m == nullptr || m->method_idnum() != idnum) { 4431 for (int index = 0; index < methods()->length(); ++index) { 4432 m = methods()->at(index); 4433 if (m->method_idnum() == idnum) { 4434 return m; 4435 } 4436 } 4437 // None found, return null for the caller to handle. 4438 return nullptr; 4439 } 4440 return m; 4441 } 4442 4443 4444 Method* InstanceKlass::method_with_orig_idnum(int idnum) { 4445 if (idnum >= methods()->length()) { 4446 return nullptr; 4447 } 4448 Method* m = methods()->at(idnum); 4449 if (m != nullptr && m->orig_method_idnum() == idnum) { 4450 return m; 4451 } 4452 // Obsolete method idnum does not match the original idnum 4453 for (int index = 0; index < methods()->length(); ++index) { 4454 m = methods()->at(index); 4455 if (m->orig_method_idnum() == idnum) { 4456 return m; 4457 } 4458 } 4459 // None found, return null for the caller to handle. 4460 return nullptr; 4461 } 4462 4463 4464 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) { 4465 InstanceKlass* holder = get_klass_version(version); 4466 if (holder == nullptr) { 4467 return nullptr; // The version of klass is gone, no method is found 4468 } 4469 Method* method = holder->method_with_orig_idnum(idnum); 4470 return method; 4471 } 4472 4473 #if INCLUDE_JVMTI 4474 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() { 4475 return _cached_class_file; 4476 } 4477 4478 jint InstanceKlass::get_cached_class_file_len() { 4479 return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file); 4480 } 4481 4482 unsigned char * InstanceKlass::get_cached_class_file_bytes() { 4483 return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file); 4484 } 4485 #endif 4486 4487 // Make a step iterating over the class hierarchy under the root class. 4488 // Skips subclasses if requested. 4489 void ClassHierarchyIterator::next() { 4490 assert(_current != nullptr, "required"); 4491 if (_visit_subclasses && _current->subklass() != nullptr) { 4492 _current = _current->subklass(); 4493 return; // visit next subclass 4494 } 4495 _visit_subclasses = true; // reset 4496 while (_current->next_sibling() == nullptr && _current != _root) { 4497 _current = _current->superklass(); // backtrack; no more sibling subclasses left 4498 } 4499 if (_current == _root) { 4500 // Iteration is over (back at root after backtracking). Invalidate the iterator. 4501 _current = nullptr; 4502 return; 4503 } 4504 _current = _current->next_sibling(); 4505 return; // visit next sibling subclass 4506 }