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