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