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