1 /*
2 * Copyright (c) 1997, 2026, 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 "cds/aotClassInitializer.hpp"
26 #include "cds/aotMetaspace.hpp"
27 #include "cds/archiveUtils.hpp"
28 #include "cds/cdsConfig.hpp"
29 #include "cds/cdsEnumKlass.hpp"
30 #include "cds/classListWriter.hpp"
31 #include "cds/heapShared.hpp"
32 #include "classfile/classFileParser.hpp"
33 #include "classfile/classFileStream.hpp"
34 #include "classfile/classLoader.hpp"
35 #include "classfile/classLoaderData.inline.hpp"
36 #include "classfile/javaClasses.hpp"
37 #include "classfile/moduleEntry.hpp"
38 #include "classfile/systemDictionary.hpp"
39 #include "classfile/systemDictionaryShared.hpp"
40 #include "classfile/verifier.hpp"
41 #include "classfile/vmClasses.hpp"
42 #include "classfile/vmSymbols.hpp"
43 #include "code/codeCache.hpp"
44 #include "code/dependencyContext.hpp"
45 #include "compiler/compilationPolicy.hpp"
46 #include "compiler/compileBroker.hpp"
47 #include "gc/shared/collectedHeap.inline.hpp"
48 #include "interpreter/bytecodeStream.hpp"
49 #include "interpreter/oopMapCache.hpp"
50 #include "interpreter/rewriter.hpp"
51 #include "jvm.h"
52 #include "jvmtifiles/jvmti.h"
53 #include "klass.inline.hpp"
54 #include "logging/log.hpp"
55 #include "logging/logMessage.hpp"
56 #include "logging/logStream.hpp"
57 #include "memory/allocation.inline.hpp"
58 #include "memory/iterator.inline.hpp"
59 #include "memory/metadataFactory.hpp"
60 #include "memory/metaspaceClosure.hpp"
61 #include "memory/oopFactory.hpp"
62 #include "memory/resourceArea.hpp"
63 #include "memory/universe.hpp"
64 #include "oops/constantPool.hpp"
65 #include "oops/fieldStreams.inline.hpp"
66 #include "oops/inlineKlass.hpp"
67 #include "oops/instanceClassLoaderKlass.hpp"
68 #include "oops/instanceKlass.inline.hpp"
69 #include "oops/instanceMirrorKlass.hpp"
70 #include "oops/instanceOop.hpp"
71 #include "oops/instanceStackChunkKlass.hpp"
72 #include "oops/klass.inline.hpp"
73 #include "oops/markWord.hpp"
74 #include "oops/method.hpp"
75 #include "oops/oop.inline.hpp"
76 #include "oops/recordComponent.hpp"
77 #include "oops/refArrayKlass.hpp"
78 #include "oops/symbol.hpp"
79 #include "prims/jvmtiExport.hpp"
80 #include "prims/jvmtiRedefineClasses.hpp"
81 #include "prims/jvmtiThreadState.hpp"
82 #include "prims/methodComparator.hpp"
83 #include "runtime/arguments.hpp"
84 #include "runtime/atomicAccess.hpp"
85 #include "runtime/deoptimization.hpp"
86 #include "runtime/fieldDescriptor.inline.hpp"
87 #include "runtime/handles.inline.hpp"
88 #include "runtime/javaCalls.hpp"
89 #include "runtime/javaThread.inline.hpp"
90 #include "runtime/mutexLocker.hpp"
91 #include "runtime/orderAccess.hpp"
92 #include "runtime/os.inline.hpp"
93 #include "runtime/reflection.hpp"
94 #include "runtime/synchronizer.hpp"
95 #include "runtime/threads.hpp"
96 #include "services/classLoadingService.hpp"
97 #include "services/finalizerService.hpp"
98 #include "services/threadService.hpp"
99 #include "utilities/dtrace.hpp"
100 #include "utilities/events.hpp"
101 #include "utilities/macros.hpp"
102 #include "utilities/nativeStackPrinter.hpp"
103 #include "utilities/stringUtils.hpp"
104 #ifdef COMPILER1
105 #include "c1/c1_Compiler.hpp"
106 #endif
107 #if INCLUDE_JFR
108 #include "jfr/jfrEvents.hpp"
109 #endif
110
111 #ifdef DTRACE_ENABLED
112
113
114 #define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
115 #define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
116 #define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
117 #define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
118 #define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
119 #define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
120 #define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
121 #define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
122 #define DTRACE_CLASSINIT_PROBE(type, thread_type) \
123 { \
124 char* data = nullptr; \
125 int len = 0; \
126 Symbol* clss_name = name(); \
127 if (clss_name != nullptr) { \
128 data = (char*)clss_name->bytes(); \
129 len = clss_name->utf8_length(); \
130 } \
131 HOTSPOT_CLASS_INITIALIZATION_##type( \
132 data, len, (void*)class_loader(), thread_type); \
133 }
134
135 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait) \
136 { \
137 char* data = nullptr; \
138 int len = 0; \
139 Symbol* clss_name = name(); \
140 if (clss_name != nullptr) { \
141 data = (char*)clss_name->bytes(); \
142 len = clss_name->utf8_length(); \
143 } \
144 HOTSPOT_CLASS_INITIALIZATION_##type( \
145 data, len, (void*)class_loader(), thread_type, wait); \
146 }
147
148 #else // ndef DTRACE_ENABLED
149
150 #define DTRACE_CLASSINIT_PROBE(type, thread_type)
151 #define DTRACE_CLASSINIT_PROBE_WAIT(type, thread_type, wait)
152
153 #endif // ndef DTRACE_ENABLED
154
155 void InlineLayoutInfo::metaspace_pointers_do(MetaspaceClosure* it) {
156 log_trace(cds)("Iter(InlineFieldInfo): %p", this);
157 it->push(&_klass);
158 }
159
160 bool InstanceKlass::_finalization_enabled = true;
161
162 static inline bool is_class_loader(const Symbol* class_name,
163 const ClassFileParser& parser) {
164 assert(class_name != nullptr, "invariant");
165
166 if (class_name == vmSymbols::java_lang_ClassLoader()) {
167 return true;
168 }
169
170 if (vmClasses::ClassLoader_klass_is_loaded()) {
171 const Klass* const super_klass = parser.super_klass();
172 if (super_klass != nullptr) {
173 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
174 return true;
175 }
176 }
177 }
178 return false;
179 }
180
181 bool InstanceKlass::field_is_null_free_inline_type(int index) const {
182 return field(index).field_flags().is_null_free_inline_type();
183 }
184
185 bool InstanceKlass::is_class_in_loadable_descriptors_attribute(Symbol* name) const {
186 if (_loadable_descriptors == nullptr) return false;
187 for (int i = 0; i < _loadable_descriptors->length(); i++) {
188 Symbol* class_name = _constants->symbol_at(_loadable_descriptors->at(i));
189 if (class_name == name) return true;
190 }
191 return false;
192 }
193
194 static inline bool is_stack_chunk_class(const Symbol* class_name,
195 const ClassLoaderData* loader_data) {
196 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
197 loader_data->is_the_null_class_loader_data());
198 }
199
200 // private: called to verify that k is a static member of this nest.
201 // We know that k is an instance class in the same package and hence the
202 // same classloader.
203 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
204 assert(!is_hidden(), "unexpected hidden class");
205 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
206 if (log_is_enabled(Trace, class, nestmates)) {
207 ResourceMark rm(current);
208 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
209 k->external_name(), this->external_name());
210 }
211 return false;
212 }
213
214 if (log_is_enabled(Trace, class, nestmates)) {
215 ResourceMark rm(current);
216 log_trace(class, nestmates)("Checking nest membership of %s in %s",
217 k->external_name(), this->external_name());
218 }
219
220 // Check for the named class in _nest_members.
221 // We don't resolve, or load, any classes.
222 for (int i = 0; i < _nest_members->length(); i++) {
223 int cp_index = _nest_members->at(i);
224 Symbol* name = _constants->klass_name_at(cp_index);
225 if (name == k->name()) {
226 log_trace(class, nestmates)("- named class found at nest_members[%d] => cp[%d]", i, cp_index);
227 return true;
228 }
229 }
230 log_trace(class, nestmates)("- class is NOT a nest member!");
231 return false;
232 }
233
234 // Called to verify that k is a permitted subclass of this class.
235 // The incoming stringStream is used to format the messages for error logging and for the caller
236 // to use for exception throwing.
237 bool InstanceKlass::has_as_permitted_subclass(const InstanceKlass* k, stringStream& ss) const {
238 Thread* current = Thread::current();
239 assert(k != nullptr, "sanity check");
240 assert(_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array(),
241 "unexpected empty _permitted_subclasses array");
242
243 if (log_is_enabled(Trace, class, sealed)) {
244 ResourceMark rm(current);
245 log_trace(class, sealed)("Checking for permitted subclass %s in %s",
246 k->external_name(), this->external_name());
247 }
248
249 // Check that the class and its super are in the same module.
250 if (k->module() != this->module()) {
251 ss.print("Failed same module check: subclass %s is in module '%s' with loader %s, "
252 "and sealed class %s is in module '%s' with loader %s",
253 k->external_name(),
254 k->module()->name_as_C_string(),
255 k->module()->loader_data()->loader_name_and_id(),
256 this->external_name(),
257 this->module()->name_as_C_string(),
258 this->module()->loader_data()->loader_name_and_id());
259 log_trace(class, sealed)(" - %s", ss.as_string());
260 return false;
261 }
262
263 if (!k->is_public() && !is_same_class_package(k)) {
264 ss.print("Failed same package check: non-public subclass %s is in package '%s' with classloader %s, "
265 "and sealed class %s is in package '%s' with classloader %s",
266 k->external_name(),
267 k->package() != nullptr ? k->package()->name()->as_C_string() : "unnamed",
268 k->module()->loader_data()->loader_name_and_id(),
269 this->external_name(),
270 this->package() != nullptr ? this->package()->name()->as_C_string() : "unnamed",
271 this->module()->loader_data()->loader_name_and_id());
272 log_trace(class, sealed)(" - %s", ss.as_string());
273 return false;
274 }
275
276 for (int i = 0; i < _permitted_subclasses->length(); i++) {
277 int cp_index = _permitted_subclasses->at(i);
278 Symbol* name = _constants->klass_name_at(cp_index);
279 if (name == k->name()) {
280 log_trace(class, sealed)("- Found it at permitted_subclasses[%d] => cp[%d]", i, cp_index);
281 return true;
282 }
283 }
284
285 ss.print("Failed listed permitted subclass check: class %s is not a permitted subclass of %s",
286 k->external_name(), this->external_name());
287 log_trace(class, sealed)(" - %s", ss.as_string());
288 return false;
289 }
290
291 // Return nest-host class, resolving, validating and saving it if needed.
292 // In cases where this is called from a thread that cannot do classloading
293 // (such as a native JIT thread) then we simply return null, which in turn
294 // causes the access check to return false. Such code will retry the access
295 // from a more suitable environment later. Otherwise the _nest_host is always
296 // set once this method returns.
297 // Any errors from nest-host resolution must be preserved so they can be queried
298 // from higher-level access checking code, and reported as part of access checking
299 // exceptions.
300 // VirtualMachineErrors are propagated with a null return.
301 // Under any conditions where the _nest_host can be set to non-null the resulting
302 // value of it and, if applicable, the nest host resolution/validation error,
303 // are idempotent.
304 InstanceKlass* InstanceKlass::nest_host(TRAPS) {
305 InstanceKlass* nest_host_k = _nest_host;
306 if (nest_host_k != nullptr) {
307 return nest_host_k;
308 }
309
310 ResourceMark rm(THREAD);
311
312 // need to resolve and save our nest-host class.
313 if (_nest_host_index != 0) { // we have a real nest_host
314 // Before trying to resolve check if we're in a suitable context
315 bool can_resolve = THREAD->can_call_java();
316 if (!can_resolve && !_constants->tag_at(_nest_host_index).is_klass()) {
317 log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",
318 this->external_name());
319 return nullptr; // sentinel to say "try again from a different context"
320 }
321
322 log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",
323 this->external_name(),
324 _constants->klass_name_at(_nest_host_index)->as_C_string());
325
326 Klass* k = _constants->klass_at(_nest_host_index, THREAD);
327 if (HAS_PENDING_EXCEPTION) {
328 if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
329 return nullptr; // propagate VMEs
330 }
331 stringStream ss;
332 char* target_host_class = _constants->klass_name_at(_nest_host_index)->as_C_string();
333 ss.print("Nest host resolution of %s with host %s failed: ",
334 this->external_name(), target_host_class);
335 java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
336 constantPoolHandle cph(THREAD, constants());
337 SystemDictionary::add_nest_host_error(cph, _nest_host_index, ss);
338 CLEAR_PENDING_EXCEPTION;
339
340 log_trace(class, nestmates)("%s", ss.base());
341 } else {
342 // A valid nest-host is an instance class in the current package that lists this
343 // class as a nest member. If any of these conditions are not met the class is
344 // its own nest-host.
345 const char* error = nullptr;
346
347 // JVMS 5.4.4 indicates package check comes first
348 if (is_same_class_package(k)) {
349 // Now check actual membership. We can't be a member if our "host" is
350 // not an instance class.
351 if (k->is_instance_klass()) {
352 nest_host_k = InstanceKlass::cast(k);
353 bool is_member = nest_host_k->has_nest_member(THREAD, this);
354 if (is_member) {
355 _nest_host = nest_host_k; // save resolved nest-host value
356
357 log_trace(class, nestmates)("Resolved nest-host of %s to %s",
358 this->external_name(), k->external_name());
359 return nest_host_k;
360 } else {
361 error = "current type is not listed as a nest member";
362 }
363 } else {
364 error = "host is not an instance class";
365 }
366 } else {
367 error = "types are in different packages";
368 }
369
370 // something went wrong, so record what and log it
371 {
372 stringStream ss;
373 ss.print("Type %s (loader: %s) is not a nest member of type %s (loader: %s): %s",
374 this->external_name(),
375 this->class_loader_data()->loader_name_and_id(),
376 k->external_name(),
377 k->class_loader_data()->loader_name_and_id(),
378 error);
379 constantPoolHandle cph(THREAD, constants());
380 SystemDictionary::add_nest_host_error(cph, _nest_host_index, ss);
381 log_trace(class, nestmates)("%s", ss.base());
382 }
383 }
384 } else {
385 log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",
386 this->external_name());
387 }
388
389 // Either not in an explicit nest, or else an error occurred, so
390 // the nest-host is set to `this`. Any thread that sees this assignment
391 // will also see any setting of nest_host_error(), if applicable.
392 return (_nest_host = this);
393 }
394
395 // Dynamic nest member support: set this class's nest host to the given class.
396 // This occurs as part of the class definition, as soon as the instanceKlass
397 // has been created and doesn't require further resolution. The code:
398 // lookup().defineHiddenClass(bytes_for_X, NESTMATE);
399 // results in:
400 // class_of_X.set_nest_host(lookup().lookupClass().getNestHost())
401 // If it has an explicit _nest_host_index or _nest_members, these will be ignored.
402 // We also know the "host" is a valid nest-host in the same package so we can
403 // assert some of those facts.
404 void InstanceKlass::set_nest_host(InstanceKlass* host) {
405 assert(is_hidden(), "must be a hidden class");
406 assert(host != nullptr, "null nest host specified");
407 assert(_nest_host == nullptr, "current class has resolved nest-host");
408 assert(nest_host_error() == nullptr, "unexpected nest host resolution error exists: %s",
409 nest_host_error());
410 assert((host->_nest_host == nullptr && host->_nest_host_index == 0) ||
411 (host->_nest_host == host), "proposed host is not a valid nest-host");
412 // Can't assert this as package is not set yet:
413 // assert(is_same_class_package(host), "proposed host is in wrong package");
414
415 if (log_is_enabled(Trace, class, nestmates)) {
416 ResourceMark rm;
417 const char* msg = "";
418 // a hidden class does not expect a statically defined nest-host
419 if (_nest_host_index > 0) {
420 msg = "(the NestHost attribute in the current class is ignored)";
421 } else if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
422 msg = "(the NestMembers attribute in the current class is ignored)";
423 }
424 log_trace(class, nestmates)("Injected type %s into the nest of %s %s",
425 this->external_name(),
426 host->external_name(),
427 msg);
428 }
429 // set dynamic nest host
430 _nest_host = host;
431 // Record dependency to keep nest host from being unloaded before this class.
432 ClassLoaderData* this_key = class_loader_data();
433 assert(this_key != nullptr, "sanity");
434 this_key->record_dependency(host);
435 }
436
437 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host,
438 // or we are k's nest_host - all of which is covered by comparing the two
439 // resolved_nest_hosts.
440 // Any exceptions (i.e. VMEs) are propagated.
441 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {
442
443 assert(this != k, "this should be handled by higher-level code");
444
445 // Per JVMS 5.4.4 we first resolve and validate the current class, then
446 // the target class k.
447
448 InstanceKlass* cur_host = nest_host(CHECK_false);
449 if (cur_host == nullptr) {
450 return false;
451 }
452
453 Klass* k_nest_host = k->nest_host(CHECK_false);
454 if (k_nest_host == nullptr) {
455 return false;
456 }
457
458 bool access = (cur_host == k_nest_host);
459
460 ResourceMark rm(THREAD);
461 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
462 this->external_name(),
463 access ? "" : "NOT ",
464 k->external_name());
465 return access;
466 }
467
468 const char* InstanceKlass::nest_host_error() {
469 if (_nest_host_index == 0) {
470 return nullptr;
471 } else {
472 constantPoolHandle cph(Thread::current(), constants());
473 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
474 }
475 }
476
477 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
478 const int size = InstanceKlass::size(parser.vtable_size(),
479 parser.itable_size(),
480 nonstatic_oop_map_size(parser.total_oop_map_count()),
481 parser.is_interface(),
482 parser.is_inline_type());
483
484 const Symbol* const class_name = parser.class_name();
485 assert(class_name != nullptr, "invariant");
486 ClassLoaderData* loader_data = parser.loader_data();
487 assert(loader_data != nullptr, "invariant");
488
489 InstanceKlass* ik;
490
491 // Allocation
492 if (parser.is_instance_ref_klass()) {
493 // java.lang.ref.Reference
494 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
495 } else if (class_name == vmSymbols::java_lang_Class()) {
496 // mirror - java.lang.Class
497 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
498 } else if (is_stack_chunk_class(class_name, loader_data)) {
499 // stack chunk
500 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
501 } else if (is_class_loader(class_name, parser)) {
502 // class loader - java.lang.ClassLoader
503 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
504 } else if (parser.is_inline_type()) {
505 // inline type
506 ik = new (loader_data, size, THREAD) InlineKlass(parser);
507 } else {
508 // normal
509 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
510 }
511
512 if (ik != nullptr && UseCompressedClassPointers) {
513 assert(CompressedKlassPointers::is_encodable(ik),
514 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
515 }
516
517 // Check for pending exception before adding to the loader data and incrementing
518 // class count. Can get OOM here.
519 if (HAS_PENDING_EXCEPTION) {
520 return nullptr;
521 }
522
523 #ifdef ASSERT
524 ik->bounds_check((address) ik->start_of_vtable(), false, size);
525 ik->bounds_check((address) ik->start_of_itable(), false, size);
526 ik->bounds_check((address) ik->end_of_itable(), true, size);
527 ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
528 #endif //ASSERT
529 return ik;
530 }
531
532 #ifndef PRODUCT
533 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
534 const char* bad = nullptr;
535 address end = nullptr;
536 if (addr < (address)this) {
537 bad = "before";
538 } else if (addr == (address)this) {
539 if (edge_ok) return true;
540 bad = "just before";
541 } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
542 if (edge_ok) return true;
543 bad = "just after";
544 } else if (addr > end) {
545 bad = "after";
546 } else {
547 return true;
548 }
549 tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
550 bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
551 Verbose = WizardMode = true; this->print(); //@@
552 return false;
553 }
554 #endif //PRODUCT
555
556 // copy method ordering from resource area to Metaspace
557 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
558 if (m != nullptr) {
559 // allocate a new array and copy contents (memcpy?)
560 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
561 for (int i = 0; i < m->length(); i++) {
562 _method_ordering->at_put(i, m->at(i));
563 }
564 } else {
565 _method_ordering = Universe::the_empty_int_array();
566 }
567 }
568
569 // create a new array of vtable_indices for default methods
570 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
571 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
572 assert(default_vtable_indices() == nullptr, "only create once");
573 set_default_vtable_indices(vtable_indices);
574 return vtable_indices;
575 }
576
577
578 InstanceKlass::InstanceKlass() {
579 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
580 }
581
582 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, markWord prototype_header, ReferenceType reference_type) :
583 Klass(kind, prototype_header),
584 _nest_members(nullptr),
585 _nest_host(nullptr),
586 _permitted_subclasses(nullptr),
587 _record_components(nullptr),
588 _static_field_size(parser.static_field_size()),
589 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
590 _itable_len(parser.itable_size()),
591 _nest_host_index(0),
592 _init_state(allocated),
593 _reference_type(reference_type),
594 _acmp_maps_offset(0),
595 _init_thread(nullptr),
596 _inline_layout_info_array(nullptr),
597 _loadable_descriptors(nullptr),
598 _acmp_maps_array(nullptr),
599 _adr_inline_klass_members(nullptr)
600 {
601 set_vtable_length(parser.vtable_size());
602 set_access_flags(parser.access_flags());
603 if (parser.is_hidden()) set_is_hidden();
604 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
605 false));
606 if (parser.has_inlined_fields()) {
607 set_has_inlined_fields();
608 }
609
610 assert(nullptr == _methods, "underlying memory not zeroed?");
611 assert(is_instance_klass(), "is layout incorrect?");
612 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
613 }
614
615 void InstanceKlass::set_is_cloneable() {
616 if (name() == vmSymbols::java_lang_invoke_MemberName()) {
617 assert(is_final(), "no subclasses allowed");
618 // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
619 } else if (reference_type() != REF_NONE) {
620 // Reference cloning should not be intrinsified and always happen in JVM_Clone.
621 } else {
622 set_is_cloneable_fast();
623 }
624 }
625
626 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
627 Array<Method*>* methods) {
628 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
629 !methods->in_aot_cache()) {
630 for (int i = 0; i < methods->length(); i++) {
631 Method* method = methods->at(i);
632 if (method == nullptr) continue; // maybe null if error processing
633 // Only want to delete methods that are not executing for RedefineClasses.
634 // The previous version will point to them so they're not totally dangling
635 assert (!method->on_stack(), "shouldn't be called with methods on stack");
636 MetadataFactory::free_metadata(loader_data, method);
637 }
638 MetadataFactory::free_array<Method*>(loader_data, methods);
639 }
640 }
641
642 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
643 const InstanceKlass* super_klass,
644 Array<InstanceKlass*>* local_interfaces,
645 Array<InstanceKlass*>* transitive_interfaces) {
646 // Only deallocate transitive interfaces if not empty, same as super class
647 // or same as local interfaces. See code in parseClassFile.
648 Array<InstanceKlass*>* ti = transitive_interfaces;
649 if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {
650 // check that the interfaces don't come from super class
651 Array<InstanceKlass*>* sti = (super_klass == nullptr) ? nullptr :
652 super_klass->transitive_interfaces();
653 if (ti != sti && ti != nullptr && !ti->in_aot_cache()) {
654 MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);
655 }
656 }
657
658 // local interfaces can be empty
659 if (local_interfaces != Universe::the_empty_instance_klass_array() &&
660 local_interfaces != nullptr && !local_interfaces->in_aot_cache()) {
661 MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
662 }
663 }
664
665 void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data,
666 Array<RecordComponent*>* record_components) {
667 if (record_components != nullptr && !record_components->in_aot_cache()) {
668 for (int i = 0; i < record_components->length(); i++) {
669 RecordComponent* record_component = record_components->at(i);
670 MetadataFactory::free_metadata(loader_data, record_component);
671 }
672 MetadataFactory::free_array<RecordComponent*>(loader_data, record_components);
673 }
674 }
675
676 // This function deallocates the metadata and C heap pointers that the
677 // InstanceKlass points to.
678 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
679 // Orphan the mirror first, CMS thinks it's still live.
680 if (java_mirror() != nullptr) {
681 java_lang_Class::set_klass(java_mirror(), nullptr);
682 }
683
684 // Also remove mirror from handles
685 loader_data->remove_handle(_java_mirror);
686
687 // Need to take this class off the class loader data list.
688 loader_data->remove_class(this);
689
690 // The array_klass for this class is created later, after error handling.
691 // For class redefinition, we keep the original class so this scratch class
692 // doesn't have an array class. Either way, assert that there is nothing
693 // to deallocate.
694 assert(array_klasses() == nullptr, "array classes shouldn't be created for this class yet");
695
696 // Release C heap allocated data that this points to, which includes
697 // reference counting symbol names.
698 // Can't release the constant pool or MethodData C heap data here because the constant
699 // pool can be deallocated separately from the InstanceKlass for default methods and
700 // redefine classes. MethodData can also be released separately.
701 release_C_heap_structures(/* release_sub_metadata */ false);
702
703 deallocate_methods(loader_data, methods());
704 set_methods(nullptr);
705
706 deallocate_record_components(loader_data, record_components());
707 set_record_components(nullptr);
708
709 if (method_ordering() != nullptr &&
710 method_ordering() != Universe::the_empty_int_array() &&
711 !method_ordering()->in_aot_cache()) {
712 MetadataFactory::free_array<int>(loader_data, method_ordering());
713 }
714 set_method_ordering(nullptr);
715
716 // default methods can be empty
717 if (default_methods() != nullptr &&
718 default_methods() != Universe::the_empty_method_array() &&
719 !default_methods()->in_aot_cache()) {
720 MetadataFactory::free_array<Method*>(loader_data, default_methods());
721 }
722 // Do NOT deallocate the default methods, they are owned by superinterfaces.
723 set_default_methods(nullptr);
724
725 // default methods vtable indices can be empty
726 if (default_vtable_indices() != nullptr &&
727 !default_vtable_indices()->in_aot_cache()) {
728 MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
729 }
730 set_default_vtable_indices(nullptr);
731
732
733 // This array is in Klass, but remove it with the InstanceKlass since
734 // this place would be the only caller and it can share memory with transitive
735 // interfaces.
736 if (secondary_supers() != nullptr &&
737 secondary_supers() != Universe::the_empty_klass_array() &&
738 // see comments in compute_secondary_supers about the following cast
739 (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
740 !secondary_supers()->in_aot_cache()) {
741 MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
742 }
743 set_secondary_supers(nullptr, SECONDARY_SUPERS_BITMAP_EMPTY);
744
745 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
746 set_transitive_interfaces(nullptr);
747 set_local_interfaces(nullptr);
748
749 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
750 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
751 }
752 set_fieldinfo_stream(nullptr);
753
754 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
755 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
756 }
757 set_fieldinfo_search_table(nullptr);
758
759 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
760 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
761 }
762 set_fields_status(nullptr);
763
764 if (inline_layout_info_array() != nullptr) {
765 MetadataFactory::free_array<InlineLayoutInfo>(loader_data, inline_layout_info_array());
766 }
767 set_inline_layout_info_array(nullptr);
768
769 // If a method from a redefined class is using this constant pool, don't
770 // delete it, yet. The new class's previous version will point to this.
771 if (constants() != nullptr) {
772 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
773 if (!constants()->in_aot_cache()) {
774 MetadataFactory::free_metadata(loader_data, constants());
775 }
776 // Delete any cached resolution errors for the constant pool
777 SystemDictionary::delete_resolution_error(constants());
778
779 set_constants(nullptr);
780 }
781
782 if (inner_classes() != nullptr &&
783 inner_classes() != Universe::the_empty_short_array() &&
784 !inner_classes()->in_aot_cache()) {
785 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
786 }
787 set_inner_classes(nullptr);
788
789 if (nest_members() != nullptr &&
790 nest_members() != Universe::the_empty_short_array() &&
791 !nest_members()->in_aot_cache()) {
792 MetadataFactory::free_array<jushort>(loader_data, nest_members());
793 }
794 set_nest_members(nullptr);
795
796 if (permitted_subclasses() != nullptr &&
797 permitted_subclasses() != Universe::the_empty_short_array() &&
798 !permitted_subclasses()->in_aot_cache()) {
799 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
800 }
801 set_permitted_subclasses(nullptr);
802
803 if (loadable_descriptors() != nullptr &&
804 loadable_descriptors() != Universe::the_empty_short_array() &&
805 !loadable_descriptors()->in_aot_cache()) {
806 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
807 }
808 set_loadable_descriptors(nullptr);
809
810 if (acmp_maps_array() != nullptr) {
811 MetadataFactory::free_array<int>(loader_data, acmp_maps_array());
812 }
813 set_acmp_maps_array(nullptr);
814
815 // We should deallocate the Annotations instance if it's not in shared spaces.
816 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
817 MetadataFactory::free_metadata(loader_data, annotations());
818 }
819 set_annotations(nullptr);
820
821 SystemDictionaryShared::handle_class_unloading(this);
822
823 #if INCLUDE_CDS_JAVA_HEAP
824 if (CDSConfig::is_dumping_heap()) {
825 HeapShared::remove_scratch_objects(this);
826 }
827 #endif
828 }
829
830 bool InstanceKlass::is_record() const {
831 return _record_components != nullptr &&
832 is_final() &&
833 super() == vmClasses::Record_klass();
834 }
835
836 bool InstanceKlass::is_sealed() const {
837 return _permitted_subclasses != nullptr &&
838 _permitted_subclasses != Universe::the_empty_short_array();
839 }
840
841 // JLS 8.9: An enum class is either implicitly final and derives
842 // from java.lang.Enum, or else is implicitly sealed to its
843 // anonymous subclasses. This query detects both kinds.
844 // It does not validate the finality or
845 // sealing conditions: it merely checks for a super of Enum.
846 // This is sufficient for recognizing well-formed enums.
847 bool InstanceKlass::is_enum_subclass() const {
848 InstanceKlass* s = super();
849 return (s == vmClasses::Enum_klass() ||
850 (s != nullptr && s->super() == vmClasses::Enum_klass()));
851 }
852
853 bool InstanceKlass::should_be_initialized() const {
854 return !is_initialized();
855 }
856
857 // Static size helper
858 int InstanceKlass::size(int vtable_length,
859 int itable_length,
860 int nonstatic_oop_map_size,
861 bool is_interface,
862 bool is_inline_type) {
863 return align_metadata_size(header_size() +
864 vtable_length +
865 itable_length +
866 nonstatic_oop_map_size +
867 (is_interface ? (int)sizeof(Klass*) / wordSize : 0) +
868 (is_inline_type ? (int)sizeof(InlineKlass::Members) / wordSize : 0));
869 }
870
871 int InstanceKlass::size() const {
872 return size(vtable_length(),
873 itable_length(),
874 nonstatic_oop_map_size(),
875 is_interface(),
876 is_inline_klass());
877 }
878
879 klassItable InstanceKlass::itable() const {
880 return klassItable(const_cast<InstanceKlass*>(this));
881 }
882
883 // JVMTI spec thinks there are signers and protection domain in the
884 // instanceKlass. These accessors pretend these fields are there.
885 // The hprof specification also thinks these fields are in InstanceKlass.
886 oop InstanceKlass::protection_domain() const {
887 // return the protection_domain from the mirror
888 return java_lang_Class::protection_domain(java_mirror());
889 }
890
891 objArrayOop InstanceKlass::signers() const {
892 // return the signers from the mirror
893 return java_lang_Class::signers(java_mirror());
894 }
895
896 oop InstanceKlass::init_lock() const {
897 // return the init lock from the mirror
898 oop lock = java_lang_Class::init_lock(java_mirror());
899 // Prevent reordering with any access of initialization state
900 OrderAccess::loadload();
901 assert(lock != nullptr || !is_not_initialized(), // initialized or in_error state
902 "only fully initialized state can have a null lock");
903 return lock;
904 }
905
906 // Set the initialization lock to null so the object can be GC'ed. Any racing
907 // threads to get this lock will see a null lock and will not lock.
908 // That's okay because they all check for initialized state after getting
909 // the lock and return. For preempted vthreads we keep the oop protected
910 // in the ObjectMonitor (see ObjectMonitor::set_object_strong()).
911 void InstanceKlass::fence_and_clear_init_lock() {
912 // make sure previous stores are all done, notably the init_state.
913 OrderAccess::storestore();
914 java_lang_Class::clear_init_lock(java_mirror());
915 assert(!is_not_initialized(), "class must be initialized now");
916 }
917
918 class PreemptableInitCall {
919 JavaThread* _thread;
920 bool _previous;
921 DEBUG_ONLY(InstanceKlass* _previous_klass;)
922 public:
923 PreemptableInitCall(JavaThread* thread, InstanceKlass* ik) : _thread(thread) {
924 _previous = thread->at_preemptable_init();
925 _thread->set_at_preemptable_init(true);
926 DEBUG_ONLY(_previous_klass = _thread->preempt_init_klass();)
927 DEBUG_ONLY(_thread->set_preempt_init_klass(ik));
928 }
929 ~PreemptableInitCall() {
930 _thread->set_at_preemptable_init(_previous);
931 DEBUG_ONLY(_thread->set_preempt_init_klass(_previous_klass));
932 }
933 };
934
935 void InstanceKlass::initialize_preemptable(TRAPS) {
936 if (this->should_be_initialized()) {
937 PreemptableInitCall pic(THREAD, this);
938 initialize_impl(THREAD);
939 } else {
940 assert(is_initialized(), "sanity check");
941 }
942 }
943
944 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
945 // process. The step comments refers to the procedure described in that section.
946 // Note: implementation moved to static method to expose the this pointer.
947 void InstanceKlass::initialize(TRAPS) {
948 if (this->should_be_initialized()) {
949 initialize_impl(CHECK);
950 // Note: at this point the class may be initialized
951 // OR it may be in the state of being initialized
952 // in case of recursive initialization!
953 } else {
954 assert(is_initialized(), "sanity check");
955 }
956 }
957
958 #ifdef ASSERT
959 void InstanceKlass::assert_no_clinit_will_run_for_aot_initialized_class() const {
960 assert(has_aot_initialized_mirror(), "must be");
961
962 InstanceKlass* s = super();
963 if (s != nullptr) {
964 DEBUG_ONLY(ResourceMark rm);
965 assert(s->is_initialized(), "super class %s of aot-inited class %s must have been initialized",
966 s->external_name(), external_name());
967 s->assert_no_clinit_will_run_for_aot_initialized_class();
968 }
969
970 Array<InstanceKlass*>* interfaces = local_interfaces();
971 int len = interfaces->length();
972 for (int i = 0; i < len; i++) {
973 InstanceKlass* intf = interfaces->at(i);
974 if (!intf->is_initialized()) {
975 ResourceMark rm;
976 // Note: an interface needs to be marked as is_initialized() only if
977 // - it has a <clinit>
978 // - it has declared a default method.
979 assert(!intf->interface_needs_clinit_execution_as_super(/*also_check_supers*/false),
980 "uninitialized super interface %s of aot-inited class %s must not have <clinit>",
981 intf->external_name(), external_name());
982 }
983 }
984 }
985 #endif
986
987 #if INCLUDE_CDS
988 void InstanceKlass::initialize_with_aot_initialized_mirror(TRAPS) {
989 assert(has_aot_initialized_mirror(), "must be");
990 assert(CDSConfig::is_loading_heap(), "must be");
991 assert(CDSConfig::is_using_aot_linked_classes(), "must be");
992 assert_no_clinit_will_run_for_aot_initialized_class();
993
994 if (is_initialized()) {
995 return;
996 }
997
998 if (is_runtime_setup_required()) {
999 // Need to take the slow path, which will call the runtimeSetup() function instead
1000 // of <clinit>
1001 initialize(CHECK);
1002 return;
1003 }
1004 if (log_is_enabled(Info, aot, init)) {
1005 ResourceMark rm;
1006 log_info(aot, init)("%s (aot-inited)", external_name());
1007 }
1008
1009 link_class(CHECK);
1010
1011 #ifdef ASSERT
1012 {
1013 Handle h_init_lock(THREAD, init_lock());
1014 ObjectLocker ol(h_init_lock, THREAD);
1015 assert(!is_initialized(), "sanity");
1016 assert(!is_being_initialized(), "sanity");
1017 assert(!is_in_error_state(), "sanity");
1018 }
1019 #endif
1020
1021 set_init_thread(THREAD);
1022 set_initialization_state_and_notify(fully_initialized, CHECK);
1023 }
1024 #endif
1025
1026 bool InstanceKlass::verify_code(TRAPS) {
1027 // 1) Verify the bytecodes
1028 return Verifier::verify(this, should_verify_class(), THREAD);
1029 }
1030
1031 static void load_classes_from_loadable_descriptors_attribute(InstanceKlass *ik, TRAPS) {
1032 ResourceMark rm(THREAD);
1033 if (ik->loadable_descriptors() != nullptr && PreloadClasses) {
1034 HandleMark hm(THREAD);
1035 for (int i = 0; i < ik->loadable_descriptors()->length(); i++) {
1036 Symbol* sig = ik->constants()->symbol_at(ik->loadable_descriptors()->at(i));
1037 if (!Signature::has_envelope(sig)) continue;
1038 TempNewSymbol class_name = Signature::strip_envelope(sig);
1039 if (class_name == ik->name()) continue;
1040 log_info(class, preload)("Preloading of class %s during linking of class %s "
1041 "because of the class is listed in the LoadableDescriptors attribute",
1042 sig->as_C_string(), ik->name()->as_C_string());
1043 oop loader = ik->class_loader();
1044 Klass* klass = SystemDictionary::resolve_or_null(class_name,
1045 Handle(THREAD, loader), THREAD);
1046 if (HAS_PENDING_EXCEPTION) {
1047 CLEAR_PENDING_EXCEPTION;
1048 }
1049 if (klass != nullptr) {
1050 log_info(class, preload)("Preloading of class %s during linking of class %s "
1051 "(cause: LoadableDescriptors attribute) succeeded",
1052 class_name->as_C_string(), ik->name()->as_C_string());
1053 if (!klass->is_inline_klass()) {
1054 // Non value class are allowed by the current spec, but it could be an indication
1055 // of an issue so let's log a warning
1056 log_info(class, preload)("Preloading of class %s during linking of class %s "
1057 "(cause: LoadableDescriptors attribute) but loaded class is not a value class",
1058 class_name->as_C_string(), ik->name()->as_C_string());
1059 }
1060 } else {
1061 log_info(class, preload)("Preloading of class %s during linking of class %s "
1062 "(cause: LoadableDescriptors attribute) failed",
1063 class_name->as_C_string(), ik->name()->as_C_string());
1064 }
1065 }
1066 }
1067 }
1068
1069 void InstanceKlass::link_class(TRAPS) {
1070 assert(is_loaded(), "must be loaded");
1071 if (!is_linked()) {
1072 link_class_impl(CHECK);
1073 }
1074 }
1075
1076 // Called to verify that a class can link during initialization, without
1077 // throwing a VerifyError.
1078 bool InstanceKlass::link_class_or_fail(TRAPS) {
1079 assert(is_loaded(), "must be loaded");
1080 if (!is_linked()) {
1081 link_class_impl(CHECK_false);
1082 }
1083 return is_linked();
1084 }
1085
1086 bool InstanceKlass::link_class_impl(TRAPS) {
1087 if (CDSConfig::is_dumping_static_archive() && SystemDictionaryShared::has_class_failed_verification(this)) {
1088 // This is for CDS static dump only -- we use the in_error_state to indicate that
1089 // the class has failed verification. Throwing the NoClassDefFoundError here is just
1090 // a convenient way to stop repeat attempts to verify the same (bad) class.
1091 //
1092 // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown
1093 // if we are executing Java code. This is not a problem for CDS dumping phase since
1094 // it doesn't execute any Java code.
1095 ResourceMark rm(THREAD);
1096 // Names are all known to be < 64k so we know this formatted message is not excessively large.
1097 Exceptions::fthrow(THREAD_AND_LOCATION,
1098 vmSymbols::java_lang_NoClassDefFoundError(),
1099 "Class %s, or one of its supertypes, failed class initialization",
1100 external_name());
1101 return false;
1102 }
1103 // return if already verified
1104 if (is_linked()) {
1105 return true;
1106 }
1107
1108 // Timing
1109 // timer handles recursion
1110 JavaThread* jt = THREAD;
1111
1112 // link super class before linking this class
1113 InstanceKlass* super_klass = super();
1114 if (super_klass != nullptr) {
1115 if (super_klass->is_interface()) { // check if super class is an interface
1116 ResourceMark rm(THREAD);
1117 // Names are all known to be < 64k so we know this formatted message is not excessively large.
1118 Exceptions::fthrow(
1119 THREAD_AND_LOCATION,
1120 vmSymbols::java_lang_IncompatibleClassChangeError(),
1121 "class %s has interface %s as super class",
1122 external_name(),
1123 super_klass->external_name()
1124 );
1125 return false;
1126 }
1127
1128 super_klass->link_class_impl(CHECK_false);
1129 }
1130
1131 // link all interfaces implemented by this class before linking this class
1132 Array<InstanceKlass*>* interfaces = local_interfaces();
1133 int num_interfaces = interfaces->length();
1134 for (int index = 0; index < num_interfaces; index++) {
1135 InstanceKlass* interk = interfaces->at(index);
1136 interk->link_class_impl(CHECK_false);
1137 }
1138
1139 if (Arguments::is_valhalla_enabled()) {
1140 // Aggressively preloading all classes from the LoadableDescriptors attribute
1141 // so inline classes can be scalarized in the calling conventions computed below
1142 load_classes_from_loadable_descriptors_attribute(this, THREAD);
1143 assert(!HAS_PENDING_EXCEPTION, "Shouldn't have pending exceptions from call above");
1144 }
1145
1146 // in case the class is linked in the process of linking its superclasses
1147 if (is_linked()) {
1148 return true;
1149 }
1150
1151 // trace only the link time for this klass that includes
1152 // the verification time
1153 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1154 ClassLoader::perf_class_link_selftime(),
1155 ClassLoader::perf_classes_linked(),
1156 jt->get_thread_stat()->perf_recursion_counts_addr(),
1157 jt->get_thread_stat()->perf_timers_addr(),
1158 PerfClassTraceTime::CLASS_LINK);
1159
1160 // verification & rewriting
1161 {
1162 HandleMark hm(THREAD);
1163 Handle h_init_lock(THREAD, init_lock());
1164 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1165 // Don't allow preemption if we link/initialize classes below,
1166 // since that would release this monitor while we are in the
1167 // middle of linking this class.
1168 NoPreemptMark npm(THREAD);
1169
1170 // rewritten will have been set if loader constraint error found
1171 // on an earlier link attempt
1172 // don't verify or rewrite if already rewritten
1173 //
1174
1175 if (!is_linked()) {
1176 if (!is_rewritten()) {
1177 if (in_aot_cache()) {
1178 assert(!verified_at_dump_time(), "must be");
1179 }
1180 {
1181 bool verify_ok = verify_code(THREAD);
1182 if (!verify_ok) {
1183 return false;
1184 }
1185 }
1186
1187 // Just in case a side-effect of verify linked this class already
1188 // (which can sometimes happen since the verifier loads classes
1189 // using custom class loaders, which are free to initialize things)
1190 if (is_linked()) {
1191 return true;
1192 }
1193
1194 // also sets rewritten
1195 rewrite_class(CHECK_false);
1196 } else if (in_aot_cache()) {
1197 SystemDictionaryShared::check_verification_constraints(this, CHECK_false);
1198 }
1199
1200 // relocate jsrs and link methods after they are all rewritten
1201 link_methods(CHECK_false);
1202
1203 // Initialize the vtable and interface table after
1204 // methods have been rewritten since rewrite may
1205 // fabricate new Method*s.
1206 // also does loader constraint checking
1207 //
1208 // initialize_vtable and initialize_itable need to be rerun
1209 // for a shared class if
1210 // 1) the class is loaded by custom class loader or
1211 // 2) the class is loaded by built-in class loader but failed to add archived loader constraints or
1212 // 3) the class was not verified during dump time
1213 bool need_init_table = true;
1214 if (in_aot_cache() && verified_at_dump_time() &&
1215 SystemDictionaryShared::check_linking_constraints(THREAD, this)) {
1216 need_init_table = false;
1217 }
1218 if (need_init_table) {
1219 vtable().initialize_vtable_and_check_constraints(CHECK_false);
1220 itable().initialize_itable_and_check_constraints(CHECK_false);
1221 }
1222 #ifdef ASSERT
1223 vtable().verify(tty, true);
1224 // In case itable verification is ever added.
1225 // itable().verify(tty, true);
1226 #endif
1227 if (Universe::is_fully_initialized()) {
1228 DeoptimizationScope deopt_scope;
1229 {
1230 // Now mark all code that assumes the class is not linked.
1231 // Set state under the Compile_lock also.
1232 MutexLocker ml(THREAD, Compile_lock);
1233
1234 set_init_state(linked);
1235 CodeCache::mark_dependents_on(&deopt_scope, this);
1236 }
1237 // Perform the deopt handshake outside Compile_lock.
1238 deopt_scope.deoptimize_marked();
1239 } else {
1240 set_init_state(linked);
1241 }
1242 if (JvmtiExport::should_post_class_prepare()) {
1243 JvmtiExport::post_class_prepare(THREAD, this);
1244 }
1245 }
1246 }
1247 return true;
1248 }
1249
1250 // Rewrite the byte codes of all of the methods of a class.
1251 // The rewriter must be called exactly once. Rewriting must happen after
1252 // verification but before the first method of the class is executed.
1253 void InstanceKlass::rewrite_class(TRAPS) {
1254 assert(is_loaded(), "must be loaded");
1255 if (is_rewritten()) {
1256 assert(in_aot_cache(), "rewriting an unshared class?");
1257 return;
1258 }
1259 Rewriter::rewrite(this, CHECK);
1260 set_rewritten();
1261 }
1262
1263 // Now relocate and link method entry points after class is rewritten.
1264 // This is outside is_rewritten flag. In case of an exception, it can be
1265 // executed more than once.
1266 void InstanceKlass::link_methods(TRAPS) {
1267 PerfTraceTime timer(ClassLoader::perf_ik_link_methods_time());
1268
1269 int len = methods()->length();
1270 for (int i = len-1; i >= 0; i--) {
1271 methodHandle m(THREAD, methods()->at(i));
1272
1273 // Set up method entry points for compiler and interpreter .
1274 m->link_method(m, CHECK);
1275 }
1276 }
1277
1278 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1279 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1280 assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1281 for (int i = 0; i < local_interfaces()->length(); ++i) {
1282 InstanceKlass* ik = local_interfaces()->at(i);
1283
1284 // Initialization is depth first search ie. we start with top of the inheritance tree
1285 // has_nonstatic_concrete_methods drives searching superinterfaces since it
1286 // means has_nonstatic_concrete_methods in its superinterface hierarchy
1287 if (ik->has_nonstatic_concrete_methods()) {
1288 ik->initialize_super_interfaces(CHECK);
1289 }
1290
1291 // Only initialize() interfaces that "declare" concrete methods.
1292 if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {
1293 ik->initialize(CHECK);
1294 }
1295 }
1296 }
1297
1298 using InitializationErrorTable = HashTable<const InstanceKlass*, OopHandle, 107, AnyObj::C_HEAP, mtClass>;
1299 static InitializationErrorTable* _initialization_error_table;
1300
1301 void InstanceKlass::add_initialization_error(JavaThread* current, Handle exception) {
1302 // Create the same exception with a message indicating the thread name,
1303 // and the StackTraceElements.
1304 Handle init_error = java_lang_Throwable::create_initialization_error(current, exception);
1305 ResourceMark rm(current);
1306 if (init_error.is_null()) {
1307 log_trace(class, init)("Unable to create the desired initialization error for class %s", external_name());
1308
1309 // We failed to create the new exception, most likely due to either out-of-memory or
1310 // a stackoverflow error. If the original exception was either of those then we save
1311 // the shared, pre-allocated, stackless, instance of that exception.
1312 if (exception->klass() == vmClasses::StackOverflowError_klass()) {
1313 log_debug(class, init)("Using shared StackOverflowError as initialization error for class %s", external_name());
1314 init_error = Handle(current, Universe::class_init_stack_overflow_error());
1315 } else if (exception->klass() == vmClasses::OutOfMemoryError_klass()) {
1316 log_debug(class, init)("Using shared OutOfMemoryError as initialization error for class %s", external_name());
1317 init_error = Handle(current, Universe::class_init_out_of_memory_error());
1318 } else {
1319 return;
1320 }
1321 }
1322
1323 MutexLocker ml(current, ClassInitError_lock);
1324 OopHandle elem = OopHandle(Universe::vm_global(), init_error());
1325 bool created;
1326 if (_initialization_error_table == nullptr) {
1327 _initialization_error_table = new (mtClass) InitializationErrorTable();
1328 }
1329 _initialization_error_table->put_if_absent(this, elem, &created);
1330 assert(created, "Initialization is single threaded");
1331 log_trace(class, init)("Initialization error added for class %s", external_name());
1332 }
1333
1334 oop InstanceKlass::get_initialization_error(JavaThread* current) {
1335 MutexLocker ml(current, ClassInitError_lock);
1336 if (_initialization_error_table == nullptr) {
1337 return nullptr;
1338 }
1339 OopHandle* h = _initialization_error_table->get(this);
1340 return (h != nullptr) ? h->resolve() : nullptr;
1341 }
1342
1343 // Need to remove entries for unloaded classes.
1344 void InstanceKlass::clean_initialization_error_table() {
1345 struct InitErrorTableCleaner {
1346 bool do_entry(const InstanceKlass* ik, OopHandle h) {
1347 if (!ik->is_loader_alive()) {
1348 h.release(Universe::vm_global());
1349 return true;
1350 } else {
1351 return false;
1352 }
1353 }
1354 };
1355
1356 assert_locked_or_safepoint(ClassInitError_lock);
1357 InitErrorTableCleaner cleaner;
1358 if (_initialization_error_table != nullptr) {
1359 _initialization_error_table->unlink(&cleaner);
1360 }
1361 }
1362
1363 class ThreadWaitingForClassInit : public StackObj {
1364 JavaThread* _thread;
1365 public:
1366 ThreadWaitingForClassInit(JavaThread* thread, InstanceKlass* ik) : _thread(thread) {
1367 _thread->set_class_to_be_initialized(ik);
1368 }
1369 ~ThreadWaitingForClassInit() {
1370 _thread->set_class_to_be_initialized(nullptr);
1371 }
1372 };
1373
1374 void InstanceKlass::initialize_impl(TRAPS) {
1375 HandleMark hm(THREAD);
1376
1377 // Make sure klass is linked (verified) before initialization
1378 // A class could already be verified, since it has been reflected upon.
1379 link_class(CHECK);
1380
1381 DTRACE_CLASSINIT_PROBE(required, -1);
1382
1383 bool wait = false;
1384
1385 JavaThread* jt = THREAD;
1386
1387 bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1388
1389 // refer to the JVM book page 47 for description of steps
1390 // Step 1
1391 {
1392 Handle h_init_lock(THREAD, init_lock());
1393 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE);
1394
1395 // Step 2
1396 // If we were to use wait() instead of waitInterruptibly() then
1397 // we might end up throwing IE from link/symbol resolution sites
1398 // that aren't expected to throw. This would wreak havoc. See 6320309.
1399 while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1400 if (debug_logging_enabled) {
1401 ResourceMark rm(jt);
1402 log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1403 jt->name(), external_name(), init_thread_name());
1404 }
1405 wait = true;
1406 ThreadWaitingForClassInit twcl(THREAD, this);
1407 ol.wait_uninterruptibly(CHECK_PREEMPTABLE);
1408 }
1409
1410 // Step 3
1411 if (is_being_initialized() && is_reentrant_initialization(jt)) {
1412 if (debug_logging_enabled) {
1413 ResourceMark rm(jt);
1414 log_debug(class, init)("Thread \"%s\" recursively initializing %s",
1415 jt->name(), external_name());
1416 }
1417 DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);
1418 return;
1419 }
1420
1421 // Step 4
1422 if (is_initialized()) {
1423 if (debug_logging_enabled) {
1424 ResourceMark rm(jt);
1425 log_debug(class, init)("Thread \"%s\" found %s already initialized",
1426 jt->name(), external_name());
1427 }
1428 DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);
1429 return;
1430 }
1431
1432 // Step 5
1433 if (is_in_error_state()) {
1434 if (debug_logging_enabled) {
1435 ResourceMark rm(jt);
1436 log_debug(class, init)("Thread \"%s\" found %s is in error state",
1437 jt->name(), external_name());
1438 }
1439
1440 DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
1441 ResourceMark rm(THREAD);
1442 Handle cause(THREAD, get_initialization_error(THREAD));
1443
1444 stringStream ss;
1445 ss.print("Could not initialize class %s", external_name());
1446 if (cause.is_null()) {
1447 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1448 } else {
1449 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1450 ss.as_string(), cause);
1451 }
1452 } else {
1453
1454 // Step 6
1455 set_init_state(being_initialized);
1456 set_init_thread(jt);
1457 if (debug_logging_enabled) {
1458 ResourceMark rm(jt);
1459 log_debug(class, init)("Thread \"%s\" is initializing %s",
1460 jt->name(), external_name());
1461 }
1462 }
1463 }
1464
1465 // Block preemption once we are the initializer thread. Unmounting now
1466 // would complicate the reentrant case (identity is platform thread).
1467 NoPreemptMark npm(THREAD);
1468
1469 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1470 if (is_inline_klass()) {
1471 InlineKlass* vk = InlineKlass::cast(this);
1472 if (vk->supports_nullable_layouts()) {
1473 oop val = vk->allocate_instance(THREAD);
1474 if (HAS_PENDING_EXCEPTION) {
1475 Handle e(THREAD, PENDING_EXCEPTION);
1476 CLEAR_PENDING_EXCEPTION;
1477 {
1478 EXCEPTION_MARK;
1479 add_initialization_error(THREAD, e);
1480 // Locks object, set state, and notify all waiting threads
1481 set_initialization_state_and_notify(initialization_error, THREAD);
1482 CLEAR_PENDING_EXCEPTION;
1483 }
1484 THROW_OOP(e());
1485 }
1486 vk->set_null_reset_value(val);
1487 }
1488 }
1489
1490 // Step 7
1491 // Next, if C is a class rather than an interface, initialize it's super class and super
1492 // interfaces.
1493 if (!is_interface()) {
1494 Klass* super_klass = super();
1495 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1496 super_klass->initialize(THREAD);
1497 }
1498 // If C implements any interface that declares a non-static, concrete method,
1499 // the initialization of C triggers initialization of its super interfaces.
1500 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1501 // having a superinterface that declares, non-static, concrete methods
1502 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1503 initialize_super_interfaces(THREAD);
1504 }
1505
1506 // If any exceptions, complete abruptly, throwing the same exception as above.
1507 if (HAS_PENDING_EXCEPTION) {
1508 Handle e(THREAD, PENDING_EXCEPTION);
1509 CLEAR_PENDING_EXCEPTION;
1510 {
1511 EXCEPTION_MARK;
1512 add_initialization_error(THREAD, e);
1513 // Locks object, set state, and notify all waiting threads
1514 set_initialization_state_and_notify(initialization_error, THREAD);
1515 CLEAR_PENDING_EXCEPTION;
1516 }
1517 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1518 THROW_OOP(e());
1519 }
1520 }
1521
1522 // Step 8
1523 {
1524 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1525 if (class_initializer() != nullptr) {
1526 // Timer includes any side effects of class initialization (resolution,
1527 // etc), but not recursive entry into call_class_initializer().
1528 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1529 ClassLoader::perf_class_init_selftime(),
1530 ClassLoader::perf_classes_inited(),
1531 jt->get_thread_stat()->perf_recursion_counts_addr(),
1532 jt->get_thread_stat()->perf_timers_addr(),
1533 PerfClassTraceTime::CLASS_CLINIT);
1534 call_class_initializer(THREAD);
1535 } else {
1536 // The elapsed time is so small it's not worth counting.
1537 if (UsePerfData) {
1538 ClassLoader::perf_classes_inited()->inc();
1539 }
1540 call_class_initializer(THREAD);
1541 }
1542
1543 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION) {
1544 // Step 9 also verifies that strict static fields have been initialized.
1545 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1546 // After <clinit>, bits must all be clear, or else we must throw an error.
1547 // This is an extremely fast check, so we won't bother with a timer.
1548 assert(fields_status() != nullptr, "");
1549 Symbol* bad_strict_static = nullptr;
1550 for (int index = 0; index < fields_status()->length(); index++) {
1551 // Very fast loop over single byte array looking for a set bit.
1552 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1553 // This strict static field has not been set by the class initializer.
1554 // Note that in the common no-error case, we read no field metadata.
1555 // We only unpack it when we need to report an error.
1556 FieldInfo fi = field(index);
1557 bad_strict_static = fi.name(constants());
1558 if (debug_logging_enabled) {
1559 ResourceMark rm(jt);
1560 const char* msg = format_strict_static_message(bad_strict_static);
1561 log_debug(class, init)("%s", msg);
1562 } else {
1563 // If we are not logging, do not bother to look for a second offense.
1564 break;
1565 }
1566 }
1567 }
1568 if (bad_strict_static != nullptr) {
1569 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1570 }
1571 }
1572 }
1573
1574 // Step 9
1575 if (!HAS_PENDING_EXCEPTION) {
1576 set_initialization_state_and_notify(fully_initialized, CHECK);
1577 DEBUG_ONLY(vtable().verify(tty, true);)
1578 CompilationPolicy::replay_training_at_init(this, THREAD);
1579 }
1580 else {
1581 // Step 10 and 11
1582 Handle e(THREAD, PENDING_EXCEPTION);
1583 CLEAR_PENDING_EXCEPTION;
1584 // JVMTI has already reported the pending exception
1585 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1586 JvmtiExport::clear_detected_exception(jt);
1587 {
1588 EXCEPTION_MARK;
1589 add_initialization_error(THREAD, e);
1590 set_initialization_state_and_notify(initialization_error, THREAD);
1591 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1592 // JVMTI has already reported the pending exception
1593 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1594 JvmtiExport::clear_detected_exception(jt);
1595 }
1596 DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1597 if (e->is_a(vmClasses::Error_klass())) {
1598 THROW_OOP(e());
1599 } else {
1600 JavaCallArguments args(e);
1601 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1602 vmSymbols::throwable_void_signature(),
1603 &args);
1604 }
1605 }
1606 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1607 }
1608
1609
1610 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1611 Handle h_init_lock(THREAD, init_lock());
1612 if (h_init_lock() != nullptr) {
1613 ObjectLocker ol(h_init_lock, THREAD);
1614 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1615 set_init_state(state);
1616 fence_and_clear_init_lock();
1617 ol.notify_all(CHECK);
1618 } else {
1619 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1620 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1621 set_init_state(state);
1622 }
1623 }
1624
1625 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1626 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1627 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1628 assert(debugfi.access_flags().is_strict(), "");
1629 assert(debugfi.access_flags().is_static(), "");
1630 FieldStatus& fs = *fields_status()->adr_at(field_index);
1631 LogTarget(Trace, class, init) lt;
1632 if (lt.is_enabled()) {
1633 ResourceMark rm(THREAD);
1634 LogStream ls(lt);
1635 FieldInfo fi = field(field_index);
1636 ls.print("notify %s %s %s%s ",
1637 external_name(), is_writing? "Write" : "Read",
1638 fs.is_strict_static_unset() ? "Unset" : "(set)",
1639 fs.is_strict_static_unread() ? "+Unread" : "");
1640 fi.print(&ls, constants());
1641 }
1642 if (fs.is_strict_static_unset()) {
1643 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1644 // If it is not set, there are only two reasonable things we can do here:
1645 // - mark it set if this is putstatic
1646 // - throw an error (Read-Before-Write) if this is getstatic
1647
1648 // The unset state is (or should be) transient, and observable only in one
1649 // thread during the execution of <clinit>. Something is wrong here as this
1650 // should not be possible
1651 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1652 if (is_writing) {
1653 // clear the "unset" bit, since the field is actually going to be written
1654 fs.update_strict_static_unset(false);
1655 } else {
1656 // throw an IllegalStateException, since we are reading before writing
1657 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1658 Symbol* bad_strict_static = field(field_index).name(constants());
1659 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1660 }
1661 } else {
1662 // Ensure no write after read for final strict statics
1663 FieldInfo fi = field(field_index);
1664 bool is_final = fi.access_flags().is_final();
1665 if (is_final) {
1666 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1667 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1668 if (is_writing && !fs.is_strict_static_unread()) {
1669 Symbol* bad_strict_static = fi.name(constants());
1670 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1671 } else if (!is_writing && fs.is_strict_static_unread()) {
1672 fs.update_strict_static_unread(false);
1673 }
1674 }
1675 }
1676 }
1677
1678 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1679 ResourceMark rm(THREAD);
1680 const char* msg = format_strict_static_message(field_name, when);
1681 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1682 }
1683
1684 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1685 stringStream ss;
1686 ss.print("Strict static \"%s\" %s %s",
1687 field_name->as_C_string(),
1688 when == nullptr ? "is unset in" : when,
1689 external_name());
1690 return ss.as_string();
1691 }
1692
1693 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1694 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1695 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1696 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1697
1698 DeoptimizationScope deopt_scope;
1699 {
1700 MutexLocker ml(current, Compile_lock);
1701
1702 set_init_state(InstanceKlass::loaded);
1703 // make sure init_state store is already done.
1704 // The compiler reads the hierarchy outside of the Compile_lock.
1705 // Access ordering is used to add to hierarchy.
1706
1707 // Link into hierarchy.
1708 append_to_sibling_list(); // add to superklass/sibling list
1709 process_interfaces(); // handle all "implements" declarations
1710
1711 // Now mark all code that depended on old class hierarchy.
1712 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1713 if (Universe::is_fully_initialized()) {
1714 CodeCache::mark_dependents_on(&deopt_scope, this);
1715 }
1716 }
1717 // Perform the deopt handshake outside Compile_lock.
1718 deopt_scope.deoptimize_marked();
1719 }
1720
1721
1722 InstanceKlass* InstanceKlass::implementor() const {
1723 InstanceKlass* volatile* ik = adr_implementor();
1724 if (ik == nullptr) {
1725 return nullptr;
1726 } else {
1727 // This load races with inserts, and therefore needs acquire.
1728 InstanceKlass* ikls = AtomicAccess::load_acquire(ik);
1729 if (ikls != nullptr && !ikls->is_loader_alive()) {
1730 return nullptr; // don't return unloaded class
1731 } else {
1732 return ikls;
1733 }
1734 }
1735 }
1736
1737
1738 void InstanceKlass::set_implementor(InstanceKlass* ik) {
1739 assert_locked_or_safepoint(Compile_lock);
1740 assert(is_interface(), "not interface");
1741 InstanceKlass* volatile* addr = adr_implementor();
1742 assert(addr != nullptr, "null addr");
1743 if (addr != nullptr) {
1744 AtomicAccess::release_store(addr, ik);
1745 }
1746 }
1747
1748 int InstanceKlass::nof_implementors() const {
1749 InstanceKlass* ik = implementor();
1750 if (ik == nullptr) {
1751 return 0;
1752 } else if (ik != this) {
1753 return 1;
1754 } else {
1755 return 2;
1756 }
1757 }
1758
1759 // The embedded _implementor field can only record one implementor.
1760 // When there are more than one implementors, the _implementor field
1761 // is set to the interface Klass* itself. Following are the possible
1762 // values for the _implementor field:
1763 // null - no implementor
1764 // implementor Klass* - one implementor
1765 // self - more than one implementor
1766 //
1767 // The _implementor field only exists for interfaces.
1768 void InstanceKlass::add_implementor(InstanceKlass* ik) {
1769 if (Universe::is_fully_initialized()) {
1770 assert_lock_strong(Compile_lock);
1771 }
1772 assert(is_interface(), "not interface");
1773 // Filter out my subinterfaces.
1774 // (Note: Interfaces are never on the subklass list.)
1775 if (ik->is_interface()) return;
1776
1777 // Filter out subclasses whose supers already implement me.
1778 // (Note: CHA must walk subclasses of direct implementors
1779 // in order to locate indirect implementors.)
1780 InstanceKlass* super_ik = ik->super();
1781 if (super_ik != nullptr && super_ik->implements_interface(this))
1782 // We only need to check one immediate superclass, since the
1783 // implements_interface query looks at transitive_interfaces.
1784 // Any supers of the super have the same (or fewer) transitive_interfaces.
1785 return;
1786
1787 InstanceKlass* iklass = implementor();
1788 if (iklass == nullptr) {
1789 set_implementor(ik);
1790 } else if (iklass != this && iklass != ik) {
1791 // There is already an implementor. Use itself as an indicator of
1792 // more than one implementors.
1793 set_implementor(this);
1794 }
1795
1796 // The implementor also implements the transitive_interfaces
1797 for (int index = 0; index < local_interfaces()->length(); index++) {
1798 local_interfaces()->at(index)->add_implementor(ik);
1799 }
1800 }
1801
1802 void InstanceKlass::init_implementor() {
1803 if (is_interface()) {
1804 set_implementor(nullptr);
1805 }
1806 }
1807
1808
1809 void InstanceKlass::process_interfaces() {
1810 // link this class into the implementors list of every interface it implements
1811 for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1812 assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1813 InstanceKlass* interf = local_interfaces()->at(i);
1814 assert(interf->is_interface(), "expected interface");
1815 interf->add_implementor(this);
1816 }
1817 }
1818
1819 bool InstanceKlass::can_be_primary_super_slow() const {
1820 if (is_interface())
1821 return false;
1822 else
1823 return Klass::can_be_primary_super_slow();
1824 }
1825
1826 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,
1827 Array<InstanceKlass*>* transitive_interfaces) {
1828 // The secondaries are the implemented interfaces.
1829 // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,
1830 // (but it's safe to do here because we won't write into _secondary_supers from this point on).
1831 Array<Klass*>* interfaces = (Array<Klass*>*)(address)transitive_interfaces;
1832 int num_secondaries = num_extra_slots + interfaces->length();
1833 if (num_secondaries == 0) {
1834 // Must share this for correct bootstrapping!
1835 set_secondary_supers(Universe::the_empty_klass_array(), Universe::the_empty_klass_bitmap());
1836 return nullptr;
1837 } else if (num_extra_slots == 0 && interfaces->length() <= 1) {
1838 // We will reuse the transitive interfaces list if we're certain
1839 // it's in hash order.
1840 uintx bitmap = compute_secondary_supers_bitmap(interfaces);
1841 set_secondary_supers(interfaces, bitmap);
1842 return nullptr;
1843 }
1844 // Copy transitive interfaces to a temporary growable array to be constructed
1845 // into the secondary super list with extra slots.
1846 GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1847 for (int i = 0; i < interfaces->length(); i++) {
1848 secondaries->push(interfaces->at(i));
1849 }
1850 return secondaries;
1851 }
1852
1853 bool InstanceKlass::implements_interface(Klass* k) const {
1854 if (this == k) return true;
1855 assert(k->is_interface(), "should be an interface class");
1856 for (int i = 0; i < transitive_interfaces()->length(); i++) {
1857 if (transitive_interfaces()->at(i) == k) {
1858 return true;
1859 }
1860 }
1861 return false;
1862 }
1863
1864 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1865 // Verify direct super interface
1866 if (this == k) return true;
1867 assert(k->is_interface(), "should be an interface class");
1868 for (int i = 0; i < local_interfaces()->length(); i++) {
1869 if (local_interfaces()->at(i) == k) {
1870 return true;
1871 }
1872 }
1873 return false;
1874 }
1875
1876 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1877 if (TraceFinalizerRegistration) {
1878 tty->print("Registered ");
1879 i->print_value_on(tty);
1880 tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1881 }
1882 instanceHandle h_i(THREAD, i);
1883 // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1884 JavaValue result(T_VOID);
1885 JavaCallArguments args(h_i);
1886 methodHandle mh(THREAD, Universe::finalizer_register_method());
1887 JavaCalls::call(&result, mh, &args, CHECK_NULL);
1888 MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1889 return h_i();
1890 }
1891
1892 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1893 assert(!is_abstract() && !is_interface(), "Should not create this object");
1894 size_t size = size_helper(); // Query before forming handle.
1895 return (instanceOop)Universe::heap()->obj_allocate(this, size, CHECK_NULL);
1896 }
1897
1898 instanceOop InstanceKlass::allocate_instance(oop java_class, TRAPS) {
1899 Klass* k = java_lang_Class::as_Klass(java_class);
1900 if (k == nullptr) {
1901 ResourceMark rm(THREAD);
1902 THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1903 }
1904 InstanceKlass* ik = cast(k);
1905 ik->check_valid_for_instantiation(false, CHECK_NULL);
1906 ik->initialize(CHECK_NULL);
1907 return ik->allocate_instance(THREAD);
1908 }
1909
1910 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1911 return instanceHandle(THREAD, allocate_instance(THREAD));
1912 }
1913
1914 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1915 if (is_interface() || is_abstract()) {
1916 ResourceMark rm(THREAD);
1917 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1918 : vmSymbols::java_lang_InstantiationException(), external_name());
1919 }
1920 if (this == vmClasses::Class_klass()) {
1921 ResourceMark rm(THREAD);
1922 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1923 : vmSymbols::java_lang_IllegalAccessException(), external_name());
1924 }
1925 }
1926
1927 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
1928 // Need load-acquire for lock-free read
1929 if (array_klasses_acquire() == nullptr) {
1930
1931 // Recursively lock array allocation
1932 RecursiveLocker rl(MultiArray_lock, THREAD);
1933
1934 // Check if another thread created the array klass while we were waiting for the lock.
1935 if (array_klasses() == nullptr) {
1936 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1937 // use 'release' to pair with lock-free load
1938 release_set_array_klasses(k);
1939 }
1940 }
1941
1942 // array_klasses() will always be set at this point
1943 ArrayKlass* ak = array_klasses();
1944 assert(ak != nullptr, "should be set");
1945 return ak->array_klass(n, THREAD);
1946 }
1947
1948 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
1949 // Need load-acquire for lock-free read
1950 ArrayKlass* ak = array_klasses_acquire();
1951 if (ak == nullptr) {
1952 return nullptr;
1953 } else {
1954 return ak->array_klass_or_null(n);
1955 }
1956 }
1957
1958 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
1959 return array_klass(1, THREAD);
1960 }
1961
1962 ArrayKlass* InstanceKlass::array_klass_or_null() {
1963 return array_klass_or_null(1);
1964 }
1965
1966 static int call_class_initializer_counter = 0; // for debugging
1967
1968 Method* InstanceKlass::class_initializer() const {
1969 Method* clinit = find_method(
1970 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1971 if (clinit != nullptr && clinit->is_class_initializer()) {
1972 return clinit;
1973 }
1974 return nullptr;
1975 }
1976
1977 void InstanceKlass::call_class_initializer(TRAPS) {
1978 if (ReplayCompiles &&
1979 (ReplaySuppressInitializers == 1 ||
1980 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
1981 // Hide the existence of the initializer for the purpose of replaying the compile
1982 return;
1983 }
1984
1985 #if INCLUDE_CDS
1986 // This is needed to ensure the consistency of the archived heap objects.
1987 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
1988 AOTClassInitializer::call_runtime_setup(THREAD, this);
1989 return;
1990 } else if (has_archived_enum_objs()) {
1991 assert(in_aot_cache(), "must be");
1992 bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
1993 if (initialized) {
1994 return;
1995 }
1996 }
1997 #endif
1998
1999 methodHandle h_method(THREAD, class_initializer());
2000 assert(!is_initialized(), "we cannot initialize twice");
2001 LogTarget(Info, class, init) lt;
2002 if (lt.is_enabled()) {
2003 ResourceMark rm(THREAD);
2004 LogStream ls(lt);
2005 ls.print("%d Initializing ", call_class_initializer_counter++);
2006 name()->print_value_on(&ls);
2007 ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
2008 h_method() == nullptr ? "(no method)" : "", p2i(this),
2009 THREAD->name());
2010 }
2011 if (h_method() != nullptr) {
2012 ThreadInClassInitializer ticl(THREAD, this); // Track class being initialized
2013 JavaCallArguments args; // No arguments
2014 JavaValue result(T_VOID);
2015 JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
2016 }
2017 }
2018
2019 // If a class that implements this interface is initialized, is the JVM required
2020 // to first execute a <clinit> method declared in this interface,
2021 // or (if also_check_supers==true) any of the super types of this interface?
2022 //
2023 // JVMS 5.5. Initialization, step 7: Next, if C is a class rather than
2024 // an interface, then let SC be its superclass and let SI1, ..., SIn
2025 // be all superinterfaces of C (whether direct or indirect) that
2026 // declare at least one non-abstract, non-static method.
2027 //
2028 // So when an interface is initialized, it does not look at its
2029 // supers. But a proper class will ensure that all of its supers have
2030 // run their <clinit> methods, except that it disregards interfaces
2031 // that lack a non-static concrete method (i.e., a default method).
2032 // Therefore, you should probably call this method only when the
2033 // current class is a super of some proper class, not an interface.
2034 bool InstanceKlass::interface_needs_clinit_execution_as_super(bool also_check_supers) const {
2035 assert(is_interface(), "must be");
2036
2037 if (!has_nonstatic_concrete_methods()) {
2038 // quick check: no nonstatic concrete methods are declared by this or any super interfaces
2039 return false;
2040 }
2041
2042 // JVMS 5.5. Initialization
2043 // ...If C is an interface that declares a non-abstract,
2044 // non-static method, the initialization of a class that
2045 // implements C directly or indirectly.
2046 if (declares_nonstatic_concrete_methods() && class_initializer() != nullptr) {
2047 return true;
2048 }
2049 if (also_check_supers) {
2050 Array<InstanceKlass*>* all_ifs = transitive_interfaces();
2051 for (int i = 0; i < all_ifs->length(); ++i) {
2052 InstanceKlass* super_intf = all_ifs->at(i);
2053 if (super_intf->declares_nonstatic_concrete_methods() && super_intf->class_initializer() != nullptr) {
2054 return true;
2055 }
2056 }
2057 }
2058 return false;
2059 }
2060
2061 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2062 InterpreterOopMap* entry_for) {
2063 // Lazily create the _oop_map_cache at first request.
2064 // Load_acquire is needed to safely get instance published with CAS by another thread.
2065 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
2066 if (oop_map_cache == nullptr) {
2067 // Try to install new instance atomically.
2068 oop_map_cache = new OopMapCache();
2069 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2070 if (other != nullptr) {
2071 // Someone else managed to install before us, ditch local copy and use the existing one.
2072 delete oop_map_cache;
2073 oop_map_cache = other;
2074 }
2075 }
2076 // _oop_map_cache is constant after init; lookup below does its own locking.
2077 oop_map_cache->lookup(method, bci, entry_for);
2078 }
2079
2080
2081 FieldInfo InstanceKlass::field(int index) const {
2082 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2083 if (fs.index() == index) {
2084 return fs.to_FieldInfo();
2085 }
2086 }
2087 fatal("Field not found");
2088 return FieldInfo();
2089 }
2090
2091 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2092 JavaFieldStream fs(this);
2093 if (fs.lookup(name, sig)) {
2094 assert(fs.name() == name, "name must match");
2095 assert(fs.signature() == sig, "signature must match");
2096 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2097 return true;
2098 }
2099 return false;
2100 }
2101
2102
2103 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2104 const int n = local_interfaces()->length();
2105 for (int i = 0; i < n; i++) {
2106 InstanceKlass* intf1 = local_interfaces()->at(i);
2107 assert(intf1->is_interface(), "just checking type");
2108 // search for field in current interface
2109 if (intf1->find_local_field(name, sig, fd)) {
2110 assert(fd->is_static(), "interface field must be static");
2111 return intf1;
2112 }
2113 // search for field in direct superinterfaces
2114 Klass* intf2 = intf1->find_interface_field(name, sig, fd);
2115 if (intf2 != nullptr) return intf2;
2116 }
2117 // otherwise field lookup fails
2118 return nullptr;
2119 }
2120
2121
2122 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2123 // search order according to newest JVM spec (5.4.3.2, p.167).
2124 // 1) search for field in current klass
2125 if (find_local_field(name, sig, fd)) {
2126 return const_cast<InstanceKlass*>(this);
2127 }
2128 // 2) search for field recursively in direct superinterfaces
2129 { Klass* intf = find_interface_field(name, sig, fd);
2130 if (intf != nullptr) return intf;
2131 }
2132 // 3) apply field lookup recursively if superclass exists
2133 { InstanceKlass* supr = super();
2134 if (supr != nullptr) return supr->find_field(name, sig, fd);
2135 }
2136 // 4) otherwise field lookup fails
2137 return nullptr;
2138 }
2139
2140
2141 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2142 // search order according to newest JVM spec (5.4.3.2, p.167).
2143 // 1) search for field in current klass
2144 if (find_local_field(name, sig, fd)) {
2145 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2146 }
2147 // 2) search for field recursively in direct superinterfaces
2148 if (is_static) {
2149 Klass* intf = find_interface_field(name, sig, fd);
2150 if (intf != nullptr) return intf;
2151 }
2152 // 3) apply field lookup recursively if superclass exists
2153 { InstanceKlass* supr = super();
2154 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
2155 }
2156 // 4) otherwise field lookup fails
2157 return nullptr;
2158 }
2159
2160 bool InstanceKlass::contains_field_offset(int offset) {
2161 if (this->is_inline_klass()) {
2162 InlineKlass* vk = InlineKlass::cast(this);
2163 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2164 } else {
2165 fieldDescriptor fd;
2166 return find_field_from_offset(offset, false, &fd);
2167 }
2168 }
2169
2170 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2171 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2172 if (fs.offset() == offset) {
2173 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2174 if (fd->is_static() == is_static) return true;
2175 }
2176 }
2177 return false;
2178 }
2179
2180
2181 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2182 const InstanceKlass* klass = this;
2183 while (klass != nullptr) {
2184 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
2185 return true;
2186 }
2187 klass = klass->super();
2188 }
2189 return false;
2190 }
2191
2192
2193 void InstanceKlass::methods_do(void f(Method* method)) {
2194 // Methods aren't stable until they are loaded. This can be read outside
2195 // a lock through the ClassLoaderData for profiling
2196 // Redefined scratch classes are on the list and need to be cleaned
2197 if (!is_loaded() && !is_scratch_class()) {
2198 return;
2199 }
2200
2201 int len = methods()->length();
2202 for (int index = 0; index < len; index++) {
2203 Method* m = methods()->at(index);
2204 assert(m->is_method(), "must be method");
2205 f(m);
2206 }
2207 }
2208
2209
2210 void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
2211 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2212 if (fs.access_flags().is_static()) {
2213 fieldDescriptor& fd = fs.field_descriptor();
2214 cl->do_field(&fd);
2215 }
2216 }
2217 }
2218
2219
2220 void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
2221 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2222 if (fs.access_flags().is_static()) {
2223 fieldDescriptor& fd = fs.field_descriptor();
2224 f(&fd, mirror, CHECK);
2225 }
2226 }
2227 }
2228
2229 void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
2230 InstanceKlass* super = this->super();
2231 if (super != nullptr) {
2232 super->do_nonstatic_fields(cl);
2233 }
2234 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2235 fieldDescriptor& fd = fs.field_descriptor();
2236 if (!fd.is_static()) {
2237 cl->do_field(&fd);
2238 }
2239 }
2240 }
2241
2242 static int compare_fields_by_offset(FieldInfo* a, FieldInfo* b) {
2243 return a->offset() - b->offset();
2244 }
2245
2246 void InstanceKlass::print_nonstatic_fields(FieldClosure* cl) {
2247 InstanceKlass* super = this->super();
2248 if (super != nullptr) {
2249 super->print_nonstatic_fields(cl);
2250 }
2251 ResourceMark rm;
2252 // In DebugInfo nonstatic fields are sorted by offset.
2253 GrowableArray<FieldInfo> fields_sorted;
2254 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2255 if (!fs.access_flags().is_static()) {
2256 fields_sorted.push(fs.to_FieldInfo());
2257 }
2258 }
2259 int length = fields_sorted.length();
2260 if (length > 0) {
2261 fields_sorted.sort(compare_fields_by_offset);
2262 fieldDescriptor fd;
2263 for (int i = 0; i < length; i++) {
2264 fd.reinitialize(this, fields_sorted.at(i));
2265 assert(!fd.is_static() && fd.offset() == checked_cast<int>(fields_sorted.at(i).offset()), "only nonstatic fields");
2266 cl->do_field(&fd);
2267 }
2268 }
2269 }
2270
2271 #ifdef ASSERT
2272 static int linear_search(const Array<Method*>* methods,
2273 const Symbol* name,
2274 const Symbol* signature) {
2275 const int len = methods->length();
2276 for (int index = 0; index < len; index++) {
2277 const Method* const m = methods->at(index);
2278 assert(m->is_method(), "must be method");
2279 if (m->signature() == signature && m->name() == name) {
2280 return index;
2281 }
2282 }
2283 return -1;
2284 }
2285 #endif
2286
2287 bool InstanceKlass::_disable_method_binary_search = false;
2288
2289 NOINLINE int linear_search(const Array<Method*>* methods, const Symbol* name) {
2290 int len = methods->length();
2291 int l = 0;
2292 int h = len - 1;
2293 while (l <= h) {
2294 Method* m = methods->at(l);
2295 if (m->name() == name) {
2296 return l;
2297 }
2298 l++;
2299 }
2300 return -1;
2301 }
2302
2303 inline int InstanceKlass::quick_search(const Array<Method*>* methods, const Symbol* name) {
2304 if (_disable_method_binary_search) {
2305 assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
2306 // At the final stage of dynamic dumping, the methods array may not be sorted
2307 // by ascending addresses of their names, so we can't use binary search anymore.
2308 // However, methods with the same name are still laid out consecutively inside the
2309 // methods array, so let's look for the first one that matches.
2310 return linear_search(methods, name);
2311 }
2312
2313 int len = methods->length();
2314 int l = 0;
2315 int h = len - 1;
2316
2317 // methods are sorted by ascending addresses of their names, so do binary search
2318 while (l <= h) {
2319 int mid = (l + h) >> 1;
2320 Method* m = methods->at(mid);
2321 assert(m->is_method(), "must be method");
2322 int res = m->name()->fast_compare(name);
2323 if (res == 0) {
2324 return mid;
2325 } else if (res < 0) {
2326 l = mid + 1;
2327 } else {
2328 h = mid - 1;
2329 }
2330 }
2331 return -1;
2332 }
2333
2334 // find_method looks up the name/signature in the local methods array
2335 Method* InstanceKlass::find_method(const Symbol* name,
2336 const Symbol* signature) const {
2337 return find_method_impl(name, signature,
2338 OverpassLookupMode::find,
2339 StaticLookupMode::find,
2340 PrivateLookupMode::find);
2341 }
2342
2343 Method* InstanceKlass::find_method_impl(const Symbol* name,
2344 const Symbol* signature,
2345 OverpassLookupMode overpass_mode,
2346 StaticLookupMode static_mode,
2347 PrivateLookupMode private_mode) const {
2348 return InstanceKlass::find_method_impl(methods(),
2349 name,
2350 signature,
2351 overpass_mode,
2352 static_mode,
2353 private_mode);
2354 }
2355
2356 // find_instance_method looks up the name/signature in the local methods array
2357 // and skips over static methods
2358 Method* InstanceKlass::find_instance_method(const Array<Method*>* methods,
2359 const Symbol* name,
2360 const Symbol* signature,
2361 PrivateLookupMode private_mode) {
2362 Method* const meth = InstanceKlass::find_method_impl(methods,
2363 name,
2364 signature,
2365 OverpassLookupMode::find,
2366 StaticLookupMode::skip,
2367 private_mode);
2368 assert(((meth == nullptr) || !meth->is_static()),
2369 "find_instance_method should have skipped statics");
2370 return meth;
2371 }
2372
2373 // find_instance_method looks up the name/signature in the local methods array
2374 // and skips over static methods
2375 Method* InstanceKlass::find_instance_method(const Symbol* name,
2376 const Symbol* signature,
2377 PrivateLookupMode private_mode) const {
2378 return InstanceKlass::find_instance_method(methods(), name, signature, private_mode);
2379 }
2380
2381 // Find looks up the name/signature in the local methods array
2382 // and filters on the overpass, static and private flags
2383 // This returns the first one found
2384 // note that the local methods array can have up to one overpass, one static
2385 // and one instance (private or not) with the same name/signature
2386 Method* InstanceKlass::find_local_method(const Symbol* name,
2387 const Symbol* signature,
2388 OverpassLookupMode overpass_mode,
2389 StaticLookupMode static_mode,
2390 PrivateLookupMode private_mode) const {
2391 return InstanceKlass::find_method_impl(methods(),
2392 name,
2393 signature,
2394 overpass_mode,
2395 static_mode,
2396 private_mode);
2397 }
2398
2399 // Find looks up the name/signature in the local methods array
2400 // and filters on the overpass, static and private flags
2401 // This returns the first one found
2402 // note that the local methods array can have up to one overpass, one static
2403 // and one instance (private or not) with the same name/signature
2404 Method* InstanceKlass::find_local_method(const Array<Method*>* methods,
2405 const Symbol* name,
2406 const Symbol* signature,
2407 OverpassLookupMode overpass_mode,
2408 StaticLookupMode static_mode,
2409 PrivateLookupMode private_mode) {
2410 return InstanceKlass::find_method_impl(methods,
2411 name,
2412 signature,
2413 overpass_mode,
2414 static_mode,
2415 private_mode);
2416 }
2417
2418 Method* InstanceKlass::find_method(const Array<Method*>* methods,
2419 const Symbol* name,
2420 const Symbol* signature) {
2421 return InstanceKlass::find_method_impl(methods,
2422 name,
2423 signature,
2424 OverpassLookupMode::find,
2425 StaticLookupMode::find,
2426 PrivateLookupMode::find);
2427 }
2428
2429 Method* InstanceKlass::find_method_impl(const Array<Method*>* methods,
2430 const Symbol* name,
2431 const Symbol* signature,
2432 OverpassLookupMode overpass_mode,
2433 StaticLookupMode static_mode,
2434 PrivateLookupMode private_mode) {
2435 int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
2436 return hit >= 0 ? methods->at(hit): nullptr;
2437 }
2438
2439 // true if method matches signature and conforms to skipping_X conditions.
2440 static bool method_matches(const Method* m,
2441 const Symbol* signature,
2442 bool skipping_overpass,
2443 bool skipping_static,
2444 bool skipping_private) {
2445 return ((m->signature() == signature) &&
2446 (!skipping_overpass || !m->is_overpass()) &&
2447 (!skipping_static || !m->is_static()) &&
2448 (!skipping_private || !m->is_private()));
2449 }
2450
2451 // Used directly for default_methods to find the index into the
2452 // default_vtable_indices, and indirectly by find_method
2453 // find_method_index looks in the local methods array to return the index
2454 // of the matching name/signature. If, overpass methods are being ignored,
2455 // the search continues to find a potential non-overpass match. This capability
2456 // is important during method resolution to prefer a static method, for example,
2457 // over an overpass method.
2458 // There is the possibility in any _method's array to have the same name/signature
2459 // for a static method, an overpass method and a local instance method
2460 // To correctly catch a given method, the search criteria may need
2461 // to explicitly skip the other two. For local instance methods, it
2462 // is often necessary to skip private methods
2463 int InstanceKlass::find_method_index(const Array<Method*>* methods,
2464 const Symbol* name,
2465 const Symbol* signature,
2466 OverpassLookupMode overpass_mode,
2467 StaticLookupMode static_mode,
2468 PrivateLookupMode private_mode) {
2469 const bool skipping_overpass = (overpass_mode == OverpassLookupMode::skip);
2470 const bool skipping_static = (static_mode == StaticLookupMode::skip);
2471 const bool skipping_private = (private_mode == PrivateLookupMode::skip);
2472 const int hit = quick_search(methods, name);
2473 if (hit != -1) {
2474 const Method* const m = methods->at(hit);
2475
2476 // Do linear search to find matching signature. First, quick check
2477 // for common case, ignoring overpasses if requested.
2478 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2479 return hit;
2480 }
2481
2482 // search downwards through overloaded methods
2483 int i;
2484 for (i = hit - 1; i >= 0; --i) {
2485 const Method* const m = methods->at(i);
2486 assert(m->is_method(), "must be method");
2487 if (m->name() != name) {
2488 break;
2489 }
2490 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2491 return i;
2492 }
2493 }
2494 // search upwards
2495 for (i = hit + 1; i < methods->length(); ++i) {
2496 const Method* const m = methods->at(i);
2497 assert(m->is_method(), "must be method");
2498 if (m->name() != name) {
2499 break;
2500 }
2501 if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) {
2502 return i;
2503 }
2504 }
2505 // not found
2506 #ifdef ASSERT
2507 const int index = (skipping_overpass || skipping_static || skipping_private) ? -1 :
2508 linear_search(methods, name, signature);
2509 assert(-1 == index, "binary search should have found entry %d", index);
2510 #endif
2511 }
2512 return -1;
2513 }
2514
2515 int InstanceKlass::find_method_by_name(const Symbol* name, int* end) const {
2516 return find_method_by_name(methods(), name, end);
2517 }
2518
2519 int InstanceKlass::find_method_by_name(const Array<Method*>* methods,
2520 const Symbol* name,
2521 int* end_ptr) {
2522 assert(end_ptr != nullptr, "just checking");
2523 int start = quick_search(methods, name);
2524 int end = start + 1;
2525 if (start != -1) {
2526 while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
2527 while (end < methods->length() && (methods->at(end))->name() == name) ++end;
2528 *end_ptr = end;
2529 return start;
2530 }
2531 return -1;
2532 }
2533
2534 // uncached_lookup_method searches both the local class methods array and all
2535 // superclasses methods arrays, skipping any overpass methods in superclasses,
2536 // and possibly skipping private methods.
2537 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
2538 const Symbol* signature,
2539 OverpassLookupMode overpass_mode,
2540 PrivateLookupMode private_mode) const {
2541 OverpassLookupMode overpass_local_mode = overpass_mode;
2542 const InstanceKlass* klass = this;
2543 while (klass != nullptr) {
2544 Method* const method = klass->find_method_impl(name,
2545 signature,
2546 overpass_local_mode,
2547 StaticLookupMode::find,
2548 private_mode);
2549 if (method != nullptr) {
2550 return method;
2551 }
2552 if (name == vmSymbols::object_initializer_name()) {
2553 break; // <init> is never inherited
2554 }
2555 klass = klass->super();
2556 overpass_local_mode = OverpassLookupMode::skip; // Always ignore overpass methods in superclasses
2557 }
2558 return nullptr;
2559 }
2560
2561 #ifdef ASSERT
2562 // search through class hierarchy and return true if this class or
2563 // one of the superclasses was redefined
2564 bool InstanceKlass::has_redefined_this_or_super() const {
2565 const InstanceKlass* klass = this;
2566 while (klass != nullptr) {
2567 if (klass->has_been_redefined()) {
2568 return true;
2569 }
2570 klass = klass->super();
2571 }
2572 return false;
2573 }
2574 #endif
2575
2576 // lookup a method in the default methods list then in all transitive interfaces
2577 // Do NOT return private or static methods
2578 Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
2579 Symbol* signature) const {
2580 Method* m = nullptr;
2581 if (default_methods() != nullptr) {
2582 m = find_method(default_methods(), name, signature);
2583 }
2584 // Look up interfaces
2585 if (m == nullptr) {
2586 m = lookup_method_in_all_interfaces(name, signature, DefaultsLookupMode::find);
2587 }
2588 return m;
2589 }
2590
2591 // lookup a method in all the interfaces that this class implements
2592 // Do NOT return private or static methods, new in JDK8 which are not externally visible
2593 // They should only be found in the initial InterfaceMethodRef
2594 Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
2595 Symbol* signature,
2596 DefaultsLookupMode defaults_mode) const {
2597 Array<InstanceKlass*>* all_ifs = transitive_interfaces();
2598 int num_ifs = all_ifs->length();
2599 InstanceKlass *ik = nullptr;
2600 for (int i = 0; i < num_ifs; i++) {
2601 ik = all_ifs->at(i);
2602 Method* m = ik->lookup_method(name, signature);
2603 if (m != nullptr && m->is_public() && !m->is_static() &&
2604 ((defaults_mode != DefaultsLookupMode::skip) || !m->is_default_method())) {
2605 return m;
2606 }
2607 }
2608 return nullptr;
2609 }
2610
2611 PrintClassClosure::PrintClassClosure(outputStream* st, bool verbose)
2612 :_st(st), _verbose(verbose) {
2613 ResourceMark rm;
2614 _st->print("%-18s ", "KlassAddr");
2615 _st->print("%-4s ", "Size");
2616 _st->print("%-20s ", "State");
2617 _st->print("%-7s ", "Flags");
2618 _st->print("%-5s ", "ClassName");
2619 _st->cr();
2620 }
2621
2622 void PrintClassClosure::do_klass(Klass* k) {
2623 ResourceMark rm;
2624 // klass pointer
2625 _st->print(PTR_FORMAT " ", p2i(k));
2626 // klass size
2627 _st->print("%4d ", k->size());
2628 // initialization state
2629 if (k->is_instance_klass()) {
2630 _st->print("%-20s ",InstanceKlass::cast(k)->init_state_name());
2631 } else {
2632 _st->print("%-20s ","");
2633 }
2634 // misc flags(Changes should synced with ClassesDCmd::ClassesDCmd help doc)
2635 char buf[10];
2636 int i = 0;
2637 if (k->has_finalizer()) buf[i++] = 'F';
2638 if (k->is_instance_klass()) {
2639 InstanceKlass* ik = InstanceKlass::cast(k);
2640 if (ik->has_final_method()) buf[i++] = 'f';
2641 if (ik->is_rewritten()) buf[i++] = 'W';
2642 if (ik->is_contended()) buf[i++] = 'C';
2643 if (ik->has_been_redefined()) buf[i++] = 'R';
2644 if (ik->in_aot_cache()) buf[i++] = 'S';
2645 }
2646 buf[i++] = '\0';
2647 _st->print("%-7s ", buf);
2648 // klass name
2649 _st->print("%-5s ", k->external_name());
2650 // end
2651 _st->cr();
2652 if (_verbose) {
2653 k->print_on(_st);
2654 }
2655 }
2656
2657 /* jni_id_for for jfieldIds only */
2658 JNIid* InstanceKlass::jni_id_for(int offset) {
2659 MutexLocker ml(JfieldIdCreation_lock);
2660 JNIid* probe = jni_ids() == nullptr ? nullptr : jni_ids()->find(offset);
2661 if (probe == nullptr) {
2662 // Allocate new static field identifier
2663 probe = new JNIid(this, offset, jni_ids());
2664 set_jni_ids(probe);
2665 }
2666 return probe;
2667 }
2668
2669 u2 InstanceKlass::enclosing_method_data(int offset) const {
2670 const Array<jushort>* const inner_class_list = inner_classes();
2671 if (inner_class_list == nullptr) {
2672 return 0;
2673 }
2674 const int length = inner_class_list->length();
2675 if (length % inner_class_next_offset == 0) {
2676 return 0;
2677 }
2678 const int index = length - enclosing_method_attribute_size;
2679 assert(offset < enclosing_method_attribute_size, "invalid offset");
2680 return inner_class_list->at(index + offset);
2681 }
2682
2683 void InstanceKlass::set_enclosing_method_indices(u2 class_index,
2684 u2 method_index) {
2685 Array<jushort>* inner_class_list = inner_classes();
2686 assert (inner_class_list != nullptr, "_inner_classes list is not set up");
2687 int length = inner_class_list->length();
2688 if (length % inner_class_next_offset == enclosing_method_attribute_size) {
2689 int index = length - enclosing_method_attribute_size;
2690 inner_class_list->at_put(
2691 index + enclosing_method_class_index_offset, class_index);
2692 inner_class_list->at_put(
2693 index + enclosing_method_method_index_offset, method_index);
2694 }
2695 }
2696
2697 jmethodID InstanceKlass::update_jmethod_id(jmethodID* jmeths, Method* method, int idnum) {
2698 if (method->is_old() && !method->is_obsolete()) {
2699 // If the method passed in is old (but not obsolete), use the current version.
2700 method = method_with_idnum((int)idnum);
2701 assert(method != nullptr, "old and but not obsolete, so should exist");
2702 }
2703 jmethodID new_id = Method::make_jmethod_id(class_loader_data(), method);
2704 AtomicAccess::release_store(&jmeths[idnum + 1], new_id);
2705 return new_id;
2706 }
2707
2708 // Allocate the jmethodID cache.
2709 static jmethodID* create_jmethod_id_cache(size_t size) {
2710 jmethodID* jmeths = NEW_C_HEAP_ARRAY(jmethodID, size + 1, mtClass);
2711 memset(jmeths, 0, (size + 1) * sizeof(jmethodID));
2712 // cache size is stored in element[0], other elements offset by one
2713 jmeths[0] = (jmethodID)size;
2714 return jmeths;
2715 }
2716
2717 // When reading outside a lock, use this.
2718 jmethodID* InstanceKlass::methods_jmethod_ids_acquire() const {
2719 return AtomicAccess::load_acquire(&_methods_jmethod_ids);
2720 }
2721
2722 void InstanceKlass::release_set_methods_jmethod_ids(jmethodID* jmeths) {
2723 AtomicAccess::release_store(&_methods_jmethod_ids, jmeths);
2724 }
2725
2726 // Lookup or create a jmethodID.
2727 jmethodID InstanceKlass::get_jmethod_id(Method* method) {
2728 int idnum = method->method_idnum();
2729 jmethodID* jmeths = methods_jmethod_ids_acquire();
2730
2731 // We use a double-check locking idiom here because this cache is
2732 // performance sensitive. In the normal system, this cache only
2733 // transitions from null to non-null which is safe because we use
2734 // release_set_methods_jmethod_ids() to advertise the new cache.
2735 // A partially constructed cache should never be seen by a racing
2736 // thread. We also use release_store() to save a new jmethodID
2737 // in the cache so a partially constructed jmethodID should never be
2738 // seen either. Cache reads of existing jmethodIDs proceed without a
2739 // lock, but cache writes of a new jmethodID requires uniqueness and
2740 // creation of the cache itself requires no leaks so a lock is
2741 // acquired in those two cases.
2742 //
2743 // If the RedefineClasses() API has been used, then this cache grows
2744 // in the redefinition safepoint.
2745
2746 if (jmeths == nullptr) {
2747 MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2748 jmeths = _methods_jmethod_ids;
2749 // Still null?
2750 if (jmeths == nullptr) {
2751 size_t size = idnum_allocated_count();
2752 assert(size > (size_t)idnum, "should already have space");
2753 jmeths = create_jmethod_id_cache(size);
2754 jmethodID new_id = update_jmethod_id(jmeths, method, idnum);
2755
2756 // publish jmeths
2757 release_set_methods_jmethod_ids(jmeths);
2758 return new_id;
2759 }
2760 }
2761
2762 jmethodID id = AtomicAccess::load_acquire(&jmeths[idnum + 1]);
2763 if (id == nullptr) {
2764 MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2765 id = jmeths[idnum + 1];
2766 // Still null?
2767 if (id == nullptr) {
2768 return update_jmethod_id(jmeths, method, idnum);
2769 }
2770 }
2771 return id;
2772 }
2773
2774 void InstanceKlass::update_methods_jmethod_cache() {
2775 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
2776 jmethodID* cache = _methods_jmethod_ids;
2777 if (cache != nullptr) {
2778 size_t size = idnum_allocated_count();
2779 size_t old_size = (size_t)cache[0];
2780 if (old_size < size + 1) {
2781 // Allocate a larger one and copy entries to the new one.
2782 // They've already been updated to point to new methods where applicable (i.e., not obsolete).
2783 jmethodID* new_cache = create_jmethod_id_cache(size);
2784
2785 for (int i = 1; i <= (int)old_size; i++) {
2786 new_cache[i] = cache[i];
2787 }
2788 _methods_jmethod_ids = new_cache;
2789 FREE_C_HEAP_ARRAY(jmethodID, cache);
2790 }
2791 }
2792 }
2793
2794 // Make a jmethodID for all methods in this class. This makes getting all method
2795 // ids much, much faster with classes with more than 8
2796 // methods, and has a *substantial* effect on performance with jvmti
2797 // code that loads all jmethodIDs for all classes.
2798 void InstanceKlass::make_methods_jmethod_ids() {
2799 MutexLocker ml(JmethodIdCreation_lock, Mutex::_no_safepoint_check_flag);
2800 jmethodID* jmeths = _methods_jmethod_ids;
2801 if (jmeths == nullptr) {
2802 jmeths = create_jmethod_id_cache(idnum_allocated_count());
2803 release_set_methods_jmethod_ids(jmeths);
2804 }
2805
2806 int length = methods()->length();
2807 for (int index = 0; index < length; index++) {
2808 Method* m = methods()->at(index);
2809 int idnum = m->method_idnum();
2810 assert(!m->is_old(), "should not have old methods or I'm confused");
2811 jmethodID id = AtomicAccess::load_acquire(&jmeths[idnum + 1]);
2812 if (!m->is_overpass() && // skip overpasses
2813 id == nullptr) {
2814 id = Method::make_jmethod_id(class_loader_data(), m);
2815 AtomicAccess::release_store(&jmeths[idnum + 1], id);
2816 }
2817 }
2818 }
2819
2820 // Lookup a jmethodID, null if not found. Do no blocking, no allocations, no handles
2821 jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
2822 int idnum = method->method_idnum();
2823 jmethodID* jmeths = methods_jmethod_ids_acquire();
2824 return (jmeths != nullptr) ? jmeths[idnum + 1] : nullptr;
2825 }
2826
2827 inline DependencyContext InstanceKlass::dependencies() {
2828 DependencyContext dep_context(&_dep_context, &_dep_context_last_cleaned);
2829 return dep_context;
2830 }
2831
2832 void InstanceKlass::mark_dependent_nmethods(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
2833 dependencies().mark_dependent_nmethods(deopt_scope, changes);
2834 }
2835
2836 void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
2837 assert_lock_strong(CodeCache_lock);
2838 dependencies().add_dependent_nmethod(nm);
2839 }
2840
2841 void InstanceKlass::clean_dependency_context() {
2842 dependencies().clean_unloading_dependents();
2843 }
2844
2845 #ifndef PRODUCT
2846 void InstanceKlass::print_dependent_nmethods(bool verbose) {
2847 dependencies().print_dependent_nmethods(verbose);
2848 }
2849
2850 bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
2851 return dependencies().is_dependent_nmethod(nm);
2852 }
2853 #endif //PRODUCT
2854
2855 void InstanceKlass::clean_weak_instanceklass_links() {
2856 clean_implementors_list();
2857 clean_method_data();
2858 }
2859
2860 void InstanceKlass::clean_implementors_list() {
2861 assert(is_loader_alive(), "this klass should be live");
2862 if (is_interface()) {
2863 assert (ClassUnloading, "only called for ClassUnloading");
2864 for (;;) {
2865 // Use load_acquire due to competing with inserts
2866 InstanceKlass* volatile* iklass = adr_implementor();
2867 assert(iklass != nullptr, "Klass must not be null");
2868 InstanceKlass* impl = AtomicAccess::load_acquire(iklass);
2869 if (impl != nullptr && !impl->is_loader_alive()) {
2870 // null this field, might be an unloaded instance klass or null
2871 if (AtomicAccess::cmpxchg(iklass, impl, (InstanceKlass*)nullptr) == impl) {
2872 // Successfully unlinking implementor.
2873 if (log_is_enabled(Trace, class, unload)) {
2874 ResourceMark rm;
2875 log_trace(class, unload)("unlinking class (implementor): %s", impl->external_name());
2876 }
2877 return;
2878 }
2879 } else {
2880 return;
2881 }
2882 }
2883 }
2884 }
2885
2886 void InstanceKlass::clean_method_data() {
2887 for (int m = 0; m < methods()->length(); m++) {
2888 MethodData* mdo = methods()->at(m)->method_data();
2889 if (mdo != nullptr) {
2890 mdo->clean_method_data(/*always_clean*/false);
2891 }
2892 }
2893 }
2894
2895 void InstanceKlass::metaspace_pointers_do(MetaspaceClosure* it) {
2896 Klass::metaspace_pointers_do(it);
2897
2898 if (log_is_enabled(Trace, aot)) {
2899 ResourceMark rm;
2900 log_trace(aot)("Iter(InstanceKlass): %p (%s)", this, external_name());
2901 }
2902
2903 it->push(&_annotations);
2904 it->push((Klass**)&_array_klasses);
2905 if (!is_rewritten()) {
2906 it->push(&_constants, MetaspaceClosure::_writable);
2907 } else {
2908 it->push(&_constants);
2909 }
2910 it->push(&_inner_classes);
2911 #if INCLUDE_JVMTI
2912 it->push(&_previous_versions);
2913 #endif
2914 #if INCLUDE_CDS
2915 // For "old" classes with methods containing the jsr bytecode, the _methods array will
2916 // be rewritten during runtime (see Rewriter::rewrite_jsrs()) but they cannot be safely
2917 // checked here with ByteCodeStream. All methods that can't be verified are made writable.
2918 // The length check on the _methods is necessary because classes which don't have any
2919 // methods share the Universe::_the_empty_method_array which is in the RO region.
2920 if (_methods != nullptr && _methods->length() > 0 && !can_be_verified_at_dumptime()) {
2921 // To handle jsr bytecode, new Method* maybe stored into _methods
2922 it->push(&_methods, MetaspaceClosure::_writable);
2923 } else {
2924 #endif
2925 it->push(&_methods);
2926 #if INCLUDE_CDS
2927 }
2928 #endif
2929 it->push(&_default_methods);
2930 it->push(&_local_interfaces);
2931 it->push(&_transitive_interfaces);
2932 it->push(&_method_ordering);
2933 if (!is_rewritten()) {
2934 it->push(&_default_vtable_indices, MetaspaceClosure::_writable);
2935 } else {
2936 it->push(&_default_vtable_indices);
2937 }
2938
2939 it->push(&_fieldinfo_stream);
2940 it->push(&_fieldinfo_search_table);
2941 // _fields_status might be written into by Rewriter::scan_method() -> fd.set_has_initialized_final_update()
2942 it->push(&_fields_status, MetaspaceClosure::_writable);
2943
2944 if (itable_length() > 0) {
2945 itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2946 int method_table_offset_in_words = ioe->offset()/wordSize;
2947 int itable_offset_in_words = (int)(start_of_itable() - (intptr_t*)this);
2948
2949 int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words)
2950 / itableOffsetEntry::size();
2951
2952 for (int i = 0; i < nof_interfaces; i ++, ioe ++) {
2953 if (ioe->interface_klass() != nullptr) {
2954 it->push(ioe->interface_klass_addr());
2955 itableMethodEntry* ime = ioe->first_method_entry(this);
2956 int n = klassItable::method_count_for_interface(ioe->interface_klass());
2957 for (int index = 0; index < n; index ++) {
2958 it->push(ime[index].method_addr());
2959 }
2960 }
2961 }
2962 }
2963
2964 it->push(&_nest_host);
2965 it->push(&_nest_members);
2966 it->push(&_permitted_subclasses);
2967 it->push(&_loadable_descriptors);
2968 it->push(&_acmp_maps_array, MetaspaceClosure::_writable);
2969 it->push(&_record_components);
2970 it->push(&_inline_layout_info_array, MetaspaceClosure::_writable);
2971 }
2972
2973 #if INCLUDE_CDS
2974 void InstanceKlass::remove_unshareable_info() {
2975
2976 if (is_linked()) {
2977 assert(can_be_verified_at_dumptime(), "must be");
2978 // Remember this so we can avoid walking the hierarchy at runtime.
2979 set_verified_at_dump_time();
2980 }
2981
2982 _misc_flags.set_has_init_deps_processed(false);
2983
2984 Klass::remove_unshareable_info();
2985
2986 if (SystemDictionaryShared::has_class_failed_verification(this)) {
2987 // Classes are attempted to link during dumping and may fail,
2988 // but these classes are still in the dictionary and class list in CLD.
2989 // If the class has failed verification, there is nothing else to remove.
2990 return;
2991 }
2992
2993 // Reset to the 'allocated' state to prevent any premature accessing to
2994 // a shared class at runtime while the class is still being loaded and
2995 // restored. A class' init_state is set to 'loaded' at runtime when it's
2996 // being added to class hierarchy (see InstanceKlass:::add_to_hierarchy()).
2997 _init_state = allocated;
2998
2999 { // Otherwise this needs to take out the Compile_lock.
3000 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
3001 init_implementor();
3002 }
3003
3004 // Call remove_unshareable_info() on other objects that belong to this class, except
3005 // for constants()->remove_unshareable_info(), which is called in a separate pass in
3006 // ArchiveBuilder::make_klasses_shareable(),
3007
3008 for (int i = 0; i < methods()->length(); i++) {
3009 Method* m = methods()->at(i);
3010 m->remove_unshareable_info();
3011 }
3012
3013 // do array classes also.
3014 if (array_klasses() != nullptr) {
3015 array_klasses()->remove_unshareable_info();
3016 }
3017
3018 // These are not allocated from metaspace. They are safe to set to nullptr.
3019 _source_debug_extension = nullptr;
3020 _dep_context = nullptr;
3021 _osr_nmethods_head = nullptr;
3022 #if INCLUDE_JVMTI
3023 _breakpoints = nullptr;
3024 _previous_versions = nullptr;
3025 _cached_class_file = nullptr;
3026 _jvmti_cached_class_field_map = nullptr;
3027 #endif
3028
3029 _init_thread = nullptr;
3030 _methods_jmethod_ids = nullptr;
3031 _jni_ids = nullptr;
3032 _oop_map_cache = nullptr;
3033 if (CDSConfig::is_dumping_method_handles() && HeapShared::is_lambda_proxy_klass(this)) {
3034 // keep _nest_host
3035 } else {
3036 // clear _nest_host to ensure re-load at runtime
3037 _nest_host = nullptr;
3038 }
3039 init_shared_package_entry();
3040 _dep_context_last_cleaned = 0;
3041 DEBUG_ONLY(_shared_class_load_count = 0);
3042
3043 remove_unshareable_flags();
3044
3045 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
3046 }
3047
3048 void InstanceKlass::remove_unshareable_flags() {
3049 // clear all the flags/stats that shouldn't be in the archived version
3050 assert(!is_scratch_class(), "must be");
3051 assert(!has_been_redefined(), "must be");
3052 #if INCLUDE_JVMTI
3053 set_is_being_redefined(false);
3054 #endif
3055 set_has_resolved_methods(false);
3056 }
3057
3058 void InstanceKlass::remove_java_mirror() {
3059 Klass::remove_java_mirror();
3060
3061 // do array classes also.
3062 if (array_klasses() != nullptr) {
3063 array_klasses()->remove_java_mirror();
3064 }
3065 }
3066
3067 void InstanceKlass::init_shared_package_entry() {
3068 assert(CDSConfig::is_dumping_archive(), "must be");
3069 #if !INCLUDE_CDS_JAVA_HEAP
3070 _package_entry = nullptr;
3071 #else
3072 if (CDSConfig::is_dumping_full_module_graph()) {
3073 if (defined_by_other_loaders()) {
3074 _package_entry = nullptr;
3075 } else {
3076 _package_entry = PackageEntry::get_archived_entry(_package_entry);
3077 }
3078 } else if (CDSConfig::is_dumping_dynamic_archive() &&
3079 CDSConfig::is_using_full_module_graph() &&
3080 AOTMetaspace::in_aot_cache(_package_entry)) {
3081 // _package_entry is an archived package in the base archive. Leave it as is.
3082 } else {
3083 _package_entry = nullptr;
3084 }
3085 ArchivePtrMarker::mark_pointer((address**)&_package_entry);
3086 #endif
3087 }
3088
3089 void InstanceKlass::compute_has_loops_flag_for_methods() {
3090 Array<Method*>* methods = this->methods();
3091 for (int index = 0; index < methods->length(); ++index) {
3092 Method* m = methods->at(index);
3093 if (!m->is_overpass()) { // work around JDK-8305771
3094 m->compute_has_loops_flag();
3095 }
3096 }
3097 }
3098
3099 void InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain,
3100 PackageEntry* pkg_entry, TRAPS) {
3101 // InstanceKlass::add_to_hierarchy() sets the init_state to loaded
3102 // before the InstanceKlass is added to the SystemDictionary. Make
3103 // sure the current state is <loaded.
3104 assert(!is_loaded(), "invalid init state");
3105 assert(!shared_loading_failed(), "Must not try to load failed class again");
3106 set_package(loader_data, pkg_entry, CHECK);
3107 Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
3108
3109 if (is_inline_klass()) {
3110 InlineKlass::cast(this)->initialize_calling_convention(CHECK);
3111 }
3112
3113 Array<Method*>* methods = this->methods();
3114 int num_methods = methods->length();
3115 for (int index = 0; index < num_methods; ++index) {
3116 methods->at(index)->restore_unshareable_info(CHECK);
3117 }
3118 #if INCLUDE_JVMTI
3119 if (JvmtiExport::has_redefined_a_class()) {
3120 // Reinitialize vtable because RedefineClasses may have changed some
3121 // entries in this vtable for super classes so the CDS vtable might
3122 // point to old or obsolete entries. RedefineClasses doesn't fix up
3123 // vtables in the shared system dictionary, only the main one.
3124 // It also redefines the itable too so fix that too.
3125 // First fix any default methods that point to a super class that may
3126 // have been redefined.
3127 bool trace_name_printed = false;
3128 adjust_default_methods(&trace_name_printed);
3129 if (verified_at_dump_time()) {
3130 // Initialize vtable and itable for classes which can be verified at dump time.
3131 // Unlinked classes such as old classes with major version < 50 cannot be verified
3132 // at dump time.
3133 vtable().initialize_vtable();
3134 itable().initialize_itable();
3135 }
3136 }
3137 #endif // INCLUDE_JVMTI
3138
3139 // restore constant pool resolved references
3140 constants()->restore_unshareable_info(CHECK);
3141
3142 // Restore acmp_maps java array from the version stored in metadata.
3143 // if it cannot be found in the archive
3144 if (Arguments::is_valhalla_enabled() && has_acmp_maps_offset() && java_mirror()->obj_field(_acmp_maps_offset) == nullptr) {
3145 int acmp_maps_size = _acmp_maps_array->length();
3146 typeArrayOop map = oopFactory::new_intArray(acmp_maps_size, CHECK);
3147 typeArrayHandle map_h(THREAD, map);
3148 for (int i = 0; i < acmp_maps_size; i++) {
3149 map_h->int_at_put(i, _acmp_maps_array->at(i));
3150 }
3151 java_mirror()->obj_field_put(_acmp_maps_offset, map_h());
3152 }
3153
3154 if (array_klasses() != nullptr) {
3155 // To get a consistent list of classes we need MultiArray_lock to ensure
3156 // array classes aren't observed while they are being restored.
3157 RecursiveLocker rl(MultiArray_lock, THREAD);
3158 assert(this == ObjArrayKlass::cast(array_klasses())->bottom_klass(), "sanity");
3159 // Array classes have null protection domain.
3160 // --> see ArrayKlass::complete_create_array_klass()
3161 if (class_loader_data() == nullptr) {
3162 ResourceMark rm(THREAD);
3163 log_debug(cds)(" loader_data %s ", loader_data == nullptr ? "nullptr" : "non null");
3164 log_debug(cds)(" this %s array_klasses %s ", this->name()->as_C_string(), array_klasses()->name()->as_C_string());
3165 }
3166 assert(!array_klasses()->is_refined_objArray_klass(), "must be non-refined objarrayklass");
3167 array_klasses()->restore_unshareable_info(class_loader_data(), Handle(), CHECK);
3168 }
3169
3170 // Initialize @ValueBased class annotation if not already set in the archived klass.
3171 if (DiagnoseSyncOnValueBasedClasses && has_value_based_class_annotation() && !is_value_based()) {
3172 set_is_value_based();
3173 }
3174
3175 DEBUG_ONLY(FieldInfoStream::validate_search_table(_constants, _fieldinfo_stream, _fieldinfo_search_table));
3176 }
3177
3178 bool InstanceKlass::can_be_verified_at_dumptime() const {
3179 if (CDSConfig::is_dumping_dynamic_archive() && AOTMetaspace::in_aot_cache(this)) {
3180 // This is a class that was dumped into the base archive, so we know
3181 // it was verified at dump time.
3182 return true;
3183 }
3184
3185 if (CDSConfig::is_preserving_verification_constraints()) {
3186 return true;
3187 }
3188
3189 if (CDSConfig::is_old_class_for_verifier(this)) {
3190 // The old verifier does not save verification constraints, so at run time
3191 // SystemDictionaryShared::check_verification_constraints() will not work for this class.
3192 return false;
3193 }
3194 if (super() != nullptr && !super()->can_be_verified_at_dumptime()) {
3195 return false;
3196 }
3197 Array<InstanceKlass*>* interfaces = local_interfaces();
3198 int len = interfaces->length();
3199 for (int i = 0; i < len; i++) {
3200 if (!interfaces->at(i)->can_be_verified_at_dumptime()) {
3201 return false;
3202 }
3203 }
3204 return true;
3205 }
3206
3207 #endif // INCLUDE_CDS
3208
3209 #if INCLUDE_JVMTI
3210 static void clear_all_breakpoints(Method* m) {
3211 m->clear_all_breakpoints();
3212 }
3213 #endif
3214
3215 void InstanceKlass::unload_class(InstanceKlass* ik) {
3216
3217 if (ik->is_scratch_class()) {
3218 assert(ik->dependencies().is_empty(), "dependencies should be empty for scratch classes");
3219 return;
3220 }
3221 assert(ik->is_loaded(), "class should be loaded " PTR_FORMAT, p2i(ik));
3222
3223 // Release dependencies.
3224 ik->dependencies().remove_all_dependents();
3225
3226 // notify the debugger
3227 if (JvmtiExport::should_post_class_unload()) {
3228 JvmtiExport::post_class_unload(ik);
3229 }
3230
3231 // notify ClassLoadingService of class unload
3232 ClassLoadingService::notify_class_unloaded(ik);
3233
3234 SystemDictionaryShared::handle_class_unloading(ik);
3235
3236 if (log_is_enabled(Info, class, unload)) {
3237 ResourceMark rm;
3238 log_info(class, unload)("unloading class %s " PTR_FORMAT, ik->external_name(), p2i(ik));
3239 }
3240
3241 Events::log_class_unloading(Thread::current(), ik);
3242
3243 #if INCLUDE_JFR
3244 assert(ik != nullptr, "invariant");
3245 EventClassUnload event;
3246 event.set_unloadedClass(ik);
3247 event.set_definingClassLoader(ik->class_loader_data());
3248 event.commit();
3249 #endif
3250 }
3251
3252 static void method_release_C_heap_structures(Method* m) {
3253 m->release_C_heap_structures();
3254 }
3255
3256 // Called also by InstanceKlass::deallocate_contents, with false for release_sub_metadata.
3257 void InstanceKlass::release_C_heap_structures(bool release_sub_metadata) {
3258 // Clean up C heap
3259 Klass::release_C_heap_structures();
3260
3261 // Deallocate and call destructors for MDO mutexes
3262 if (release_sub_metadata) {
3263 methods_do(method_release_C_heap_structures);
3264 }
3265
3266 // Deallocate oop map cache
3267 if (_oop_map_cache != nullptr) {
3268 delete _oop_map_cache;
3269 _oop_map_cache = nullptr;
3270 }
3271
3272 // Deallocate JNI identifiers for jfieldIDs
3273 JNIid::deallocate(jni_ids());
3274 set_jni_ids(nullptr);
3275
3276 jmethodID* jmeths = _methods_jmethod_ids;
3277 if (jmeths != nullptr) {
3278 release_set_methods_jmethod_ids(nullptr);
3279 FreeHeap(jmeths);
3280 }
3281
3282 assert(_dep_context == nullptr,
3283 "dependencies should already be cleaned");
3284
3285 #if INCLUDE_JVMTI
3286 // Deallocate breakpoint records
3287 if (breakpoints() != nullptr) {
3288 methods_do(clear_all_breakpoints);
3289 assert(breakpoints() == nullptr, "should have cleared breakpoints");
3290 }
3291
3292 // deallocate the cached class file
3293 if (_cached_class_file != nullptr) {
3294 os::free(_cached_class_file);
3295 _cached_class_file = nullptr;
3296 }
3297 #endif
3298
3299 FREE_C_HEAP_ARRAY(char, _source_debug_extension);
3300
3301 if (release_sub_metadata) {
3302 constants()->release_C_heap_structures();
3303 }
3304 }
3305
3306 // The constant pool is on stack if any of the methods are executing or
3307 // referenced by handles.
3308 bool InstanceKlass::on_stack() const {
3309 return _constants->on_stack();
3310 }
3311
3312 Symbol* InstanceKlass::source_file_name() const { return _constants->source_file_name(); }
3313 u2 InstanceKlass::source_file_name_index() const { return _constants->source_file_name_index(); }
3314 void InstanceKlass::set_source_file_name_index(u2 sourcefile_index) { _constants->set_source_file_name_index(sourcefile_index); }
3315
3316 // minor and major version numbers of class file
3317 u2 InstanceKlass::minor_version() const { return _constants->minor_version(); }
3318 void InstanceKlass::set_minor_version(u2 minor_version) { _constants->set_minor_version(minor_version); }
3319 u2 InstanceKlass::major_version() const { return _constants->major_version(); }
3320 void InstanceKlass::set_major_version(u2 major_version) { _constants->set_major_version(major_version); }
3321
3322 bool InstanceKlass::supports_inline_types() const {
3323 return major_version() >= Verifier::VALUE_TYPES_MAJOR_VERSION && minor_version() == Verifier::JAVA_PREVIEW_MINOR_VERSION;
3324 }
3325
3326 const InstanceKlass* InstanceKlass::get_klass_version(int version) const {
3327 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->previous_versions()) {
3328 if (ik->constants()->version() == version) {
3329 return ik;
3330 }
3331 }
3332 return nullptr;
3333 }
3334
3335 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
3336 if (array == nullptr) {
3337 _source_debug_extension = nullptr;
3338 } else {
3339 // Adding one to the attribute length in order to store a null terminator
3340 // character could cause an overflow because the attribute length is
3341 // already coded with an u4 in the classfile, but in practice, it's
3342 // unlikely to happen.
3343 assert((length+1) > length, "Overflow checking");
3344 char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
3345 for (int i = 0; i < length; i++) {
3346 sde[i] = array[i];
3347 }
3348 sde[length] = '\0';
3349 _source_debug_extension = sde;
3350 }
3351 }
3352
3353 Symbol* InstanceKlass::generic_signature() const { return _constants->generic_signature(); }
3354 u2 InstanceKlass::generic_signature_index() const { return _constants->generic_signature_index(); }
3355 void InstanceKlass::set_generic_signature_index(u2 sig_index) { _constants->set_generic_signature_index(sig_index); }
3356
3357 const char* InstanceKlass::signature_name() const {
3358 return signature_name_of_carrier(JVM_SIGNATURE_CLASS);
3359 }
3360
3361 const char* InstanceKlass::signature_name_of_carrier(char c) const {
3362 // Get the internal name as a c string
3363 const char* src = (const char*) (name()->as_C_string());
3364 const int src_length = (int)strlen(src);
3365
3366 char* dest = NEW_RESOURCE_ARRAY(char, src_length + 3);
3367
3368 // Add L or Q as type indicator
3369 int dest_index = 0;
3370 dest[dest_index++] = c;
3371
3372 // Add the actual class name
3373 for (int src_index = 0; src_index < src_length; ) {
3374 dest[dest_index++] = src[src_index++];
3375 }
3376
3377 if (is_hidden()) { // Replace the last '+' with a '.'.
3378 for (int index = (int)src_length; index > 0; index--) {
3379 if (dest[index] == '+') {
3380 dest[index] = JVM_SIGNATURE_DOT;
3381 break;
3382 }
3383 }
3384 }
3385
3386 // Add the semicolon and the null
3387 dest[dest_index++] = JVM_SIGNATURE_ENDCLASS;
3388 dest[dest_index] = '\0';
3389 return dest;
3390 }
3391
3392 ModuleEntry* InstanceKlass::module() const {
3393 if (is_hidden() &&
3394 in_unnamed_package() &&
3395 class_loader_data()->has_class_mirror_holder()) {
3396 // For a non-strong hidden class defined to an unnamed package,
3397 // its (class held) CLD will not have an unnamed module created for it.
3398 // Two choices to find the correct ModuleEntry:
3399 // 1. If hidden class is within a nest, use nest host's module
3400 // 2. Find the unnamed module off from the class loader
3401 // For now option #2 is used since a nest host is not set until
3402 // after the instance class is created in jvm_lookup_define_class().
3403 if (class_loader_data()->is_boot_class_loader_data()) {
3404 return ClassLoaderData::the_null_class_loader_data()->unnamed_module();
3405 } else {
3406 oop module = java_lang_ClassLoader::unnamedModule(class_loader_data()->class_loader());
3407 assert(java_lang_Module::is_instance(module), "Not an instance of java.lang.Module");
3408 return java_lang_Module::module_entry(module);
3409 }
3410 }
3411
3412 // Class is in a named package
3413 if (!in_unnamed_package()) {
3414 return _package_entry->module();
3415 }
3416
3417 // Class is in an unnamed package, return its loader's unnamed module
3418 return class_loader_data()->unnamed_module();
3419 }
3420
3421 bool InstanceKlass::in_javabase_module() const {
3422 return module()->name() == vmSymbols::java_base();
3423 }
3424
3425 void InstanceKlass::set_package(ClassLoaderData* loader_data, PackageEntry* pkg_entry, TRAPS) {
3426
3427 // ensure java/ packages only loaded by boot or platform builtin loaders
3428 // not needed for shared class since CDS does not archive prohibited classes.
3429 if (!in_aot_cache()) {
3430 check_prohibited_package(name(), loader_data, CHECK);
3431 }
3432
3433 if (in_aot_cache() && _package_entry != nullptr) {
3434 if (CDSConfig::is_using_full_module_graph() && _package_entry == pkg_entry) {
3435 // we can use the saved package
3436 assert(AOTMetaspace::in_aot_cache(_package_entry), "must be");
3437 return;
3438 } else {
3439 _package_entry = nullptr;
3440 }
3441 }
3442
3443 // ClassLoader::package_from_class_name has already incremented the refcount of the symbol
3444 // it returns, so we need to decrement it when the current function exits.
3445 TempNewSymbol from_class_name =
3446 (pkg_entry != nullptr) ? nullptr : ClassLoader::package_from_class_name(name());
3447
3448 Symbol* pkg_name;
3449 if (pkg_entry != nullptr) {
3450 pkg_name = pkg_entry->name();
3451 } else {
3452 pkg_name = from_class_name;
3453 }
3454
3455 if (pkg_name != nullptr && loader_data != nullptr) {
3456
3457 // Find in class loader's package entry table.
3458 _package_entry = pkg_entry != nullptr ? pkg_entry : loader_data->packages()->lookup_only(pkg_name);
3459
3460 // If the package name is not found in the loader's package
3461 // entry table, it is an indication that the package has not
3462 // been defined. Consider it defined within the unnamed module.
3463 if (_package_entry == nullptr) {
3464
3465 if (!ModuleEntryTable::javabase_defined()) {
3466 // Before java.base is defined during bootstrapping, define all packages in
3467 // the java.base module. If a non-java.base package is erroneously placed
3468 // in the java.base module it will be caught later when java.base
3469 // is defined by ModuleEntryTable::verify_javabase_packages check.
3470 assert(ModuleEntryTable::javabase_moduleEntry() != nullptr, JAVA_BASE_NAME " module is null");
3471 _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, ModuleEntryTable::javabase_moduleEntry());
3472 } else {
3473 assert(loader_data->unnamed_module() != nullptr, "unnamed module is null");
3474 _package_entry = loader_data->packages()->create_entry_if_absent(pkg_name, loader_data->unnamed_module());
3475 }
3476
3477 // A package should have been successfully created
3478 DEBUG_ONLY(ResourceMark rm(THREAD));
3479 assert(_package_entry != nullptr, "Package entry for class %s not found, loader %s",
3480 name()->as_C_string(), loader_data->loader_name_and_id());
3481 }
3482
3483 if (log_is_enabled(Debug, module)) {
3484 ResourceMark rm(THREAD);
3485 ModuleEntry* m = _package_entry->module();
3486 log_trace(module)("Setting package: class: %s, package: %s, loader: %s, module: %s",
3487 external_name(),
3488 pkg_name->as_C_string(),
3489 loader_data->loader_name_and_id(),
3490 (m->is_named() ? m->name()->as_C_string() : UNNAMED_MODULE));
3491 }
3492 } else {
3493 ResourceMark rm(THREAD);
3494 log_trace(module)("Setting package: class: %s, package: unnamed, loader: %s, module: %s",
3495 external_name(),
3496 (loader_data != nullptr) ? loader_data->loader_name_and_id() : "null",
3497 UNNAMED_MODULE);
3498 }
3499 }
3500
3501 // Function set_classpath_index ensures that for a non-null _package_entry
3502 // of the InstanceKlass, the entry is in the boot loader's package entry table.
3503 // It then sets the classpath_index in the package entry record.
3504 //
3505 // The classpath_index field is used to find the entry on the boot loader class
3506 // path for packages with classes loaded by the boot loader from -Xbootclasspath/a
3507 // in an unnamed module. It is also used to indicate (for all packages whose
3508 // classes are loaded by the boot loader) that at least one of the package's
3509 // classes has been loaded.
3510 void InstanceKlass::set_classpath_index(s2 path_index) {
3511 if (_package_entry != nullptr) {
3512 DEBUG_ONLY(PackageEntryTable* pkg_entry_tbl = ClassLoaderData::the_null_class_loader_data()->packages();)
3513 assert(pkg_entry_tbl->lookup_only(_package_entry->name()) == _package_entry, "Should be same");
3514 assert(path_index != -1, "Unexpected classpath_index");
3515 _package_entry->set_classpath_index(path_index);
3516 }
3517 }
3518
3519 // different versions of is_same_class_package
3520
3521 bool InstanceKlass::is_same_class_package(const Klass* class2) const {
3522 oop classloader1 = this->class_loader();
3523 PackageEntry* classpkg1 = this->package();
3524 if (class2->is_objArray_klass()) {
3525 class2 = ObjArrayKlass::cast(class2)->bottom_klass();
3526 }
3527
3528 oop classloader2;
3529 PackageEntry* classpkg2;
3530 if (class2->is_instance_klass()) {
3531 classloader2 = class2->class_loader();
3532 classpkg2 = class2->package();
3533 } else {
3534 assert(class2->is_typeArray_klass(), "should be type array");
3535 classloader2 = nullptr;
3536 classpkg2 = nullptr;
3537 }
3538
3539 // Same package is determined by comparing class loader
3540 // and package entries. Both must be the same. This rule
3541 // applies even to classes that are defined in the unnamed
3542 // package, they still must have the same class loader.
3543 if ((classloader1 == classloader2) && (classpkg1 == classpkg2)) {
3544 return true;
3545 }
3546
3547 return false;
3548 }
3549
3550 // return true if this class and other_class are in the same package. Classloader
3551 // and classname information is enough to determine a class's package
3552 bool InstanceKlass::is_same_class_package(oop other_class_loader,
3553 const Symbol* other_class_name) const {
3554 if (class_loader() != other_class_loader) {
3555 return false;
3556 }
3557 if (name()->fast_compare(other_class_name) == 0) {
3558 return true;
3559 }
3560
3561 {
3562 ResourceMark rm;
3563
3564 bool bad_class_name = false;
3565 TempNewSymbol other_pkg = ClassLoader::package_from_class_name(other_class_name, &bad_class_name);
3566 if (bad_class_name) {
3567 return false;
3568 }
3569 // Check that package_from_class_name() returns null, not "", if there is no package.
3570 assert(other_pkg == nullptr || other_pkg->utf8_length() > 0, "package name is empty string");
3571
3572 const Symbol* const this_package_name =
3573 this->package() != nullptr ? this->package()->name() : nullptr;
3574
3575 if (this_package_name == nullptr || other_pkg == nullptr) {
3576 // One of the two doesn't have a package. Only return true if the other
3577 // one also doesn't have a package.
3578 return this_package_name == other_pkg;
3579 }
3580
3581 // Check if package is identical
3582 return this_package_name->fast_compare(other_pkg) == 0;
3583 }
3584 }
3585
3586 static bool is_prohibited_package_slow(Symbol* class_name) {
3587 // Caller has ResourceMark
3588 int length;
3589 jchar* unicode = class_name->as_unicode(length);
3590 return (length >= 5 &&
3591 unicode[0] == 'j' &&
3592 unicode[1] == 'a' &&
3593 unicode[2] == 'v' &&
3594 unicode[3] == 'a' &&
3595 unicode[4] == '/');
3596 }
3597
3598 // Only boot and platform class loaders can define classes in "java/" packages.
3599 void InstanceKlass::check_prohibited_package(Symbol* class_name,
3600 ClassLoaderData* loader_data,
3601 TRAPS) {
3602 if (!loader_data->is_boot_class_loader_data() &&
3603 !loader_data->is_platform_class_loader_data() &&
3604 class_name != nullptr && class_name->utf8_length() >= 5) {
3605 ResourceMark rm(THREAD);
3606 bool prohibited;
3607 const u1* base = class_name->base();
3608 if ((base[0] | base[1] | base[2] | base[3] | base[4]) & 0x80) {
3609 prohibited = is_prohibited_package_slow(class_name);
3610 } else {
3611 char* name = class_name->as_C_string();
3612 prohibited = (strncmp(name, JAVAPKG, JAVAPKG_LEN) == 0 && name[JAVAPKG_LEN] == '/');
3613 }
3614 if (prohibited) {
3615 TempNewSymbol pkg_name = ClassLoader::package_from_class_name(class_name);
3616 assert(pkg_name != nullptr, "Error in parsing package name starting with 'java/'");
3617 char* name = pkg_name->as_C_string();
3618 const char* class_loader_name = loader_data->loader_name_and_id();
3619 StringUtils::replace_no_expand(name, "/", ".");
3620 const char* msg_text1 = "Class loader (instance of): ";
3621 const char* msg_text2 = " tried to load prohibited package name: ";
3622 size_t len = strlen(msg_text1) + strlen(class_loader_name) + strlen(msg_text2) + strlen(name) + 1;
3623 char* message = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
3624 jio_snprintf(message, len, "%s%s%s%s", msg_text1, class_loader_name, msg_text2, name);
3625 THROW_MSG(vmSymbols::java_lang_SecurityException(), message);
3626 }
3627 }
3628 return;
3629 }
3630
3631 bool InstanceKlass::find_inner_classes_attr(int* ooff, int* noff, TRAPS) const {
3632 constantPoolHandle i_cp(THREAD, constants());
3633 for (InnerClassesIterator iter(this); !iter.done(); iter.next()) {
3634 int ioff = iter.inner_class_info_index();
3635 if (ioff != 0) {
3636 // Check to see if the name matches the class we're looking for
3637 // before attempting to find the class.
3638 if (i_cp->klass_name_at_matches(this, ioff)) {
3639 Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
3640 if (this == inner_klass) {
3641 *ooff = iter.outer_class_info_index();
3642 *noff = iter.inner_name_index();
3643 return true;
3644 }
3645 }
3646 }
3647 }
3648 return false;
3649 }
3650
3651 void InstanceKlass::check_can_be_annotated_with_NullRestricted(InstanceKlass* type, Symbol* container_klass_name, TRAPS) {
3652 assert(type->is_instance_klass(), "Sanity check");
3653 if (type->is_identity_class()) {
3654 ResourceMark rm(THREAD);
3655 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3656 err_msg("Class %s expects class %s to be a value class, but it is an identity class",
3657 container_klass_name->as_C_string(),
3658 type->external_name()));
3659 }
3660
3661 if (type->is_abstract()) {
3662 ResourceMark rm(THREAD);
3663 THROW_MSG(vmSymbols::java_lang_IncompatibleClassChangeError(),
3664 err_msg("Class %s expects class %s to be concrete value type, but it is an abstract class",
3665 container_klass_name->as_C_string(),
3666 type->external_name()));
3667 }
3668 }
3669
3670 InstanceKlass* InstanceKlass::compute_enclosing_class(bool* inner_is_member, TRAPS) const {
3671 InstanceKlass* outer_klass = nullptr;
3672 *inner_is_member = false;
3673 int ooff = 0, noff = 0;
3674 bool has_inner_classes_attr = find_inner_classes_attr(&ooff, &noff, THREAD);
3675 if (has_inner_classes_attr) {
3676 constantPoolHandle i_cp(THREAD, constants());
3677 if (ooff != 0) {
3678 Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
3679 if (!ok->is_instance_klass()) {
3680 // If the outer class is not an instance klass then it cannot have
3681 // declared any inner classes.
3682 ResourceMark rm(THREAD);
3683 // Names are all known to be < 64k so we know this formatted message is not excessively large.
3684 Exceptions::fthrow(
3685 THREAD_AND_LOCATION,
3686 vmSymbols::java_lang_IncompatibleClassChangeError(),
3687 "%s and %s disagree on InnerClasses attribute",
3688 ok->external_name(),
3689 external_name());
3690 return nullptr;
3691 }
3692 outer_klass = InstanceKlass::cast(ok);
3693 *inner_is_member = true;
3694 }
3695 if (nullptr == outer_klass) {
3696 // It may be a local class; try for that.
3697 int encl_method_class_idx = enclosing_method_class_index();
3698 if (encl_method_class_idx != 0) {
3699 Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
3700 outer_klass = InstanceKlass::cast(ok);
3701 *inner_is_member = false;
3702 }
3703 }
3704 }
3705
3706 // If no inner class attribute found for this class.
3707 if (nullptr == outer_klass) return nullptr;
3708
3709 // Throws an exception if outer klass has not declared k as an inner klass
3710 // We need evidence that each klass knows about the other, or else
3711 // the system could allow a spoof of an inner class to gain access rights.
3712 Reflection::check_for_inner_class(outer_klass, this, *inner_is_member, CHECK_NULL);
3713 return outer_klass;
3714 }
3715
3716 u2 InstanceKlass::compute_modifier_flags() const {
3717 u2 access = access_flags().as_unsigned_short();
3718
3719 // But check if it happens to be member class.
3720 InnerClassesIterator iter(this);
3721 for (; !iter.done(); iter.next()) {
3722 int ioff = iter.inner_class_info_index();
3723 // Inner class attribute can be zero, skip it.
3724 // Strange but true: JVM spec. allows null inner class refs.
3725 if (ioff == 0) continue;
3726
3727 // only look at classes that are already loaded
3728 // since we are looking for the flags for our self.
3729 Symbol* inner_name = constants()->klass_name_at(ioff);
3730 if (name() == inner_name) {
3731 // This is really a member class.
3732 access = iter.inner_access_flags();
3733 break;
3734 }
3735 }
3736 return access;
3737 }
3738
3739 jint InstanceKlass::jvmti_class_status() const {
3740 jint result = 0;
3741
3742 if (is_linked()) {
3743 result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
3744 }
3745
3746 if (is_initialized()) {
3747 assert(is_linked(), "Class status is not consistent");
3748 result |= JVMTI_CLASS_STATUS_INITIALIZED;
3749 }
3750 if (is_in_error_state()) {
3751 result |= JVMTI_CLASS_STATUS_ERROR;
3752 }
3753 return result;
3754 }
3755
3756 Method* InstanceKlass::method_at_itable(InstanceKlass* holder, int index, TRAPS) {
3757 bool implements_interface; // initialized by method_at_itable_or_null
3758 Method* m = method_at_itable_or_null(holder, index,
3759 implements_interface); // out parameter
3760 if (m != nullptr) {
3761 assert(implements_interface, "sanity");
3762 return m;
3763 } else if (implements_interface) {
3764 // Throw AbstractMethodError since corresponding itable slot is empty.
3765 THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
3766 } else {
3767 // If the interface isn't implemented by the receiver class,
3768 // the VM should throw IncompatibleClassChangeError.
3769 ResourceMark rm(THREAD);
3770 stringStream ss;
3771 bool same_module = (module() == holder->module());
3772 ss.print("Receiver class %s does not implement "
3773 "the interface %s defining the method to be called "
3774 "(%s%s%s)",
3775 external_name(), holder->external_name(),
3776 (same_module) ? joint_in_module_of_loader(holder) : class_in_module_of_loader(),
3777 (same_module) ? "" : "; ",
3778 (same_module) ? "" : holder->class_in_module_of_loader());
3779 THROW_MSG_NULL(vmSymbols::java_lang_IncompatibleClassChangeError(), ss.as_string());
3780 }
3781 }
3782
3783 Method* InstanceKlass::method_at_itable_or_null(InstanceKlass* holder, int index, bool& implements_interface) {
3784 klassItable itable(this);
3785 for (int i = 0; i < itable.size_offset_table(); i++) {
3786 itableOffsetEntry* offset_entry = itable.offset_entry(i);
3787 if (offset_entry->interface_klass() == holder) {
3788 implements_interface = true;
3789 itableMethodEntry* ime = offset_entry->first_method_entry(this);
3790 Method* m = ime[index].method();
3791 return m;
3792 }
3793 }
3794 implements_interface = false;
3795 return nullptr; // offset entry not found
3796 }
3797
3798 int InstanceKlass::vtable_index_of_interface_method(Method* intf_method) {
3799 assert(is_linked(), "required");
3800 assert(intf_method->method_holder()->is_interface(), "not an interface method");
3801 assert(is_subtype_of(intf_method->method_holder()), "interface not implemented");
3802
3803 int vtable_index = Method::invalid_vtable_index;
3804 Symbol* name = intf_method->name();
3805 Symbol* signature = intf_method->signature();
3806
3807 // First check in default method array
3808 if (!intf_method->is_abstract() && default_methods() != nullptr) {
3809 int index = find_method_index(default_methods(),
3810 name, signature,
3811 Klass::OverpassLookupMode::find,
3812 Klass::StaticLookupMode::find,
3813 Klass::PrivateLookupMode::find);
3814 if (index >= 0) {
3815 vtable_index = default_vtable_indices()->at(index);
3816 }
3817 }
3818 if (vtable_index == Method::invalid_vtable_index) {
3819 // get vtable_index for miranda methods
3820 klassVtable vt = vtable();
3821 vtable_index = vt.index_of_miranda(name, signature);
3822 }
3823 return vtable_index;
3824 }
3825
3826 #if INCLUDE_JVMTI
3827 // update default_methods for redefineclasses for methods that are
3828 // not yet in the vtable due to concurrent subclass define and superinterface
3829 // redefinition
3830 // Note: those in the vtable, should have been updated via adjust_method_entries
3831 void InstanceKlass::adjust_default_methods(bool* trace_name_printed) {
3832 // search the default_methods for uses of either obsolete or EMCP methods
3833 if (default_methods() != nullptr) {
3834 for (int index = 0; index < default_methods()->length(); index ++) {
3835 Method* old_method = default_methods()->at(index);
3836 if (old_method == nullptr || !old_method->is_old()) {
3837 continue; // skip uninteresting entries
3838 }
3839 assert(!old_method->is_deleted(), "default methods may not be deleted");
3840 Method* new_method = old_method->get_new_method();
3841 default_methods()->at_put(index, new_method);
3842
3843 if (log_is_enabled(Info, redefine, class, update)) {
3844 ResourceMark rm;
3845 if (!(*trace_name_printed)) {
3846 log_info(redefine, class, update)
3847 ("adjust: klassname=%s default methods from name=%s",
3848 external_name(), old_method->method_holder()->external_name());
3849 *trace_name_printed = true;
3850 }
3851 log_debug(redefine, class, update, vtables)
3852 ("default method update: %s(%s) ",
3853 new_method->name()->as_C_string(), new_method->signature()->as_C_string());
3854 }
3855 }
3856 }
3857 }
3858 #endif // INCLUDE_JVMTI
3859
3860 // On-stack replacement stuff
3861 void InstanceKlass::add_osr_nmethod(nmethod* n) {
3862 assert_lock_strong(NMethodState_lock);
3863 #ifndef PRODUCT
3864 nmethod* prev = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), n->comp_level(), true);
3865 assert(prev == nullptr || !prev->is_in_use() COMPILER2_PRESENT(|| StressRecompilation),
3866 "redundant OSR recompilation detected. memory leak in CodeCache!");
3867 #endif
3868 // only one compilation can be active
3869 assert(n->is_osr_method(), "wrong kind of nmethod");
3870 n->set_osr_link(osr_nmethods_head());
3871 set_osr_nmethods_head(n);
3872 // Raise the highest osr level if necessary
3873 n->method()->set_highest_osr_comp_level(MAX2(n->method()->highest_osr_comp_level(), n->comp_level()));
3874
3875 // Get rid of the osr methods for the same bci that have lower levels.
3876 for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
3877 nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
3878 if (inv != nullptr && inv->is_in_use()) {
3879 inv->make_not_entrant(nmethod::InvalidationReason::OSR_INVALIDATION_OF_LOWER_LEVEL);
3880 }
3881 }
3882 }
3883
3884 // Remove osr nmethod from the list. Return true if found and removed.
3885 bool InstanceKlass::remove_osr_nmethod(nmethod* n) {
3886 // This is a short non-blocking critical region, so the no safepoint check is ok.
3887 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
3888 assert(n->is_osr_method(), "wrong kind of nmethod");
3889 nmethod* last = nullptr;
3890 nmethod* cur = osr_nmethods_head();
3891 int max_level = CompLevel_none; // Find the max comp level excluding n
3892 Method* m = n->method();
3893 // Search for match
3894 bool found = false;
3895 while(cur != nullptr && cur != n) {
3896 if (m == cur->method()) {
3897 // Find max level before n
3898 max_level = MAX2(max_level, cur->comp_level());
3899 }
3900 last = cur;
3901 cur = cur->osr_link();
3902 }
3903 nmethod* next = nullptr;
3904 if (cur == n) {
3905 found = true;
3906 next = cur->osr_link();
3907 if (last == nullptr) {
3908 // Remove first element
3909 set_osr_nmethods_head(next);
3910 } else {
3911 last->set_osr_link(next);
3912 }
3913 }
3914 n->set_osr_link(nullptr);
3915 cur = next;
3916 while (cur != nullptr) {
3917 // Find max level after n
3918 if (m == cur->method()) {
3919 max_level = MAX2(max_level, cur->comp_level());
3920 }
3921 cur = cur->osr_link();
3922 }
3923 m->set_highest_osr_comp_level(max_level);
3924 return found;
3925 }
3926
3927 int InstanceKlass::mark_osr_nmethods(DeoptimizationScope* deopt_scope, const Method* m) {
3928 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
3929 nmethod* osr = osr_nmethods_head();
3930 int found = 0;
3931 while (osr != nullptr) {
3932 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3933 if (osr->method() == m) {
3934 deopt_scope->mark(osr);
3935 found++;
3936 }
3937 osr = osr->osr_link();
3938 }
3939 return found;
3940 }
3941
3942 nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
3943 ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
3944 nmethod* osr = osr_nmethods_head();
3945 nmethod* best = nullptr;
3946 while (osr != nullptr) {
3947 assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
3948 // There can be a time when a c1 osr method exists but we are waiting
3949 // for a c2 version. When c2 completes its osr nmethod we will trash
3950 // the c1 version and only be able to find the c2 version. However
3951 // while we overflow in the c1 code at back branches we don't want to
3952 // try and switch to the same code as we are already running
3953
3954 if (osr->method() == m &&
3955 (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
3956 if (match_level) {
3957 if (osr->comp_level() == comp_level) {
3958 // Found a match - return it.
3959 return osr;
3960 }
3961 } else {
3962 if (best == nullptr || (osr->comp_level() > best->comp_level())) {
3963 if (osr->comp_level() == CompilationPolicy::highest_compile_level()) {
3964 // Found the best possible - return it.
3965 return osr;
3966 }
3967 best = osr;
3968 }
3969 }
3970 }
3971 osr = osr->osr_link();
3972 }
3973
3974 assert(match_level == false || best == nullptr, "shouldn't pick up anything if match_level is set");
3975 if (best != nullptr && best->comp_level() >= comp_level) {
3976 return best;
3977 }
3978 return nullptr;
3979 }
3980
3981 // -----------------------------------------------------------------------------------------------------
3982 // Printing
3983
3984 #define BULLET " - "
3985
3986 static const char* state_names[] = {
3987 "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3988 };
3989
3990 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3991 ResourceMark rm;
3992 int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3993 for (int i = 0; i < len; i++) forward_refs[i] = 0;
3994 for (int i = 0; i < len; i++) {
3995 intptr_t e = start[i];
3996 st->print("%d : " INTPTR_FORMAT, i, e);
3997 if (forward_refs[i] != 0) {
3998 int from = forward_refs[i];
3999 int off = (int) start[from];
4000 st->print(" (offset %d <= [%d])", off, from);
4001 }
4002 if (MetaspaceObj::is_valid((Metadata*)e)) {
4003 st->print(" ");
4004 ((Metadata*)e)->print_value_on(st);
4005 } else if (self != nullptr && e > 0 && e < 0x10000) {
4006 address location = self + e;
4007 int index = (int)((intptr_t*)location - start);
4008 st->print(" (offset %d => [%d])", (int)e, index);
4009 if (index >= 0 && index < len)
4010 forward_refs[index] = i;
4011 }
4012 st->cr();
4013 }
4014 }
4015
4016 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
4017 return print_vtable(nullptr, reinterpret_cast<intptr_t*>(start), len, st);
4018 }
4019
4020 template<typename T>
4021 static void print_array_on(outputStream* st, Array<T>* array) {
4022 if (array == nullptr) { st->print_cr("nullptr"); return; }
4023 array->print_value_on(st); st->cr();
4024 if (Verbose || WizardMode) {
4025 for (int i = 0; i < array->length(); i++) {
4026 st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
4027 }
4028 }
4029 }
4030
4031 static void print_array_on(outputStream* st, Array<int>* array) {
4032 if (array == nullptr) { st->print_cr("nullptr"); return; }
4033 array->print_value_on(st); st->cr();
4034 if (Verbose || WizardMode) {
4035 for (int i = 0; i < array->length(); i++) {
4036 st->print("%d : %d", i, array->at(i)); st->cr();
4037 }
4038 }
4039 }
4040
4041 const char* InstanceKlass::init_state_name() const {
4042 return state_names[init_state()];
4043 }
4044
4045 void InstanceKlass::print_on(outputStream* st) const {
4046 assert(is_klass(), "must be klass");
4047 Klass::print_on(st);
4048
4049 st->print(BULLET"instance size: %d", size_helper()); st->cr();
4050 st->print(BULLET"klass size: %d", size()); st->cr();
4051 st->print(BULLET"access: "); access_flags().print_on(st); st->cr();
4052 st->print(BULLET"flags: "); _misc_flags.print_on(st); st->cr();
4053 st->print(BULLET"state: "); st->print_cr("%s", init_state_name());
4054 st->print(BULLET"name: "); name()->print_value_on(st); st->cr();
4055 st->print(BULLET"super: "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
4056 st->print(BULLET"sub: ");
4057 Klass* sub = subklass();
4058 int n;
4059 for (n = 0; sub != nullptr; n++, sub = sub->next_sibling()) {
4060 if (n < MaxSubklassPrintSize) {
4061 sub->print_value_on(st);
4062 st->print(" ");
4063 }
4064 }
4065 if (n >= MaxSubklassPrintSize) st->print("(%zd more klasses...)", n - MaxSubklassPrintSize);
4066 st->cr();
4067
4068 if (is_interface()) {
4069 st->print_cr(BULLET"nof implementors: %d", nof_implementors());
4070 if (nof_implementors() == 1) {
4071 st->print_cr(BULLET"implementor: ");
4072 st->print(" ");
4073 implementor()->print_value_on(st);
4074 st->cr();
4075 }
4076 }
4077
4078 st->print(BULLET"arrays: "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
4079 st->print(BULLET"methods: "); print_array_on(st, methods());
4080 st->print(BULLET"method ordering: "); print_array_on(st, method_ordering());
4081 if (default_methods() != nullptr) {
4082 st->print(BULLET"default_methods: "); print_array_on(st, default_methods());
4083 }
4084 print_on_maybe_null(st, BULLET"default vtable indices: ", default_vtable_indices());
4085 st->print(BULLET"local interfaces: "); local_interfaces()->print_value_on(st); st->cr();
4086 st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
4087
4088 st->print(BULLET"secondary supers: "); secondary_supers()->print_value_on(st); st->cr();
4089
4090 st->print(BULLET"hash_slot: %d", hash_slot()); st->cr();
4091 st->print(BULLET"secondary bitmap: " UINTX_FORMAT_X_0, _secondary_supers_bitmap); st->cr();
4092
4093 if (secondary_supers() != nullptr) {
4094 if (Verbose) {
4095 bool is_hashed = (_secondary_supers_bitmap != SECONDARY_SUPERS_BITMAP_FULL);
4096 st->print_cr(BULLET"---- secondary supers (%d words):", _secondary_supers->length());
4097 for (int i = 0; i < _secondary_supers->length(); i++) {
4098 ResourceMark rm; // for external_name()
4099 Klass* secondary_super = _secondary_supers->at(i);
4100 st->print(BULLET"%2d:", i);
4101 if (is_hashed) {
4102 int home_slot = compute_home_slot(secondary_super, _secondary_supers_bitmap);
4103 int distance = (i - home_slot) & SECONDARY_SUPERS_TABLE_MASK;
4104 st->print(" dist:%02d:", distance);
4105 }
4106 st->print_cr(" %p %s", secondary_super, secondary_super->external_name());
4107 }
4108 }
4109 }
4110 st->print(BULLET"constants: "); constants()->print_value_on(st); st->cr();
4111
4112 print_on_maybe_null(st, BULLET"class loader data: ", class_loader_data());
4113 print_on_maybe_null(st, BULLET"source file: ", source_file_name());
4114 if (source_debug_extension() != nullptr) {
4115 st->print(BULLET"source debug extension: ");
4116 st->print("%s", source_debug_extension());
4117 st->cr();
4118 }
4119 print_on_maybe_null(st, BULLET"class annotations: ", class_annotations());
4120 print_on_maybe_null(st, BULLET"class type annotations: ", class_type_annotations());
4121 print_on_maybe_null(st, BULLET"field annotations: ", fields_annotations());
4122 print_on_maybe_null(st, BULLET"field type annotations: ", fields_type_annotations());
4123 {
4124 bool have_pv = false;
4125 // previous versions are linked together through the InstanceKlass
4126 for (InstanceKlass* pv_node = previous_versions();
4127 pv_node != nullptr;
4128 pv_node = pv_node->previous_versions()) {
4129 if (!have_pv)
4130 st->print(BULLET"previous version: ");
4131 have_pv = true;
4132 pv_node->constants()->print_value_on(st);
4133 }
4134 if (have_pv) st->cr();
4135 }
4136
4137 print_on_maybe_null(st, BULLET"generic signature: ", generic_signature());
4138 st->print(BULLET"inner classes: "); inner_classes()->print_value_on(st); st->cr();
4139 st->print(BULLET"nest members: "); nest_members()->print_value_on(st); st->cr();
4140 print_on_maybe_null(st, BULLET"record components: ", record_components());
4141 st->print(BULLET"permitted subclasses: "); permitted_subclasses()->print_value_on(st); st->cr();
4142 st->print(BULLET"loadable descriptors: "); loadable_descriptors()->print_value_on(st); st->cr();
4143 if (java_mirror() != nullptr) {
4144 st->print(BULLET"java mirror: ");
4145 java_mirror()->print_value_on(st);
4146 st->cr();
4147 } else {
4148 st->print_cr(BULLET"java mirror: null");
4149 }
4150 st->print(BULLET"vtable length %d (start addr: " PTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
4151 if (vtable_length() > 0 && (Verbose || WizardMode)) print_vtable(start_of_vtable(), vtable_length(), st);
4152 st->print(BULLET"itable length %d (start addr: " PTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
4153 if (itable_length() > 0 && (Verbose || WizardMode)) print_vtable(nullptr, start_of_itable(), itable_length(), st);
4154 st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
4155
4156 FieldPrinter print_static_field(st);
4157 ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
4158 st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
4159 FieldPrinter print_nonstatic_field(st);
4160 InstanceKlass* ik = const_cast<InstanceKlass*>(this);
4161 ik->print_nonstatic_fields(&print_nonstatic_field);
4162
4163 st->print(BULLET"non-static oop maps (%d entries): ", nonstatic_oop_map_count());
4164 OopMapBlock* map = start_of_nonstatic_oop_maps();
4165 OopMapBlock* end_map = map + nonstatic_oop_map_count();
4166 while (map < end_map) {
4167 st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
4168 map++;
4169 }
4170 st->cr();
4171
4172 if (fieldinfo_search_table() != nullptr) {
4173 st->print_cr(BULLET"---- field info search table:");
4174 FieldInfoStream::print_search_table(st, _constants, _fieldinfo_stream, _fieldinfo_search_table);
4175 }
4176 }
4177
4178 void InstanceKlass::print_value_on(outputStream* st) const {
4179 assert(is_klass(), "must be klass");
4180 if (Verbose || WizardMode) access_flags().print_on(st);
4181 name()->print_value_on(st);
4182 }
4183
4184 void FieldPrinter::do_field(fieldDescriptor* fd) {
4185 for (int i = 0; i < _indent; i++) _st->print(" ");
4186 _st->print(BULLET);
4187 if (_obj == nullptr) {
4188 fd->print_on(_st, _base_offset);
4189 _st->cr();
4190 } else {
4191 fd->print_on_for(_st, _obj, _indent, _base_offset);
4192 if (!fd->field_flags().is_flat()) _st->cr();
4193 }
4194 }
4195
4196
4197 void InstanceKlass::oop_print_on(oop obj, outputStream* st, int indent, int base_offset) {
4198 Klass::oop_print_on(obj, st);
4199
4200 if (this == vmClasses::String_klass()) {
4201 typeArrayOop value = java_lang_String::value(obj);
4202 juint length = java_lang_String::length(obj);
4203 if (value != nullptr &&
4204 value->is_typeArray() &&
4205 length <= (juint) value->length()) {
4206 st->print(BULLET"string: ");
4207 java_lang_String::print(obj, st);
4208 st->cr();
4209 }
4210 }
4211
4212 st->print_cr(BULLET"---- fields (total size %zu words):", oop_size(obj));
4213 FieldPrinter print_field(st, obj, indent, base_offset);
4214 print_nonstatic_fields(&print_field);
4215
4216 if (this == vmClasses::Class_klass()) {
4217 st->print(BULLET"signature: ");
4218 java_lang_Class::print_signature(obj, st);
4219 st->cr();
4220 Klass* real_klass = java_lang_Class::as_Klass(obj);
4221 if (real_klass != nullptr && real_klass->is_instance_klass()) {
4222 st->print_cr(BULLET"---- static fields (%d):", java_lang_Class::static_oop_field_count(obj));
4223 InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
4224 }
4225 } else if (this == vmClasses::MethodType_klass()) {
4226 st->print(BULLET"signature: ");
4227 java_lang_invoke_MethodType::print_signature(obj, st);
4228 st->cr();
4229 }
4230 }
4231
4232 #ifndef PRODUCT
4233
4234 bool InstanceKlass::verify_itable_index(int i) {
4235 int method_count = klassItable::method_count_for_interface(this);
4236 assert(i >= 0 && i < method_count, "index out of bounds");
4237 return true;
4238 }
4239
4240 #endif //PRODUCT
4241
4242 void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
4243 st->print("a ");
4244 name()->print_value_on(st);
4245 obj->print_address_on(st);
4246 if (this == vmClasses::String_klass()
4247 && java_lang_String::value(obj) != nullptr) {
4248 ResourceMark rm;
4249 int len = java_lang_String::length(obj);
4250 int plen = (len < 24 ? len : 12);
4251 char* str = java_lang_String::as_utf8_string(obj, 0, plen);
4252 st->print(" = \"%s\"", str);
4253 if (len > plen)
4254 st->print("...[%d]", len);
4255 } else if (this == vmClasses::Class_klass()) {
4256 Klass* k = java_lang_Class::as_Klass(obj);
4257 st->print(" = ");
4258 if (k != nullptr) {
4259 k->print_value_on(st);
4260 } else {
4261 const char* tname = type2name(java_lang_Class::primitive_type(obj));
4262 st->print("%s", tname ? tname : "type?");
4263 }
4264 } else if (this == vmClasses::MethodType_klass()) {
4265 st->print(" = ");
4266 java_lang_invoke_MethodType::print_signature(obj, st);
4267 } else if (java_lang_boxing_object::is_instance(obj)) {
4268 st->print(" = ");
4269 java_lang_boxing_object::print(obj, st);
4270 } else if (this == vmClasses::LambdaForm_klass()) {
4271 oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
4272 if (vmentry != nullptr) {
4273 st->print(" => ");
4274 vmentry->print_value_on(st);
4275 }
4276 } else if (this == vmClasses::MemberName_klass()) {
4277 Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
4278 if (vmtarget != nullptr) {
4279 st->print(" = ");
4280 vmtarget->print_value_on(st);
4281 } else {
4282 oop clazz = java_lang_invoke_MemberName::clazz(obj);
4283 oop name = java_lang_invoke_MemberName::name(obj);
4284 if (clazz != nullptr) {
4285 clazz->print_value_on(st);
4286 } else {
4287 st->print("null");
4288 }
4289 st->print(".");
4290 if (name != nullptr) {
4291 name->print_value_on(st);
4292 } else {
4293 st->print("null");
4294 }
4295 }
4296 }
4297 }
4298
4299 const char* InstanceKlass::internal_name() const {
4300 return external_name();
4301 }
4302
4303 void InstanceKlass::print_class_load_logging(ClassLoaderData* loader_data,
4304 const ModuleEntry* module_entry,
4305 const ClassFileStream* cfs) const {
4306
4307 if (ClassListWriter::is_enabled()) {
4308 ClassListWriter::write(this, cfs);
4309 }
4310
4311 print_class_load_helper(loader_data, module_entry, cfs);
4312 print_class_load_cause_logging();
4313 }
4314
4315 void InstanceKlass::print_class_load_helper(ClassLoaderData* loader_data,
4316 const ModuleEntry* module_entry,
4317 const ClassFileStream* cfs) const {
4318
4319 if (!log_is_enabled(Info, class, load)) {
4320 return;
4321 }
4322
4323 ResourceMark rm;
4324 LogMessage(class, load) msg;
4325 stringStream info_stream;
4326
4327 // Name and class hierarchy info
4328 info_stream.print("%s", external_name());
4329
4330 // Source
4331 if (cfs != nullptr) {
4332 if (cfs->source() != nullptr) {
4333 const char* module_name = (module_entry->name() == nullptr) ? UNNAMED_MODULE : module_entry->name()->as_C_string();
4334 if (module_name != nullptr) {
4335 // When the boot loader created the stream, it didn't know the module name
4336 // yet. Let's format it now.
4337 if (cfs->from_boot_loader_modules_image()) {
4338 info_stream.print(" source: jrt:/%s", module_name);
4339 } else {
4340 info_stream.print(" source: %s", cfs->source());
4341 }
4342 } else {
4343 info_stream.print(" source: %s", cfs->source());
4344 }
4345 } else if (loader_data == ClassLoaderData::the_null_class_loader_data()) {
4346 Thread* current = Thread::current();
4347 Klass* caller = current->is_Java_thread() ?
4348 JavaThread::cast(current)->security_get_caller_class(1):
4349 nullptr;
4350 // caller can be null, for example, during a JVMTI VM_Init hook
4351 if (caller != nullptr) {
4352 info_stream.print(" source: instance of %s", caller->external_name());
4353 } else {
4354 // source is unknown
4355 }
4356 } else {
4357 oop class_loader = loader_data->class_loader();
4358 info_stream.print(" source: %s", class_loader->klass()->external_name());
4359 }
4360 } else {
4361 assert(this->in_aot_cache(), "must be");
4362 if (AOTMetaspace::in_aot_cache_dynamic_region((void*)this)) {
4363 info_stream.print(" source: shared objects file (top)");
4364 } else {
4365 info_stream.print(" source: shared objects file");
4366 }
4367 }
4368
4369 msg.info("%s", info_stream.as_string());
4370
4371 if (log_is_enabled(Debug, class, load)) {
4372 stringStream debug_stream;
4373
4374 // Class hierarchy info
4375 debug_stream.print(" klass: " PTR_FORMAT " super: " PTR_FORMAT,
4376 p2i(this), p2i(super()));
4377
4378 // Interfaces
4379 if (local_interfaces() != nullptr && local_interfaces()->length() > 0) {
4380 debug_stream.print(" interfaces:");
4381 int length = local_interfaces()->length();
4382 for (int i = 0; i < length; i++) {
4383 debug_stream.print(" " PTR_FORMAT,
4384 p2i(local_interfaces()->at(i)));
4385 }
4386 }
4387
4388 // Class loader
4389 debug_stream.print(" loader: [");
4390 loader_data->print_value_on(&debug_stream);
4391 debug_stream.print("]");
4392
4393 // Classfile checksum
4394 if (cfs) {
4395 debug_stream.print(" bytes: %d checksum: %08x",
4396 cfs->length(),
4397 ClassLoader::crc32(0, (const char*)cfs->buffer(),
4398 cfs->length()));
4399 }
4400
4401 msg.debug("%s", debug_stream.as_string());
4402 }
4403 }
4404
4405 void InstanceKlass::print_class_load_cause_logging() const {
4406 bool log_cause_native = log_is_enabled(Info, class, load, cause, native);
4407 if (log_cause_native || log_is_enabled(Info, class, load, cause)) {
4408 JavaThread* current = JavaThread::current();
4409 ResourceMark rm(current);
4410 const char* name = external_name();
4411
4412 if (LogClassLoadingCauseFor == nullptr ||
4413 (strcmp("*", LogClassLoadingCauseFor) != 0 &&
4414 strstr(name, LogClassLoadingCauseFor) == nullptr)) {
4415 return;
4416 }
4417
4418 // Log Java stack first
4419 {
4420 LogMessage(class, load, cause) msg;
4421 NonInterleavingLogStream info_stream{LogLevelType::Info, msg};
4422
4423 info_stream.print_cr("Java stack when loading %s:", name);
4424 current->print_stack_on(&info_stream);
4425 }
4426
4427 // Log native stack second
4428 if (log_cause_native) {
4429 // Log to string first so that lines can be indented
4430 stringStream stack_stream;
4431 char buf[O_BUFLEN];
4432 address lastpc = nullptr;
4433 NativeStackPrinter nsp(current);
4434 nsp.print_stack(&stack_stream, buf, sizeof(buf), lastpc,
4435 true /* print_source_info */, -1 /* max stack */);
4436
4437 LogMessage(class, load, cause, native) msg;
4438 NonInterleavingLogStream info_stream{LogLevelType::Info, msg};
4439 info_stream.print_cr("Native stack when loading %s:", name);
4440
4441 // Print each native stack line to the log
4442 int size = (int) stack_stream.size();
4443 char* stack = stack_stream.as_string();
4444 char* stack_end = stack + size;
4445 char* line_start = stack;
4446 for (char* p = stack; p < stack_end; p++) {
4447 if (*p == '\n') {
4448 *p = '\0';
4449 info_stream.print_cr("\t%s", line_start);
4450 line_start = p + 1;
4451 }
4452 }
4453 if (line_start < stack_end) {
4454 info_stream.print_cr("\t%s", line_start);
4455 }
4456 }
4457 }
4458 }
4459
4460 // Verification
4461
4462 class VerifyFieldClosure: public BasicOopIterateClosure {
4463 protected:
4464 template <class T> void do_oop_work(T* p) {
4465 oop obj = RawAccess<>::oop_load(p);
4466 if (!oopDesc::is_oop_or_null(obj)) {
4467 tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
4468 Universe::print_on(tty);
4469 guarantee(false, "boom");
4470 }
4471 }
4472 public:
4473 virtual void do_oop(oop* p) { VerifyFieldClosure::do_oop_work(p); }
4474 virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
4475 };
4476
4477 void InstanceKlass::verify_on(outputStream* st) {
4478 #ifndef PRODUCT
4479 // Avoid redundant verifies, this really should be in product.
4480 if (_verify_count == Universe::verify_count()) return;
4481 _verify_count = Universe::verify_count();
4482 #endif
4483
4484 // Verify Klass
4485 Klass::verify_on(st);
4486
4487 // Verify that klass is present in ClassLoaderData
4488 guarantee(class_loader_data()->contains_klass(this),
4489 "this class isn't found in class loader data");
4490
4491 // Verify vtables
4492 if (is_linked()) {
4493 // $$$ This used to be done only for m/s collections. Doing it
4494 // always seemed a valid generalization. (DLD -- 6/00)
4495 vtable().verify(st);
4496 }
4497
4498 // Verify first subklass
4499 if (subklass() != nullptr) {
4500 guarantee(subklass()->is_klass(), "should be klass");
4501 }
4502
4503 // Verify siblings
4504 Klass* super = this->super();
4505 Klass* sib = next_sibling();
4506 if (sib != nullptr) {
4507 if (sib == this) {
4508 fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
4509 }
4510
4511 guarantee(sib->is_klass(), "should be klass");
4512 guarantee(sib->super() == super, "siblings should have same superklass");
4513 }
4514
4515 // Verify local interfaces
4516 if (local_interfaces()) {
4517 Array<InstanceKlass*>* local_interfaces = this->local_interfaces();
4518 for (int j = 0; j < local_interfaces->length(); j++) {
4519 InstanceKlass* e = local_interfaces->at(j);
4520 guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
4521 }
4522 }
4523
4524 // Verify transitive interfaces
4525 if (transitive_interfaces() != nullptr) {
4526 Array<InstanceKlass*>* transitive_interfaces = this->transitive_interfaces();
4527 for (int j = 0; j < transitive_interfaces->length(); j++) {
4528 InstanceKlass* e = transitive_interfaces->at(j);
4529 guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
4530 }
4531 }
4532
4533 // Verify methods
4534 if (methods() != nullptr) {
4535 Array<Method*>* methods = this->methods();
4536 for (int j = 0; j < methods->length(); j++) {
4537 guarantee(methods->at(j)->is_method(), "non-method in methods array");
4538 }
4539 for (int j = 0; j < methods->length() - 1; j++) {
4540 Method* m1 = methods->at(j);
4541 Method* m2 = methods->at(j + 1);
4542 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
4543 }
4544 }
4545
4546 // Verify method ordering
4547 if (method_ordering() != nullptr) {
4548 Array<int>* method_ordering = this->method_ordering();
4549 int length = method_ordering->length();
4550 if (JvmtiExport::can_maintain_original_method_order() ||
4551 ((CDSConfig::is_using_archive() || CDSConfig::is_dumping_archive()) && length != 0)) {
4552 guarantee(length == methods()->length(), "invalid method ordering length");
4553 jlong sum = 0;
4554 for (int j = 0; j < length; j++) {
4555 int original_index = method_ordering->at(j);
4556 guarantee(original_index >= 0, "invalid method ordering index");
4557 guarantee(original_index < length, "invalid method ordering index");
4558 sum += original_index;
4559 }
4560 // Verify sum of indices 0,1,...,length-1
4561 guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
4562 } else {
4563 guarantee(length == 0, "invalid method ordering length");
4564 }
4565 }
4566
4567 // Verify default methods
4568 if (default_methods() != nullptr) {
4569 Array<Method*>* methods = this->default_methods();
4570 for (int j = 0; j < methods->length(); j++) {
4571 guarantee(methods->at(j)->is_method(), "non-method in methods array");
4572 }
4573 for (int j = 0; j < methods->length() - 1; j++) {
4574 Method* m1 = methods->at(j);
4575 Method* m2 = methods->at(j + 1);
4576 guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
4577 }
4578 }
4579
4580 // Verify JNI static field identifiers
4581 if (jni_ids() != nullptr) {
4582 jni_ids()->verify(this);
4583 }
4584
4585 // Verify other fields
4586 if (constants() != nullptr) {
4587 guarantee(constants()->is_constantPool(), "should be constant pool");
4588 }
4589 }
4590
4591 void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
4592 Klass::oop_verify_on(obj, st);
4593 VerifyFieldClosure blk;
4594 obj->oop_iterate(&blk);
4595 }
4596
4597 // JNIid class for jfieldIDs only
4598 // Note to reviewers:
4599 // These JNI functions are just moved over to column 1 and not changed
4600 // in the compressed oops workspace.
4601 JNIid::JNIid(InstanceKlass* holder, int offset, JNIid* next) {
4602 _holder = holder;
4603 _offset = offset;
4604 _next = next;
4605 DEBUG_ONLY(_is_static_field_id = false;)
4606 }
4607
4608 JNIid* JNIid::find(int offset) {
4609 JNIid* current = this;
4610 while (current != nullptr) {
4611 if (current->offset() == offset) return current;
4612 current = current->next();
4613 }
4614 return nullptr;
4615 }
4616
4617 void JNIid::deallocate(JNIid* current) {
4618 while (current != nullptr) {
4619 JNIid* next = current->next();
4620 delete current;
4621 current = next;
4622 }
4623 }
4624
4625 void JNIid::verify(InstanceKlass* holder) {
4626 int first_field_offset = InstanceMirrorKlass::offset_of_static_fields();
4627 int end_field_offset;
4628 end_field_offset = first_field_offset + (holder->static_field_size() * wordSize);
4629
4630 JNIid* current = this;
4631 while (current != nullptr) {
4632 guarantee(current->holder() == holder, "Invalid klass in JNIid");
4633 #ifdef ASSERT
4634 int o = current->offset();
4635 if (current->is_static_field_id()) {
4636 guarantee(o >= first_field_offset && o < end_field_offset, "Invalid static field offset in JNIid");
4637 }
4638 #endif
4639 current = current->next();
4640 }
4641 }
4642
4643 void InstanceKlass::set_init_state(ClassState state) {
4644 #ifdef ASSERT
4645 bool good_state = in_aot_cache() ? (_init_state <= state)
4646 : (_init_state < state);
4647 assert(good_state || state == allocated, "illegal state transition");
4648 #endif
4649 assert(_init_thread == nullptr, "should be cleared before state change");
4650 AtomicAccess::release_store(&_init_state, state);
4651 }
4652
4653 #if INCLUDE_JVMTI
4654
4655 // RedefineClasses() support for previous versions
4656
4657 // Globally, there is at least one previous version of a class to walk
4658 // during class unloading, which is saved because old methods in the class
4659 // are still running. Otherwise the previous version list is cleaned up.
4660 bool InstanceKlass::_should_clean_previous_versions = false;
4661
4662 // Returns true if there are previous versions of a class for class
4663 // unloading only. Also resets the flag to false. purge_previous_version
4664 // will set the flag to true if there are any left, i.e., if there's any
4665 // work to do for next time. This is to avoid the expensive code cache
4666 // walk in CLDG::clean_deallocate_lists().
4667 bool InstanceKlass::should_clean_previous_versions_and_reset() {
4668 bool ret = _should_clean_previous_versions;
4669 log_trace(redefine, class, iklass, purge)("Class unloading: should_clean_previous_versions = %s",
4670 ret ? "true" : "false");
4671 _should_clean_previous_versions = false;
4672 return ret;
4673 }
4674
4675 // This nulls out the jmethodID for all obsolete methods in the previous version of the 'klass'.
4676 // These obsolete methods only exist in the previous version and we're about to delete the memory for them.
4677 // The jmethodID for these are deallocated when we unload the class, so this doesn't remove them from the table.
4678 void InstanceKlass::clear_obsolete_jmethod_ids(InstanceKlass* klass) {
4679 Array<Method*>* method_refs = klass->methods();
4680 for (int k = 0; k < method_refs->length(); k++) {
4681 Method* method = method_refs->at(k);
4682 // Only need to clear obsolete methods.
4683 if (method != nullptr && method->is_obsolete()) {
4684 method->clear_jmethod_id();
4685 }
4686 }
4687 }
4688
4689 // Purge previous versions before adding new previous versions of the class and
4690 // during class unloading.
4691 void InstanceKlass::purge_previous_version_list() {
4692 assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
4693 assert(has_been_redefined(), "Should only be called for main class");
4694
4695 // Quick exit.
4696 if (previous_versions() == nullptr) {
4697 return;
4698 }
4699
4700 // This klass has previous versions so see what we can cleanup
4701 // while it is safe to do so.
4702
4703 int deleted_count = 0; // leave debugging breadcrumbs
4704 int live_count = 0;
4705 ClassLoaderData* loader_data = class_loader_data();
4706 assert(loader_data != nullptr, "should never be null");
4707
4708 ResourceMark rm;
4709 log_trace(redefine, class, iklass, purge)("%s: previous versions", external_name());
4710
4711 // previous versions are linked together through the InstanceKlass
4712 InstanceKlass* pv_node = previous_versions();
4713 InstanceKlass* last = this;
4714 int version = 0;
4715
4716 // check the previous versions list
4717 for (; pv_node != nullptr; ) {
4718
4719 ConstantPool* pvcp = pv_node->constants();
4720 assert(pvcp != nullptr, "cp ref was unexpectedly cleared");
4721
4722 if (!pvcp->on_stack()) {
4723 // If the constant pool isn't on stack, none of the methods
4724 // are executing. Unlink this previous_version.
4725 // The previous version InstanceKlass is on the ClassLoaderData deallocate list
4726 // so will be deallocated during the next phase of class unloading.
4727 log_trace(redefine, class, iklass, purge)
4728 ("previous version " PTR_FORMAT " is dead.", p2i(pv_node));
4729 // Unlink from previous version list.
4730 assert(pv_node->class_loader_data() == loader_data, "wrong loader_data");
4731 InstanceKlass* next = pv_node->previous_versions();
4732 clear_obsolete_jmethod_ids(pv_node); // jmethodID maintenance for the unloaded class
4733 pv_node->link_previous_versions(nullptr); // point next to null
4734 last->link_previous_versions(next);
4735 // Delete this node directly. Nothing is referring to it and we don't
4736 // want it to increase the counter for metadata to delete in CLDG.
4737 MetadataFactory::free_metadata(loader_data, pv_node);
4738 pv_node = next;
4739 deleted_count++;
4740 version++;
4741 continue;
4742 } else {
4743 assert(pvcp->pool_holder() != nullptr, "Constant pool with no holder");
4744 guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
4745 live_count++;
4746 if (pvcp->in_aot_cache()) {
4747 // Shared previous versions can never be removed so no cleaning is needed.
4748 log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is shared", p2i(pv_node));
4749 } else {
4750 // Previous version alive, set that clean is needed for next time.
4751 _should_clean_previous_versions = true;
4752 log_trace(redefine, class, iklass, purge)("previous version " PTR_FORMAT " is alive", p2i(pv_node));
4753 }
4754 }
4755
4756 // next previous version
4757 last = pv_node;
4758 pv_node = pv_node->previous_versions();
4759 version++;
4760 }
4761 log_trace(redefine, class, iklass, purge)
4762 ("previous version stats: live=%d, deleted=%d", live_count, deleted_count);
4763 }
4764
4765 void InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
4766 int emcp_method_count) {
4767 int obsolete_method_count = old_methods->length() - emcp_method_count;
4768
4769 if (emcp_method_count != 0 && obsolete_method_count != 0 &&
4770 _previous_versions != nullptr) {
4771 // We have a mix of obsolete and EMCP methods so we have to
4772 // clear out any matching EMCP method entries the hard way.
4773 int local_count = 0;
4774 for (int i = 0; i < old_methods->length(); i++) {
4775 Method* old_method = old_methods->at(i);
4776 if (old_method->is_obsolete()) {
4777 // only obsolete methods are interesting
4778 Symbol* m_name = old_method->name();
4779 Symbol* m_signature = old_method->signature();
4780
4781 // previous versions are linked together through the InstanceKlass
4782 int j = 0;
4783 for (InstanceKlass* prev_version = _previous_versions;
4784 prev_version != nullptr;
4785 prev_version = prev_version->previous_versions(), j++) {
4786
4787 Array<Method*>* method_refs = prev_version->methods();
4788 for (int k = 0; k < method_refs->length(); k++) {
4789 Method* method = method_refs->at(k);
4790
4791 if (!method->is_obsolete() &&
4792 method->name() == m_name &&
4793 method->signature() == m_signature) {
4794 // The current RedefineClasses() call has made all EMCP
4795 // versions of this method obsolete so mark it as obsolete
4796 log_trace(redefine, class, iklass, add)
4797 ("%s(%s): flush obsolete method @%d in version @%d",
4798 m_name->as_C_string(), m_signature->as_C_string(), k, j);
4799
4800 method->set_is_obsolete();
4801 break;
4802 }
4803 }
4804
4805 // The previous loop may not find a matching EMCP method, but
4806 // that doesn't mean that we can optimize and not go any
4807 // further back in the PreviousVersion generations. The EMCP
4808 // method for this generation could have already been made obsolete,
4809 // but there still may be an older EMCP method that has not
4810 // been made obsolete.
4811 }
4812
4813 if (++local_count >= obsolete_method_count) {
4814 // no more obsolete methods so bail out now
4815 break;
4816 }
4817 }
4818 }
4819 }
4820 }
4821
4822 // Save the scratch_class as the previous version if any of the methods are running.
4823 // The previous_versions are used to set breakpoints in EMCP methods and they are
4824 // also used to clean MethodData links to redefined methods that are no longer running.
4825 void InstanceKlass::add_previous_version(InstanceKlass* scratch_class,
4826 int emcp_method_count) {
4827 assert(Thread::current()->is_VM_thread(),
4828 "only VMThread can add previous versions");
4829
4830 ResourceMark rm;
4831 log_trace(redefine, class, iklass, add)
4832 ("adding previous version ref for %s, EMCP_cnt=%d", scratch_class->external_name(), emcp_method_count);
4833
4834 // Clean out old previous versions for this class
4835 purge_previous_version_list();
4836
4837 // Mark newly obsolete methods in remaining previous versions. An EMCP method from
4838 // a previous redefinition may be made obsolete by this redefinition.
4839 Array<Method*>* old_methods = scratch_class->methods();
4840 mark_newly_obsolete_methods(old_methods, emcp_method_count);
4841
4842 // If the constant pool for this previous version of the class
4843 // is not marked as being on the stack, then none of the methods
4844 // in this previous version of the class are on the stack so
4845 // we don't need to add this as a previous version.
4846 ConstantPool* cp_ref = scratch_class->constants();
4847 if (!cp_ref->on_stack()) {
4848 log_trace(redefine, class, iklass, add)("scratch class not added; no methods are running");
4849 scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class);
4850 return;
4851 }
4852
4853 // Add previous version if any methods are still running or if this is
4854 // a shared class which should never be removed.
4855 assert(scratch_class->previous_versions() == nullptr, "shouldn't have a previous version");
4856 scratch_class->link_previous_versions(previous_versions());
4857 link_previous_versions(scratch_class);
4858 if (cp_ref->in_aot_cache()) {
4859 log_trace(redefine, class, iklass, add) ("scratch class added; class is shared");
4860 } else {
4861 // We only set clean_previous_versions flag for processing during class
4862 // unloading for non-shared classes.
4863 _should_clean_previous_versions = true;
4864 log_trace(redefine, class, iklass, add) ("scratch class added; one of its methods is on_stack.");
4865 }
4866 } // end add_previous_version()
4867
4868 #endif // INCLUDE_JVMTI
4869
4870 Method* InstanceKlass::method_with_idnum(int idnum) const {
4871 Method* m = nullptr;
4872 if (idnum < methods()->length()) {
4873 m = methods()->at(idnum);
4874 }
4875 if (m == nullptr || m->method_idnum() != idnum) {
4876 for (int index = 0; index < methods()->length(); ++index) {
4877 m = methods()->at(index);
4878 if (m->method_idnum() == idnum) {
4879 return m;
4880 }
4881 }
4882 // None found, return null for the caller to handle.
4883 return nullptr;
4884 }
4885 return m;
4886 }
4887
4888
4889 Method* InstanceKlass::method_with_orig_idnum(int idnum) const {
4890 if (idnum >= methods()->length()) {
4891 return nullptr;
4892 }
4893 Method* m = methods()->at(idnum);
4894 if (m != nullptr && m->orig_method_idnum() == idnum) {
4895 return m;
4896 }
4897 // Obsolete method idnum does not match the original idnum
4898 for (int index = 0; index < methods()->length(); ++index) {
4899 m = methods()->at(index);
4900 if (m->orig_method_idnum() == idnum) {
4901 return m;
4902 }
4903 }
4904 // None found, return null for the caller to handle.
4905 return nullptr;
4906 }
4907
4908
4909 Method* InstanceKlass::method_with_orig_idnum(int idnum, int version) const {
4910 const InstanceKlass* holder = get_klass_version(version);
4911 if (holder == nullptr) {
4912 return nullptr; // The version of klass is gone, no method is found
4913 }
4914 return holder->method_with_orig_idnum(idnum);
4915 }
4916
4917 #if INCLUDE_JVMTI
4918 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4919 return _cached_class_file;
4920 }
4921
4922 jint InstanceKlass::get_cached_class_file_len() {
4923 return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4924 }
4925
4926 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4927 return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4928 }
4929 #endif
4930
4931 // Make a step iterating over the class hierarchy under the root class.
4932 // Skips subclasses if requested.
4933 void ClassHierarchyIterator::next() {
4934 assert(_current != nullptr, "required");
4935 if (_visit_subclasses && _current->subklass() != nullptr) {
4936 _current = _current->subklass();
4937 return; // visit next subclass
4938 }
4939 _visit_subclasses = true; // reset
4940 while (_current->next_sibling() == nullptr && _current != _root) {
4941 _current = _current->java_super(); // backtrack; no more sibling subclasses left
4942 }
4943 if (_current == _root) {
4944 // Iteration is over (back at root after backtracking). Invalidate the iterator.
4945 _current = nullptr;
4946 return;
4947 }
4948 _current = _current->next_sibling();
4949 return; // visit next sibling subclass
4950 }