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