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->is_class_initializer()) { 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 if (name == vmSymbols::object_initializer_name()) { 1917 break; // <init> is never inherited, not even as a static factory 1918 } 1919 klass = klass->super(); 1920 overpass_local_mode = skip_overpass; // Always ignore overpass methods in superclasses 1921 } 1922 return NULL; 1923 } 1924 1925 #ifdef ASSERT 1926 // search through class hierarchy and return true if this class or 1927 // one of the superclasses was redefined 1928 bool InstanceKlass::has_redefined_this_or_super() const { 1929 const Klass* klass = this; 1930 while (klass != NULL) { 1931 if (InstanceKlass::cast(klass)->has_been_redefined()) { 1932 return true; 1933 } 1934 klass = klass->super(); 1935 } 1936 return false; 1937 } 1938 #endif 1939 1940 // lookup a method in the default methods list then in all transitive interfaces 1941 // Do NOT return private or static methods 1942 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name, 1943 Symbol* signature) const { 1944 Method* m = NULL; 1945 if (default_methods() != NULL) { 1946 m = find_method(default_methods(), name, signature); 1947 } 1948 // Look up interfaces 1949 if (m == NULL) { 1950 m = lookup_method_in_all_interfaces(name, signature, find_defaults); 1951 } 1952 return m; 1953 } 1954 1955 // lookup a method in all the interfaces that this class implements 1956 // Do NOT return private or static methods, new in JDK8 which are not externally visible 1957 // They should only be found in the initial InterfaceMethodRef 1958 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name, 1959 Symbol* signature, 1960 DefaultsLookupMode defaults_mode) const { 1961 Array<InstanceKlass*>* all_ifs = transitive_interfaces(); 1962 int num_ifs = all_ifs->length(); 1963 InstanceKlass *ik = NULL; 1964 for (int i = 0; i < num_ifs; i++) { 1965 ik = all_ifs->at(i); 1966 Method* m = ik->lookup_method(name, signature); 1967 if (m != NULL && m->is_public() && !m->is_static() && 1968 ((defaults_mode != skip_defaults) || !m->is_default_method())) { 1969 return m; 1970 } 1971 } 1972 return NULL; 1973 } 1974 1975 /* jni_id_for_impl for jfieldIds only */ 1976 JNIid* InstanceKlass::jni_id_for_impl(int offset) { 1977 MutexLocker ml(JfieldIdCreation_lock); 1978 // Retry lookup after we got the lock 1979 JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset); 1980 if (probe == NULL) { 1981 // Slow case, allocate new static field identifier 1982 probe = new JNIid(this, offset, jni_ids()); 1983 set_jni_ids(probe); 1984 } 1985 return probe; 1986 } 1987 1988 1989 /* jni_id_for for jfieldIds only */ 1990 JNIid* InstanceKlass::jni_id_for(int offset) { 1991 JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset); 1992 if (probe == NULL) { 1993 probe = jni_id_for_impl(offset); 1994 } 1995 return probe; 1996 } 1997 1998 u2 InstanceKlass::enclosing_method_data(int offset) const { 1999 const Array<jushort>* const inner_class_list = inner_classes(); 2000 if (inner_class_list == NULL) { 2001 return 0; 2002 } 2003 const int length = inner_class_list->length(); 2004 if (length % inner_class_next_offset == 0) { 2005 return 0; 2006 } 2007 const int index = length - enclosing_method_attribute_size; 2008 assert(offset < enclosing_method_attribute_size, "invalid offset"); 2009 return inner_class_list->at(index + offset); 2010 } 2011 2012 void InstanceKlass::set_enclosing_method_indices(u2 class_index, 2013 u2 method_index) { 2014 Array<jushort>* inner_class_list = inner_classes(); 2015 assert (inner_class_list != NULL, "_inner_classes list is not set up"); 2016 int length = inner_class_list->length(); 2017 if (length % inner_class_next_offset == enclosing_method_attribute_size) { 2018 int index = length - enclosing_method_attribute_size; 2019 inner_class_list->at_put( 2020 index + enclosing_method_class_index_offset, class_index); 2021 inner_class_list->at_put( 2022 index + enclosing_method_method_index_offset, method_index); 2023 } 2024 } 2025 2026 // Lookup or create a jmethodID. 2027 // This code is called by the VMThread and JavaThreads so the 2028 // locking has to be done very carefully to avoid deadlocks 2029 // and/or other cache consistency problems. 2030 // 2031 jmethodID InstanceKlass::get_jmethod_id(const methodHandle& method_h) { 2032 size_t idnum = (size_t)method_h->method_idnum(); 2033 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2034 size_t length = 0; 2035 jmethodID id = NULL; 2036 2037 // We use a double-check locking idiom here because this cache is 2038 // performance sensitive. In the normal system, this cache only 2039 // transitions from NULL to non-NULL which is safe because we use 2040 // release_set_methods_jmethod_ids() to advertise the new cache. 2041 // A partially constructed cache should never be seen by a racing 2042 // thread. We also use release_store() to save a new jmethodID 2043 // in the cache so a partially constructed jmethodID should never be 2044 // seen either. Cache reads of existing jmethodIDs proceed without a 2045 // lock, but cache writes of a new jmethodID requires uniqueness and 2046 // creation of the cache itself requires no leaks so a lock is 2047 // generally acquired in those two cases. 2048 // 2049 // If the RedefineClasses() API has been used, then this cache can 2050 // grow and we'll have transitions from non-NULL to bigger non-NULL. 2051 // Cache creation requires no leaks and we require safety between all 2052 // cache accesses and freeing of the old cache so a lock is generally 2053 // acquired when the RedefineClasses() API has been used. 2054 2055 if (jmeths != NULL) { 2056 // the cache already exists 2057 if (!idnum_can_increment()) { 2058 // the cache can't grow so we can just get the current values 2059 get_jmethod_id_length_value(jmeths, idnum, &length, &id); 2060 } else { 2061 // cache can grow so we have to be more careful 2062 if (Threads::number_of_threads() == 0 || 2063 SafepointSynchronize::is_at_safepoint()) { 2064 // we're single threaded or at a safepoint - no locking needed 2065 get_jmethod_id_length_value(jmeths, idnum, &length, &id); 2066 } else { 2067 MutexLocker ml(JmethodIdCreation_lock); 2068 get_jmethod_id_length_value(jmeths, idnum, &length, &id); 2069 } 2070 } 2071 } 2072 // implied else: 2073 // we need to allocate a cache so default length and id values are good 2074 2075 if (jmeths == NULL || // no cache yet 2076 length <= idnum || // cache is too short 2077 id == NULL) { // cache doesn't contain entry 2078 2079 // This function can be called by the VMThread so we have to do all 2080 // things that might block on a safepoint before grabbing the lock. 2081 // Otherwise, we can deadlock with the VMThread or have a cache 2082 // consistency issue. These vars keep track of what we might have 2083 // to free after the lock is dropped. 2084 jmethodID to_dealloc_id = NULL; 2085 jmethodID* to_dealloc_jmeths = NULL; 2086 2087 // may not allocate new_jmeths or use it if we allocate it 2088 jmethodID* new_jmeths = NULL; 2089 if (length <= idnum) { 2090 // allocate a new cache that might be used 2091 size_t size = MAX2(idnum+1, (size_t)idnum_allocated_count()); 2092 new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass); 2093 memset(new_jmeths, 0, (size+1)*sizeof(jmethodID)); 2094 // cache size is stored in element[0], other elements offset by one 2095 new_jmeths[0] = (jmethodID)size; 2096 } 2097 2098 // allocate a new jmethodID that might be used 2099 jmethodID new_id = NULL; 2100 if (method_h->is_old() && !method_h->is_obsolete()) { 2101 // The method passed in is old (but not obsolete), we need to use the current version 2102 Method* current_method = method_with_idnum((int)idnum); 2103 assert(current_method != NULL, "old and but not obsolete, so should exist"); 2104 new_id = Method::make_jmethod_id(class_loader_data(), current_method); 2105 } else { 2106 // It is the current version of the method or an obsolete method, 2107 // use the version passed in 2108 new_id = Method::make_jmethod_id(class_loader_data(), method_h()); 2109 } 2110 2111 if (Threads::number_of_threads() == 0 || 2112 SafepointSynchronize::is_at_safepoint()) { 2113 // we're single threaded or at a safepoint - no locking needed 2114 id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths, 2115 &to_dealloc_id, &to_dealloc_jmeths); 2116 } else { 2117 MutexLocker ml(JmethodIdCreation_lock); 2118 id = get_jmethod_id_fetch_or_update(idnum, new_id, new_jmeths, 2119 &to_dealloc_id, &to_dealloc_jmeths); 2120 } 2121 2122 // The lock has been dropped so we can free resources. 2123 // Free up either the old cache or the new cache if we allocated one. 2124 if (to_dealloc_jmeths != NULL) { 2125 FreeHeap(to_dealloc_jmeths); 2126 } 2127 // free up the new ID since it wasn't needed 2128 if (to_dealloc_id != NULL) { 2129 Method::destroy_jmethod_id(class_loader_data(), to_dealloc_id); 2130 } 2131 } 2132 return id; 2133 } 2134 2135 // Figure out how many jmethodIDs haven't been allocated, and make 2136 // sure space for them is pre-allocated. This makes getting all 2137 // method ids much, much faster with classes with more than 8 2138 // methods, and has a *substantial* effect on performance with jvmti 2139 // code that loads all jmethodIDs for all classes. 2140 void InstanceKlass::ensure_space_for_methodids(int start_offset) { 2141 int new_jmeths = 0; 2142 int length = methods()->length(); 2143 for (int index = start_offset; index < length; index++) { 2144 Method* m = methods()->at(index); 2145 jmethodID id = m->find_jmethod_id_or_null(); 2146 if (id == NULL) { 2147 new_jmeths++; 2148 } 2149 } 2150 if (new_jmeths != 0) { 2151 Method::ensure_jmethod_ids(class_loader_data(), new_jmeths); 2152 } 2153 } 2154 2155 // Common code to fetch the jmethodID from the cache or update the 2156 // cache with the new jmethodID. This function should never do anything 2157 // that causes the caller to go to a safepoint or we can deadlock with 2158 // the VMThread or have cache consistency issues. 2159 // 2160 jmethodID InstanceKlass::get_jmethod_id_fetch_or_update( 2161 size_t idnum, jmethodID new_id, 2162 jmethodID* new_jmeths, jmethodID* to_dealloc_id_p, 2163 jmethodID** to_dealloc_jmeths_p) { 2164 assert(new_id != NULL, "sanity check"); 2165 assert(to_dealloc_id_p != NULL, "sanity check"); 2166 assert(to_dealloc_jmeths_p != NULL, "sanity check"); 2167 assert(Threads::number_of_threads() == 0 || 2168 SafepointSynchronize::is_at_safepoint() || 2169 JmethodIdCreation_lock->owned_by_self(), "sanity check"); 2170 2171 // reacquire the cache - we are locked, single threaded or at a safepoint 2172 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2173 jmethodID id = NULL; 2174 size_t length = 0; 2175 2176 if (jmeths == NULL || // no cache yet 2177 (length = (size_t)jmeths[0]) <= idnum) { // cache is too short 2178 if (jmeths != NULL) { 2179 // copy any existing entries from the old cache 2180 for (size_t index = 0; index < length; index++) { 2181 new_jmeths[index+1] = jmeths[index+1]; 2182 } 2183 *to_dealloc_jmeths_p = jmeths; // save old cache for later delete 2184 } 2185 release_set_methods_jmethod_ids(jmeths = new_jmeths); 2186 } else { 2187 // fetch jmethodID (if any) from the existing cache 2188 id = jmeths[idnum+1]; 2189 *to_dealloc_jmeths_p = new_jmeths; // save new cache for later delete 2190 } 2191 if (id == NULL) { 2192 // No matching jmethodID in the existing cache or we have a new 2193 // cache or we just grew the cache. This cache write is done here 2194 // by the first thread to win the foot race because a jmethodID 2195 // needs to be unique once it is generally available. 2196 id = new_id; 2197 2198 // The jmethodID cache can be read while unlocked so we have to 2199 // make sure the new jmethodID is complete before installing it 2200 // in the cache. 2201 OrderAccess::release_store(&jmeths[idnum+1], id); 2202 } else { 2203 *to_dealloc_id_p = new_id; // save new id for later delete 2204 } 2205 return id; 2206 } 2207 2208 2209 // Common code to get the jmethodID cache length and the jmethodID 2210 // value at index idnum if there is one. 2211 // 2212 void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache, 2213 size_t idnum, size_t *length_p, jmethodID* id_p) { 2214 assert(cache != NULL, "sanity check"); 2215 assert(length_p != NULL, "sanity check"); 2216 assert(id_p != NULL, "sanity check"); 2217 2218 // cache size is stored in element[0], other elements offset by one 2219 *length_p = (size_t)cache[0]; 2220 if (*length_p <= idnum) { // cache is too short 2221 *id_p = NULL; 2222 } else { 2223 *id_p = cache[idnum+1]; // fetch jmethodID (if any) 2224 } 2225 } 2226 2227 2228 // Lookup a jmethodID, NULL if not found. Do no blocking, no allocations, no handles 2229 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) { 2230 size_t idnum = (size_t)method->method_idnum(); 2231 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2232 size_t length; // length assigned as debugging crumb 2233 jmethodID id = NULL; 2234 if (jmeths != NULL && // If there is a cache 2235 (length = (size_t)jmeths[0]) > idnum) { // and if it is long enough, 2236 id = jmeths[idnum+1]; // Look up the id (may be NULL) 2237 } 2238 return id; 2239 } 2240 2241 inline DependencyContext InstanceKlass::dependencies() { 2242 DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned); 2243 return dep_context; 2244 } 2245 2246 int InstanceKlass::mark_dependent_nmethods(KlassDepChange& changes) { 2247 return dependencies().mark_dependent_nmethods(changes); 2248 } 2249 2250 void InstanceKlass::add_dependent_nmethod(nmethod* nm) { 2251 dependencies().add_dependent_nmethod(nm); 2252 } 2253 2254 void InstanceKlass::remove_dependent_nmethod(nmethod* nm) { 2255 dependencies().remove_dependent_nmethod(nm); 2256 } 2257 2258 void InstanceKlass::clean_dependency_context() { 2259 dependencies().clean_unloading_dependents(); 2260 } 2261 2262 #ifndef PRODUCT 2263 void InstanceKlass::print_dependent_nmethods(bool verbose) { 2264 dependencies().print_dependent_nmethods(verbose); 2265 } 2266 2267 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) { 2268 return dependencies().is_dependent_nmethod(nm); 2269 } 2270 #endif //PRODUCT 2271 2272 void InstanceKlass::clean_weak_instanceklass_links() { 2273 clean_implementors_list(); 2274 clean_method_data(); 2275 } 2276 2277 void InstanceKlass::clean_implementors_list() { 2278 assert(is_loader_alive(), "this klass should be live"); 2279 if (is_interface()) { 2280 assert (ClassUnloading, "only called for ClassUnloading"); 2281 for (;;) { 2282 // Use load_acquire due to competing with inserts 2283 Klass* impl = OrderAccess::load_acquire(adr_implementor()); 2284 if (impl != NULL && !impl->is_loader_alive()) { 2285 // NULL this field, might be an unloaded klass or NULL 2286 Klass* volatile* klass = adr_implementor(); 2287 if (Atomic::cmpxchg((Klass*)NULL, klass, impl) == impl) { 2288 // Successfully unlinking implementor. 2289 if (log_is_enabled(Trace, class, unload)) { 2290 ResourceMark rm; 2291 log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name()); 2292 } 2293 return; 2294 } 2295 } else { 2296 return; 2297 } 2298 } 2299 } 2300 } 2301 2302 void InstanceKlass::clean_method_data() { 2303 for (int m = 0; m < methods()->length(); m++) { 2304 MethodData* mdo = methods()->at(m)->method_data(); 2305 if (mdo != NULL) { 2306 MutexLockerEx ml(SafepointSynchronize::is_at_safepoint() ? NULL : mdo->extra_data_lock()); 2307 mdo->clean_method_data(/*always_clean*/false); 2308 } 2309 } 2310 } 2311 2312 bool InstanceKlass::supers_have_passed_fingerprint_checks() { 2313 if (java_super() != NULL && !java_super()->has_passed_fingerprint_check()) { 2314 ResourceMark rm; 2315 log_trace(class, fingerprint)("%s : super %s not fingerprinted", external_name(), java_super()->external_name()); 2316 return false; 2317 } 2318 2319 Array<InstanceKlass*>* local_interfaces = this->local_interfaces(); 2320 if (local_interfaces != NULL) { 2321 int length = local_interfaces->length(); 2322 for (int i = 0; i < length; i++) { 2323 InstanceKlass* intf = local_interfaces->at(i); 2324 if (!intf->has_passed_fingerprint_check()) { 2325 ResourceMark rm; 2326 log_trace(class, fingerprint)("%s : interface %s not fingerprinted", external_name(), intf->external_name()); 2327 return false; 2328 } 2329 } 2330 } 2331 2332 return true; 2333 } 2334 2335 bool InstanceKlass::should_store_fingerprint(bool is_unsafe_anonymous) { 2336 #if INCLUDE_AOT 2337 // We store the fingerprint into the InstanceKlass only in the following 2 cases: 2338 if (CalculateClassFingerprint) { 2339 // (1) We are running AOT to generate a shared library. 2340 return true; 2341 } 2342 if (DumpSharedSpaces) { 2343 // (2) We are running -Xshare:dump to create a shared archive 2344 return true; 2345 } 2346 if (UseAOT && is_unsafe_anonymous) { 2347 // (3) We are using AOT code from a shared library and see an unsafe anonymous class 2348 return true; 2349 } 2350 #endif 2351 2352 // In all other cases we might set the _misc_has_passed_fingerprint_check bit, 2353 // but do not store the 64-bit fingerprint to save space. 2354 return false; 2355 } 2356 2357 bool InstanceKlass::has_stored_fingerprint() const { 2358 #if INCLUDE_AOT 2359 return should_store_fingerprint() || is_shared(); 2360 #else 2361 return false; 2362 #endif 2363 } 2364 2365 uint64_t InstanceKlass::get_stored_fingerprint() const { 2366 address adr = adr_fingerprint(); 2367 if (adr != NULL) { 2368 return (uint64_t)Bytes::get_native_u8(adr); // adr may not be 64-bit aligned 2369 } 2370 return 0; 2371 } 2372 2373 void InstanceKlass::store_fingerprint(uint64_t fingerprint) { 2374 address adr = adr_fingerprint(); 2375 if (adr != NULL) { 2376 Bytes::put_native_u8(adr, (u8)fingerprint); // adr may not be 64-bit aligned 2377 2378 ResourceMark rm; 2379 log_trace(class, fingerprint)("stored as " PTR64_FORMAT " for class %s", fingerprint, external_name()); 2380 } 2381 } 2382 2383 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) { 2384 Klass::metaspace_pointers_do(it); 2385 2386 if (log_is_enabled(Trace, cds)) { 2387 ResourceMark rm; 2388 log_trace(cds)("Iter(InstanceKlass): %p (%s)", this, external_name()); 2389 } 2390 2391 it->push(&_annotations); 2392 it->push((Klass**)&_array_klasses); 2393 it->push(&_constants); 2394 it->push(&_inner_classes); 2395 it->push(&_array_name); 2396 #if INCLUDE_JVMTI 2397 it->push(&_previous_versions); 2398 #endif 2399 it->push(&_methods); 2400 it->push(&_default_methods); 2401 it->push(&_local_interfaces); 2402 it->push(&_transitive_interfaces); 2403 it->push(&_method_ordering); 2404 it->push(&_default_vtable_indices); 2405 it->push(&_fields); 2406 2407 if (itable_length() > 0) { 2408 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable(); 2409 int method_table_offset_in_words = ioe->offset()/wordSize; 2410 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words()) 2411 / itableOffsetEntry::size(); 2412 2413 for (int i = 0; i < nof_interfaces; i ++, ioe ++) { 2414 if (ioe->interface_klass() != NULL) { 2415 it->push(ioe->interface_klass_addr()); 2416 itableMethodEntry* ime = ioe->first_method_entry(this); 2417 int n = klassItable::method_count_for_interface(ioe->interface_klass()); 2418 for (int index = 0; index < n; index ++) { 2419 it->push(ime[index].method_addr()); 2420 } 2421 } 2422 } 2423 } 2424 2425 it->push(&_nest_members); 2426 } 2427 2428 void InstanceKlass::remove_unshareable_info() { 2429 Klass::remove_unshareable_info(); 2430 2431 if (is_in_error_state()) { 2432 // Classes are attempted to link during dumping and may fail, 2433 // but these classes are still in the dictionary and class list in CLD. 2434 // Check in_error state first because in_error is > linked state, so 2435 // is_linked() is true. 2436 // If there's a linking error, there is nothing else to remove. 2437 return; 2438 } 2439 2440 // Reset to the 'allocated' state to prevent any premature accessing to 2441 // a shared class at runtime while the class is still being loaded and 2442 // restored. A class' init_state is set to 'loaded' at runtime when it's 2443 // being added to class hierarchy (see SystemDictionary:::add_to_hierarchy()). 2444 _init_state = allocated; 2445 2446 { 2447 MutexLocker ml(Compile_lock); 2448 init_implementor(); 2449 } 2450 2451 constants()->remove_unshareable_info(); 2452 2453 for (int i = 0; i < methods()->length(); i++) { 2454 Method* m = methods()->at(i); 2455 m->remove_unshareable_info(); 2456 } 2457 2458 // do array classes also. 2459 if (array_klasses() != NULL) { 2460 array_klasses()->remove_unshareable_info(); 2461 } 2462 2463 // These are not allocated from metaspace, but they should should all be empty 2464 // during dump time, so we don't need to worry about them in InstanceKlass::iterate(). 2465 guarantee(_source_debug_extension == NULL, "must be"); 2466 guarantee(_dep_context == NULL, "must be"); 2467 guarantee(_osr_nmethods_head == NULL, "must be"); 2468 2469 #if INCLUDE_JVMTI 2470 guarantee(_breakpoints == NULL, "must be"); 2471 guarantee(_previous_versions == NULL, "must be"); 2472 _cached_class_file = NULL; 2473 #endif 2474 2475 _init_thread = NULL; 2476 _methods_jmethod_ids = NULL; 2477 _jni_ids = NULL; 2478 _oop_map_cache = NULL; 2479 // clear _nest_host to ensure re-load at runtime 2480 _nest_host = NULL; 2481 } 2482 2483 void InstanceKlass::remove_java_mirror() { 2484 Klass::remove_java_mirror(); 2485 2486 // do array classes also. 2487 if (array_klasses() != NULL) { 2488 array_klasses()->remove_java_mirror(); 2489 } 2490 } 2491 2492 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) { 2493 // SystemDictionary::add_to_hierarchy() sets the init_state to loaded 2494 // before the InstanceKlass is added to the SystemDictionary. Make 2495 // sure the current state is <loaded. 2496 assert(!is_loaded(), "invalid init state"); 2497 set_package(loader_data, CHECK); 2498 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK); 2499 2500 Array<Method*>* methods = this->methods(); 2501 int num_methods = methods->length(); 2502 for (int index = 0; index < num_methods; ++index) { 2503 methods->at(index)->restore_unshareable_info(CHECK); 2504 } 2505 if (JvmtiExport::has_redefined_a_class()) { 2506 // Reinitialize vtable because RedefineClasses may have changed some 2507 // entries in this vtable for super classes so the CDS vtable might 2508 // point to old or obsolete entries. RedefineClasses doesn't fix up 2509 // vtables in the shared system dictionary, only the main one. 2510 // It also redefines the itable too so fix that too. 2511 vtable().initialize_vtable(false, CHECK); 2512 itable().initialize_itable(false, CHECK); 2513 } 2514 2515 // restore constant pool resolved references 2516 constants()->restore_unshareable_info(CHECK); 2517 2518 if (array_klasses() != NULL) { 2519 // Array classes have null protection domain. 2520 // --> see ArrayKlass::complete_create_array_klass() 2521 array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK); 2522 } 2523 } 2524 2525 // returns true IFF is_in_error_state() has been changed as a result of this call. 2526 bool InstanceKlass::check_sharing_error_state() { 2527 assert(DumpSharedSpaces, "should only be called during dumping"); 2528 bool old_state = is_in_error_state(); 2529 2530 if (!is_in_error_state()) { 2531 bool bad = false; 2532 for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) { 2533 if (sup->is_in_error_state()) { 2534 bad = true; 2535 break; 2536 } 2537 } 2538 if (!bad) { 2539 Array<InstanceKlass*>* interfaces = transitive_interfaces(); 2540 for (int i = 0; i < interfaces->length(); i++) { 2541 InstanceKlass* iface = interfaces->at(i); 2542 if (iface->is_in_error_state()) { 2543 bad = true; 2544 break; 2545 } 2546 } 2547 } 2548 2549 if (bad) { 2550 set_in_error_state(); 2551 } 2552 } 2553 2554 return (old_state != is_in_error_state()); 2555 } 2556 2557 void InstanceKlass::set_class_loader_type(s2 loader_type) { 2558 switch (loader_type) { 2559 case ClassLoader::BOOT_LOADER: 2560 _misc_flags |= _misc_is_shared_boot_class; 2561 break; 2562 case ClassLoader::PLATFORM_LOADER: 2563 _misc_flags |= _misc_is_shared_platform_class; 2564 break; 2565 case ClassLoader::APP_LOADER: 2566 _misc_flags |= _misc_is_shared_app_class; 2567 break; 2568 default: 2569 ShouldNotReachHere(); 2570 break; 2571 } 2572 } 2573 2574 #if INCLUDE_JVMTI 2575 static void clear_all_breakpoints(Method* m) { 2576 m->clear_all_breakpoints(); 2577 } 2578 #endif 2579 2580 void InstanceKlass::unload_class(InstanceKlass* ik) { 2581 // Release dependencies. 2582 ik->dependencies().remove_all_dependents(); 2583 2584 // notify the debugger 2585 if (JvmtiExport::should_post_class_unload()) { 2586 JvmtiExport::post_class_unload(ik); 2587 } 2588 2589 // notify ClassLoadingService of class unload 2590 ClassLoadingService::notify_class_unloaded(ik); 2591 2592 if (log_is_enabled(Info, class, unload)) { 2593 ResourceMark rm; 2594 log_info(class, unload)("unloading class %s " INTPTR_FORMAT, ik->external_name(), p2i(ik)); 2595 } 2596 2597 Events::log_class_unloading(Thread::current(), ik); 2598 2599 #if INCLUDE_JFR 2600 assert(ik != NULL, "invariant"); 2601 EventClassUnload event; 2602 event.set_unloadedClass(ik); 2603 event.set_definingClassLoader(ik->class_loader_data()); 2604 event.commit(); 2605 #endif 2606 } 2607 2608 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) { 2609 // Clean up C heap 2610 ik->release_C_heap_structures(); 2611 ik->constants()->release_C_heap_structures(); 2612 } 2613 2614 void InstanceKlass::release_C_heap_structures() { 2615 // Can't release the constant pool here because the constant pool can be 2616 // deallocated separately from the InstanceKlass for default methods and 2617 // redefine classes. 2618 2619 // Deallocate oop map cache 2620 if (_oop_map_cache != NULL) { 2621 delete _oop_map_cache; 2622 _oop_map_cache = NULL; 2623 } 2624 2625 // Deallocate JNI identifiers for jfieldIDs 2626 JNIid::deallocate(jni_ids()); 2627 set_jni_ids(NULL); 2628 2629 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2630 if (jmeths != (jmethodID*)NULL) { 2631 release_set_methods_jmethod_ids(NULL); 2632 FreeHeap(jmeths); 2633 } 2634 2635 assert(_dep_context == NULL, 2636 "dependencies should already be cleaned"); 2637 2638 #if INCLUDE_JVMTI 2639 // Deallocate breakpoint records 2640 if (breakpoints() != 0x0) { 2641 methods_do(clear_all_breakpoints); 2642 assert(breakpoints() == 0x0, "should have cleared breakpoints"); 2643 } 2644 2645 // deallocate the cached class file 2646 if (_cached_class_file != NULL) { 2647 os::free(_cached_class_file); 2648 _cached_class_file = NULL; 2649 } 2650 #endif 2651 2652 // Decrement symbol reference counts associated with the unloaded class. 2653 if (_name != NULL) _name->decrement_refcount(); 2654 // unreference array name derived from this class name (arrays of an unloaded 2655 // class can't be referenced anymore). 2656 if (_array_name != NULL) _array_name->decrement_refcount(); 2657 if (_value_types != NULL) { 2658 for (int i = 0; i < _value_types->length(); i++) { 2659 Symbol* s = _value_types->at(i)._class_name; 2660 if (s != NULL) { 2661 s->decrement_refcount(); 2662 } 2663 } 2664 } 2665 if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension); 2666 } 2667 2668 void InstanceKlass::set_source_debug_extension(const char* array, int length) { 2669 if (array == NULL) { 2670 _source_debug_extension = NULL; 2671 } else { 2672 // Adding one to the attribute length in order to store a null terminator 2673 // character could cause an overflow because the attribute length is 2674 // already coded with an u4 in the classfile, but in practice, it's 2675 // unlikely to happen. 2676 assert((length+1) > length, "Overflow checking"); 2677 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass); 2678 for (int i = 0; i < length; i++) { 2679 sde[i] = array[i]; 2680 } 2681 sde[length] = '\0'; 2682 _source_debug_extension = sde; 2683 } 2684 } 2685 2686 const char* InstanceKlass::signature_name() const { 2687 return signature_name_of(is_value() ? 'Q' : 'L'); 2688 } 2689 2690 const char* InstanceKlass::signature_name_of(char c) const { 2691 int hash_len = 0; 2692 char hash_buf[40]; 2693 2694 // If this is an unsafe anonymous class, append a hash to make the name unique 2695 if (is_unsafe_anonymous()) { 2696 intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0; 2697 jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash); 2698 hash_len = (int)strlen(hash_buf); 2699 } 2700 2701 // Get the internal name as a c string 2702 const char* src = (const char*) (name()->as_C_string()); 2703 const int src_length = (int)strlen(src); 2704 2705 char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3); 2706 2707 // Add L or Q as type indicator 2708 int dest_index = 0; 2709 dest[dest_index++] = c; 2710 2711 // Add the actual class name 2712 for (int src_index = 0; src_index < src_length; ) { 2713 dest[dest_index++] = src[src_index++]; 2714 } 2715 2716 // If we have a hash, append it 2717 for (int hash_index = 0; hash_index < hash_len; ) { 2718 dest[dest_index++] = hash_buf[hash_index++]; 2719 } 2720 2721 // Add the semicolon and the NULL 2722 dest[dest_index++] = ';'; 2723 dest[dest_index] = '\0'; 2724 return dest; 2725 } 2726 2727 // Used to obtain the package name from a fully qualified class name. 2728 Symbol* InstanceKlass::package_from_name(const Symbol* name, TRAPS) { 2729 if (name == NULL) { 2730 return NULL; 2731 } else { 2732 if (name->utf8_length() <= 0) { 2733 return NULL; 2734 } 2735 ResourceMark rm; 2736 const char* package_name = ClassLoader::package_from_name((const char*) name->as_C_string()); 2737 if (package_name == NULL) { 2738 return NULL; 2739 } 2740 Symbol* pkg_name = SymbolTable::new_symbol(package_name, THREAD); 2741 return pkg_name; 2742 } 2743 } 2744 2745 ModuleEntry* InstanceKlass::module() const { 2746 // For an unsafe anonymous class return the host class' module 2747 if (is_unsafe_anonymous()) { 2748 assert(unsafe_anonymous_host() != NULL, "unsafe anonymous class must have a host class"); 2749 return unsafe_anonymous_host()->module(); 2750 } 2751 2752 // Class is in a named package 2753 if (!in_unnamed_package()) { 2754 return _package_entry->module(); 2755 } 2756 2757 // Class is in an unnamed package, return its loader's unnamed module 2758 return class_loader_data()->unnamed_module(); 2759 } 2760 2761 void InstanceKlass::set_package(ClassLoaderData* loader_data, TRAPS) { 2762 2763 // ensure java/ packages only loaded by boot or platform builtin loaders 2764 check_prohibited_package(name(), loader_data, CHECK); 2765 2766 TempNewSymbol pkg_name = package_from_name(name(), CHECK); 2767 2768 if (pkg_name != NULL && loader_data != NULL) { 2769 2770 // Find in class loader's package entry table. 2771 _package_entry = loader_data->packages()->lookup_only(pkg_name); 2772 2773 // If the package name is not found in the loader's package 2774 // entry table, it is an indication that the package has not 2775 // been defined. Consider it defined within the unnamed module. 2776 if (_package_entry == NULL) { 2777 ResourceMark rm; 2778 2779 if (!ModuleEntryTable::javabase_defined()) { 2780 // Before java.base is defined during bootstrapping, define all packages in 2781 // the java.base module. If a non-java.base package is erroneously placed 2782 // in the java.base module it will be caught later when java.base 2783 // is defined by ModuleEntryTable::verify_javabase_packages check. 2784 assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL"); 2785 _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry()); 2786 } else { 2787 assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL"); 2788 _package_entry = loader_data->packages()->lookup(pkg_name, 2789 loader_data->unnamed_module()); 2790 } 2791 2792 // A package should have been successfully created 2793 assert(_package_entry != NULL, "Package entry for class %s not found, loader %s", 2794 name()->as_C_string(), loader_data->loader_name_and_id()); 2795 } 2796 2797 if (log_is_enabled(Debug, module)) { 2798 ResourceMark rm; 2799 ModuleEntry* m = _package_entry->module(); 2800 log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s", 2801 external_name(), 2802 pkg_name->as_C_string(), 2803 loader_data->loader_name_and_id(), 2804 (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE)); 2805 } 2806 } else { 2807 ResourceMark rm; 2808 log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s", 2809 external_name(), 2810 (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL", 2811 UNNAMED_MODULE); 2812 } 2813 } 2814 2815 2816 // different versions of is_same_class_package 2817 2818 bool InstanceKlass::is_same_class_package(const Klass* class2) const { 2819 oop classloader1 = this->class_loader(); 2820 PackageEntry* classpkg1 = this->package(); 2821 if (class2->is_objArray_klass()) { 2822 class2 = ObjArrayKlass::cast(class2)->bottom_klass(); 2823 } 2824 2825 oop classloader2; 2826 PackageEntry* classpkg2; 2827 if (class2->is_instance_klass()) { 2828 classloader2 = class2->class_loader(); 2829 classpkg2 = class2->package(); 2830 } else { 2831 assert(class2->is_typeArray_klass(), "should be type array"); 2832 classloader2 = NULL; 2833 classpkg2 = NULL; 2834 } 2835 2836 // Same package is determined by comparing class loader 2837 // and package entries. Both must be the same. This rule 2838 // applies even to classes that are defined in the unnamed 2839 // package, they still must have the same class loader. 2840 if (oopDesc::equals(classloader1, classloader2) && (classpkg1 == classpkg2)) { 2841 return true; 2842 } 2843 2844 return false; 2845 } 2846 2847 // return true if this class and other_class are in the same package. Classloader 2848 // and classname information is enough to determine a class's package 2849 bool InstanceKlass::is_same_class_package(oop other_class_loader, 2850 const Symbol* other_class_name) const { 2851 if (!oopDesc::equals(class_loader(), other_class_loader)) { 2852 return false; 2853 } 2854 if (name()->fast_compare(other_class_name) == 0) { 2855 return true; 2856 } 2857 2858 { 2859 ResourceMark rm; 2860 2861 bool bad_class_name = false; 2862 const char* other_pkg = 2863 ClassLoader::package_from_name((const char*) other_class_name->as_C_string(), &bad_class_name); 2864 if (bad_class_name) { 2865 return false; 2866 } 2867 // Check that package_from_name() returns NULL, not "", if there is no package. 2868 assert(other_pkg == NULL || strlen(other_pkg) > 0, "package name is empty string"); 2869 2870 const Symbol* const this_package_name = 2871 this->package() != NULL ? this->package()->name() : NULL; 2872 2873 if (this_package_name == NULL || other_pkg == NULL) { 2874 // One of the two doesn't have a package. Only return true if the other 2875 // one also doesn't have a package. 2876 return (const char*)this_package_name == other_pkg; 2877 } 2878 2879 // Check if package is identical 2880 return this_package_name->equals(other_pkg); 2881 } 2882 } 2883 2884 // Returns true iff super_method can be overridden by a method in targetclassname 2885 // See JLS 3rd edition 8.4.6.1 2886 // Assumes name-signature match 2887 // "this" is InstanceKlass of super_method which must exist 2888 // note that the InstanceKlass of the method in the targetclassname has not always been created yet 2889 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) { 2890 // Private methods can not be overridden 2891 if (super_method->is_private()) { 2892 return false; 2893 } 2894 // If super method is accessible, then override 2895 if ((super_method->is_protected()) || 2896 (super_method->is_public())) { 2897 return true; 2898 } 2899 // Package-private methods are not inherited outside of package 2900 assert(super_method->is_package_private(), "must be package private"); 2901 return(is_same_class_package(targetclassloader(), targetclassname)); 2902 } 2903 2904 // Only boot and platform class loaders can define classes in "java/" packages. 2905 void InstanceKlass::check_prohibited_package(Symbol* class_name, 2906 ClassLoaderData* loader_data, 2907 TRAPS) { 2908 if (!loader_data->is_boot_class_loader_data() && 2909 !loader_data->is_platform_class_loader_data() && 2910 class_name != NULL) { 2911 ResourceMark rm(THREAD); 2912 char* name = class_name->as_C_string(); 2913 if (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/') { 2914 TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK); 2915 assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'"); 2916 name = pkg_name->as_C_string(); 2917 const char* class_loader_name = loader_data->loader_name_and_id(); 2918 StringUtils::replace_no_expand(name, "/", "."); 2919 const char* msg_text1 = "Class loader (instance of): "; 2920 const char* msg_text2 = " tried to load prohibited package name: "; 2921 size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1; 2922 char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len); 2923 jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name); 2924 THROW_MSG(vmSymbols::java_lang_SecurityException(), message); 2925 } 2926 } 2927 return; 2928 } 2929 2930 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const { 2931 constantPoolHandle i_cp(THREAD, constants()); 2932 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) { 2933 int ioff = iter.inner_class_info_index(); 2934 if (ioff != 0) { 2935 // Check to see if the name matches the class we're looking for 2936 // before attempting to find the class. 2937 if (i_cp->klass_name_at_matches(this, ioff)) { 2938 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false); 2939 if (this == inner_klass) { 2940 *ooff = iter.outer_class_info_index(); 2941 *noff = iter.inner_name_index(); 2942 return true; 2943 } 2944 } 2945 } 2946 } 2947 return false; 2948 } 2949 2950 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const { 2951 InstanceKlass* outer_klass = NULL; 2952 *inner_is_member = false; 2953 int ooff = 0, noff = 0; 2954 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD); 2955 if (has_inner_classes_attr) { 2956 constantPoolHandle i_cp(THREAD, constants()); 2957 if (ooff != 0) { 2958 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL); 2959 outer_klass = InstanceKlass::cast(ok); 2960 *inner_is_member = true; 2961 } 2962 if (NULL == outer_klass) { 2963 // It may be unsafe anonymous; try for that. 2964 int encl_method_class_idx = enclosing_method_class_index(); 2965 if (encl_method_class_idx != 0) { 2966 Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL); 2967 outer_klass = InstanceKlass::cast(ok); 2968 *inner_is_member = false; 2969 } 2970 } 2971 } 2972 2973 // If no inner class attribute found for this class. 2974 if (NULL == outer_klass) return NULL; 2975 2976 // Throws an exception if outer klass has not declared k as an inner klass 2977 // We need evidence that each klass knows about the other, or else 2978 // the system could allow a spoof of an inner class to gain access rights. 2979 Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL); 2980 return outer_klass; 2981 } 2982 2983 jint InstanceKlass::compute_modifier_flags(TRAPS) const { 2984 jint access = access_flags().as_int(); 2985 2986 // But check if it happens to be member class. 2987 InnerClassesIterator iter(this); 2988 for (; !iter.done(); iter.next()) { 2989 int ioff = iter.inner_class_info_index(); 2990 // Inner class attribute can be zero, skip it. 2991 // Strange but true: JVM spec. allows null inner class refs. 2992 if (ioff == 0) continue; 2993 2994 // only look at classes that are already loaded 2995 // since we are looking for the flags for our self. 2996 Symbol* inner_name = constants()->klass_name_at(ioff); 2997 if (name() == inner_name) { 2998 // This is really a member class. 2999 access = iter.inner_access_flags(); 3000 break; 3001 } 3002 } 3003 // Remember to strip ACC_SUPER bit 3004 return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS; 3005 } 3006 3007 jint InstanceKlass::jvmti_class_status() const { 3008 jint result = 0; 3009 3010 if (is_linked()) { 3011 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED; 3012 } 3013 3014 if (is_initialized()) { 3015 assert(is_linked(), "Class status is not consistent"); 3016 result |= JVMTI_CLASS_STATUS_INITIALIZED; 3017 } 3018 if (is_in_error_state()) { 3019 result |= JVMTI_CLASS_STATUS_ERROR; 3020 } 3021 return result; 3022 } 3023 3024 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) { 3025 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable(); 3026 int method_table_offset_in_words = ioe->offset()/wordSize; 3027 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words()) 3028 / itableOffsetEntry::size(); 3029 3030 for (int cnt = 0 ; ; cnt ++, ioe ++) { 3031 // If the interface isn't implemented by the receiver class, 3032 // the VM should throw IncompatibleClassChangeError. 3033 if (cnt >= nof_interfaces) { 3034 ResourceMark rm(THREAD); 3035 stringStream ss; 3036 bool same_module = (module() == holder->module()); 3037 ss.print("Receiver class %s does not implement " 3038 "the interface %s defining the method to be called " 3039 "(%s%s%s)", 3040 external_name(), holder->external_name(), 3041 (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(), 3042 (same_module) ? "" : "; ", 3043 (same_module) ? "" : holder->class_in_module_of_loader()); 3044 THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string()); 3045 } 3046 3047 Klass* ik = ioe->interface_klass(); 3048 if (ik == holder) break; 3049 } 3050 3051 itableMethodEntry* ime = ioe->first_method_entry(this); 3052 Method* m = ime[index].method(); 3053 if (m == NULL) { 3054 THROW_NULL(vmSymbols::java_lang_AbstractMethodError()); 3055 } 3056 return m; 3057 } 3058 3059 3060 #if INCLUDE_JVMTI 3061 // update default_methods for redefineclasses for methods that are 3062 // not yet in the vtable due to concurrent subclass define and superinterface 3063 // redefinition 3064 // Note: those in the vtable, should have been updated via adjust_method_entries 3065 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) { 3066 // search the default_methods for uses of either obsolete or EMCP methods 3067 if (default_methods() != NULL) { 3068 for (int index = 0; index < default_methods()->length(); index ++) { 3069 Method* old_method = default_methods()->at(index); 3070 if (old_method == NULL || !old_method->is_old()) { 3071 continue; // skip uninteresting entries 3072 } 3073 assert(!old_method->is_deleted(), "default methods may not be deleted"); 3074 Method* new_method = old_method->get_new_method(); 3075 default_methods()->at_put(index, new_method); 3076 3077 if (log_is_enabled(Info, redefine, class, update)) { 3078 ResourceMark rm; 3079 if (!(*trace_name_printed)) { 3080 log_info(redefine, class, update) 3081 ("adjust: klassname=%s default methods from name=%s", 3082 external_name(), old_method->method_holder()->external_name()); 3083 *trace_name_printed = true; 3084 } 3085 log_debug(redefine, class, update, vtables) 3086 ("default method update: %s(%s) ", 3087 new_method->name()->as_C_string(), new_method->signature()->as_C_string()); 3088 } 3089 } 3090 } 3091 } 3092 #endif // INCLUDE_JVMTI 3093 3094 // On-stack replacement stuff 3095 void InstanceKlass::add_osr_nmethod(nmethod* n) { 3096 // only one compilation can be active 3097 { 3098 // This is a short non-blocking critical region, so the no safepoint check is ok. 3099 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 3100 assert(n->is_osr_method(), "wrong kind of nmethod"); 3101 n->set_osr_link(osr_nmethods_head()); 3102 set_osr_nmethods_head(n); 3103 // Raise the highest osr level if necessary 3104 if (TieredCompilation) { 3105 Method* m = n->method(); 3106 m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level())); 3107 } 3108 } 3109 3110 // Get rid of the osr methods for the same bci that have lower levels. 3111 if (TieredCompilation) { 3112 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) { 3113 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true); 3114 if (inv != NULL && inv->is_in_use()) { 3115 inv->make_not_entrant(); 3116 } 3117 } 3118 } 3119 } 3120 3121 // Remove osr nmethod from the list. Return true if found and removed. 3122 bool InstanceKlass::remove_osr_nmethod(nmethod* n) { 3123 // This is a short non-blocking critical region, so the no safepoint check is ok. 3124 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 3125 assert(n->is_osr_method(), "wrong kind of nmethod"); 3126 nmethod* last = NULL; 3127 nmethod* cur = osr_nmethods_head(); 3128 int max_level = CompLevel_none; // Find the max comp level excluding n 3129 Method* m = n->method(); 3130 // Search for match 3131 bool found = false; 3132 while(cur != NULL && cur != n) { 3133 if (TieredCompilation && m == cur->method()) { 3134 // Find max level before n 3135 max_level = MAX2(max_level, cur->comp_level()); 3136 } 3137 last = cur; 3138 cur = cur->osr_link(); 3139 } 3140 nmethod* next = NULL; 3141 if (cur == n) { 3142 found = true; 3143 next = cur->osr_link(); 3144 if (last == NULL) { 3145 // Remove first element 3146 set_osr_nmethods_head(next); 3147 } else { 3148 last->set_osr_link(next); 3149 } 3150 } 3151 n->set_osr_link(NULL); 3152 if (TieredCompilation) { 3153 cur = next; 3154 while (cur != NULL) { 3155 // Find max level after n 3156 if (m == cur->method()) { 3157 max_level = MAX2(max_level, cur->comp_level()); 3158 } 3159 cur = cur->osr_link(); 3160 } 3161 m->set_highest_osr_comp_level(max_level); 3162 } 3163 return found; 3164 } 3165 3166 int InstanceKlass::mark_osr_nmethods(const Method* m) { 3167 // This is a short non-blocking critical region, so the no safepoint check is ok. 3168 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 3169 nmethod* osr = osr_nmethods_head(); 3170 int found = 0; 3171 while (osr != NULL) { 3172 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3173 if (osr->method() == m) { 3174 osr->mark_for_deoptimization(); 3175 found++; 3176 } 3177 osr = osr->osr_link(); 3178 } 3179 return found; 3180 } 3181 3182 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const { 3183 // This is a short non-blocking critical region, so the no safepoint check is ok. 3184 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 3185 nmethod* osr = osr_nmethods_head(); 3186 nmethod* best = NULL; 3187 while (osr != NULL) { 3188 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3189 // There can be a time when a c1 osr method exists but we are waiting 3190 // for a c2 version. When c2 completes its osr nmethod we will trash 3191 // the c1 version and only be able to find the c2 version. However 3192 // while we overflow in the c1 code at back branches we don't want to 3193 // try and switch to the same code as we are already running 3194 3195 if (osr->method() == m && 3196 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) { 3197 if (match_level) { 3198 if (osr->comp_level() == comp_level) { 3199 // Found a match - return it. 3200 return osr; 3201 } 3202 } else { 3203 if (best == NULL || (osr->comp_level() > best->comp_level())) { 3204 if (osr->comp_level() == CompLevel_highest_tier) { 3205 // Found the best possible - return it. 3206 return osr; 3207 } 3208 best = osr; 3209 } 3210 } 3211 } 3212 osr = osr->osr_link(); 3213 } 3214 if (best != NULL && best->comp_level() >= comp_level && match_level == false) { 3215 return best; 3216 } 3217 return NULL; 3218 } 3219 3220 // ----------------------------------------------------------------------------------------------------- 3221 // Printing 3222 3223 #ifndef PRODUCT 3224 3225 #define BULLET " - " 3226 3227 static const char* state_names[] = { 3228 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error" 3229 }; 3230 3231 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) { 3232 ResourceMark rm; 3233 int* forward_refs = NEW_RESOURCE_ARRAY(int, len); 3234 for (int i = 0; i < len; i++) forward_refs[i] = 0; 3235 for (int i = 0; i < len; i++) { 3236 intptr_t e = start[i]; 3237 st->print("%d : " INTPTR_FORMAT, i, e); 3238 if (forward_refs[i] != 0) { 3239 int from = forward_refs[i]; 3240 int off = (int) start[from]; 3241 st->print(" (offset %d <= [%d])", off, from); 3242 } 3243 if (MetaspaceObj::is_valid((Metadata*)e)) { 3244 st->print(" "); 3245 ((Metadata*)e)->print_value_on(st); 3246 } else if (self != NULL && e > 0 && e < 0x10000) { 3247 address location = self + e; 3248 int index = (int)((intptr_t*)location - start); 3249 st->print(" (offset %d => [%d])", (int)e, index); 3250 if (index >= 0 && index < len) 3251 forward_refs[index] = i; 3252 } 3253 st->cr(); 3254 } 3255 } 3256 3257 static void print_vtable(vtableEntry* start, int len, outputStream* st) { 3258 return print_vtable(NULL, reinterpret_cast<intptr_t*>(start), len, st); 3259 } 3260 3261 template<typename T> 3262 static void print_array_on(outputStream* st, Array<T>* array) { 3263 if (array == NULL) { st->print_cr("NULL"); return; } 3264 array->print_value_on(st); st->cr(); 3265 if (Verbose || WizardMode) { 3266 for (int i = 0; i < array->length(); i++) { 3267 st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr(); 3268 } 3269 } 3270 } 3271 3272 static void print_array_on(outputStream* st, Array<int>* array) { 3273 if (array == NULL) { st->print_cr("NULL"); return; } 3274 array->print_value_on(st); st->cr(); 3275 if (Verbose || WizardMode) { 3276 for (int i = 0; i < array->length(); i++) { 3277 st->print("%d : %d", i, array->at(i)); st->cr(); 3278 } 3279 } 3280 } 3281 3282 void InstanceKlass::print_on(outputStream* st) const { 3283 assert(is_klass(), "must be klass"); 3284 Klass::print_on(st); 3285 3286 st->print(BULLET"instance size: %d", size_helper()); st->cr(); 3287 st->print(BULLET"klass size: %d", size()); st->cr(); 3288 st->print(BULLET"access: "); access_flags().print_on(st); st->cr(); 3289 st->print(BULLET"misc flags: 0x%x", _misc_flags); st->cr(); 3290 st->print(BULLET"state: "); st->print_cr("%s", state_names[_init_state]); 3291 st->print(BULLET"name: "); name()->print_value_on(st); st->cr(); 3292 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr(); 3293 st->print(BULLET"sub: "); 3294 Klass* sub = subklass(); 3295 int n; 3296 for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) { 3297 if (n < MaxSubklassPrintSize) { 3298 sub->print_value_on(st); 3299 st->print(" "); 3300 } 3301 } 3302 if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize); 3303 st->cr(); 3304 3305 if (is_interface()) { 3306 st->print_cr(BULLET"nof implementors: %d", nof_implementors()); 3307 if (nof_implementors() == 1) { 3308 st->print_cr(BULLET"implementor: "); 3309 st->print(" "); 3310 implementor()->print_value_on(st); 3311 st->cr(); 3312 } 3313 } 3314 3315 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr(); 3316 st->print(BULLET"methods: "); print_array_on(st, methods()); 3317 st->print(BULLET"method ordering: "); print_array_on(st, method_ordering()); 3318 st->print(BULLET"default_methods: "); print_array_on(st, default_methods()); 3319 if (default_vtable_indices() != NULL) { 3320 st->print(BULLET"default vtable indices: "); print_array_on(st, default_vtable_indices()); 3321 } 3322 st->print(BULLET"local interfaces: "); print_array_on(st, local_interfaces()); 3323 st->print(BULLET"trans. interfaces: "); print_array_on(st, transitive_interfaces()); 3324 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr(); 3325 if (class_loader_data() != NULL) { 3326 st->print(BULLET"class loader data: "); 3327 class_loader_data()->print_value_on(st); 3328 st->cr(); 3329 } 3330 st->print(BULLET"unsafe anonymous host class: "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr(); 3331 if (source_file_name() != NULL) { 3332 st->print(BULLET"source file: "); 3333 source_file_name()->print_value_on(st); 3334 st->cr(); 3335 } 3336 if (source_debug_extension() != NULL) { 3337 st->print(BULLET"source debug extension: "); 3338 st->print("%s", source_debug_extension()); 3339 st->cr(); 3340 } 3341 st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr(); 3342 st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr(); 3343 st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr(); 3344 st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr(); 3345 { 3346 bool have_pv = false; 3347 // previous versions are linked together through the InstanceKlass 3348 for (InstanceKlass* pv_node = previous_versions(); 3349 pv_node != NULL; 3350 pv_node = pv_node->previous_versions()) { 3351 if (!have_pv) 3352 st->print(BULLET"previous version: "); 3353 have_pv = true; 3354 pv_node->constants()->print_value_on(st); 3355 } 3356 if (have_pv) st->cr(); 3357 } 3358 3359 if (generic_signature() != NULL) { 3360 st->print(BULLET"generic signature: "); 3361 generic_signature()->print_value_on(st); 3362 st->cr(); 3363 } 3364 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr(); 3365 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr(); 3366 if (java_mirror() != NULL) { 3367 st->print(BULLET"java mirror: "); 3368 java_mirror()->print_value_on(st); 3369 st->cr(); 3370 } else { 3371 st->print_cr(BULLET"java mirror: NULL"); 3372 } 3373 st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr(); 3374 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st); 3375 st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr(); 3376 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(NULL, start_of_itable(), itable_length(), st); 3377 st->print_cr(BULLET"---- static fields (%d words):", static_field_size()); 3378 FieldPrinter print_static_field(st); 3379 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field); 3380 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size()); 3381 FieldPrinter print_nonstatic_field(st); 3382 InstanceKlass* ik = const_cast<InstanceKlass*>(this); 3383 ik->do_nonstatic_fields(&print_nonstatic_field); 3384 3385 st->print(BULLET"non-static oop maps: "); 3386 OopMapBlock* map = start_of_nonstatic_oop_maps(); 3387 OopMapBlock* end_map = map + nonstatic_oop_map_count(); 3388 while (map < end_map) { 3389 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1)); 3390 map++; 3391 } 3392 st->cr(); 3393 } 3394 3395 #endif //PRODUCT 3396 3397 void InstanceKlass::print_value_on(outputStream* st) const { 3398 assert(is_klass(), "must be klass"); 3399 if (Verbose || WizardMode) access_flags().print_on(st); 3400 name()->print_value_on(st); 3401 } 3402 3403 #ifndef PRODUCT 3404 3405 void FieldPrinter::do_field(fieldDescriptor* fd) { 3406 _st->print(BULLET); 3407 if (_obj == NULL) { 3408 fd->print_on(_st); 3409 _st->cr(); 3410 } else { 3411 fd->print_on_for(_st, _obj); 3412 _st->cr(); 3413 } 3414 } 3415 3416 3417 void InstanceKlass::oop_print_on(oop obj, outputStream* st) { 3418 Klass::oop_print_on(obj, st); 3419 3420 if (this == SystemDictionary::String_klass()) { 3421 typeArrayOop value = java_lang_String::value(obj); 3422 juint length = java_lang_String::length(obj); 3423 if (value != NULL && 3424 value->is_typeArray() && 3425 length <= (juint) value->length()) { 3426 st->print(BULLET"string: "); 3427 java_lang_String::print(obj, st); 3428 st->cr(); 3429 if (!WizardMode) return; // that is enough 3430 } 3431 } 3432 3433 st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj)); 3434 FieldPrinter print_field(st, obj); 3435 do_nonstatic_fields(&print_field); 3436 3437 if (this == SystemDictionary::Class_klass()) { 3438 st->print(BULLET"signature: "); 3439 java_lang_Class::print_signature(obj, st); 3440 st->cr(); 3441 Klass* mirrored_klass = java_lang_Class::as_Klass(obj); 3442 st->print(BULLET"fake entry for mirror: "); 3443 Metadata::print_value_on_maybe_null(st, mirrored_klass); 3444 st->cr(); 3445 Klass* array_klass = java_lang_Class::array_klass_acquire(obj); 3446 st->print(BULLET"fake entry for array: "); 3447 Metadata::print_value_on_maybe_null(st, array_klass); 3448 st->cr(); 3449 st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj)); 3450 st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj)); 3451 Klass* real_klass = java_lang_Class::as_Klass(obj); 3452 if (real_klass != NULL && real_klass->is_instance_klass()) { 3453 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field); 3454 } 3455 } else if (this == SystemDictionary::MethodType_klass()) { 3456 st->print(BULLET"signature: "); 3457 java_lang_invoke_MethodType::print_signature(obj, st); 3458 st->cr(); 3459 } 3460 } 3461 3462 bool InstanceKlass::verify_itable_index(int i) { 3463 int method_count = klassItable::method_count_for_interface(this); 3464 assert(i >= 0 && i < method_count, "index out of bounds"); 3465 return true; 3466 } 3467 3468 #endif //PRODUCT 3469 3470 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) { 3471 st->print("a "); 3472 name()->print_value_on(st); 3473 obj->print_address_on(st); 3474 if (this == SystemDictionary::String_klass() 3475 && java_lang_String::value(obj) != NULL) { 3476 ResourceMark rm; 3477 int len = java_lang_String::length(obj); 3478 int plen = (len < 24 ? len : 12); 3479 char* str = java_lang_String::as_utf8_string(obj, 0, plen); 3480 st->print(" = \"%s\"", str); 3481 if (len > plen) 3482 st->print("...[%d]", len); 3483 } else if (this == SystemDictionary::Class_klass()) { 3484 Klass* k = java_lang_Class::as_Klass(obj); 3485 st->print(" = "); 3486 if (k != NULL) { 3487 k->print_value_on(st); 3488 } else { 3489 const char* tname = type2name(java_lang_Class::primitive_type(obj)); 3490 st->print("%s", tname ? tname : "type?"); 3491 } 3492 } else if (this == SystemDictionary::MethodType_klass()) { 3493 st->print(" = "); 3494 java_lang_invoke_MethodType::print_signature(obj, st); 3495 } else if (java_lang_boxing_object::is_instance(obj)) { 3496 st->print(" = "); 3497 java_lang_boxing_object::print(obj, st); 3498 } else if (this == SystemDictionary::LambdaForm_klass()) { 3499 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj); 3500 if (vmentry != NULL) { 3501 st->print(" => "); 3502 vmentry->print_value_on(st); 3503 } 3504 } else if (this == SystemDictionary::MemberName_klass()) { 3505 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj); 3506 if (vmtarget != NULL) { 3507 st->print(" = "); 3508 vmtarget->print_value_on(st); 3509 } else { 3510 java_lang_invoke_MemberName::clazz(obj)->print_value_on(st); 3511 st->print("."); 3512 java_lang_invoke_MemberName::name(obj)->print_value_on(st); 3513 } 3514 } 3515 } 3516 3517 const char* InstanceKlass::internal_name() const { 3518 return external_name(); 3519 } 3520 3521 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data, 3522 const char* module_name, 3523 const ClassFileStream* cfs) const { 3524 if (!log_is_enabled(Info, class, load)) { 3525 return; 3526 } 3527 3528 ResourceMark rm; 3529 LogMessage(class, load) msg; 3530 stringStream info_stream; 3531 3532 // Name and class hierarchy info 3533 info_stream.print("%s", external_name()); 3534 3535 // Source 3536 if (cfs != NULL) { 3537 if (cfs->source() != NULL) { 3538 if (module_name != NULL) { 3539 // When the boot loader created the stream, it didn't know the module name 3540 // yet. Let's format it now. 3541 if (cfs->from_boot_loader_modules_image()) { 3542 info_stream.print(" source: jrt:/%s", module_name); 3543 } else { 3544 info_stream.print(" source: %s", cfs->source()); 3545 } 3546 } else { 3547 info_stream.print(" source: %s", cfs->source()); 3548 } 3549 } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) { 3550 Thread* THREAD = Thread::current(); 3551 Klass* caller = 3552 THREAD->is_Java_thread() 3553 ? ((JavaThread*)THREAD)->security_get_caller_class(1) 3554 : NULL; 3555 // caller can be NULL, for example, during a JVMTI VM_Init hook 3556 if (caller != NULL) { 3557 info_stream.print(" source: instance of %s", caller->external_name()); 3558 } else { 3559 // source is unknown 3560 } 3561 } else { 3562 oop class_loader = loader_data->class_loader(); 3563 info_stream.print(" source: %s", class_loader->klass()->external_name()); 3564 } 3565 } else { 3566 info_stream.print(" source: shared objects file"); 3567 } 3568 3569 msg.info("%s", info_stream.as_string()); 3570 3571 if (log_is_enabled(Debug, class, load)) { 3572 stringStream debug_stream; 3573 3574 // Class hierarchy info 3575 debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT, 3576 p2i(this), p2i(superklass())); 3577 3578 // Interfaces 3579 if (local_interfaces() != NULL && local_interfaces()->length() > 0) { 3580 debug_stream.print(" interfaces:"); 3581 int length = local_interfaces()->length(); 3582 for (int i = 0; i < length; i++) { 3583 debug_stream.print(" " INTPTR_FORMAT, 3584 p2i(InstanceKlass::cast(local_interfaces()->at(i)))); 3585 } 3586 } 3587 3588 // Class loader 3589 debug_stream.print(" loader: ["); 3590 loader_data->print_value_on(&debug_stream); 3591 debug_stream.print("]"); 3592 3593 // Classfile checksum 3594 if (cfs) { 3595 debug_stream.print(" bytes: %d checksum: %08x", 3596 cfs->length(), 3597 ClassLoader::crc32(0, (const char*)cfs->buffer(), 3598 cfs->length())); 3599 } 3600 3601 msg.debug("%s", debug_stream.as_string()); 3602 } 3603 } 3604 3605 #if INCLUDE_SERVICES 3606 // Size Statistics 3607 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const { 3608 Klass::collect_statistics(sz); 3609 3610 sz->_inst_size = wordSize * size_helper(); 3611 sz->_vtab_bytes = wordSize * vtable_length(); 3612 sz->_itab_bytes = wordSize * itable_length(); 3613 sz->_nonstatic_oopmap_bytes = wordSize * nonstatic_oop_map_size(); 3614 3615 int n = 0; 3616 n += (sz->_methods_array_bytes = sz->count_array(methods())); 3617 n += (sz->_method_ordering_bytes = sz->count_array(method_ordering())); 3618 n += (sz->_local_interfaces_bytes = sz->count_array(local_interfaces())); 3619 n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces())); 3620 n += (sz->_fields_bytes = sz->count_array(fields())); 3621 n += (sz->_inner_classes_bytes = sz->count_array(inner_classes())); 3622 n += (sz->_nest_members_bytes = sz->count_array(nest_members())); 3623 sz->_ro_bytes += n; 3624 3625 const ConstantPool* cp = constants(); 3626 if (cp) { 3627 cp->collect_statistics(sz); 3628 } 3629 3630 const Annotations* anno = annotations(); 3631 if (anno) { 3632 anno->collect_statistics(sz); 3633 } 3634 3635 const Array<Method*>* methods_array = methods(); 3636 if (methods()) { 3637 for (int i = 0; i < methods_array->length(); i++) { 3638 Method* method = methods_array->at(i); 3639 if (method) { 3640 sz->_method_count ++; 3641 method->collect_statistics(sz); 3642 } 3643 } 3644 } 3645 } 3646 #endif // INCLUDE_SERVICES 3647 3648 // Verification 3649 3650 class VerifyFieldClosure: public BasicOopIterateClosure { 3651 protected: 3652 template <class T> void do_oop_work(T* p) { 3653 oop obj = RawAccess<>::oop_load(p); 3654 if (!oopDesc::is_oop_or_null(obj)) { 3655 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj)); 3656 Universe::print_on(tty); 3657 guarantee(false, "boom"); 3658 } 3659 } 3660 public: 3661 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); } 3662 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); } 3663 }; 3664 3665 void InstanceKlass::verify_on(outputStream* st) { 3666 #ifndef PRODUCT 3667 // Avoid redundant verifies, this really should be in product. 3668 if (_verify_count == Universe::verify_count()) return; 3669 _verify_count = Universe::verify_count(); 3670 #endif 3671 3672 // Verify Klass 3673 Klass::verify_on(st); 3674 3675 // Verify that klass is present in ClassLoaderData 3676 guarantee(class_loader_data()->contains_klass(this), 3677 "this class isn't found in class loader data"); 3678 3679 // Verify vtables 3680 if (is_linked()) { 3681 // $$$ This used to be done only for m/s collections. Doing it 3682 // always seemed a valid generalization. (DLD -- 6/00) 3683 vtable().verify(st); 3684 } 3685 3686 // Verify first subklass 3687 if (subklass() != NULL) { 3688 guarantee(subklass()->is_klass(), "should be klass"); 3689 } 3690 3691 // Verify siblings 3692 Klass* super = this->super(); 3693 Klass* sib = next_sibling(); 3694 if (sib != NULL) { 3695 if (sib == this) { 3696 fatal("subclass points to itself " PTR_FORMAT, p2i(sib)); 3697 } 3698 3699 guarantee(sib->is_klass(), "should be klass"); 3700 guarantee(sib->super() == super, "siblings should have same superklass"); 3701 } 3702 3703 // Verify local interfaces 3704 if (local_interfaces()) { 3705 Array<InstanceKlass*>* local_interfaces = this->local_interfaces(); 3706 for (int j = 0; j < local_interfaces->length(); j++) { 3707 InstanceKlass* e = local_interfaces->at(j); 3708 guarantee(e->is_klass() && e->is_interface(), "invalid local interface"); 3709 } 3710 } 3711 3712 // Verify transitive interfaces 3713 if (transitive_interfaces() != NULL) { 3714 Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces(); 3715 for (int j = 0; j < transitive_interfaces->length(); j++) { 3716 InstanceKlass* e = transitive_interfaces->at(j); 3717 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface"); 3718 } 3719 } 3720 3721 // Verify methods 3722 if (methods() != NULL) { 3723 Array<Method*>* methods = this->methods(); 3724 for (int j = 0; j < methods->length(); j++) { 3725 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 3726 } 3727 for (int j = 0; j < methods->length() - 1; j++) { 3728 Method* m1 = methods->at(j); 3729 Method* m2 = methods->at(j + 1); 3730 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 3731 } 3732 } 3733 3734 // Verify method ordering 3735 if (method_ordering() != NULL) { 3736 Array<int>* method_ordering = this->method_ordering(); 3737 int length = method_ordering->length(); 3738 if (JvmtiExport::can_maintain_original_method_order() || 3739 ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) { 3740 guarantee(length == methods()->length(), "invalid method ordering length"); 3741 jlong sum = 0; 3742 for (int j = 0; j < length; j++) { 3743 int original_index = method_ordering->at(j); 3744 guarantee(original_index >= 0, "invalid method ordering index"); 3745 guarantee(original_index < length, "invalid method ordering index"); 3746 sum += original_index; 3747 } 3748 // Verify sum of indices 0,1,...,length-1 3749 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum"); 3750 } else { 3751 guarantee(length == 0, "invalid method ordering length"); 3752 } 3753 } 3754 3755 // Verify default methods 3756 if (default_methods() != NULL) { 3757 Array<Method*>* methods = this->default_methods(); 3758 for (int j = 0; j < methods->length(); j++) { 3759 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 3760 } 3761 for (int j = 0; j < methods->length() - 1; j++) { 3762 Method* m1 = methods->at(j); 3763 Method* m2 = methods->at(j + 1); 3764 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 3765 } 3766 } 3767 3768 // Verify JNI static field identifiers 3769 if (jni_ids() != NULL) { 3770 jni_ids()->verify(this); 3771 } 3772 3773 // Verify other fields 3774 if (array_klasses() != NULL) { 3775 guarantee(array_klasses()->is_klass(), "should be klass"); 3776 } 3777 if (constants() != NULL) { 3778 guarantee(constants()->is_constantPool(), "should be constant pool"); 3779 } 3780 const Klass* anonymous_host = unsafe_anonymous_host(); 3781 if (anonymous_host != NULL) { 3782 guarantee(anonymous_host->is_klass(), "should be klass"); 3783 } 3784 } 3785 3786 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) { 3787 Klass::oop_verify_on(obj, st); 3788 VerifyFieldClosure blk; 3789 obj->oop_iterate(&blk); 3790 } 3791 3792 3793 // JNIid class for jfieldIDs only 3794 // Note to reviewers: 3795 // These JNI functions are just moved over to column 1 and not changed 3796 // in the compressed oops workspace. 3797 JNIid::JNIid(Klass* holder, int offset, JNIid* next) { 3798 _holder = holder; 3799 _offset = offset; 3800 _next = next; 3801 debug_only(_is_static_field_id = false;) 3802 } 3803 3804 3805 JNIid* JNIid::find(int offset) { 3806 JNIid* current = this; 3807 while (current != NULL) { 3808 if (current->offset() == offset) return current; 3809 current = current->next(); 3810 } 3811 return NULL; 3812 } 3813 3814 void JNIid::deallocate(JNIid* current) { 3815 while (current != NULL) { 3816 JNIid* next = current->next(); 3817 delete current; 3818 current = next; 3819 } 3820 } 3821 3822 3823 void JNIid::verify(Klass* holder) { 3824 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields(); 3825 int end_field_offset; 3826 end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize); 3827 3828 JNIid* current = this; 3829 while (current != NULL) { 3830 guarantee(current->holder() == holder, "Invalid klass in JNIid"); 3831 #ifdef ASSERT 3832 int o = current->offset(); 3833 if (current->is_static_field_id()) { 3834 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid"); 3835 } 3836 #endif 3837 current = current->next(); 3838 } 3839 } 3840 3841 void InstanceKlass::set_init_state(ClassState state) { 3842 #ifdef ASSERT 3843 bool good_state = is_shared() ? (_init_state <= state) 3844 : (_init_state < state); 3845 assert(good_state || state == allocated, "illegal state transition"); 3846 #endif 3847 _init_state = (u1)state; 3848 } 3849 3850 #if INCLUDE_JVMTI 3851 3852 // RedefineClasses() support for previous versions 3853 3854 // Globally, there is at least one previous version of a class to walk 3855 // during class unloading, which is saved because old methods in the class 3856 // are still running. Otherwise the previous version list is cleaned up. 3857 bool InstanceKlass::_has_previous_versions = false; 3858 3859 // Returns true if there are previous versions of a class for class 3860 // unloading only. Also resets the flag to false. purge_previous_version 3861 // will set the flag to true if there are any left, i.e., if there's any 3862 // work to do for next time. This is to avoid the expensive code cache 3863 // walk in CLDG::clean_deallocate_lists(). 3864 bool InstanceKlass::has_previous_versions_and_reset() { 3865 bool ret = _has_previous_versions; 3866 log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s", 3867 ret ? "true" : "false"); 3868 _has_previous_versions = false; 3869 return ret; 3870 } 3871 3872 // Purge previous versions before adding new previous versions of the class and 3873 // during class unloading. 3874 void InstanceKlass::purge_previous_version_list() { 3875 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 3876 assert(has_been_redefined(), "Should only be called for main class"); 3877 3878 // Quick exit. 3879 if (previous_versions() == NULL) { 3880 return; 3881 } 3882 3883 // This klass has previous versions so see what we can cleanup 3884 // while it is safe to do so. 3885 3886 int deleted_count = 0; // leave debugging breadcrumbs 3887 int live_count = 0; 3888 ClassLoaderData* loader_data = class_loader_data(); 3889 assert(loader_data != NULL, "should never be null"); 3890 3891 ResourceMark rm; 3892 log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name()); 3893 3894 // previous versions are linked together through the InstanceKlass 3895 InstanceKlass* pv_node = previous_versions(); 3896 InstanceKlass* last = this; 3897 int version = 0; 3898 3899 // check the previous versions list 3900 for (; pv_node != NULL; ) { 3901 3902 ConstantPool* pvcp = pv_node->constants(); 3903 assert(pvcp != NULL, "cp ref was unexpectedly cleared"); 3904 3905 if (!pvcp->on_stack()) { 3906 // If the constant pool isn't on stack, none of the methods 3907 // are executing. Unlink this previous_version. 3908 // The previous version InstanceKlass is on the ClassLoaderData deallocate list 3909 // so will be deallocated during the next phase of class unloading. 3910 log_trace(redefine, class, iklass, purge) 3911 ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node)); 3912 // For debugging purposes. 3913 pv_node->set_is_scratch_class(); 3914 // Unlink from previous version list. 3915 assert(pv_node->class_loader_data() == loader_data, "wrong loader_data"); 3916 InstanceKlass* next = pv_node->previous_versions(); 3917 pv_node->link_previous_versions(NULL); // point next to NULL 3918 last->link_previous_versions(next); 3919 // Add to the deallocate list after unlinking 3920 loader_data->add_to_deallocate_list(pv_node); 3921 pv_node = next; 3922 deleted_count++; 3923 version++; 3924 continue; 3925 } else { 3926 log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node)); 3927 assert(pvcp->pool_holder() != NULL, "Constant pool with no holder"); 3928 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack"); 3929 live_count++; 3930 // found a previous version for next time we do class unloading 3931 _has_previous_versions = true; 3932 } 3933 3934 // At least one method is live in this previous version. 3935 // Reset dead EMCP methods not to get breakpoints. 3936 // All methods are deallocated when all of the methods for this class are no 3937 // longer running. 3938 Array<Method*>* method_refs = pv_node->methods(); 3939 if (method_refs != NULL) { 3940 log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length()); 3941 for (int j = 0; j < method_refs->length(); j++) { 3942 Method* method = method_refs->at(j); 3943 3944 if (!method->on_stack()) { 3945 // no breakpoints for non-running methods 3946 if (method->is_running_emcp()) { 3947 method->set_running_emcp(false); 3948 } 3949 } else { 3950 assert (method->is_obsolete() || method->is_running_emcp(), 3951 "emcp method cannot run after emcp bit is cleared"); 3952 log_trace(redefine, class, iklass, purge) 3953 ("purge: %s(%s): prev method @%d in version @%d is alive", 3954 method->name()->as_C_string(), method->signature()->as_C_string(), j, version); 3955 } 3956 } 3957 } 3958 // next previous version 3959 last = pv_node; 3960 pv_node = pv_node->previous_versions(); 3961 version++; 3962 } 3963 log_trace(redefine, class, iklass, purge) 3964 ("previous version stats: live=%d, deleted=%d", live_count, deleted_count); 3965 } 3966 3967 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods, 3968 int emcp_method_count) { 3969 int obsolete_method_count = old_methods->length() - emcp_method_count; 3970 3971 if (emcp_method_count != 0 && obsolete_method_count != 0 && 3972 _previous_versions != NULL) { 3973 // We have a mix of obsolete and EMCP methods so we have to 3974 // clear out any matching EMCP method entries the hard way. 3975 int local_count = 0; 3976 for (int i = 0; i < old_methods->length(); i++) { 3977 Method* old_method = old_methods->at(i); 3978 if (old_method->is_obsolete()) { 3979 // only obsolete methods are interesting 3980 Symbol* m_name = old_method->name(); 3981 Symbol* m_signature = old_method->signature(); 3982 3983 // previous versions are linked together through the InstanceKlass 3984 int j = 0; 3985 for (InstanceKlass* prev_version = _previous_versions; 3986 prev_version != NULL; 3987 prev_version = prev_version->previous_versions(), j++) { 3988 3989 Array<Method*>* method_refs = prev_version->methods(); 3990 for (int k = 0; k < method_refs->length(); k++) { 3991 Method* method = method_refs->at(k); 3992 3993 if (!method->is_obsolete() && 3994 method->name() == m_name && 3995 method->signature() == m_signature) { 3996 // The current RedefineClasses() call has made all EMCP 3997 // versions of this method obsolete so mark it as obsolete 3998 log_trace(redefine, class, iklass, add) 3999 ("%s(%s): flush obsolete method @%d in version @%d", 4000 m_name->as_C_string(), m_signature->as_C_string(), k, j); 4001 4002 method->set_is_obsolete(); 4003 break; 4004 } 4005 } 4006 4007 // The previous loop may not find a matching EMCP method, but 4008 // that doesn't mean that we can optimize and not go any 4009 // further back in the PreviousVersion generations. The EMCP 4010 // method for this generation could have already been made obsolete, 4011 // but there still may be an older EMCP method that has not 4012 // been made obsolete. 4013 } 4014 4015 if (++local_count >= obsolete_method_count) { 4016 // no more obsolete methods so bail out now 4017 break; 4018 } 4019 } 4020 } 4021 } 4022 } 4023 4024 // Save the scratch_class as the previous version if any of the methods are running. 4025 // The previous_versions are used to set breakpoints in EMCP methods and they are 4026 // also used to clean MethodData links to redefined methods that are no longer running. 4027 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class, 4028 int emcp_method_count) { 4029 assert(Thread::current()->is_VM_thread(), 4030 "only VMThread can add previous versions"); 4031 4032 ResourceMark rm; 4033 log_trace(redefine, class, iklass, add) 4034 ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count); 4035 4036 // Clean out old previous versions for this class 4037 purge_previous_version_list(); 4038 4039 // Mark newly obsolete methods in remaining previous versions. An EMCP method from 4040 // a previous redefinition may be made obsolete by this redefinition. 4041 Array<Method*>* old_methods = scratch_class->methods(); 4042 mark_newly_obsolete_methods(old_methods, emcp_method_count); 4043 4044 // If the constant pool for this previous version of the class 4045 // is not marked as being on the stack, then none of the methods 4046 // in this previous version of the class are on the stack so 4047 // we don't need to add this as a previous version. 4048 ConstantPool* cp_ref = scratch_class->constants(); 4049 if (!cp_ref->on_stack()) { 4050 log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running"); 4051 // For debugging purposes. 4052 scratch_class->set_is_scratch_class(); 4053 scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class); 4054 return; 4055 } 4056 4057 if (emcp_method_count != 0) { 4058 // At least one method is still running, check for EMCP methods 4059 for (int i = 0; i < old_methods->length(); i++) { 4060 Method* old_method = old_methods->at(i); 4061 if (!old_method->is_obsolete() && old_method->on_stack()) { 4062 // if EMCP method (not obsolete) is on the stack, mark as EMCP so that 4063 // we can add breakpoints for it. 4064 4065 // We set the method->on_stack bit during safepoints for class redefinition 4066 // and use this bit to set the is_running_emcp bit. 4067 // After the safepoint, the on_stack bit is cleared and the running emcp 4068 // method may exit. If so, we would set a breakpoint in a method that 4069 // is never reached, but this won't be noticeable to the programmer. 4070 old_method->set_running_emcp(true); 4071 log_trace(redefine, class, iklass, add) 4072 ("EMCP method %s is on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method)); 4073 } else if (!old_method->is_obsolete()) { 4074 log_trace(redefine, class, iklass, add) 4075 ("EMCP method %s is NOT on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method)); 4076 } 4077 } 4078 } 4079 4080 // Add previous version if any methods are still running. 4081 // Set has_previous_version flag for processing during class unloading. 4082 _has_previous_versions = true; 4083 log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack."); 4084 assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version"); 4085 scratch_class->link_previous_versions(previous_versions()); 4086 link_previous_versions(scratch_class); 4087 } // end add_previous_version() 4088 4089 #endif // INCLUDE_JVMTI 4090 4091 Method* InstanceKlass::method_with_idnum(int idnum) { 4092 Method* m = NULL; 4093 if (idnum < methods()->length()) { 4094 m = methods()->at(idnum); 4095 } 4096 if (m == NULL || m->method_idnum() != idnum) { 4097 for (int index = 0; index < methods()->length(); ++index) { 4098 m = methods()->at(index); 4099 if (m->method_idnum() == idnum) { 4100 return m; 4101 } 4102 } 4103 // None found, return null for the caller to handle. 4104 return NULL; 4105 } 4106 return m; 4107 } 4108 4109 4110 Method* InstanceKlass::method_with_orig_idnum(int idnum) { 4111 if (idnum >= methods()->length()) { 4112 return NULL; 4113 } 4114 Method* m = methods()->at(idnum); 4115 if (m != NULL && m->orig_method_idnum() == idnum) { 4116 return m; 4117 } 4118 // Obsolete method idnum does not match the original idnum 4119 for (int index = 0; index < methods()->length(); ++index) { 4120 m = methods()->at(index); 4121 if (m->orig_method_idnum() == idnum) { 4122 return m; 4123 } 4124 } 4125 // None found, return null for the caller to handle. 4126 return NULL; 4127 } 4128 4129 4130 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) { 4131 InstanceKlass* holder = get_klass_version(version); 4132 if (holder == NULL) { 4133 return NULL; // The version of klass is gone, no method is found 4134 } 4135 Method* method = holder->method_with_orig_idnum(idnum); 4136 return method; 4137 } 4138 4139 #if INCLUDE_JVMTI 4140 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() { 4141 return _cached_class_file; 4142 } 4143 4144 jint InstanceKlass::get_cached_class_file_len() { 4145 return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file); 4146 } 4147 4148 unsigned char * InstanceKlass::get_cached_class_file_bytes() { 4149 return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file); 4150 } 4151 #endif 4152 4153 #define THROW_DVT_ERROR(s) \ 4154 Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), \ 4155 "ValueCapableClass class '%s' %s", external_name(),(s)); \ 4156 return