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