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