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