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