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