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