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 names first and if they match then check actual klass. This avoids 169 // resolving anything unnecessarily. 170 for (int i = 0; i < _nest_members->length(); i++) { 171 int cp_index = _nest_members->at(i); 172 Symbol* name = _constants->klass_name_at(cp_index); 173 if (name == k->name()) { 174 log_trace(class, nestmates)("- Found it at nest_members[%d] => cp[%d]", i, cp_index); 175 176 // names match so check actual klass - this may trigger class loading if 177 // it doesn't match (but that should be impossible) 178 Klass* k2 = _constants->klass_at(cp_index, CHECK_false); 179 if (k2 == k) { 180 log_trace(class, nestmates)("- class is listed as a nest member"); 181 return true; 182 } else { 183 // same name but different klass! 184 log_trace(class, nestmates)(" - klass comparison failed!"); 185 // can't have different classes for the same name, so we're done 186 return false; 187 } 188 } 189 } 190 log_trace(class, nestmates)("- class is NOT a nest member!"); 191 return false; 192 } 193 194 // Return nest-host class, resolving, validating and saving it if needed. 195 // In cases where this is called from a thread that can not do classloading 196 // (such as a native JIT thread) then we simply return NULL, which in turn 197 // causes the access check to return false. Such code will retry the access 198 // from a more suitable environment later. 199 InstanceKlass* InstanceKlass::nest_host(Symbol* validationException, TRAPS) { 200 InstanceKlass* nest_host_k = _nest_host; 201 if (nest_host_k == NULL) { 202 // need to resolve and save our nest-host class. This could be attempted 203 // concurrently but as the result is idempotent and we don't use the class 204 // then we do not need any synchronization beyond what is implicitly used 205 // during class loading. 206 if (_nest_host_index != 0) { // we have a real nest_host 207 // Before trying to resolve check if we're in a suitable context 208 if (!THREAD->can_call_java() && !_constants->tag_at(_nest_host_index).is_klass()) { 209 if (log_is_enabled(Trace, class, nestmates)) { 210 ResourceMark rm(THREAD); 211 log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread", 212 this->external_name()); 213 } 214 return NULL; 215 } 216 217 if (log_is_enabled(Trace, class, nestmates)) { 218 ResourceMark rm(THREAD); 219 log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s", 220 this->external_name(), 221 _constants->klass_name_at(_nest_host_index)->as_C_string()); 222 } 223 224 Klass* k = _constants->klass_at(_nest_host_index, THREAD); 225 if (HAS_PENDING_EXCEPTION) { 226 Handle exc_h = Handle(THREAD, PENDING_EXCEPTION); 227 if (exc_h->is_a(SystemDictionary::NoClassDefFoundError_klass())) { 228 // throw a new CDNFE with the original as its cause, and a clear msg 229 ResourceMark rm(THREAD); 230 char buf[200]; 231 CLEAR_PENDING_EXCEPTION; 232 jio_snprintf(buf, sizeof(buf), 233 "Unable to load nest-host class (%s) of %s", 234 _constants->klass_name_at(_nest_host_index)->as_C_string(), 235 this->external_name()); 236 log_trace(class, nestmates)("%s - NoClassDefFoundError", buf); 237 THROW_MSG_CAUSE_NULL(vmSymbols::java_lang_NoClassDefFoundError(), buf, exc_h); 238 } 239 // All other exceptions pass through (OOME, StackOverflowError, LinkageErrors etc). 240 return NULL; 241 } 242 243 // A valid nest-host is an instance class in the current package that lists this 244 // class as a nest member. If any of these conditions are not met we post the 245 // requested exception type (if any) and return NULL 246 247 const char* error = NULL; 248 249 // JVMS 5.4.4 indicates package check comes first 250 if (is_same_class_package(k)) { 251 252 // Now check actual membership. We can't be a member if our "host" is 253 // not an instance class. 254 if (k->is_instance_klass()) { 255 nest_host_k = InstanceKlass::cast(k); 256 257 bool is_member = nest_host_k->has_nest_member(this, CHECK_NULL); 258 if (is_member) { 259 // save resolved nest-host value 260 _nest_host = nest_host_k; 261 262 if (log_is_enabled(Trace, class, nestmates)) { 263 ResourceMark rm(THREAD); 264 log_trace(class, nestmates)("Resolved nest-host of %s to %s", 265 this->external_name(), k->external_name()); 266 } 267 return nest_host_k; 268 } 269 } 270 error = "current type is not listed as a nest member"; 271 } else { 272 error = "types are in different packages"; 273 } 274 275 if (log_is_enabled(Trace, class, nestmates)) { 276 ResourceMark rm(THREAD); 277 log_trace(class, nestmates)("Type %s is not a nest member of resolved type %s: %s", 278 this->external_name(), 279 k->external_name(), 280 error); 281 } 282 283 if (validationException != NULL) { 284 ResourceMark rm(THREAD); 285 Exceptions::fthrow(THREAD_AND_LOCATION, 286 validationException, 287 "Type %s is not a nest member of %s: %s", 288 this->external_name(), 289 k->external_name(), 290 error 291 ); 292 } 293 return NULL; 294 } else { 295 if (log_is_enabled(Trace, class, nestmates)) { 296 ResourceMark rm(THREAD); 297 log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self", 298 this->external_name()); 299 } 300 // save resolved nest-host value 301 return (_nest_host = this); 302 } 303 } 304 return nest_host_k; 305 } 306 307 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host, 308 // or we are k's nest_host - all of which is covered by comparing the two 309 // resolved_nest_hosts 310 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) { 311 312 assert(this != k, "this should be handled by higher-level code"); 313 314 // Per JVMS 5.4.4 we first resolve and validate the current class, then 315 // the target class k. Resolution exceptions will be passed on by upper 316 // layers. IncompatibleClassChangeErrors from membership validation failures 317 // will also be passed through. 318 319 Symbol* icce = vmSymbols::java_lang_IncompatibleClassChangeError(); 320 InstanceKlass* cur_host = nest_host(icce, CHECK_false); 321 if (cur_host == NULL) { 322 return false; 323 } 324 325 Klass* k_nest_host = k->nest_host(icce, CHECK_false); 326 if (k_nest_host == NULL) { 327 return false; 328 } 329 330 bool access = (cur_host == k_nest_host); 331 332 if (log_is_enabled(Trace, class, nestmates)) { 333 ResourceMark rm(THREAD); 334 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s", 335 this->external_name(), 336 access ? "" : "NOT ", 337 k->external_name()); 338 } 339 340 return access; 341 } 342 343 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) { 344 const int size = InstanceKlass::size(parser.vtable_size(), 345 parser.itable_size(), 346 nonstatic_oop_map_size(parser.total_oop_map_count()), 347 parser.is_interface(), 348 parser.is_unsafe_anonymous(), 349 should_store_fingerprint(parser.is_unsafe_anonymous())); 350 351 const Symbol* const class_name = parser.class_name(); 352 assert(class_name != NULL, "invariant"); 353 ClassLoaderData* loader_data = parser.loader_data(); 354 assert(loader_data != NULL, "invariant"); 355 356 InstanceKlass* ik; 357 358 // Allocation 359 if (REF_NONE == parser.reference_type()) { 360 if (class_name == vmSymbols::java_lang_Class()) { 361 // mirror 362 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser); 363 } 364 else if (is_class_loader(class_name, parser)) { 365 // class loader 366 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser); 367 } else { 368 // normal 369 ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_misc_kind_other); 370 } 371 } else { 372 // reference 373 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser); 374 } 375 376 // Check for pending exception before adding to the loader data and incrementing 377 // class count. Can get OOM here. 378 if (HAS_PENDING_EXCEPTION) { 379 return NULL; 380 } 381 382 return ik; 383 } 384 385 386 // copy method ordering from resource area to Metaspace 387 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) { 388 if (m != NULL) { 389 // allocate a new array and copy contents (memcpy?) 390 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK); 391 for (int i = 0; i < m->length(); i++) { 392 _method_ordering->at_put(i, m->at(i)); 393 } 394 } else { 395 _method_ordering = Universe::the_empty_int_array(); 396 } 397 } 398 399 // create a new array of vtable_indices for default methods 400 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) { 401 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL); 402 assert(default_vtable_indices() == NULL, "only create once"); 403 set_default_vtable_indices(vtable_indices); 404 return vtable_indices; 405 } 406 407 InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) : 408 Klass(id), 409 _nest_members(NULL), 410 _nest_host_index(0), 411 _nest_host(NULL), 412 _static_field_size(parser.static_field_size()), 413 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())), 414 _itable_len(parser.itable_size()), 415 _reference_type(parser.reference_type()) { 416 set_vtable_length(parser.vtable_size()); 417 set_kind(kind); 418 set_access_flags(parser.access_flags()); 419 set_is_unsafe_anonymous(parser.is_unsafe_anonymous()); 420 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(), 421 false)); 422 423 assert(NULL == _methods, "underlying memory not zeroed?"); 424 assert(is_instance_klass(), "is layout incorrect?"); 425 assert(size_helper() == parser.layout_size(), "incorrect size_helper?"); 426 } 427 428 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data, 429 Array<Method*>* methods) { 430 if (methods != NULL && methods != Universe::the_empty_method_array() && 431 !methods->is_shared()) { 432 for (int i = 0; i < methods->length(); i++) { 433 Method* method = methods->at(i); 434 if (method == NULL) continue; // maybe null if error processing 435 // Only want to delete methods that are not executing for RedefineClasses. 436 // The previous version will point to them so they're not totally dangling 437 assert (!method->on_stack(), "shouldn't be called with methods on stack"); 438 MetadataFactory::free_metadata(loader_data, method); 439 } 440 MetadataFactory::free_array<Method*>(loader_data, methods); 441 } 442 } 443 444 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data, 445 const Klass* super_klass, 446 Array<InstanceKlass*>* local_interfaces, 447 Array<InstanceKlass*>* transitive_interfaces) { 448 // Only deallocate transitive interfaces if not empty, same as super class 449 // or same as local interfaces. See code in parseClassFile. 450 Array<InstanceKlass*>* ti = transitive_interfaces; 451 if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) { 452 // check that the interfaces don't come from super class 453 Array<InstanceKlass*>* sti = (super_klass == NULL) ? NULL : 454 InstanceKlass::cast(super_klass)->transitive_interfaces(); 455 if (ti != sti && ti != NULL && !ti->is_shared()) { 456 MetadataFactory::free_array<InstanceKlass*>(loader_data, ti); 457 } 458 } 459 460 // local interfaces can be empty 461 if (local_interfaces != Universe::the_empty_instance_klass_array() && 462 local_interfaces != NULL && !local_interfaces->is_shared()) { 463 MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces); 464 } 465 } 466 467 // This function deallocates the metadata and C heap pointers that the 468 // InstanceKlass points to. 469 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) { 470 471 // Orphan the mirror first, CMS thinks it's still live. 472 if (java_mirror() != NULL) { 473 java_lang_Class::set_klass(java_mirror(), NULL); 474 } 475 476 // Also remove mirror from handles 477 loader_data->remove_handle(_java_mirror); 478 479 // Need to take this class off the class loader data list. 480 loader_data->remove_class(this); 481 482 // The array_klass for this class is created later, after error handling. 483 // For class redefinition, we keep the original class so this scratch class 484 // doesn't have an array class. Either way, assert that there is nothing 485 // to deallocate. 486 assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet"); 487 488 // Release C heap allocated data that this might point to, which includes 489 // reference counting symbol names. 490 release_C_heap_structures(); 491 492 deallocate_methods(loader_data, methods()); 493 set_methods(NULL); 494 495 if (method_ordering() != NULL && 496 method_ordering() != Universe::the_empty_int_array() && 497 !method_ordering()->is_shared()) { 498 MetadataFactory::free_array<int>(loader_data, method_ordering()); 499 } 500 set_method_ordering(NULL); 501 502 // default methods can be empty 503 if (default_methods() != NULL && 504 default_methods() != Universe::the_empty_method_array() && 505 !default_methods()->is_shared()) { 506 MetadataFactory::free_array<Method*>(loader_data, default_methods()); 507 } 508 // Do NOT deallocate the default methods, they are owned by superinterfaces. 509 set_default_methods(NULL); 510 511 // default methods vtable indices can be empty 512 if (default_vtable_indices() != NULL && 513 !default_vtable_indices()->is_shared()) { 514 MetadataFactory::free_array<int>(loader_data, default_vtable_indices()); 515 } 516 set_default_vtable_indices(NULL); 517 518 519 // This array is in Klass, but remove it with the InstanceKlass since 520 // this place would be the only caller and it can share memory with transitive 521 // interfaces. 522 if (secondary_supers() != NULL && 523 secondary_supers() != Universe::the_empty_klass_array() && 524 // see comments in compute_secondary_supers about the following cast 525 (address)(secondary_supers()) != (address)(transitive_interfaces()) && 526 !secondary_supers()->is_shared()) { 527 MetadataFactory::free_array<Klass*>(loader_data, secondary_supers()); 528 } 529 set_secondary_supers(NULL); 530 531 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces()); 532 set_transitive_interfaces(NULL); 533 set_local_interfaces(NULL); 534 535 if (fields() != NULL && !fields()->is_shared()) { 536 MetadataFactory::free_array<jushort>(loader_data, fields()); 537 } 538 set_fields(NULL, 0); 539 540 // If a method from a redefined class is using this constant pool, don't 541 // delete it, yet. The new class's previous version will point to this. 542 if (constants() != NULL) { 543 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack"); 544 if (!constants()->is_shared()) { 545 MetadataFactory::free_metadata(loader_data, constants()); 546 } 547 // Delete any cached resolution errors for the constant pool 548 SystemDictionary::delete_resolution_error(constants()); 549 550 set_constants(NULL); 551 } 552 553 if (inner_classes() != NULL && 554 inner_classes() != Universe::the_empty_short_array() && 555 !inner_classes()->is_shared()) { 556 MetadataFactory::free_array<jushort>(loader_data, inner_classes()); 557 } 558 set_inner_classes(NULL); 559 560 if (nest_members() != NULL && 561 nest_members() != Universe::the_empty_short_array() && 562 !nest_members()->is_shared()) { 563 MetadataFactory::free_array<jushort>(loader_data, nest_members()); 564 } 565 set_nest_members(NULL); 566 567 // We should deallocate the Annotations instance if it's not in shared spaces. 568 if (annotations() != NULL && !annotations()->is_shared()) { 569 MetadataFactory::free_metadata(loader_data, annotations()); 570 } 571 set_annotations(NULL); 572 } 573 574 bool InstanceKlass::should_be_initialized() const { 575 return !is_initialized(); 576 } 577 578 klassItable InstanceKlass::itable() const { 579 return klassItable(const_cast<InstanceKlass*>(this)); 580 } 581 582 void InstanceKlass::eager_initialize(Thread *thread) { 583 if (!EagerInitialization) return; 584 585 if (this->is_not_initialized()) { 586 // abort if the the class has a class initializer 587 if (this->class_initializer() != NULL) return; 588 589 // abort if it is java.lang.Object (initialization is handled in genesis) 590 Klass* super_klass = super(); 591 if (super_klass == NULL) return; 592 593 // abort if the super class should be initialized 594 if (!InstanceKlass::cast(super_klass)->is_initialized()) return; 595 596 // call body to expose the this pointer 597 eager_initialize_impl(); 598 } 599 } 600 601 // JVMTI spec thinks there are signers and protection domain in the 602 // instanceKlass. These accessors pretend these fields are there. 603 // The hprof specification also thinks these fields are in InstanceKlass. 604 oop InstanceKlass::protection_domain() const { 605 // return the protection_domain from the mirror 606 return java_lang_Class::protection_domain(java_mirror()); 607 } 608 609 // To remove these from requires an incompatible change and CCC request. 610 objArrayOop InstanceKlass::signers() const { 611 // return the signers from the mirror 612 return java_lang_Class::signers(java_mirror()); 613 } 614 615 oop InstanceKlass::init_lock() const { 616 // return the init lock from the mirror 617 oop lock = java_lang_Class::init_lock(java_mirror()); 618 // Prevent reordering with any access of initialization state 619 OrderAccess::loadload(); 620 assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state 621 "only fully initialized state can have a null lock"); 622 return lock; 623 } 624 625 // Set the initialization lock to null so the object can be GC'ed. Any racing 626 // threads to get this lock will see a null lock and will not lock. 627 // That's okay because they all check for initialized state after getting 628 // the lock and return. 629 void InstanceKlass::fence_and_clear_init_lock() { 630 // make sure previous stores are all done, notably the init_state. 631 OrderAccess::storestore(); 632 java_lang_Class::set_init_lock(java_mirror(), NULL); 633 assert(!is_not_initialized(), "class must be initialized now"); 634 } 635 636 void InstanceKlass::eager_initialize_impl() { 637 EXCEPTION_MARK; 638 HandleMark hm(THREAD); 639 Handle h_init_lock(THREAD, init_lock()); 640 ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL); 641 642 // abort if someone beat us to the initialization 643 if (!is_not_initialized()) return; // note: not equivalent to is_initialized() 644 645 ClassState old_state = init_state(); 646 link_class_impl(true, THREAD); 647 if (HAS_PENDING_EXCEPTION) { 648 CLEAR_PENDING_EXCEPTION; 649 // Abort if linking the class throws an exception. 650 651 // Use a test to avoid redundantly resetting the state if there's 652 // no change. Set_init_state() asserts that state changes make 653 // progress, whereas here we might just be spinning in place. 654 if (old_state != _init_state) 655 set_init_state(old_state); 656 } else { 657 // linking successfull, mark class as initialized 658 set_init_state(fully_initialized); 659 fence_and_clear_init_lock(); 660 // trace 661 if (log_is_enabled(Info, class, init)) { 662 ResourceMark rm(THREAD); 663 log_info(class, init)("[Initialized %s without side effects]", external_name()); 664 } 665 } 666 } 667 668 669 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization 670 // process. The step comments refers to the procedure described in that section. 671 // Note: implementation moved to static method to expose the this pointer. 672 void InstanceKlass::initialize(TRAPS) { 673 if (this->should_be_initialized()) { 674 initialize_impl(CHECK); 675 // Note: at this point the class may be initialized 676 // OR it may be in the state of being initialized 677 // in case of recursive initialization! 678 } else { 679 assert(is_initialized(), "sanity check"); 680 } 681 } 682 683 684 bool InstanceKlass::verify_code(bool throw_verifyerror, TRAPS) { 685 // 1) Verify the bytecodes 686 Verifier::Mode mode = 687 throw_verifyerror ? Verifier::ThrowException : Verifier::NoException; 688 return Verifier::verify(this, mode, should_verify_class(), THREAD); 689 } 690 691 692 // Used exclusively by the shared spaces dump mechanism to prevent 693 // classes mapped into the shared regions in new VMs from appearing linked. 694 695 void InstanceKlass::unlink_class() { 696 assert(is_linked(), "must be linked"); 697 _init_state = loaded; 698 } 699 700 void InstanceKlass::link_class(TRAPS) { 701 assert(is_loaded(), "must be loaded"); 702 if (!is_linked()) { 703 link_class_impl(true, CHECK); 704 } 705 } 706 707 // Called to verify that a class can link during initialization, without 708 // throwing a VerifyError. 709 bool InstanceKlass::link_class_or_fail(TRAPS) { 710 assert(is_loaded(), "must be loaded"); 711 if (!is_linked()) { 712 link_class_impl(false, CHECK_false); 713 } 714 return is_linked(); 715 } 716 717 bool InstanceKlass::link_class_impl(bool throw_verifyerror, TRAPS) { 718 if (DumpSharedSpaces && is_in_error_state()) { 719 // This is for CDS dumping phase only -- we use the in_error_state to indicate that 720 // the class has failed verification. Throwing the NoClassDefFoundError here is just 721 // a convenient way to stop repeat attempts to verify the same (bad) class. 722 // 723 // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown 724 // if we are executing Java code. This is not a problem for CDS dumping phase since 725 // it doesn't execute any Java code. 726 ResourceMark rm(THREAD); 727 Exceptions::fthrow(THREAD_AND_LOCATION, 728 vmSymbols::java_lang_NoClassDefFoundError(), 729 "Class %s, or one of its supertypes, failed class initialization", 730 external_name()); 731 return false; 732 } 733 // return if already verified 734 if (is_linked()) { 735 return true; 736 } 737 738 // Timing 739 // timer handles recursion 740 assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl"); 741 JavaThread* jt = (JavaThread*)THREAD; 742 743 // link super class before linking this class 744 Klass* super_klass = super(); 745 if (super_klass != NULL) { 746 if (super_klass->is_interface()) { // check if super class is an interface 747 ResourceMark rm(THREAD); 748 Exceptions::fthrow( 749 THREAD_AND_LOCATION, 750 vmSymbols::java_lang_IncompatibleClassChangeError(), 751 "class %s has interface %s as super class", 752 external_name(), 753 super_klass->external_name() 754 ); 755 return false; 756 } 757 758 InstanceKlass* ik_super = InstanceKlass::cast(super_klass); 759 ik_super->link_class_impl(throw_verifyerror, CHECK_false); 760 } 761 762 // link all interfaces implemented by this class before linking this class 763 Array<InstanceKlass*>* interfaces = local_interfaces(); 764 int num_interfaces = interfaces->length(); 765 for (int index = 0; index < num_interfaces; index++) { 766 InstanceKlass* interk = interfaces->at(index); 767 interk->link_class_impl(throw_verifyerror, CHECK_false); 768 } 769 770 // in case the class is linked in the process of linking its superclasses 771 if (is_linked()) { 772 return true; 773 } 774 775 // trace only the link time for this klass that includes 776 // the verification time 777 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(), 778 ClassLoader::perf_class_link_selftime(), 779 ClassLoader::perf_classes_linked(), 780 jt->get_thread_stat()->perf_recursion_counts_addr(), 781 jt->get_thread_stat()->perf_timers_addr(), 782 PerfClassTraceTime::CLASS_LINK); 783 784 // verification & rewriting 785 { 786 HandleMark hm(THREAD); 787 Handle h_init_lock(THREAD, init_lock()); 788 ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL); 789 // rewritten will have been set if loader constraint error found 790 // on an earlier link attempt 791 // don't verify or rewrite if already rewritten 792 // 793 794 if (!is_linked()) { 795 if (!is_rewritten()) { 796 { 797 bool verify_ok = verify_code(throw_verifyerror, THREAD); 798 if (!verify_ok) { 799 return false; 800 } 801 } 802 803 // Just in case a side-effect of verify linked this class already 804 // (which can sometimes happen since the verifier loads classes 805 // using custom class loaders, which are free to initialize things) 806 if (is_linked()) { 807 return true; 808 } 809 810 // also sets rewritten 811 rewrite_class(CHECK_false); 812 } else if (is_shared()) { 813 SystemDictionaryShared::check_verification_constraints(this, CHECK_false); 814 } 815 816 // relocate jsrs and link methods after they are all rewritten 817 link_methods(CHECK_false); 818 819 // Initialize the vtable and interface table after 820 // methods have been rewritten since rewrite may 821 // fabricate new Method*s. 822 // also does loader constraint checking 823 // 824 // initialize_vtable and initialize_itable need to be rerun for 825 // a shared class if the class is not loaded by the NULL classloader. 826 ClassLoaderData * loader_data = class_loader_data(); 827 if (!(is_shared() && 828 loader_data->is_the_null_class_loader_data())) { 829 vtable().initialize_vtable(true, CHECK_false); 830 itable().initialize_itable(true, CHECK_false); 831 } 832 #ifdef ASSERT 833 else { 834 vtable().verify(tty, true); 835 // In case itable verification is ever added. 836 // itable().verify(tty, true); 837 } 838 #endif 839 set_init_state(linked); 840 if (JvmtiExport::should_post_class_prepare()) { 841 Thread *thread = THREAD; 842 assert(thread->is_Java_thread(), "thread->is_Java_thread()"); 843 JvmtiExport::post_class_prepare((JavaThread *) thread, this); 844 } 845 } 846 } 847 return true; 848 } 849 850 // Rewrite the byte codes of all of the methods of a class. 851 // The rewriter must be called exactly once. Rewriting must happen after 852 // verification but before the first method of the class is executed. 853 void InstanceKlass::rewrite_class(TRAPS) { 854 assert(is_loaded(), "must be loaded"); 855 if (is_rewritten()) { 856 assert(is_shared(), "rewriting an unshared class?"); 857 return; 858 } 859 Rewriter::rewrite(this, CHECK); 860 set_rewritten(); 861 } 862 863 // Now relocate and link method entry points after class is rewritten. 864 // This is outside is_rewritten flag. In case of an exception, it can be 865 // executed more than once. 866 void InstanceKlass::link_methods(TRAPS) { 867 int len = methods()->length(); 868 for (int i = len-1; i >= 0; i--) { 869 methodHandle m(THREAD, methods()->at(i)); 870 871 // Set up method entry points for compiler and interpreter . 872 m->link_method(m, CHECK); 873 } 874 } 875 876 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access) 877 void InstanceKlass::initialize_super_interfaces(TRAPS) { 878 assert (has_nonstatic_concrete_methods(), "caller should have checked this"); 879 for (int i = 0; i < local_interfaces()->length(); ++i) { 880 InstanceKlass* ik = local_interfaces()->at(i); 881 882 // Initialization is depth first search ie. we start with top of the inheritance tree 883 // has_nonstatic_concrete_methods drives searching superinterfaces since it 884 // means has_nonstatic_concrete_methods in its superinterface hierarchy 885 if (ik->has_nonstatic_concrete_methods()) { 886 ik->initialize_super_interfaces(CHECK); 887 } 888 889 // Only initialize() interfaces that "declare" concrete methods. 890 if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) { 891 ik->initialize(CHECK); 892 } 893 } 894 } 895 896 void InstanceKlass::initialize_impl(TRAPS) { 897 HandleMark hm(THREAD); 898 899 // Make sure klass is linked (verified) before initialization 900 // A class could already be verified, since it has been reflected upon. 901 link_class(CHECK); 902 903 DTRACE_CLASSINIT_PROBE(required, -1); 904 905 bool wait = false; 906 907 // refer to the JVM book page 47 for description of steps 908 // Step 1 909 { 910 Handle h_init_lock(THREAD, init_lock()); 911 ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL); 912 913 Thread *self = THREAD; // it's passed the current thread 914 915 // Step 2 916 // If we were to use wait() instead of waitInterruptibly() then 917 // we might end up throwing IE from link/symbol resolution sites 918 // that aren't expected to throw. This would wreak havoc. See 6320309. 919 while(is_being_initialized() && !is_reentrant_initialization(self)) { 920 wait = true; 921 ol.waitUninterruptibly(CHECK); 922 } 923 924 // Step 3 925 if (is_being_initialized() && is_reentrant_initialization(self)) { 926 DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait); 927 return; 928 } 929 930 // Step 4 931 if (is_initialized()) { 932 DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait); 933 return; 934 } 935 936 // Step 5 937 if (is_in_error_state()) { 938 DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait); 939 ResourceMark rm(THREAD); 940 const char* desc = "Could not initialize class "; 941 const char* className = external_name(); 942 size_t msglen = strlen(desc) + strlen(className) + 1; 943 char* message = NEW_RESOURCE_ARRAY(char, msglen); 944 if (NULL == message) { 945 // Out of memory: can't create detailed error message 946 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className); 947 } else { 948 jio_snprintf(message, msglen, "%s%s", desc, className); 949 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message); 950 } 951 } 952 953 // Step 6 954 set_init_state(being_initialized); 955 set_init_thread(self); 956 } 957 958 // Step 7 959 // Next, if C is a class rather than an interface, initialize it's super class and super 960 // interfaces. 961 if (!is_interface()) { 962 Klass* super_klass = super(); 963 if (super_klass != NULL && super_klass->should_be_initialized()) { 964 super_klass->initialize(THREAD); 965 } 966 // If C implements any interface that declares a non-static, concrete method, 967 // the initialization of C triggers initialization of its super interfaces. 968 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and 969 // having a superinterface that declares, non-static, concrete methods 970 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) { 971 initialize_super_interfaces(THREAD); 972 } 973 974 // If any exceptions, complete abruptly, throwing the same exception as above. 975 if (HAS_PENDING_EXCEPTION) { 976 Handle e(THREAD, PENDING_EXCEPTION); 977 CLEAR_PENDING_EXCEPTION; 978 { 979 EXCEPTION_MARK; 980 // Locks object, set state, and notify all waiting threads 981 set_initialization_state_and_notify(initialization_error, THREAD); 982 CLEAR_PENDING_EXCEPTION; 983 } 984 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait); 985 THROW_OOP(e()); 986 } 987 } 988 989 990 // Look for aot compiled methods for this klass, including class initializer. 991 AOTLoader::load_for_klass(this, THREAD); 992 993 // Step 8 994 { 995 assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl"); 996 JavaThread* jt = (JavaThread*)THREAD; 997 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait); 998 // Timer includes any side effects of class initialization (resolution, 999 // etc), but not recursive entry into call_class_initializer(). 1000 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(), 1001 ClassLoader::perf_class_init_selftime(), 1002 ClassLoader::perf_classes_inited(), 1003 jt->get_thread_stat()->perf_recursion_counts_addr(), 1004 jt->get_thread_stat()->perf_timers_addr(), 1005 PerfClassTraceTime::CLASS_CLINIT); 1006 call_class_initializer(THREAD); 1007 } 1008 1009 // Step 9 1010 if (!HAS_PENDING_EXCEPTION) { 1011 set_initialization_state_and_notify(fully_initialized, CHECK); 1012 { 1013 debug_only(vtable().verify(tty, true);) 1014 } 1015 } 1016 else { 1017 // Step 10 and 11 1018 Handle e(THREAD, PENDING_EXCEPTION); 1019 CLEAR_PENDING_EXCEPTION; 1020 // JVMTI has already reported the pending exception 1021 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError 1022 JvmtiExport::clear_detected_exception((JavaThread*)THREAD); 1023 { 1024 EXCEPTION_MARK; 1025 set_initialization_state_and_notify(initialization_error, THREAD); 1026 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below 1027 // JVMTI has already reported the pending exception 1028 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError 1029 JvmtiExport::clear_detected_exception((JavaThread*)THREAD); 1030 } 1031 DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait); 1032 if (e->is_a(SystemDictionary::Error_klass())) { 1033 THROW_OOP(e()); 1034 } else { 1035 JavaCallArguments args(e); 1036 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(), 1037 vmSymbols::throwable_void_signature(), 1038 &args); 1039 } 1040 } 1041 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait); 1042 } 1043 1044 1045 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) { 1046 Handle h_init_lock(THREAD, init_lock()); 1047 if (h_init_lock() != NULL) { 1048 ObjectLocker ol(h_init_lock, THREAD); 1049 set_init_state(state); 1050 fence_and_clear_init_lock(); 1051 ol.notify_all(CHECK); 1052 } else { 1053 assert(h_init_lock() != NULL, "The initialization state should never be set twice"); 1054 set_init_state(state); 1055 } 1056 } 1057 1058 Klass* InstanceKlass::implementor() const { 1059 assert_locked_or_safepoint(Compile_lock); 1060 Klass** k = adr_implementor(); 1061 if (k == NULL) { 1062 return NULL; 1063 } else { 1064 return *k; 1065 } 1066 } 1067 1068 void InstanceKlass::set_implementor(Klass* k) { 1069 assert_lock_strong(Compile_lock); 1070 assert(is_interface(), "not interface"); 1071 Klass** addr = adr_implementor(); 1072 assert(addr != NULL, "null addr"); 1073 if (addr != NULL) { 1074 *addr = k; 1075 } 1076 } 1077 1078 int InstanceKlass::nof_implementors() const { 1079 assert_lock_strong(Compile_lock); 1080 Klass* k = implementor(); 1081 if (k == NULL) { 1082 return 0; 1083 } else if (k != this) { 1084 return 1; 1085 } else { 1086 return 2; 1087 } 1088 } 1089 1090 // The embedded _implementor field can only record one implementor. 1091 // When there are more than one implementors, the _implementor field 1092 // is set to the interface Klass* itself. Following are the possible 1093 // values for the _implementor field: 1094 // NULL - no implementor 1095 // implementor Klass* - one implementor 1096 // self - more than one implementor 1097 // 1098 // The _implementor field only exists for interfaces. 1099 void InstanceKlass::add_implementor(Klass* k) { 1100 assert_lock_strong(Compile_lock); 1101 assert(is_interface(), "not interface"); 1102 // Filter out my subinterfaces. 1103 // (Note: Interfaces are never on the subklass list.) 1104 if (InstanceKlass::cast(k)->is_interface()) return; 1105 1106 // Filter out subclasses whose supers already implement me. 1107 // (Note: CHA must walk subclasses of direct implementors 1108 // in order to locate indirect implementors.) 1109 Klass* sk = k->super(); 1110 if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this)) 1111 // We only need to check one immediate superclass, since the 1112 // implements_interface query looks at transitive_interfaces. 1113 // Any supers of the super have the same (or fewer) transitive_interfaces. 1114 return; 1115 1116 Klass* ik = implementor(); 1117 if (ik == NULL) { 1118 set_implementor(k); 1119 } else if (ik != this) { 1120 // There is already an implementor. Use itself as an indicator of 1121 // more than one implementors. 1122 set_implementor(this); 1123 } 1124 1125 // The implementor also implements the transitive_interfaces 1126 for (int index = 0; index < local_interfaces()->length(); index++) { 1127 InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k); 1128 } 1129 } 1130 1131 void InstanceKlass::init_implementor() { 1132 if (is_interface()) { 1133 set_implementor(NULL); 1134 } 1135 } 1136 1137 1138 void InstanceKlass::process_interfaces(Thread *thread) { 1139 // link this class into the implementors list of every interface it implements 1140 for (int i = local_interfaces()->length() - 1; i >= 0; i--) { 1141 assert(local_interfaces()->at(i)->is_klass(), "must be a klass"); 1142 InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i)); 1143 assert(interf->is_interface(), "expected interface"); 1144 interf->add_implementor(this); 1145 } 1146 } 1147 1148 bool InstanceKlass::can_be_primary_super_slow() const { 1149 if (is_interface()) 1150 return false; 1151 else 1152 return Klass::can_be_primary_super_slow(); 1153 } 1154 1155 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots, 1156 Array<InstanceKlass*>* transitive_interfaces) { 1157 // The secondaries are the implemented interfaces. 1158 Array<InstanceKlass*>* interfaces = transitive_interfaces; 1159 int num_secondaries = num_extra_slots + interfaces->length(); 1160 if (num_secondaries == 0) { 1161 // Must share this for correct bootstrapping! 1162 set_secondary_supers(Universe::the_empty_klass_array()); 1163 return NULL; 1164 } else if (num_extra_slots == 0) { 1165 // The secondary super list is exactly the same as the transitive interfaces, so 1166 // let's use it instead of making a copy. 1167 // Redefine classes has to be careful not to delete this! 1168 // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>, 1169 // (but it's safe to do here because we won't write into _secondary_supers from this point on). 1170 set_secondary_supers((Array<Klass*>*)(address)interfaces); 1171 return NULL; 1172 } else { 1173 // Copy transitive interfaces to a temporary growable array to be constructed 1174 // into the secondary super list with extra slots. 1175 GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length()); 1176 for (int i = 0; i < interfaces->length(); i++) { 1177 secondaries->push(interfaces->at(i)); 1178 } 1179 return secondaries; 1180 } 1181 } 1182 1183 bool InstanceKlass::compute_is_subtype_of(Klass* k) { 1184 if (k->is_interface()) { 1185 return implements_interface(k); 1186 } else { 1187 return Klass::compute_is_subtype_of(k); 1188 } 1189 } 1190 1191 bool InstanceKlass::implements_interface(Klass* k) const { 1192 if (this == k) return true; 1193 assert(k->is_interface(), "should be an interface class"); 1194 for (int i = 0; i < transitive_interfaces()->length(); i++) { 1195 if (transitive_interfaces()->at(i) == k) { 1196 return true; 1197 } 1198 } 1199 return false; 1200 } 1201 1202 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const { 1203 // Verify direct super interface 1204 if (this == k) return true; 1205 assert(k->is_interface(), "should be an interface class"); 1206 for (int i = 0; i < local_interfaces()->length(); i++) { 1207 if (local_interfaces()->at(i) == k) { 1208 return true; 1209 } 1210 } 1211 return false; 1212 } 1213 1214 objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) { 1215 if (length < 0) { 1216 THROW_MSG_0(vmSymbols::java_lang_NegativeArraySizeException(), err_msg("%d", length)); 1217 } 1218 if (length > arrayOopDesc::max_array_length(T_OBJECT)) { 1219 report_java_out_of_memory("Requested array size exceeds VM limit"); 1220 JvmtiExport::post_array_size_exhausted(); 1221 THROW_OOP_0(Universe::out_of_memory_error_array_size()); 1222 } 1223 int size = objArrayOopDesc::object_size(length); 1224 Klass* ak = array_klass(n, CHECK_NULL); 1225 objArrayOop o = (objArrayOop)Universe::heap()->array_allocate(ak, size, length, 1226 /* do_zero */ true, CHECK_NULL); 1227 return o; 1228 } 1229 1230 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) { 1231 if (TraceFinalizerRegistration) { 1232 tty->print("Registered "); 1233 i->print_value_on(tty); 1234 tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i)); 1235 } 1236 instanceHandle h_i(THREAD, i); 1237 // Pass the handle as argument, JavaCalls::call expects oop as jobjects 1238 JavaValue result(T_VOID); 1239 JavaCallArguments args(h_i); 1240 methodHandle mh (THREAD, Universe::finalizer_register_method()); 1241 JavaCalls::call(&result, mh, &args, CHECK_NULL); 1242 return h_i(); 1243 } 1244 1245 instanceOop InstanceKlass::allocate_instance(TRAPS) { 1246 bool has_finalizer_flag = has_finalizer(); // Query before possible GC 1247 int size = size_helper(); // Query before forming handle. 1248 1249 instanceOop i; 1250 1251 i = (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL); 1252 if (has_finalizer_flag && !RegisterFinalizersAtInit) { 1253 i = register_finalizer(i, CHECK_NULL); 1254 } 1255 return i; 1256 } 1257 1258 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) { 1259 return instanceHandle(THREAD, allocate_instance(THREAD)); 1260 } 1261 1262 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) { 1263 if (is_interface() || is_abstract()) { 1264 ResourceMark rm(THREAD); 1265 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError() 1266 : vmSymbols::java_lang_InstantiationException(), external_name()); 1267 } 1268 if (this == SystemDictionary::Class_klass()) { 1269 ResourceMark rm(THREAD); 1270 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError() 1271 : vmSymbols::java_lang_IllegalAccessException(), external_name()); 1272 } 1273 } 1274 1275 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) { 1276 // Need load-acquire for lock-free read 1277 if (array_klasses_acquire() == NULL) { 1278 if (or_null) return NULL; 1279 1280 ResourceMark rm; 1281 JavaThread *jt = (JavaThread *)THREAD; 1282 { 1283 // Atomic creation of array_klasses 1284 MutexLocker mc(Compile_lock, THREAD); // for vtables 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); 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, bool delete_immediately) { 2127 dependencies().remove_dependent_nmethod(nm, delete_immediately); 2128 } 2129 2130 #ifndef PRODUCT 2131 void InstanceKlass::print_dependent_nmethods(bool verbose) { 2132 dependencies().print_dependent_nmethods(verbose); 2133 } 2134 2135 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) { 2136 return dependencies().is_dependent_nmethod(nm); 2137 } 2138 #endif //PRODUCT 2139 2140 void InstanceKlass::clean_weak_instanceklass_links() { 2141 clean_implementors_list(); 2142 clean_method_data(); 2143 2144 // Since GC iterates InstanceKlasses sequentially, it is safe to remove stale entries here. 2145 DependencyContext dep_context(&_dep_context); 2146 dep_context.expunge_stale_entries(); 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 // Unlink the class 2306 if (is_linked()) { 2307 unlink_class(); 2308 } 2309 { 2310 MutexLocker ml(Compile_lock); 2311 init_implementor(); 2312 } 2313 2314 constants()->remove_unshareable_info(); 2315 2316 for (int i = 0; i < methods()->length(); i++) { 2317 Method* m = methods()->at(i); 2318 m->remove_unshareable_info(); 2319 } 2320 2321 // do array classes also. 2322 if (array_klasses() != NULL) { 2323 array_klasses()->remove_unshareable_info(); 2324 } 2325 2326 // These are not allocated from metaspace, but they should should all be empty 2327 // during dump time, so we don't need to worry about them in InstanceKlass::iterate(). 2328 guarantee(_source_debug_extension == NULL, "must be"); 2329 guarantee(_dep_context == DependencyContext::EMPTY, "must be"); 2330 guarantee(_osr_nmethods_head == NULL, "must be"); 2331 2332 #if INCLUDE_JVMTI 2333 guarantee(_breakpoints == NULL, "must be"); 2334 guarantee(_previous_versions == NULL, "must be"); 2335 #endif 2336 2337 _init_thread = NULL; 2338 _methods_jmethod_ids = NULL; 2339 _jni_ids = NULL; 2340 _oop_map_cache = NULL; 2341 // clear _nest_host to ensure re-load at runtime 2342 _nest_host = NULL; 2343 } 2344 2345 void InstanceKlass::remove_java_mirror() { 2346 Klass::remove_java_mirror(); 2347 2348 // do array classes also. 2349 if (array_klasses() != NULL) { 2350 array_klasses()->remove_java_mirror(); 2351 } 2352 } 2353 2354 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) { 2355 set_package(loader_data, CHECK); 2356 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK); 2357 2358 Array<Method*>* methods = this->methods(); 2359 int num_methods = methods->length(); 2360 for (int index2 = 0; index2 < num_methods; ++index2) { 2361 methodHandle m(THREAD, methods->at(index2)); 2362 m->restore_unshareable_info(CHECK); 2363 } 2364 if (JvmtiExport::has_redefined_a_class()) { 2365 // Reinitialize vtable because RedefineClasses may have changed some 2366 // entries in this vtable for super classes so the CDS vtable might 2367 // point to old or obsolete entries. RedefineClasses doesn't fix up 2368 // vtables in the shared system dictionary, only the main one. 2369 // It also redefines the itable too so fix that too. 2370 vtable().initialize_vtable(false, CHECK); 2371 itable().initialize_itable(false, CHECK); 2372 } 2373 2374 // restore constant pool resolved references 2375 constants()->restore_unshareable_info(CHECK); 2376 2377 if (array_klasses() != NULL) { 2378 // Array classes have null protection domain. 2379 // --> see ArrayKlass::complete_create_array_klass() 2380 array_klasses()->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK); 2381 } 2382 } 2383 2384 // returns true IFF is_in_error_state() has been changed as a result of this call. 2385 bool InstanceKlass::check_sharing_error_state() { 2386 assert(DumpSharedSpaces, "should only be called during dumping"); 2387 bool old_state = is_in_error_state(); 2388 2389 if (!is_in_error_state()) { 2390 bool bad = false; 2391 for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) { 2392 if (sup->is_in_error_state()) { 2393 bad = true; 2394 break; 2395 } 2396 } 2397 if (!bad) { 2398 Array<InstanceKlass*>* interfaces = transitive_interfaces(); 2399 for (int i = 0; i < interfaces->length(); i++) { 2400 InstanceKlass* iface = interfaces->at(i); 2401 if (iface->is_in_error_state()) { 2402 bad = true; 2403 break; 2404 } 2405 } 2406 } 2407 2408 if (bad) { 2409 set_in_error_state(); 2410 } 2411 } 2412 2413 return (old_state != is_in_error_state()); 2414 } 2415 2416 #if INCLUDE_JVMTI 2417 static void clear_all_breakpoints(Method* m) { 2418 m->clear_all_breakpoints(); 2419 } 2420 #endif 2421 2422 void InstanceKlass::notify_unload_class(InstanceKlass* ik) { 2423 // notify the debugger 2424 if (JvmtiExport::should_post_class_unload()) { 2425 JvmtiExport::post_class_unload(ik); 2426 } 2427 2428 // notify ClassLoadingService of class unload 2429 ClassLoadingService::notify_class_unloaded(ik); 2430 2431 #if INCLUDE_JFR 2432 assert(ik != NULL, "invariant"); 2433 EventClassUnload event; 2434 event.set_unloadedClass(ik); 2435 event.set_definingClassLoader(ik->class_loader_data()); 2436 event.commit(); 2437 #endif 2438 } 2439 2440 void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) { 2441 // Clean up C heap 2442 ik->release_C_heap_structures(); 2443 ik->constants()->release_C_heap_structures(); 2444 } 2445 2446 void InstanceKlass::release_C_heap_structures() { 2447 // Can't release the constant pool here because the constant pool can be 2448 // deallocated separately from the InstanceKlass for default methods and 2449 // redefine classes. 2450 2451 // Deallocate oop map cache 2452 if (_oop_map_cache != NULL) { 2453 delete _oop_map_cache; 2454 _oop_map_cache = NULL; 2455 } 2456 2457 // Deallocate JNI identifiers for jfieldIDs 2458 JNIid::deallocate(jni_ids()); 2459 set_jni_ids(NULL); 2460 2461 jmethodID* jmeths = methods_jmethod_ids_acquire(); 2462 if (jmeths != (jmethodID*)NULL) { 2463 release_set_methods_jmethod_ids(NULL); 2464 FreeHeap(jmeths); 2465 } 2466 2467 // Release dependencies. 2468 // It is desirable to use DC::remove_all_dependents() here, but, unfortunately, 2469 // it is not safe (see JDK-8143408). The problem is that the klass dependency 2470 // context can contain live dependencies, since there's a race between nmethod & 2471 // klass unloading. If the klass is dead when nmethod unloading happens, relevant 2472 // dependencies aren't removed from the context associated with the class (see 2473 // nmethod::flush_dependencies). It ends up during klass unloading as seemingly 2474 // live dependencies pointing to unloaded nmethods and causes a crash in 2475 // DC::remove_all_dependents() when it touches unloaded nmethod. 2476 dependencies().wipe(); 2477 2478 #if INCLUDE_JVMTI 2479 // Deallocate breakpoint records 2480 if (breakpoints() != 0x0) { 2481 methods_do(clear_all_breakpoints); 2482 assert(breakpoints() == 0x0, "should have cleared breakpoints"); 2483 } 2484 2485 // deallocate the cached class file 2486 if (_cached_class_file != NULL && !MetaspaceShared::is_in_shared_metaspace(_cached_class_file)) { 2487 os::free(_cached_class_file); 2488 _cached_class_file = NULL; 2489 } 2490 #endif 2491 2492 // Decrement symbol reference counts associated with the unloaded class. 2493 if (_name != NULL) _name->decrement_refcount(); 2494 // unreference array name derived from this class name (arrays of an unloaded 2495 // class can't be referenced anymore). 2496 if (_array_name != NULL) _array_name->decrement_refcount(); 2497 if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension); 2498 } 2499 2500 void InstanceKlass::set_source_debug_extension(const char* array, int length) { 2501 if (array == NULL) { 2502 _source_debug_extension = NULL; 2503 } else { 2504 // Adding one to the attribute length in order to store a null terminator 2505 // character could cause an overflow because the attribute length is 2506 // already coded with an u4 in the classfile, but in practice, it's 2507 // unlikely to happen. 2508 assert((length+1) > length, "Overflow checking"); 2509 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass); 2510 for (int i = 0; i < length; i++) { 2511 sde[i] = array[i]; 2512 } 2513 sde[length] = '\0'; 2514 _source_debug_extension = sde; 2515 } 2516 } 2517 2518 const char* InstanceKlass::signature_name() const { 2519 int hash_len = 0; 2520 char hash_buf[40]; 2521 2522 // If this is an unsafe anonymous class, append a hash to make the name unique 2523 if (is_unsafe_anonymous()) { 2524 intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0; 2525 jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash); 2526 hash_len = (int)strlen(hash_buf); 2527 } 2528 2529 // Get the internal name as a c string 2530 const char* src = (const char*) (name()->as_C_string()); 2531 const int src_length = (int)strlen(src); 2532 2533 char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3); 2534 2535 // Add L as type indicator 2536 int dest_index = 0; 2537 dest[dest_index++] = 'L'; 2538 2539 // Add the actual class name 2540 for (int src_index = 0; src_index < src_length; ) { 2541 dest[dest_index++] = src[src_index++]; 2542 } 2543 2544 // If we have a hash, append it 2545 for (int hash_index = 0; hash_index < hash_len; ) { 2546 dest[dest_index++] = hash_buf[hash_index++]; 2547 } 2548 2549 // Add the semicolon and the NULL 2550 dest[dest_index++] = ';'; 2551 dest[dest_index] = '\0'; 2552 return dest; 2553 } 2554 2555 // Used to obtain the package name from a fully qualified class name. 2556 Symbol* InstanceKlass::package_from_name(const Symbol* name, TRAPS) { 2557 if (name == NULL) { 2558 return NULL; 2559 } else { 2560 if (name->utf8_length() <= 0) { 2561 return NULL; 2562 } 2563 ResourceMark rm; 2564 const char* package_name = ClassLoader::package_from_name((const char*) name->as_C_string()); 2565 if (package_name == NULL) { 2566 return NULL; 2567 } 2568 Symbol* pkg_name = SymbolTable::new_symbol(package_name, THREAD); 2569 return pkg_name; 2570 } 2571 } 2572 2573 ModuleEntry* InstanceKlass::module() const { 2574 // For an unsafe anonymous class return the host class' module 2575 if (is_unsafe_anonymous()) { 2576 assert(unsafe_anonymous_host() != NULL, "unsafe anonymous class must have a host class"); 2577 return unsafe_anonymous_host()->module(); 2578 } 2579 2580 // Class is in a named package 2581 if (!in_unnamed_package()) { 2582 return _package_entry->module(); 2583 } 2584 2585 // Class is in an unnamed package, return its loader's unnamed module 2586 return class_loader_data()->unnamed_module(); 2587 } 2588 2589 void InstanceKlass::set_package(ClassLoaderData* loader_data, TRAPS) { 2590 2591 // ensure java/ packages only loaded by boot or platform builtin loaders 2592 check_prohibited_package(name(), loader_data, CHECK); 2593 2594 TempNewSymbol pkg_name = package_from_name(name(), CHECK); 2595 2596 if (pkg_name != NULL && loader_data != NULL) { 2597 2598 // Find in class loader's package entry table. 2599 _package_entry = loader_data->packages()->lookup_only(pkg_name); 2600 2601 // If the package name is not found in the loader's package 2602 // entry table, it is an indication that the package has not 2603 // been defined. Consider it defined within the unnamed module. 2604 if (_package_entry == NULL) { 2605 ResourceMark rm; 2606 2607 if (!ModuleEntryTable::javabase_defined()) { 2608 // Before java.base is defined during bootstrapping, define all packages in 2609 // the java.base module. If a non-java.base package is erroneously placed 2610 // in the java.base module it will be caught later when java.base 2611 // is defined by ModuleEntryTable::verify_javabase_packages check. 2612 assert(ModuleEntryTable::javabase_moduleEntry() != NULL, JAVA_BASE_NAME " module is NULL"); 2613 _package_entry = loader_data->packages()->lookup(pkg_name, ModuleEntryTable::javabase_moduleEntry()); 2614 } else { 2615 assert(loader_data->unnamed_module() != NULL, "unnamed module is NULL"); 2616 _package_entry = loader_data->packages()->lookup(pkg_name, 2617 loader_data->unnamed_module()); 2618 } 2619 2620 // A package should have been successfully created 2621 assert(_package_entry != NULL, "Package entry for class %s not found, loader %s", 2622 name()->as_C_string(), loader_data->loader_name_and_id()); 2623 } 2624 2625 if (log_is_enabled(Debug, module)) { 2626 ResourceMark rm; 2627 ModuleEntry* m = _package_entry->module(); 2628 log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s", 2629 external_name(), 2630 pkg_name->as_C_string(), 2631 loader_data->loader_name_and_id(), 2632 (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE)); 2633 } 2634 } else { 2635 ResourceMark rm; 2636 log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s", 2637 external_name(), 2638 (loader_data != NULL) ? loader_data->loader_name_and_id() : "NULL", 2639 UNNAMED_MODULE); 2640 } 2641 } 2642 2643 2644 // different versions of is_same_class_package 2645 2646 bool InstanceKlass::is_same_class_package(const Klass* class2) const { 2647 oop classloader1 = this->class_loader(); 2648 PackageEntry* classpkg1 = this->package(); 2649 if (class2->is_objArray_klass()) { 2650 class2 = ObjArrayKlass::cast(class2)->bottom_klass(); 2651 } 2652 2653 oop classloader2; 2654 PackageEntry* classpkg2; 2655 if (class2->is_instance_klass()) { 2656 classloader2 = class2->class_loader(); 2657 classpkg2 = class2->package(); 2658 } else { 2659 assert(class2->is_typeArray_klass(), "should be type array"); 2660 classloader2 = NULL; 2661 classpkg2 = NULL; 2662 } 2663 2664 // Same package is determined by comparing class loader 2665 // and package entries. Both must be the same. This rule 2666 // applies even to classes that are defined in the unnamed 2667 // package, they still must have the same class loader. 2668 if (oopDesc::equals(classloader1, classloader2) && (classpkg1 == classpkg2)) { 2669 return true; 2670 } 2671 2672 return false; 2673 } 2674 2675 // return true if this class and other_class are in the same package. Classloader 2676 // and classname information is enough to determine a class's package 2677 bool InstanceKlass::is_same_class_package(oop other_class_loader, 2678 const Symbol* other_class_name) const { 2679 if (!oopDesc::equals(class_loader(), other_class_loader)) { 2680 return false; 2681 } 2682 if (name()->fast_compare(other_class_name) == 0) { 2683 return true; 2684 } 2685 2686 { 2687 ResourceMark rm; 2688 2689 bool bad_class_name = false; 2690 const char* other_pkg = 2691 ClassLoader::package_from_name((const char*) other_class_name->as_C_string(), &bad_class_name); 2692 if (bad_class_name) { 2693 return false; 2694 } 2695 // Check that package_from_name() returns NULL, not "", if there is no package. 2696 assert(other_pkg == NULL || strlen(other_pkg) > 0, "package name is empty string"); 2697 2698 const Symbol* const this_package_name = 2699 this->package() != NULL ? this->package()->name() : NULL; 2700 2701 if (this_package_name == NULL || other_pkg == NULL) { 2702 // One of the two doesn't have a package. Only return true if the other 2703 // one also doesn't have a package. 2704 return (const char*)this_package_name == other_pkg; 2705 } 2706 2707 // Check if package is identical 2708 return this_package_name->equals(other_pkg); 2709 } 2710 } 2711 2712 // Returns true iff super_method can be overridden by a method in targetclassname 2713 // See JLS 3rd edition 8.4.6.1 2714 // Assumes name-signature match 2715 // "this" is InstanceKlass of super_method which must exist 2716 // note that the InstanceKlass of the method in the targetclassname has not always been created yet 2717 bool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) { 2718 // Private methods can not be overridden 2719 if (super_method->is_private()) { 2720 return false; 2721 } 2722 // If super method is accessible, then override 2723 if ((super_method->is_protected()) || 2724 (super_method->is_public())) { 2725 return true; 2726 } 2727 // Package-private methods are not inherited outside of package 2728 assert(super_method->is_package_private(), "must be package private"); 2729 return(is_same_class_package(targetclassloader(), targetclassname)); 2730 } 2731 2732 // Only boot and platform class loaders can define classes in "java/" packages. 2733 void InstanceKlass::check_prohibited_package(Symbol* class_name, 2734 ClassLoaderData* loader_data, 2735 TRAPS) { 2736 if (!loader_data->is_boot_class_loader_data() && 2737 !loader_data->is_platform_class_loader_data() && 2738 class_name != NULL) { 2739 ResourceMark rm(THREAD); 2740 char* name = class_name->as_C_string(); 2741 if (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/') { 2742 TempNewSymbol pkg_name = InstanceKlass::package_from_name(class_name, CHECK); 2743 assert(pkg_name != NULL, "Error in parsing package name starting with 'java/'"); 2744 name = pkg_name->as_C_string(); 2745 const char* class_loader_name = loader_data->loader_name_and_id(); 2746 StringUtils::replace_no_expand(name, "/", "."); 2747 const char* msg_text1 = "Class loader (instance of): "; 2748 const char* msg_text2 = " tried to load prohibited package name: "; 2749 size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1; 2750 char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len); 2751 jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name); 2752 THROW_MSG(vmSymbols::java_lang_SecurityException(), message); 2753 } 2754 } 2755 return; 2756 } 2757 2758 // tell if two classes have the same enclosing class (at package level) 2759 bool InstanceKlass::is_same_package_member(const Klass* class2, TRAPS) const { 2760 if (class2 == this) return true; 2761 if (!class2->is_instance_klass()) return false; 2762 2763 // must be in same package before we try anything else 2764 if (!is_same_class_package(class2)) 2765 return false; 2766 2767 // As long as there is an outer_this.getEnclosingClass, 2768 // shift the search outward. 2769 const InstanceKlass* outer_this = this; 2770 for (;;) { 2771 // As we walk along, look for equalities between outer_this and class2. 2772 // Eventually, the walks will terminate as outer_this stops 2773 // at the top-level class around the original class. 2774 bool ignore_inner_is_member; 2775 const Klass* next = outer_this->compute_enclosing_class(&ignore_inner_is_member, 2776 CHECK_false); 2777 if (next == NULL) break; 2778 if (next == class2) return true; 2779 outer_this = InstanceKlass::cast(next); 2780 } 2781 2782 // Now do the same for class2. 2783 const InstanceKlass* outer2 = InstanceKlass::cast(class2); 2784 for (;;) { 2785 bool ignore_inner_is_member; 2786 Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member, 2787 CHECK_false); 2788 if (next == NULL) break; 2789 // Might as well check the new outer against all available values. 2790 if (next == this) return true; 2791 if (next == outer_this) return true; 2792 outer2 = InstanceKlass::cast(next); 2793 } 2794 2795 // If by this point we have not found an equality between the 2796 // two classes, we know they are in separate package members. 2797 return false; 2798 } 2799 2800 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const { 2801 constantPoolHandle i_cp(THREAD, constants()); 2802 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) { 2803 int ioff = iter.inner_class_info_index(); 2804 if (ioff != 0) { 2805 // Check to see if the name matches the class we're looking for 2806 // before attempting to find the class. 2807 if (i_cp->klass_name_at_matches(this, ioff)) { 2808 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false); 2809 if (this == inner_klass) { 2810 *ooff = iter.outer_class_info_index(); 2811 *noff = iter.inner_name_index(); 2812 return true; 2813 } 2814 } 2815 } 2816 } 2817 return false; 2818 } 2819 2820 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const { 2821 InstanceKlass* outer_klass = NULL; 2822 *inner_is_member = false; 2823 int ooff = 0, noff = 0; 2824 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD); 2825 if (has_inner_classes_attr) { 2826 constantPoolHandle i_cp(THREAD, constants()); 2827 if (ooff != 0) { 2828 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL); 2829 outer_klass = InstanceKlass::cast(ok); 2830 *inner_is_member = true; 2831 } 2832 if (NULL == outer_klass) { 2833 // It may be unsafe anonymous; try for that. 2834 int encl_method_class_idx = enclosing_method_class_index(); 2835 if (encl_method_class_idx != 0) { 2836 Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL); 2837 outer_klass = InstanceKlass::cast(ok); 2838 *inner_is_member = false; 2839 } 2840 } 2841 } 2842 2843 // If no inner class attribute found for this class. 2844 if (NULL == outer_klass) return NULL; 2845 2846 // Throws an exception if outer klass has not declared k as an inner klass 2847 // We need evidence that each klass knows about the other, or else 2848 // the system could allow a spoof of an inner class to gain access rights. 2849 Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL); 2850 return outer_klass; 2851 } 2852 2853 jint InstanceKlass::compute_modifier_flags(TRAPS) const { 2854 jint access = access_flags().as_int(); 2855 2856 // But check if it happens to be member class. 2857 InnerClassesIterator iter(this); 2858 for (; !iter.done(); iter.next()) { 2859 int ioff = iter.inner_class_info_index(); 2860 // Inner class attribute can be zero, skip it. 2861 // Strange but true: JVM spec. allows null inner class refs. 2862 if (ioff == 0) continue; 2863 2864 // only look at classes that are already loaded 2865 // since we are looking for the flags for our self. 2866 Symbol* inner_name = constants()->klass_name_at(ioff); 2867 if (name() == inner_name) { 2868 // This is really a member class. 2869 access = iter.inner_access_flags(); 2870 break; 2871 } 2872 } 2873 // Remember to strip ACC_SUPER bit 2874 return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS; 2875 } 2876 2877 jint InstanceKlass::jvmti_class_status() const { 2878 jint result = 0; 2879 2880 if (is_linked()) { 2881 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED; 2882 } 2883 2884 if (is_initialized()) { 2885 assert(is_linked(), "Class status is not consistent"); 2886 result |= JVMTI_CLASS_STATUS_INITIALIZED; 2887 } 2888 if (is_in_error_state()) { 2889 result |= JVMTI_CLASS_STATUS_ERROR; 2890 } 2891 return result; 2892 } 2893 2894 Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) { 2895 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable(); 2896 int method_table_offset_in_words = ioe->offset()/wordSize; 2897 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words()) 2898 / itableOffsetEntry::size(); 2899 2900 for (int cnt = 0 ; ; cnt ++, ioe ++) { 2901 // If the interface isn't implemented by the receiver class, 2902 // the VM should throw IncompatibleClassChangeError. 2903 if (cnt >= nof_interfaces) { 2904 ResourceMark rm(THREAD); 2905 stringStream ss; 2906 bool same_module = (module() == holder->module()); 2907 ss.print("Receiver class %s does not implement " 2908 "the interface %s defining the method to be called " 2909 "(%s%s%s)", 2910 external_name(), holder->external_name(), 2911 (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(), 2912 (same_module) ? "" : "; ", 2913 (same_module) ? "" : holder->class_in_module_of_loader()); 2914 THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string()); 2915 } 2916 2917 Klass* ik = ioe->interface_klass(); 2918 if (ik == holder) break; 2919 } 2920 2921 itableMethodEntry* ime = ioe->first_method_entry(this); 2922 Method* m = ime[index].method(); 2923 if (m == NULL) { 2924 THROW_NULL(vmSymbols::java_lang_AbstractMethodError()); 2925 } 2926 return m; 2927 } 2928 2929 2930 #if INCLUDE_JVMTI 2931 // update default_methods for redefineclasses for methods that are 2932 // not yet in the vtable due to concurrent subclass define and superinterface 2933 // redefinition 2934 // Note: those in the vtable, should have been updated via adjust_method_entries 2935 void InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) { 2936 // search the default_methods for uses of either obsolete or EMCP methods 2937 if (default_methods() != NULL) { 2938 for (int index = 0; index < default_methods()->length(); index ++) { 2939 Method* old_method = default_methods()->at(index); 2940 if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) { 2941 continue; // skip uninteresting entries 2942 } 2943 assert(!old_method->is_deleted(), "default methods may not be deleted"); 2944 2945 Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum()); 2946 2947 assert(new_method != NULL, "method_with_idnum() should not be NULL"); 2948 assert(old_method != new_method, "sanity check"); 2949 2950 default_methods()->at_put(index, new_method); 2951 if (log_is_enabled(Info, redefine, class, update)) { 2952 ResourceMark rm; 2953 if (!(*trace_name_printed)) { 2954 log_info(redefine, class, update) 2955 ("adjust: klassname=%s default methods from name=%s", 2956 external_name(), old_method->method_holder()->external_name()); 2957 *trace_name_printed = true; 2958 } 2959 log_debug(redefine, class, update, vtables) 2960 ("default method update: %s(%s) ", 2961 new_method->name()->as_C_string(), new_method->signature()->as_C_string()); 2962 } 2963 } 2964 } 2965 } 2966 #endif // INCLUDE_JVMTI 2967 2968 // On-stack replacement stuff 2969 void InstanceKlass::add_osr_nmethod(nmethod* n) { 2970 // only one compilation can be active 2971 { 2972 // This is a short non-blocking critical region, so the no safepoint check is ok. 2973 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 2974 assert(n->is_osr_method(), "wrong kind of nmethod"); 2975 n->set_osr_link(osr_nmethods_head()); 2976 set_osr_nmethods_head(n); 2977 // Raise the highest osr level if necessary 2978 if (TieredCompilation) { 2979 Method* m = n->method(); 2980 m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level())); 2981 } 2982 } 2983 2984 // Get rid of the osr methods for the same bci that have lower levels. 2985 if (TieredCompilation) { 2986 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) { 2987 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true); 2988 if (inv != NULL && inv->is_in_use()) { 2989 inv->make_not_entrant(); 2990 } 2991 } 2992 } 2993 } 2994 2995 // Remove osr nmethod from the list. Return true if found and removed. 2996 bool InstanceKlass::remove_osr_nmethod(nmethod* n) { 2997 // This is a short non-blocking critical region, so the no safepoint check is ok. 2998 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 2999 assert(n->is_osr_method(), "wrong kind of nmethod"); 3000 nmethod* last = NULL; 3001 nmethod* cur = osr_nmethods_head(); 3002 int max_level = CompLevel_none; // Find the max comp level excluding n 3003 Method* m = n->method(); 3004 // Search for match 3005 bool found = false; 3006 while(cur != NULL && cur != n) { 3007 if (TieredCompilation && m == cur->method()) { 3008 // Find max level before n 3009 max_level = MAX2(max_level, cur->comp_level()); 3010 } 3011 last = cur; 3012 cur = cur->osr_link(); 3013 } 3014 nmethod* next = NULL; 3015 if (cur == n) { 3016 found = true; 3017 next = cur->osr_link(); 3018 if (last == NULL) { 3019 // Remove first element 3020 set_osr_nmethods_head(next); 3021 } else { 3022 last->set_osr_link(next); 3023 } 3024 } 3025 n->set_osr_link(NULL); 3026 if (TieredCompilation) { 3027 cur = next; 3028 while (cur != NULL) { 3029 // Find max level after n 3030 if (m == cur->method()) { 3031 max_level = MAX2(max_level, cur->comp_level()); 3032 } 3033 cur = cur->osr_link(); 3034 } 3035 m->set_highest_osr_comp_level(max_level); 3036 } 3037 return found; 3038 } 3039 3040 int InstanceKlass::mark_osr_nmethods(const Method* m) { 3041 // This is a short non-blocking critical region, so the no safepoint check is ok. 3042 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 3043 nmethod* osr = osr_nmethods_head(); 3044 int found = 0; 3045 while (osr != NULL) { 3046 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3047 if (osr->method() == m) { 3048 osr->mark_for_deoptimization(); 3049 found++; 3050 } 3051 osr = osr->osr_link(); 3052 } 3053 return found; 3054 } 3055 3056 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const { 3057 // This is a short non-blocking critical region, so the no safepoint check is ok. 3058 MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag); 3059 nmethod* osr = osr_nmethods_head(); 3060 nmethod* best = NULL; 3061 while (osr != NULL) { 3062 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain"); 3063 // There can be a time when a c1 osr method exists but we are waiting 3064 // for a c2 version. When c2 completes its osr nmethod we will trash 3065 // the c1 version and only be able to find the c2 version. However 3066 // while we overflow in the c1 code at back branches we don't want to 3067 // try and switch to the same code as we are already running 3068 3069 if (osr->method() == m && 3070 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) { 3071 if (match_level) { 3072 if (osr->comp_level() == comp_level) { 3073 // Found a match - return it. 3074 return osr; 3075 } 3076 } else { 3077 if (best == NULL || (osr->comp_level() > best->comp_level())) { 3078 if (osr->comp_level() == CompLevel_highest_tier) { 3079 // Found the best possible - return it. 3080 return osr; 3081 } 3082 best = osr; 3083 } 3084 } 3085 } 3086 osr = osr->osr_link(); 3087 } 3088 if (best != NULL && best->comp_level() >= comp_level && match_level == false) { 3089 return best; 3090 } 3091 return NULL; 3092 } 3093 3094 // ----------------------------------------------------------------------------------------------------- 3095 // Printing 3096 3097 #ifndef PRODUCT 3098 3099 #define BULLET " - " 3100 3101 static const char* state_names[] = { 3102 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error" 3103 }; 3104 3105 static void print_vtable(intptr_t* start, int len, outputStream* st) { 3106 for (int i = 0; i < len; i++) { 3107 intptr_t e = start[i]; 3108 st->print("%d : " INTPTR_FORMAT, i, e); 3109 if (e != 0 && ((Metadata*)e)->is_metaspace_object()) { 3110 st->print(" "); 3111 ((Metadata*)e)->print_value_on(st); 3112 } 3113 st->cr(); 3114 } 3115 } 3116 3117 static void print_vtable(vtableEntry* start, int len, outputStream* st) { 3118 return print_vtable(reinterpret_cast<intptr_t*>(start), len, st); 3119 } 3120 3121 void InstanceKlass::print_on(outputStream* st) const { 3122 assert(is_klass(), "must be klass"); 3123 Klass::print_on(st); 3124 3125 st->print(BULLET"instance size: %d", size_helper()); st->cr(); 3126 st->print(BULLET"klass size: %d", size()); st->cr(); 3127 st->print(BULLET"access: "); access_flags().print_on(st); st->cr(); 3128 st->print(BULLET"state: "); st->print_cr("%s", state_names[_init_state]); 3129 st->print(BULLET"name: "); name()->print_value_on(st); st->cr(); 3130 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr(); 3131 st->print(BULLET"sub: "); 3132 Klass* sub = subklass(); 3133 int n; 3134 for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) { 3135 if (n < MaxSubklassPrintSize) { 3136 sub->print_value_on(st); 3137 st->print(" "); 3138 } 3139 } 3140 if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize); 3141 st->cr(); 3142 3143 if (is_interface()) { 3144 MutexLocker ml(Compile_lock); 3145 st->print_cr(BULLET"nof implementors: %d", nof_implementors()); 3146 if (nof_implementors() == 1) { 3147 st->print_cr(BULLET"implementor: "); 3148 st->print(" "); 3149 implementor()->print_value_on(st); 3150 st->cr(); 3151 } 3152 } 3153 3154 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr(); 3155 st->print(BULLET"methods: "); methods()->print_value_on(st); st->cr(); 3156 if (Verbose || WizardMode) { 3157 Array<Method*>* method_array = methods(); 3158 for (int i = 0; i < method_array->length(); i++) { 3159 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr(); 3160 } 3161 } 3162 st->print(BULLET"method ordering: "); method_ordering()->print_value_on(st); st->cr(); 3163 st->print(BULLET"default_methods: "); default_methods()->print_value_on(st); st->cr(); 3164 if (Verbose && default_methods() != NULL) { 3165 Array<Method*>* method_array = default_methods(); 3166 for (int i = 0; i < method_array->length(); i++) { 3167 st->print("%d : ", i); method_array->at(i)->print_value(); st->cr(); 3168 } 3169 } 3170 if (default_vtable_indices() != NULL) { 3171 st->print(BULLET"default vtable indices: "); default_vtable_indices()->print_value_on(st); st->cr(); 3172 } 3173 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr(); 3174 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr(); 3175 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr(); 3176 if (class_loader_data() != NULL) { 3177 st->print(BULLET"class loader data: "); 3178 class_loader_data()->print_value_on(st); 3179 st->cr(); 3180 } 3181 st->print(BULLET"unsafe anonymous host class: "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr(); 3182 if (source_file_name() != NULL) { 3183 st->print(BULLET"source file: "); 3184 source_file_name()->print_value_on(st); 3185 st->cr(); 3186 } 3187 if (source_debug_extension() != NULL) { 3188 st->print(BULLET"source debug extension: "); 3189 st->print("%s", source_debug_extension()); 3190 st->cr(); 3191 } 3192 st->print(BULLET"class annotations: "); class_annotations()->print_value_on(st); st->cr(); 3193 st->print(BULLET"class type annotations: "); class_type_annotations()->print_value_on(st); st->cr(); 3194 st->print(BULLET"field annotations: "); fields_annotations()->print_value_on(st); st->cr(); 3195 st->print(BULLET"field type annotations: "); fields_type_annotations()->print_value_on(st); st->cr(); 3196 { 3197 bool have_pv = false; 3198 // previous versions are linked together through the InstanceKlass 3199 for (InstanceKlass* pv_node = previous_versions(); 3200 pv_node != NULL; 3201 pv_node = pv_node->previous_versions()) { 3202 if (!have_pv) 3203 st->print(BULLET"previous version: "); 3204 have_pv = true; 3205 pv_node->constants()->print_value_on(st); 3206 } 3207 if (have_pv) st->cr(); 3208 } 3209 3210 if (generic_signature() != NULL) { 3211 st->print(BULLET"generic signature: "); 3212 generic_signature()->print_value_on(st); 3213 st->cr(); 3214 } 3215 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr(); 3216 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr(); 3217 if (java_mirror() != NULL) { 3218 st->print(BULLET"java mirror: "); 3219 java_mirror()->print_value_on(st); 3220 st->cr(); 3221 } else { 3222 st->print_cr(BULLET"java mirror: NULL"); 3223 } 3224 st->print(BULLET"vtable length %d (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr(); 3225 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st); 3226 st->print(BULLET"itable length %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr(); 3227 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_itable(), itable_length(), st); 3228 st->print_cr(BULLET"---- static fields (%d words):", static_field_size()); 3229 FieldPrinter print_static_field(st); 3230 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field); 3231 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size()); 3232 FieldPrinter print_nonstatic_field(st); 3233 InstanceKlass* ik = const_cast<InstanceKlass*>(this); 3234 ik->do_nonstatic_fields(&print_nonstatic_field); 3235 3236 st->print(BULLET"non-static oop maps: "); 3237 OopMapBlock* map = start_of_nonstatic_oop_maps(); 3238 OopMapBlock* end_map = map + nonstatic_oop_map_count(); 3239 while (map < end_map) { 3240 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1)); 3241 map++; 3242 } 3243 st->cr(); 3244 } 3245 3246 #endif //PRODUCT 3247 3248 void InstanceKlass::print_value_on(outputStream* st) const { 3249 assert(is_klass(), "must be klass"); 3250 if (Verbose || WizardMode) access_flags().print_on(st); 3251 name()->print_value_on(st); 3252 } 3253 3254 #ifndef PRODUCT 3255 3256 void FieldPrinter::do_field(fieldDescriptor* fd) { 3257 _st->print(BULLET); 3258 if (_obj == NULL) { 3259 fd->print_on(_st); 3260 _st->cr(); 3261 } else { 3262 fd->print_on_for(_st, _obj); 3263 _st->cr(); 3264 } 3265 } 3266 3267 3268 void InstanceKlass::oop_print_on(oop obj, outputStream* st) { 3269 Klass::oop_print_on(obj, st); 3270 3271 if (this == SystemDictionary::String_klass()) { 3272 typeArrayOop value = java_lang_String::value(obj); 3273 juint length = java_lang_String::length(obj); 3274 if (value != NULL && 3275 value->is_typeArray() && 3276 length <= (juint) value->length()) { 3277 st->print(BULLET"string: "); 3278 java_lang_String::print(obj, st); 3279 st->cr(); 3280 if (!WizardMode) return; // that is enough 3281 } 3282 } 3283 3284 st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj)); 3285 FieldPrinter print_field(st, obj); 3286 do_nonstatic_fields(&print_field); 3287 3288 if (this == SystemDictionary::Class_klass()) { 3289 st->print(BULLET"signature: "); 3290 java_lang_Class::print_signature(obj, st); 3291 st->cr(); 3292 Klass* mirrored_klass = java_lang_Class::as_Klass(obj); 3293 st->print(BULLET"fake entry for mirror: "); 3294 Metadata::print_value_on_maybe_null(st, mirrored_klass); 3295 st->cr(); 3296 Klass* array_klass = java_lang_Class::array_klass_acquire(obj); 3297 st->print(BULLET"fake entry for array: "); 3298 Metadata::print_value_on_maybe_null(st, array_klass); 3299 st->cr(); 3300 st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj)); 3301 st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj)); 3302 Klass* real_klass = java_lang_Class::as_Klass(obj); 3303 if (real_klass != NULL && real_klass->is_instance_klass()) { 3304 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field); 3305 } 3306 } else if (this == SystemDictionary::MethodType_klass()) { 3307 st->print(BULLET"signature: "); 3308 java_lang_invoke_MethodType::print_signature(obj, st); 3309 st->cr(); 3310 } 3311 } 3312 3313 bool InstanceKlass::verify_itable_index(int i) { 3314 int method_count = klassItable::method_count_for_interface(this); 3315 assert(i >= 0 && i < method_count, "index out of bounds"); 3316 return true; 3317 } 3318 3319 #endif //PRODUCT 3320 3321 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) { 3322 st->print("a "); 3323 name()->print_value_on(st); 3324 obj->print_address_on(st); 3325 if (this == SystemDictionary::String_klass() 3326 && java_lang_String::value(obj) != NULL) { 3327 ResourceMark rm; 3328 int len = java_lang_String::length(obj); 3329 int plen = (len < 24 ? len : 12); 3330 char* str = java_lang_String::as_utf8_string(obj, 0, plen); 3331 st->print(" = \"%s\"", str); 3332 if (len > plen) 3333 st->print("...[%d]", len); 3334 } else if (this == SystemDictionary::Class_klass()) { 3335 Klass* k = java_lang_Class::as_Klass(obj); 3336 st->print(" = "); 3337 if (k != NULL) { 3338 k->print_value_on(st); 3339 } else { 3340 const char* tname = type2name(java_lang_Class::primitive_type(obj)); 3341 st->print("%s", tname ? tname : "type?"); 3342 } 3343 } else if (this == SystemDictionary::MethodType_klass()) { 3344 st->print(" = "); 3345 java_lang_invoke_MethodType::print_signature(obj, st); 3346 } else if (java_lang_boxing_object::is_instance(obj)) { 3347 st->print(" = "); 3348 java_lang_boxing_object::print(obj, st); 3349 } else if (this == SystemDictionary::LambdaForm_klass()) { 3350 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj); 3351 if (vmentry != NULL) { 3352 st->print(" => "); 3353 vmentry->print_value_on(st); 3354 } 3355 } else if (this == SystemDictionary::MemberName_klass()) { 3356 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj); 3357 if (vmtarget != NULL) { 3358 st->print(" = "); 3359 vmtarget->print_value_on(st); 3360 } else { 3361 java_lang_invoke_MemberName::clazz(obj)->print_value_on(st); 3362 st->print("."); 3363 java_lang_invoke_MemberName::name(obj)->print_value_on(st); 3364 } 3365 } 3366 } 3367 3368 const char* InstanceKlass::internal_name() const { 3369 return external_name(); 3370 } 3371 3372 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data, 3373 const char* module_name, 3374 const ClassFileStream* cfs) const { 3375 if (!log_is_enabled(Info, class, load)) { 3376 return; 3377 } 3378 3379 ResourceMark rm; 3380 LogMessage(class, load) msg; 3381 stringStream info_stream; 3382 3383 // Name and class hierarchy info 3384 info_stream.print("%s", external_name()); 3385 3386 // Source 3387 if (cfs != NULL) { 3388 if (cfs->source() != NULL) { 3389 if (module_name != NULL) { 3390 if (ClassLoader::is_modules_image(cfs->source())) { 3391 info_stream.print(" source: jrt:/%s", module_name); 3392 } else { 3393 info_stream.print(" source: %s", cfs->source()); 3394 } 3395 } else { 3396 info_stream.print(" source: %s", cfs->source()); 3397 } 3398 } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) { 3399 Thread* THREAD = Thread::current(); 3400 Klass* caller = 3401 THREAD->is_Java_thread() 3402 ? ((JavaThread*)THREAD)->security_get_caller_class(1) 3403 : NULL; 3404 // caller can be NULL, for example, during a JVMTI VM_Init hook 3405 if (caller != NULL) { 3406 info_stream.print(" source: instance of %s", caller->external_name()); 3407 } else { 3408 // source is unknown 3409 } 3410 } else { 3411 oop class_loader = loader_data->class_loader(); 3412 info_stream.print(" source: %s", class_loader->klass()->external_name()); 3413 } 3414 } else { 3415 info_stream.print(" source: shared objects file"); 3416 } 3417 3418 msg.info("%s", info_stream.as_string()); 3419 3420 if (log_is_enabled(Debug, class, load)) { 3421 stringStream debug_stream; 3422 3423 // Class hierarchy info 3424 debug_stream.print(" klass: " INTPTR_FORMAT " super: " INTPTR_FORMAT, 3425 p2i(this), p2i(superklass())); 3426 3427 // Interfaces 3428 if (local_interfaces() != NULL && local_interfaces()->length() > 0) { 3429 debug_stream.print(" interfaces:"); 3430 int length = local_interfaces()->length(); 3431 for (int i = 0; i < length; i++) { 3432 debug_stream.print(" " INTPTR_FORMAT, 3433 p2i(InstanceKlass::cast(local_interfaces()->at(i)))); 3434 } 3435 } 3436 3437 // Class loader 3438 debug_stream.print(" loader: ["); 3439 loader_data->print_value_on(&debug_stream); 3440 debug_stream.print("]"); 3441 3442 // Classfile checksum 3443 if (cfs) { 3444 debug_stream.print(" bytes: %d checksum: %08x", 3445 cfs->length(), 3446 ClassLoader::crc32(0, (const char*)cfs->buffer(), 3447 cfs->length())); 3448 } 3449 3450 msg.debug("%s", debug_stream.as_string()); 3451 } 3452 } 3453 3454 #if INCLUDE_SERVICES 3455 // Size Statistics 3456 void InstanceKlass::collect_statistics(KlassSizeStats *sz) const { 3457 Klass::collect_statistics(sz); 3458 3459 sz->_inst_size = wordSize * size_helper(); 3460 sz->_vtab_bytes = wordSize * vtable_length(); 3461 sz->_itab_bytes = wordSize * itable_length(); 3462 sz->_nonstatic_oopmap_bytes = wordSize * nonstatic_oop_map_size(); 3463 3464 int n = 0; 3465 n += (sz->_methods_array_bytes = sz->count_array(methods())); 3466 n += (sz->_method_ordering_bytes = sz->count_array(method_ordering())); 3467 n += (sz->_local_interfaces_bytes = sz->count_array(local_interfaces())); 3468 n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces())); 3469 n += (sz->_fields_bytes = sz->count_array(fields())); 3470 n += (sz->_inner_classes_bytes = sz->count_array(inner_classes())); 3471 n += (sz->_nest_members_bytes = sz->count_array(nest_members())); 3472 sz->_ro_bytes += n; 3473 3474 const ConstantPool* cp = constants(); 3475 if (cp) { 3476 cp->collect_statistics(sz); 3477 } 3478 3479 const Annotations* anno = annotations(); 3480 if (anno) { 3481 anno->collect_statistics(sz); 3482 } 3483 3484 const Array<Method*>* methods_array = methods(); 3485 if (methods()) { 3486 for (int i = 0; i < methods_array->length(); i++) { 3487 Method* method = methods_array->at(i); 3488 if (method) { 3489 sz->_method_count ++; 3490 method->collect_statistics(sz); 3491 } 3492 } 3493 } 3494 } 3495 #endif // INCLUDE_SERVICES 3496 3497 // Verification 3498 3499 class VerifyFieldClosure: public BasicOopIterateClosure { 3500 protected: 3501 template <class T> void do_oop_work(T* p) { 3502 oop obj = RawAccess<>::oop_load(p); 3503 if (!oopDesc::is_oop_or_null(obj)) { 3504 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj)); 3505 Universe::print_on(tty); 3506 guarantee(false, "boom"); 3507 } 3508 } 3509 public: 3510 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); } 3511 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); } 3512 }; 3513 3514 void InstanceKlass::verify_on(outputStream* st) { 3515 #ifndef PRODUCT 3516 // Avoid redundant verifies, this really should be in product. 3517 if (_verify_count == Universe::verify_count()) return; 3518 _verify_count = Universe::verify_count(); 3519 #endif 3520 3521 // Verify Klass 3522 Klass::verify_on(st); 3523 3524 // Verify that klass is present in ClassLoaderData 3525 guarantee(class_loader_data()->contains_klass(this), 3526 "this class isn't found in class loader data"); 3527 3528 // Verify vtables 3529 if (is_linked()) { 3530 // $$$ This used to be done only for m/s collections. Doing it 3531 // always seemed a valid generalization. (DLD -- 6/00) 3532 vtable().verify(st); 3533 } 3534 3535 // Verify first subklass 3536 if (subklass() != NULL) { 3537 guarantee(subklass()->is_klass(), "should be klass"); 3538 } 3539 3540 // Verify siblings 3541 Klass* super = this->super(); 3542 Klass* sib = next_sibling(); 3543 if (sib != NULL) { 3544 if (sib == this) { 3545 fatal("subclass points to itself " PTR_FORMAT, p2i(sib)); 3546 } 3547 3548 guarantee(sib->is_klass(), "should be klass"); 3549 guarantee(sib->super() == super, "siblings should have same superklass"); 3550 } 3551 3552 // Verify implementor fields requires the Compile_lock, but this is sometimes 3553 // called inside a safepoint, so don't verify. 3554 3555 // Verify local interfaces 3556 if (local_interfaces()) { 3557 Array<InstanceKlass*>* local_interfaces = this->local_interfaces(); 3558 for (int j = 0; j < local_interfaces->length(); j++) { 3559 InstanceKlass* e = local_interfaces->at(j); 3560 guarantee(e->is_klass() && e->is_interface(), "invalid local interface"); 3561 } 3562 } 3563 3564 // Verify transitive interfaces 3565 if (transitive_interfaces() != NULL) { 3566 Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces(); 3567 for (int j = 0; j < transitive_interfaces->length(); j++) { 3568 InstanceKlass* e = transitive_interfaces->at(j); 3569 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface"); 3570 } 3571 } 3572 3573 // Verify methods 3574 if (methods() != NULL) { 3575 Array<Method*>* methods = this->methods(); 3576 for (int j = 0; j < methods->length(); j++) { 3577 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 3578 } 3579 for (int j = 0; j < methods->length() - 1; j++) { 3580 Method* m1 = methods->at(j); 3581 Method* m2 = methods->at(j + 1); 3582 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 3583 } 3584 } 3585 3586 // Verify method ordering 3587 if (method_ordering() != NULL) { 3588 Array<int>* method_ordering = this->method_ordering(); 3589 int length = method_ordering->length(); 3590 if (JvmtiExport::can_maintain_original_method_order() || 3591 ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) { 3592 guarantee(length == methods()->length(), "invalid method ordering length"); 3593 jlong sum = 0; 3594 for (int j = 0; j < length; j++) { 3595 int original_index = method_ordering->at(j); 3596 guarantee(original_index >= 0, "invalid method ordering index"); 3597 guarantee(original_index < length, "invalid method ordering index"); 3598 sum += original_index; 3599 } 3600 // Verify sum of indices 0,1,...,length-1 3601 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum"); 3602 } else { 3603 guarantee(length == 0, "invalid method ordering length"); 3604 } 3605 } 3606 3607 // Verify default methods 3608 if (default_methods() != NULL) { 3609 Array<Method*>* methods = this->default_methods(); 3610 for (int j = 0; j < methods->length(); j++) { 3611 guarantee(methods->at(j)->is_method(), "non-method in methods array"); 3612 } 3613 for (int j = 0; j < methods->length() - 1; j++) { 3614 Method* m1 = methods->at(j); 3615 Method* m2 = methods->at(j + 1); 3616 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly"); 3617 } 3618 } 3619 3620 // Verify JNI static field identifiers 3621 if (jni_ids() != NULL) { 3622 jni_ids()->verify(this); 3623 } 3624 3625 // Verify other fields 3626 if (array_klasses() != NULL) { 3627 guarantee(array_klasses()->is_klass(), "should be klass"); 3628 } 3629 if (constants() != NULL) { 3630 guarantee(constants()->is_constantPool(), "should be constant pool"); 3631 } 3632 const Klass* anonymous_host = unsafe_anonymous_host(); 3633 if (anonymous_host != NULL) { 3634 guarantee(anonymous_host->is_klass(), "should be klass"); 3635 } 3636 } 3637 3638 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) { 3639 Klass::oop_verify_on(obj, st); 3640 VerifyFieldClosure blk; 3641 obj->oop_iterate(&blk); 3642 } 3643 3644 3645 // JNIid class for jfieldIDs only 3646 // Note to reviewers: 3647 // These JNI functions are just moved over to column 1 and not changed 3648 // in the compressed oops workspace. 3649 JNIid::JNIid(Klass* holder, int offset, JNIid* next) { 3650 _holder = holder; 3651 _offset = offset; 3652 _next = next; 3653 debug_only(_is_static_field_id = false;) 3654 } 3655 3656 3657 JNIid* JNIid::find(int offset) { 3658 JNIid* current = this; 3659 while (current != NULL) { 3660 if (current->offset() == offset) return current; 3661 current = current->next(); 3662 } 3663 return NULL; 3664 } 3665 3666 void JNIid::deallocate(JNIid* current) { 3667 while (current != NULL) { 3668 JNIid* next = current->next(); 3669 delete current; 3670 current = next; 3671 } 3672 } 3673 3674 3675 void JNIid::verify(Klass* holder) { 3676 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields(); 3677 int end_field_offset; 3678 end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize); 3679 3680 JNIid* current = this; 3681 while (current != NULL) { 3682 guarantee(current->holder() == holder, "Invalid klass in JNIid"); 3683 #ifdef ASSERT 3684 int o = current->offset(); 3685 if (current->is_static_field_id()) { 3686 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid"); 3687 } 3688 #endif 3689 current = current->next(); 3690 } 3691 } 3692 3693 #ifdef ASSERT 3694 void InstanceKlass::set_init_state(ClassState state) { 3695 bool good_state = is_shared() ? (_init_state <= state) 3696 : (_init_state < state); 3697 assert(good_state || state == allocated, "illegal state transition"); 3698 _init_state = (u1)state; 3699 } 3700 #endif 3701 3702 #if INCLUDE_JVMTI 3703 3704 // RedefineClasses() support for previous versions 3705 3706 // Globally, there is at least one previous version of a class to walk 3707 // during class unloading, which is saved because old methods in the class 3708 // are still running. Otherwise the previous version list is cleaned up. 3709 bool InstanceKlass::_has_previous_versions = false; 3710 3711 // Returns true if there are previous versions of a class for class 3712 // unloading only. Also resets the flag to false. purge_previous_version 3713 // will set the flag to true if there are any left, i.e., if there's any 3714 // work to do for next time. This is to avoid the expensive code cache 3715 // walk in CLDG::clean_deallocate_lists(). 3716 bool InstanceKlass::has_previous_versions_and_reset() { 3717 bool ret = _has_previous_versions; 3718 log_trace(redefine, class, iklass, purge)("Class unloading: has_previous_versions = %s", 3719 ret ? "true" : "false"); 3720 _has_previous_versions = false; 3721 return ret; 3722 } 3723 3724 // Purge previous versions before adding new previous versions of the class and 3725 // during class unloading. 3726 void InstanceKlass::purge_previous_version_list() { 3727 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint"); 3728 assert(has_been_redefined(), "Should only be called for main class"); 3729 3730 // Quick exit. 3731 if (previous_versions() == NULL) { 3732 return; 3733 } 3734 3735 // This klass has previous versions so see what we can cleanup 3736 // while it is safe to do so. 3737 3738 int deleted_count = 0; // leave debugging breadcrumbs 3739 int live_count = 0; 3740 ClassLoaderData* loader_data = class_loader_data(); 3741 assert(loader_data != NULL, "should never be null"); 3742 3743 ResourceMark rm; 3744 log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name()); 3745 3746 // previous versions are linked together through the InstanceKlass 3747 InstanceKlass* pv_node = previous_versions(); 3748 InstanceKlass* last = this; 3749 int version = 0; 3750 3751 // check the previous versions list 3752 for (; pv_node != NULL; ) { 3753 3754 ConstantPool* pvcp = pv_node->constants(); 3755 assert(pvcp != NULL, "cp ref was unexpectedly cleared"); 3756 3757 if (!pvcp->on_stack()) { 3758 // If the constant pool isn't on stack, none of the methods 3759 // are executing. Unlink this previous_version. 3760 // The previous version InstanceKlass is on the ClassLoaderData deallocate list 3761 // so will be deallocated during the next phase of class unloading. 3762 log_trace(redefine, class, iklass, purge) 3763 ("previous version " INTPTR_FORMAT " is dead.", p2i(pv_node)); 3764 // For debugging purposes. 3765 pv_node->set_is_scratch_class(); 3766 // Unlink from previous version list. 3767 assert(pv_node->class_loader_data() == loader_data, "wrong loader_data"); 3768 InstanceKlass* next = pv_node->previous_versions(); 3769 pv_node->link_previous_versions(NULL); // point next to NULL 3770 last->link_previous_versions(next); 3771 // Add to the deallocate list after unlinking 3772 loader_data->add_to_deallocate_list(pv_node); 3773 pv_node = next; 3774 deleted_count++; 3775 version++; 3776 continue; 3777 } else { 3778 log_trace(redefine, class, iklass, purge)("previous version " INTPTR_FORMAT " is alive", p2i(pv_node)); 3779 assert(pvcp->pool_holder() != NULL, "Constant pool with no holder"); 3780 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack"); 3781 live_count++; 3782 // found a previous version for next time we do class unloading 3783 _has_previous_versions = true; 3784 } 3785 3786 // At least one method is live in this previous version. 3787 // Reset dead EMCP methods not to get breakpoints. 3788 // All methods are deallocated when all of the methods for this class are no 3789 // longer running. 3790 Array<Method*>* method_refs = pv_node->methods(); 3791 if (method_refs != NULL) { 3792 log_trace(redefine, class, iklass, purge)("previous methods length=%d", method_refs->length()); 3793 for (int j = 0; j < method_refs->length(); j++) { 3794 Method* method = method_refs->at(j); 3795 3796 if (!method->on_stack()) { 3797 // no breakpoints for non-running methods 3798 if (method->is_running_emcp()) { 3799 method->set_running_emcp(false); 3800 } 3801 } else { 3802 assert (method->is_obsolete() || method->is_running_emcp(), 3803 "emcp method cannot run after emcp bit is cleared"); 3804 log_trace(redefine, class, iklass, purge) 3805 ("purge: %s(%s): prev method @%d in version @%d is alive", 3806 method->name()->as_C_string(), method->signature()->as_C_string(), j, version); 3807 } 3808 } 3809 } 3810 // next previous version 3811 last = pv_node; 3812 pv_node = pv_node->previous_versions(); 3813 version++; 3814 } 3815 log_trace(redefine, class, iklass, purge) 3816 ("previous version stats: live=%d, deleted=%d", live_count, deleted_count); 3817 } 3818 3819 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods, 3820 int emcp_method_count) { 3821 int obsolete_method_count = old_methods->length() - emcp_method_count; 3822 3823 if (emcp_method_count != 0 && obsolete_method_count != 0 && 3824 _previous_versions != NULL) { 3825 // We have a mix of obsolete and EMCP methods so we have to 3826 // clear out any matching EMCP method entries the hard way. 3827 int local_count = 0; 3828 for (int i = 0; i < old_methods->length(); i++) { 3829 Method* old_method = old_methods->at(i); 3830 if (old_method->is_obsolete()) { 3831 // only obsolete methods are interesting 3832 Symbol* m_name = old_method->name(); 3833 Symbol* m_signature = old_method->signature(); 3834 3835 // previous versions are linked together through the InstanceKlass 3836 int j = 0; 3837 for (InstanceKlass* prev_version = _previous_versions; 3838 prev_version != NULL; 3839 prev_version = prev_version->previous_versions(), j++) { 3840 3841 Array<Method*>* method_refs = prev_version->methods(); 3842 for (int k = 0; k < method_refs->length(); k++) { 3843 Method* method = method_refs->at(k); 3844 3845 if (!method->is_obsolete() && 3846 method->name() == m_name && 3847 method->signature() == m_signature) { 3848 // The current RedefineClasses() call has made all EMCP 3849 // versions of this method obsolete so mark it as obsolete 3850 log_trace(redefine, class, iklass, add) 3851 ("%s(%s): flush obsolete method @%d in version @%d", 3852 m_name->as_C_string(), m_signature->as_C_string(), k, j); 3853 3854 method->set_is_obsolete(); 3855 break; 3856 } 3857 } 3858 3859 // The previous loop may not find a matching EMCP method, but 3860 // that doesn't mean that we can optimize and not go any 3861 // further back in the PreviousVersion generations. The EMCP 3862 // method for this generation could have already been made obsolete, 3863 // but there still may be an older EMCP method that has not 3864 // been made obsolete. 3865 } 3866 3867 if (++local_count >= obsolete_method_count) { 3868 // no more obsolete methods so bail out now 3869 break; 3870 } 3871 } 3872 } 3873 } 3874 } 3875 3876 // Save the scratch_class as the previous version if any of the methods are running. 3877 // The previous_versions are used to set breakpoints in EMCP methods and they are 3878 // also used to clean MethodData links to redefined methods that are no longer running. 3879 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class, 3880 int emcp_method_count) { 3881 assert(Thread::current()->is_VM_thread(), 3882 "only VMThread can add previous versions"); 3883 3884 ResourceMark rm; 3885 log_trace(redefine, class, iklass, add) 3886 ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count); 3887 3888 // Clean out old previous versions for this class 3889 purge_previous_version_list(); 3890 3891 // Mark newly obsolete methods in remaining previous versions. An EMCP method from 3892 // a previous redefinition may be made obsolete by this redefinition. 3893 Array<Method*>* old_methods = scratch_class->methods(); 3894 mark_newly_obsolete_methods(old_methods, emcp_method_count); 3895 3896 // If the constant pool for this previous version of the class 3897 // is not marked as being on the stack, then none of the methods 3898 // in this previous version of the class are on the stack so 3899 // we don't need to add this as a previous version. 3900 ConstantPool* cp_ref = scratch_class->constants(); 3901 if (!cp_ref->on_stack()) { 3902 log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running"); 3903 // For debugging purposes. 3904 scratch_class->set_is_scratch_class(); 3905 scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class); 3906 return; 3907 } 3908 3909 if (emcp_method_count != 0) { 3910 // At least one method is still running, check for EMCP methods 3911 for (int i = 0; i < old_methods->length(); i++) { 3912 Method* old_method = old_methods->at(i); 3913 if (!old_method->is_obsolete() && old_method->on_stack()) { 3914 // if EMCP method (not obsolete) is on the stack, mark as EMCP so that 3915 // we can add breakpoints for it. 3916 3917 // We set the method->on_stack bit during safepoints for class redefinition 3918 // and use this bit to set the is_running_emcp bit. 3919 // After the safepoint, the on_stack bit is cleared and the running emcp 3920 // method may exit. If so, we would set a breakpoint in a method that 3921 // is never reached, but this won't be noticeable to the programmer. 3922 old_method->set_running_emcp(true); 3923 log_trace(redefine, class, iklass, add) 3924 ("EMCP method %s is on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method)); 3925 } else if (!old_method->is_obsolete()) { 3926 log_trace(redefine, class, iklass, add) 3927 ("EMCP method %s is NOT on_stack " INTPTR_FORMAT, old_method->name_and_sig_as_C_string(), p2i(old_method)); 3928 } 3929 } 3930 } 3931 3932 // Add previous version if any methods are still running. 3933 // Set has_previous_version flag for processing during class unloading. 3934 _has_previous_versions = true; 3935 log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack."); 3936 assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version"); 3937 scratch_class->link_previous_versions(previous_versions()); 3938 link_previous_versions(scratch_class); 3939 } // end add_previous_version() 3940 3941 #endif // INCLUDE_JVMTI 3942 3943 Method* InstanceKlass::method_with_idnum(int idnum) { 3944 Method* m = NULL; 3945 if (idnum < methods()->length()) { 3946 m = methods()->at(idnum); 3947 } 3948 if (m == NULL || m->method_idnum() != idnum) { 3949 for (int index = 0; index < methods()->length(); ++index) { 3950 m = methods()->at(index); 3951 if (m->method_idnum() == idnum) { 3952 return m; 3953 } 3954 } 3955 // None found, return null for the caller to handle. 3956 return NULL; 3957 } 3958 return m; 3959 } 3960 3961 3962 Method* InstanceKlass::method_with_orig_idnum(int idnum) { 3963 if (idnum >= methods()->length()) { 3964 return NULL; 3965 } 3966 Method* m = methods()->at(idnum); 3967 if (m != NULL && m->orig_method_idnum() == idnum) { 3968 return m; 3969 } 3970 // Obsolete method idnum does not match the original idnum 3971 for (int index = 0; index < methods()->length(); ++index) { 3972 m = methods()->at(index); 3973 if (m->orig_method_idnum() == idnum) { 3974 return m; 3975 } 3976 } 3977 // None found, return null for the caller to handle. 3978 return NULL; 3979 } 3980 3981 3982 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) { 3983 InstanceKlass* holder = get_klass_version(version); 3984 if (holder == NULL) { 3985 return NULL; // The version of klass is gone, no method is found 3986 } 3987 Method* method = holder->method_with_orig_idnum(idnum); 3988 return method; 3989 } 3990 3991 #if INCLUDE_JVMTI 3992 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() { 3993 if (MetaspaceShared::is_in_shared_metaspace(_cached_class_file)) { 3994 // Ignore the archived class stream data 3995 return NULL; 3996 } else { 3997 return _cached_class_file; 3998 } 3999 } 4000 4001 jint InstanceKlass::get_cached_class_file_len() { 4002 return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file); 4003 } 4004 4005 unsigned char * InstanceKlass::get_cached_class_file_bytes() { 4006 return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file); 4007 } 4008 4009 #if INCLUDE_CDS 4010 JvmtiCachedClassFileData* InstanceKlass::get_archived_class_data() { 4011 if (DumpSharedSpaces) { 4012 return _cached_class_file; 4013 } else { 4014 assert(this->is_shared(), "class should be shared"); 4015 if (MetaspaceShared::is_in_shared_metaspace(_cached_class_file)) { 4016 return _cached_class_file; 4017 } else { 4018 return NULL; 4019 } 4020 } 4021 } 4022 #endif 4023 #endif