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