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