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