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