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