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