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