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