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