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