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/aotSystemDictionary.hpp"
30 #include "cds/archiveUtils.hpp"
31 #include "cds/cdsConfig.hpp"
32 #include "cds/cdsEnumKlass.hpp"
33 #include "cds/classListWriter.hpp"
34 #include "classfile/classFileParser.hpp"
35 #include "classfile/classFileStream.hpp"
36 #include "classfile/classLoader.hpp"
37 #include "classfile/classLoaderData.inline.hpp"
38 #include "classfile/javaClasses.hpp"
39 #include "classfile/javaStackTraceClasses.hpp"
40 #include "classfile/moduleEntry.hpp"
41 #include "classfile/systemDictionary.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 if (!_optional_flat_layout.is_initialized()) {
178 st->print("uninitialized");
179 } else if (_optional_flat_layout.is_flat()) {
180 _optional_flat_layout.get().print_on(st);
181 } else {
182 st->print("reference");
183 }
184 }
185
186 // A value class is considered naturally atomic if its layout,
187 // once all fields flattening have been applied, contains a single primitive
188 // or oop field. Because primitive types and oops are already handled
189 // atomically by the JVM, it means that there's no need to take
190 // special precautions when reading or writing this value to guarantee
191 // cross-fields invariants. Nullability has to be taken into consideration,
192 // as the null-marker has to be considered as a pseudo-field which must
193 // be kept consistent with the payload. The only kind of value class
194 // that can be considered naturally atomic when nullable is the empty
195 // value classes because the dummy field is re-used as a null-marker.
196 bool InstanceKlass::is_naturally_atomic(bool null_free) const {
197 assert(!is_identity_class(), "Doesn't make sense for an identity class");
198 if (null_free) {
199 // No extra null-marker, just check the layout of the fields
200 return _misc_flags.is_naturally_atomic();
201 } else {
202 // Requires a null-marker, can't have any other fields
203 return ValueKlass::cast(this)->is_empty_value_type();
204 }
205 }
206
207 bool InstanceKlass::_finalization_enabled = true;
208 static int call_class_initializer_counter = 0; // for debugging
209
210 static inline bool is_class_loader(const Symbol* class_name,
211 const ClassFileParser& parser) {
212 assert(class_name != nullptr, "invariant");
213
214 if (class_name == vmSymbols::java_lang_ClassLoader()) {
215 return true;
216 }
217
218 if (vmClasses::ClassLoader_klass_is_loaded()) {
219 const Klass* const super_klass = parser.super_klass();
220 if (super_klass != nullptr) {
221 if (super_klass->is_subtype_of(vmClasses::ClassLoader_klass())) {
222 return true;
223 }
224 }
225 }
226 return false;
227 }
228
229 bool InstanceKlass::field_is_null_free_value_type(int index) const {
230 return field(index).field_flags().is_null_free_value_type();
231 }
232
233 bool InstanceKlass::is_class_in_loadable_descriptors_attribute(Symbol* name) const {
234 if (_loadable_descriptors == nullptr) return false;
235 for (int i = 0; i < _loadable_descriptors->length(); i++) {
236 Symbol* class_name = _constants->symbol_at(_loadable_descriptors->at(i));
237 if (class_name == name) return true;
238 }
239 return false;
240 }
241
242 int InstanceKlass::field_null_marker_offset(int index) const {
243 const FieldInfo field = this->field(index);
244 if (!field.field_flags().has_null_marker()) {
245 return -1;
246 }
247
248 const ValueKlass* const vk = value_field_info(index).klass();
249 const int nm_offset = vk->null_marker_offset_in_payload();
250 return field_offset(index) + nm_offset;
251 }
252
253 static inline bool is_stack_chunk_class(const Symbol* class_name,
254 const ClassLoaderData* loader_data) {
255 return (class_name == vmSymbols::jdk_internal_vm_StackChunk() &&
256 loader_data->is_the_null_class_loader_data());
257 }
258
259 // private: called to verify that k is a static member of this nest.
260 // We know that k is an instance class in the same package and hence the
261 // same classloader.
262 bool InstanceKlass::has_nest_member(JavaThread* current, InstanceKlass* k) const {
263 assert(!is_hidden(), "unexpected hidden class");
264 if (_nest_members == nullptr || _nest_members == Universe::the_empty_short_array()) {
265 if (log_is_enabled(Trace, class, nestmates)) {
266 ResourceMark rm(current);
267 log_trace(class, nestmates)("Checked nest membership of %s in non-nest-host class %s",
268 k->external_name(), this->external_name());
269 }
270 return false;
271 }
272
273 if (log_is_enabled(Trace, class, nestmates)) {
274 ResourceMark rm(current);
275 log_trace(class, nestmates)("Checking nest membership of %s in %s",
276 k->external_name(), this->external_name());
277 }
278
279 // Check for the named class in _nest_members.
280 // We don't resolve, or load, any classes.
281 for (int i = 0; i < _nest_members->length(); i++) {
282 int cp_index = _nest_members->at(i);
283 Symbol* name = _constants->klass_name_at(cp_index);
284 if (name == k->name()) {
285 log_trace(class, nestmates)("- named class found at nest_members[%d] => cp[%d]", i, cp_index);
286 return true;
287 }
288 }
289 log_trace(class, nestmates)("- class is NOT a nest member!");
290 return false;
291 }
292
293 // Called to verify that k is a permitted subclass of this class.
294 // The incoming stringStream is used to format the messages for error logging and for the caller
295 // to use for exception throwing.
296 bool InstanceKlass::has_as_permitted_subclass(const InstanceKlass* k, stringStream& ss) const {
297 Thread* current = Thread::current();
298 assert(k != nullptr, "sanity check");
299 assert(_permitted_subclasses != nullptr && _permitted_subclasses != Universe::the_empty_short_array(),
300 "unexpected empty _permitted_subclasses array");
301
302 if (log_is_enabled(Trace, class, sealed)) {
303 ResourceMark rm(current);
304 log_trace(class, sealed)("Checking for permitted subclass %s in %s",
305 k->external_name(), this->external_name());
306 }
307
308 // Check that the class and its super are in the same module.
309 if (k->module() != this->module()) {
310 ss.print("Failed same module check: subclass %s is in module '%s' with loader %s, "
311 "and sealed class %s is in module '%s' with loader %s",
312 k->external_name(),
313 k->module()->name_as_C_string(),
314 k->module()->loader_data()->loader_name_and_id(),
315 this->external_name(),
316 this->module()->name_as_C_string(),
317 this->module()->loader_data()->loader_name_and_id());
318 log_trace(class, sealed)(" - %s", ss.as_string());
319 return false;
320 }
321
322 if (!k->is_public() && !is_same_class_package(k)) {
323 ss.print("Failed same package check: non-public subclass %s is in package '%s' with classloader %s, "
324 "and sealed class %s is in package '%s' with classloader %s",
325 k->external_name(),
326 k->package() != nullptr ? k->package()->name()->as_C_string() : "unnamed",
327 k->module()->loader_data()->loader_name_and_id(),
328 this->external_name(),
329 this->package() != nullptr ? this->package()->name()->as_C_string() : "unnamed",
330 this->module()->loader_data()->loader_name_and_id());
331 log_trace(class, sealed)(" - %s", ss.as_string());
332 return false;
333 }
334
335 for (int i = 0; i < _permitted_subclasses->length(); i++) {
336 int cp_index = _permitted_subclasses->at(i);
337 Symbol* name = _constants->klass_name_at(cp_index);
338 if (name == k->name()) {
339 log_trace(class, sealed)("- Found it at permitted_subclasses[%d] => cp[%d]", i, cp_index);
340 return true;
341 }
342 }
343
344 ss.print("Failed listed permitted subclass check: class %s is not a permitted subclass of %s",
345 k->external_name(), this->external_name());
346 log_trace(class, sealed)(" - %s", ss.as_string());
347 return false;
348 }
349
350 // Return nest-host class, resolving, validating and saving it if needed.
351 // In cases where this is called from a thread that cannot do classloading
352 // (such as a native JIT thread) then we simply return null, which in turn
353 // causes the access check to return false. Such code will retry the access
354 // from a more suitable environment later. Otherwise the _nest_host is always
355 // set once this method returns.
356 // Any errors from nest-host resolution must be preserved so they can be queried
357 // from higher-level access checking code, and reported as part of access checking
358 // exceptions.
359 // VirtualMachineErrors are propagated with a null return.
360 // Under any conditions where the _nest_host can be set to non-null the resulting
361 // value of it and, if applicable, the nest host resolution/validation error,
362 // are idempotent.
363 InstanceKlass* InstanceKlass::nest_host(TRAPS) {
364 InstanceKlass* nest_host_k = _nest_host;
365 if (nest_host_k != nullptr) {
366 return nest_host_k;
367 }
368
369 ResourceMark rm(THREAD);
370
371 // need to resolve and save our nest-host class.
372 if (_nest_host_index != 0) { // we have a real nest_host
373 // Before trying to resolve check if we're in a suitable context
374 bool can_resolve = THREAD->can_call_java();
375 if (!can_resolve && !_constants->tag_at(_nest_host_index).is_klass()) {
376 log_trace(class, nestmates)("Rejected resolution of nest-host of %s in unsuitable thread",
377 this->external_name());
378 return nullptr; // sentinel to say "try again from a different context"
379 }
380
381 log_trace(class, nestmates)("Resolving nest-host of %s using cp entry for %s",
382 this->external_name(),
383 _constants->klass_name_at(_nest_host_index)->as_C_string());
384
385 Klass* k = _constants->klass_at(_nest_host_index, THREAD);
386 if (HAS_PENDING_EXCEPTION) {
387 if (PENDING_EXCEPTION->is_a(vmClasses::VirtualMachineError_klass())) {
388 return nullptr; // propagate VMEs
389 }
390 stringStream ss;
391 char* target_host_class = _constants->klass_name_at(_nest_host_index)->as_C_string();
392 ss.print("Nest host resolution of %s with host %s failed: ",
393 this->external_name(), target_host_class);
394 java_lang_Throwable::print(PENDING_EXCEPTION, &ss);
395 constantPoolHandle cph(THREAD, constants());
396 SystemDictionary::add_nest_host_error(cph, _nest_host_index, ss);
397 CLEAR_PENDING_EXCEPTION;
398
399 log_trace(class, nestmates)("%s", ss.base());
400 } else {
401 // A valid nest-host is an instance class in the current package that lists this
402 // class as a nest member. If any of these conditions are not met the class is
403 // its own nest-host.
404 const char* error = nullptr;
405
406 // JVMS 5.4.4 indicates package check comes first
407 if (is_same_class_package(k)) {
408 // Now check actual membership. We can't be a member if our "host" is
409 // not an instance class.
410 if (k->is_instance_klass()) {
411 nest_host_k = InstanceKlass::cast(k);
412 bool is_member = nest_host_k->has_nest_member(THREAD, this);
413 if (is_member) {
414 _nest_host = nest_host_k; // save resolved nest-host value
415
416 log_trace(class, nestmates)("Resolved nest-host of %s to %s",
417 this->external_name(), k->external_name());
418 return nest_host_k;
419 } else {
420 error = "current type is not listed as a nest member";
421 }
422 } else {
423 error = "host is not an instance class";
424 }
425 } else {
426 error = "types are in different packages";
427 }
428
429 // something went wrong, so record what and log it
430 {
431 stringStream ss;
432 ss.print("Type %s (loader: %s) is not a nest member of type %s (loader: %s): %s",
433 this->external_name(),
434 this->class_loader_data()->loader_name_and_id(),
435 k->external_name(),
436 k->class_loader_data()->loader_name_and_id(),
437 error);
438 constantPoolHandle cph(THREAD, constants());
439 SystemDictionary::add_nest_host_error(cph, _nest_host_index, ss);
440 log_trace(class, nestmates)("%s", ss.base());
441 }
442 }
443 } else {
444 log_trace(class, nestmates)("Type %s is not part of a nest: setting nest-host to self",
445 this->external_name());
446 }
447
448 // Either not in an explicit nest, or else an error occurred, so
449 // the nest-host is set to `this`. Any thread that sees this assignment
450 // will also see any setting of nest_host_error(), if applicable.
451 return (_nest_host = this);
452 }
453
454 // Dynamic nest member support: set this class's nest host to the given class.
455 // This occurs as part of the class definition, as soon as the instanceKlass
456 // has been created and doesn't require further resolution. The code:
457 // lookup().defineHiddenClass(bytes_for_X, NESTMATE);
458 // results in:
459 // class_of_X.set_nest_host(lookup().lookupClass().getNestHost())
460 // If it has an explicit _nest_host_index or _nest_members, these will be ignored.
461 // We also know the "host" is a valid nest-host in the same package so we can
462 // assert some of those facts.
463 void InstanceKlass::set_nest_host(InstanceKlass* host) {
464 assert(is_hidden(), "must be a hidden class");
465 assert(host != nullptr, "null nest host specified");
466 assert(_nest_host == nullptr, "current class has resolved nest-host");
467 assert(nest_host_error() == nullptr, "unexpected nest host resolution error exists: %s",
468 nest_host_error());
469 assert((host->_nest_host == nullptr && host->_nest_host_index == 0) ||
470 (host->_nest_host == host), "proposed host is not a valid nest-host");
471 // Can't assert this as package is not set yet:
472 // assert(is_same_class_package(host), "proposed host is in wrong package");
473
474 if (log_is_enabled(Trace, class, nestmates)) {
475 ResourceMark rm;
476 const char* msg = "";
477 // a hidden class does not expect a statically defined nest-host
478 if (_nest_host_index > 0) {
479 msg = "(the NestHost attribute in the current class is ignored)";
480 } else if (_nest_members != nullptr && _nest_members != Universe::the_empty_short_array()) {
481 msg = "(the NestMembers attribute in the current class is ignored)";
482 }
483 log_trace(class, nestmates)("Injected type %s into the nest of %s %s",
484 this->external_name(),
485 host->external_name(),
486 msg);
487 }
488 // set dynamic nest host
489 _nest_host = host;
490 // Record dependency to keep nest host from being unloaded before this class.
491 ClassLoaderData* this_key = class_loader_data();
492 assert(this_key != nullptr, "sanity");
493 this_key->record_dependency(host);
494 }
495
496 // check if 'this' and k are nestmates (same nest_host), or k is our nest_host,
497 // or we are k's nest_host - all of which is covered by comparing the two
498 // resolved_nest_hosts.
499 // Any exceptions (i.e. VMEs) are propagated.
500 bool InstanceKlass::has_nestmate_access_to(InstanceKlass* k, TRAPS) {
501
502 assert(this != k, "this should be handled by higher-level code");
503
504 // Per JVMS 5.4.4 we first resolve and validate the current class, then
505 // the target class k.
506
507 InstanceKlass* cur_host = nest_host(CHECK_false);
508 if (cur_host == nullptr) {
509 return false;
510 }
511
512 Klass* k_nest_host = k->nest_host(CHECK_false);
513 if (k_nest_host == nullptr) {
514 return false;
515 }
516
517 bool access = (cur_host == k_nest_host);
518
519 ResourceMark rm(THREAD);
520 log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
521 this->external_name(),
522 access ? "" : "NOT ",
523 k->external_name());
524 return access;
525 }
526
527 const char* InstanceKlass::nest_host_error() {
528 if (_nest_host_index == 0) {
529 return nullptr;
530 } else {
531 constantPoolHandle cph(Thread::current(), constants());
532 return SystemDictionary::find_nest_host_error(cph, (int)_nest_host_index);
533 }
534 }
535
536 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
537 const int size = InstanceKlass::size(parser.vtable_size(),
538 parser.itable_size(),
539 nonstatic_oop_map_size(parser.total_oop_map_count()),
540 parser.is_interface(),
541 parser.is_concrete_value_class());
542
543 const Symbol* const class_name = parser.class_name();
544 assert(class_name != nullptr, "invariant");
545 ClassLoaderData* loader_data = parser.loader_data();
546 assert(loader_data != nullptr, "invariant");
547
548 InstanceKlass* ik;
549
550 // Allocation
551 if (parser.is_instance_ref_klass()) {
552 // java.lang.ref.Reference
553 ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
554 } else if (class_name == vmSymbols::java_lang_Class()) {
555 // mirror - java.lang.Class
556 ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
557 } else if (is_stack_chunk_class(class_name, loader_data)) {
558 // stack chunk
559 ik = new (loader_data, size, THREAD) InstanceStackChunkKlass(parser);
560 } else if (is_class_loader(class_name, parser)) {
561 // class loader - java.lang.ClassLoader
562 ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
563 } else if (parser.is_concrete_value_class()) {
564 // value type
565 ik = new (loader_data, size, THREAD) ValueKlass(parser);
566 } else {
567 // normal
568 ik = new (loader_data, size, THREAD) InstanceKlass(parser);
569 }
570
571 assert(ik == nullptr || CompressedKlassPointers::is_encodable(ik),
572 "Klass " PTR_FORMAT "needs a narrow Klass ID, but is not encodable", p2i(ik));
573
574 // Check for pending exception before adding to the loader data and incrementing
575 // class count. Can get OOM here.
576 if (HAS_PENDING_EXCEPTION) {
577 return nullptr;
578 }
579
580 return ik;
581 }
582
583 // copy method ordering from resource area to Metaspace
584 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
585 if (m != nullptr) {
586 // allocate a new array and copy contents (memcpy?)
587 _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
588 for (int i = 0; i < m->length(); i++) {
589 _method_ordering->at_put(i, m->at(i));
590 }
591 } else {
592 _method_ordering = Universe::the_empty_int_array();
593 }
594 }
595
596 // create a new array of vtable_indices for default methods
597 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
598 Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
599 assert(default_vtable_indices() == nullptr, "only create once");
600 set_default_vtable_indices(vtable_indices);
601 return vtable_indices;
602 }
603
604
605 InstanceKlass::InstanceKlass() {
606 assert(CDSConfig::is_dumping_static_archive() || CDSConfig::is_using_archive(), "only for CDS");
607 }
608
609 InstanceKlass::InstanceKlass(const ClassFileParser& parser, KlassKind kind, markWord prototype_header, ReferenceType reference_type) :
610 Klass(kind, prototype_header),
611 _nest_members(nullptr),
612 _nest_host(nullptr),
613 _permitted_subclasses(nullptr),
614 _record_components(nullptr),
615 _static_field_size(parser.static_field_size()),
616 _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
617 _itable_len(parser.itable_size()),
618 _nest_host_index(0),
619 _init_state(allocated),
620 _reference_type(reference_type),
621 _acmp_maps_offset(0),
622 _init_thread(nullptr),
623 _value_field_info_array(nullptr),
624 _loadable_descriptors(nullptr),
625 _acmp_maps_array(nullptr),
626 _adr_value_klass_members(nullptr)
627 {
628 set_vtable_length(parser.vtable_size());
629 set_access_flags(parser.access_flags());
630 if (parser.is_hidden()) set_is_hidden();
631 set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
632 false));
633 if (parser.has_flat_fields()) {
634 set_has_flat_fields();
635 }
636
637 assert(nullptr == _methods, "underlying memory not zeroed?");
638 assert(is_instance_klass(), "is layout incorrect?");
639 assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
640 }
641
642 void InstanceKlass::set_is_cloneable() {
643 if (name() == vmSymbols::java_lang_invoke_MemberName()) {
644 assert(is_final(), "no subclasses allowed");
645 // MemberName cloning should not be intrinsified and always happen in JVM_Clone.
646 } else if (reference_type() != REF_NONE) {
647 // Reference cloning should not be intrinsified and always happen in JVM_Clone.
648 } else {
649 set_is_cloneable_fast();
650 }
651 }
652
653 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
654 Array<Method*>* methods) {
655 if (methods != nullptr && methods != Universe::the_empty_method_array() &&
656 !methods->in_aot_cache()) {
657 for (int i = 0; i < methods->length(); i++) {
658 Method* method = methods->at(i);
659 if (method == nullptr) continue; // maybe null if error processing
660 // Only want to delete methods that are not executing for RedefineClasses.
661 // The previous version will point to them so they're not totally dangling
662 assert (!method->on_stack(), "shouldn't be called with methods on stack");
663 MetadataFactory::free_metadata(loader_data, method);
664 }
665 MetadataFactory::free_array<Method*>(loader_data, methods);
666 }
667 }
668
669 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
670 const InstanceKlass* super_klass,
671 Array<InstanceKlass*>* local_interfaces,
672 Array<InstanceKlass*>* transitive_interfaces) {
673 // Only deallocate transitive interfaces if not empty, same as super class
674 // or same as local interfaces. See code in parseClassFile.
675 Array<InstanceKlass*>* ti = transitive_interfaces;
676 if (ti != Universe::the_empty_instance_klass_array() && ti != local_interfaces) {
677 // check that the interfaces don't come from super class
678 Array<InstanceKlass*>* sti = (super_klass == nullptr) ? nullptr :
679 super_klass->transitive_interfaces();
680 if (ti != sti && ti != nullptr && !ti->in_aot_cache()) {
681 MetadataFactory::free_array<InstanceKlass*>(loader_data, ti);
682 }
683 }
684
685 // local interfaces can be empty
686 if (local_interfaces != Universe::the_empty_instance_klass_array() &&
687 local_interfaces != nullptr && !local_interfaces->in_aot_cache()) {
688 MetadataFactory::free_array<InstanceKlass*>(loader_data, local_interfaces);
689 }
690 }
691
692 void InstanceKlass::deallocate_record_components(ClassLoaderData* loader_data,
693 Array<RecordComponent*>* record_components) {
694 if (record_components != nullptr && !record_components->in_aot_cache()) {
695 for (int i = 0; i < record_components->length(); i++) {
696 RecordComponent* record_component = record_components->at(i);
697 MetadataFactory::free_metadata(loader_data, record_component);
698 }
699 MetadataFactory::free_array<RecordComponent*>(loader_data, record_components);
700 }
701 }
702
703 // This function deallocates the metadata and C heap pointers that the
704 // InstanceKlass points to.
705 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
706 // Orphan the mirror first, CMS thinks it's still live.
707 if (java_mirror() != nullptr) {
708 java_lang_Class::set_klass(java_mirror(), nullptr);
709 }
710
711 // Also remove mirror from handles
712 loader_data->remove_handle(_java_mirror);
713
714 // Need to take this class off the class loader data list.
715 loader_data->remove_class(this);
716
717 // The array_klass for this class is created later, after error handling.
718 // For class redefinition, we keep the original class so this scratch class
719 // doesn't have an array class. Either way, assert that there is nothing
720 // to deallocate.
721 assert(array_klasses() == nullptr, "array classes shouldn't be created for this class yet");
722
723 // Release C heap allocated data that this points to, which includes
724 // reference counting symbol names.
725 // Can't release the constant pool or MethodData C heap data here because the constant
726 // pool can be deallocated separately from the InstanceKlass for default methods and
727 // redefine classes. MethodData can also be released separately.
728 release_C_heap_structures(/* release_sub_metadata */ false);
729
730 deallocate_methods(loader_data, methods());
731 set_methods(nullptr);
732
733 deallocate_record_components(loader_data, record_components());
734 set_record_components(nullptr);
735
736 if (method_ordering() != nullptr &&
737 method_ordering() != Universe::the_empty_int_array() &&
738 !method_ordering()->in_aot_cache()) {
739 MetadataFactory::free_array<int>(loader_data, method_ordering());
740 }
741 set_method_ordering(nullptr);
742
743 // default methods can be empty
744 if (default_methods() != nullptr &&
745 default_methods() != Universe::the_empty_method_array() &&
746 !default_methods()->in_aot_cache()) {
747 MetadataFactory::free_array<Method*>(loader_data, default_methods());
748 }
749 // Do NOT deallocate the default methods, they are owned by superinterfaces.
750 set_default_methods(nullptr);
751
752 // default methods vtable indices can be empty
753 if (default_vtable_indices() != nullptr &&
754 !default_vtable_indices()->in_aot_cache()) {
755 MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
756 }
757 set_default_vtable_indices(nullptr);
758
759
760 // This array is in Klass, but remove it with the InstanceKlass since
761 // this place would be the only caller and it can share memory with transitive
762 // interfaces.
763 if (secondary_supers() != nullptr &&
764 secondary_supers() != Universe::the_empty_klass_array() &&
765 // see comments in compute_secondary_supers about the following cast
766 (address)(secondary_supers()) != (address)(transitive_interfaces()) &&
767 !secondary_supers()->in_aot_cache()) {
768 MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
769 }
770 set_secondary_supers(nullptr, SECONDARY_SUPERS_BITMAP_EMPTY);
771
772 deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
773 set_transitive_interfaces(nullptr);
774 set_local_interfaces(nullptr);
775
776 if (fieldinfo_stream() != nullptr && !fieldinfo_stream()->in_aot_cache()) {
777 MetadataFactory::free_array<u1>(loader_data, fieldinfo_stream());
778 }
779 set_fieldinfo_stream(nullptr);
780
781 if (fieldinfo_search_table() != nullptr && !fieldinfo_search_table()->in_aot_cache()) {
782 MetadataFactory::free_array<u1>(loader_data, fieldinfo_search_table());
783 }
784 set_fieldinfo_search_table(nullptr);
785
786 if (fields_status() != nullptr && !fields_status()->in_aot_cache()) {
787 MetadataFactory::free_array<FieldStatus>(loader_data, fields_status());
788 }
789 set_fields_status(nullptr);
790
791 if (value_field_info_array() != nullptr) {
792 MetadataFactory::free_array<ValueFieldInfo>(loader_data, value_field_info_array());
793 }
794 set_value_field_info_array(nullptr);
795
796 // If a method from a redefined class is using this constant pool, don't
797 // delete it, yet. The new class's previous version will point to this.
798 if (constants() != nullptr) {
799 assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
800 if (!constants()->in_aot_cache()) {
801 AOTHeap::remove_scratch_resolved_references(constants());
802 MetadataFactory::free_metadata(loader_data, constants());
803 }
804 // Delete any cached resolution errors for the constant pool
805 SystemDictionary::delete_resolution_error(constants());
806
807 set_constants(nullptr);
808 }
809
810 if (inner_classes() != nullptr &&
811 inner_classes() != Universe::the_empty_short_array() &&
812 !inner_classes()->in_aot_cache()) {
813 MetadataFactory::free_array<jushort>(loader_data, inner_classes());
814 }
815 set_inner_classes(nullptr);
816
817 if (nest_members() != nullptr &&
818 nest_members() != Universe::the_empty_short_array() &&
819 !nest_members()->in_aot_cache()) {
820 MetadataFactory::free_array<jushort>(loader_data, nest_members());
821 }
822 set_nest_members(nullptr);
823
824 if (permitted_subclasses() != nullptr &&
825 permitted_subclasses() != Universe::the_empty_short_array() &&
826 !permitted_subclasses()->in_aot_cache()) {
827 MetadataFactory::free_array<jushort>(loader_data, permitted_subclasses());
828 }
829 set_permitted_subclasses(nullptr);
830
831 if (loadable_descriptors() != nullptr &&
832 loadable_descriptors() != Universe::the_empty_short_array() &&
833 !loadable_descriptors()->in_aot_cache()) {
834 MetadataFactory::free_array<jushort>(loader_data, loadable_descriptors());
835 }
836 set_loadable_descriptors(nullptr);
837
838 if (acmp_maps_array() != nullptr) {
839 MetadataFactory::free_array<int>(loader_data, acmp_maps_array());
840 }
841 set_acmp_maps_array(nullptr);
842
843 // We should deallocate the Annotations instance if it's not in shared spaces.
844 if (annotations() != nullptr && !annotations()->in_aot_cache()) {
845 MetadataFactory::free_metadata(loader_data, annotations());
846 }
847 set_annotations(nullptr);
848
849 AOTSystemDictionary::handle_class_unloading(this);
850
851 #if INCLUDE_CDS_JAVA_HEAP
852 if (CDSConfig::is_dumping_heap()) {
853 AOTHeap::remove_scratch_objects(this);
854 }
855 #endif
856 }
857
858 bool InstanceKlass::is_record() const {
859 return _record_components != nullptr &&
860 is_final() &&
861 super() == vmClasses::Record_klass();
862 }
863
864 bool InstanceKlass::is_sealed() const {
865 return _permitted_subclasses != nullptr &&
866 _permitted_subclasses != Universe::the_empty_short_array();
867 }
868
869 // JLS 8.9: An enum class is either implicitly final and derives
870 // from java.lang.Enum, or else is implicitly sealed to its
871 // anonymous subclasses. This query detects both kinds.
872 // It does not validate the finality or
873 // sealing conditions: it merely checks for a super of Enum.
874 // This is sufficient for recognizing well-formed enums.
875 bool InstanceKlass::is_enum_subclass() const {
876 InstanceKlass* s = super();
877 return (s == vmClasses::Enum_klass() ||
878 (s != nullptr && s->super() == vmClasses::Enum_klass()));
879 }
880
881 bool InstanceKlass::should_be_initialized() const {
882 return !is_initialized();
883 }
884
885 // Static size helper
886 int InstanceKlass::size(int vtable_length,
887 int itable_length,
888 int nonstatic_oop_map_size,
889 bool is_interface,
890 bool is_concrete_value_class) {
891 return align_metadata_size(header_size() +
892 vtable_length +
893 itable_length +
894 nonstatic_oop_map_size +
895 (is_interface ? (int)sizeof(Klass*) / wordSize : 0) +
896 (is_concrete_value_class ? (int)sizeof(ValueKlass::Members) / wordSize : 0));
897 }
898
899 int InstanceKlass::size() const {
900 return size(vtable_length(),
901 itable_length(),
902 nonstatic_oop_map_size(),
903 is_interface(),
904 is_value_klass());
905 }
906
907 klassItable InstanceKlass::itable() const {
908 return klassItable(const_cast<InstanceKlass*>(this));
909 }
910
911 // JVMTI spec thinks there are signers and protection domain in the
912 // instanceKlass. These accessors pretend these fields are there.
913 // The hprof specification also thinks these fields are in InstanceKlass.
914 oop InstanceKlass::protection_domain() const {
915 // return the protection_domain from the mirror
916 return java_lang_Class::protection_domain(java_mirror());
917 }
918
919 objArrayOop InstanceKlass::signers() const {
920 // return the signers from the mirror
921 return java_lang_Class::signers(java_mirror());
922 }
923
924 oop InstanceKlass::init_lock() const {
925 // return the init lock from the mirror
926 oop lock = java_lang_Class::init_lock(java_mirror());
927 // Prevent reordering with any access of initialization state
928 OrderAccess::loadload();
929 assert(lock != nullptr || !is_not_initialized(), // initialized or in_error state
930 "only fully initialized state can have a null lock");
931 return lock;
932 }
933
934 // Set the initialization lock to null so the object can be GC'ed. Any racing
935 // threads to get this lock will see a null lock and will not lock.
936 // That's okay because they all check for initialized state after getting
937 // the lock and return. For preempted vthreads we keep the oop protected
938 // in the ObjectMonitor (see ObjectMonitor::set_object_strong()).
939 void InstanceKlass::fence_and_clear_init_lock() {
940 // make sure previous stores are all done, notably the init_state.
941 OrderAccess::storestore();
942 java_lang_Class::clear_init_lock(java_mirror());
943 assert(!is_not_initialized(), "class must be initialized now");
944 }
945
946 class PreemptableInitCall {
947 JavaThread* _thread;
948 bool _previous;
949 DEBUG_ONLY(InstanceKlass* _previous_klass;)
950 public:
951 PreemptableInitCall(JavaThread* thread, InstanceKlass* ik) : _thread(thread) {
952 _previous = thread->at_preemptable_init();
953 _thread->set_at_preemptable_init(true);
954 DEBUG_ONLY(_previous_klass = _thread->preempt_init_klass();)
955 DEBUG_ONLY(_thread->set_preempt_init_klass(ik));
956 }
957 ~PreemptableInitCall() {
958 _thread->set_at_preemptable_init(_previous);
959 DEBUG_ONLY(_thread->set_preempt_init_klass(_previous_klass));
960 }
961 };
962
963 void InstanceKlass::initialize_preemptable(TRAPS) {
964 if (this->should_be_initialized()) {
965 PreemptableInitCall pic(THREAD, this);
966 initialize_impl(THREAD);
967 } else {
968 assert(is_initialized(), "sanity check");
969 }
970 }
971
972 // See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
973 // process. The step comments refers to the procedure described in that section.
974 // Note: implementation moved to static method to expose the this pointer.
975 void InstanceKlass::initialize(TRAPS) {
976 if (this->should_be_initialized()) {
977 initialize_impl(CHECK);
978 // Note: at this point the class may be initialized
979 // OR it may be in the state of being initialized
980 // in case of recursive initialization!
981 } else {
982 assert(is_initialized(), "sanity check");
983 }
984 }
985
986 #ifdef ASSERT
987 void InstanceKlass::assert_no_clinit_will_run_for_aot_initialized_class() const {
988 assert(has_aot_initialized_mirror(), "must be");
989
990 InstanceKlass* s = super();
991 if (s != nullptr) {
992 DEBUG_ONLY(ResourceMark rm);
993 assert(s->is_initialized(), "super class %s of aot-inited class %s must have been initialized",
994 s->external_name(), external_name());
995 s->assert_no_clinit_will_run_for_aot_initialized_class();
996 }
997
998 Array<InstanceKlass*>* interfaces = local_interfaces();
999 int len = interfaces->length();
1000 for (int i = 0; i < len; i++) {
1001 InstanceKlass* intf = interfaces->at(i);
1002 if (!intf->is_initialized()) {
1003 ResourceMark rm;
1004 // Note: an interface needs to be marked as is_initialized() only if
1005 // - it has a <clinit>
1006 // - it has declared a default method.
1007 assert(!intf->interface_needs_clinit_execution_as_super(/*also_check_supers*/false),
1008 "uninitialized super interface %s of aot-inited class %s must not have <clinit>",
1009 intf->external_name(), external_name());
1010 }
1011 }
1012 }
1013 #endif
1014
1015 #if INCLUDE_CDS
1016 // early_init -- we are moving this class into the fully_initialized state before the
1017 // JVM is able to execute any bytecodes. See AOTLinkedClassBulkLoader::is_initializing_classes_early().
1018 void InstanceKlass::initialize_with_aot_initialized_mirror(bool early_init, TRAPS) {
1019 assert(has_aot_initialized_mirror(), "must be");
1020 assert(CDSConfig::is_loading_heap(), "must be");
1021 assert(CDSConfig::is_using_aot_linked_classes(), "must be");
1022 assert_no_clinit_will_run_for_aot_initialized_class();
1023
1024 if (is_initialized()) {
1025 return;
1026 }
1027
1028 if (log_is_enabled(Info, aot, init)) {
1029 ResourceMark rm;
1030 log_info(aot, init)("%s (aot-inited%s)", external_name(), early_init ? ", early" : "");
1031 }
1032
1033 if (is_runtime_setup_required()) {
1034 assert(!early_init, "must not call");
1035 // Need to take the slow path, which will call the runtimeSetup() function instead
1036 // of <clinit>
1037 initialize(CHECK);
1038 return;
1039 }
1040
1041 LogTarget(Info, class, init) lt;
1042 if (lt.is_enabled()) {
1043 ResourceMark rm(THREAD);
1044 LogStream ls(lt);
1045 ls.print("%d Initializing ", call_class_initializer_counter++);
1046 name()->print_value_on(&ls);
1047 ls.print_cr("(aot-inited) (" PTR_FORMAT ") by thread \"%s\"",
1048 p2i(this), THREAD->name());
1049 }
1050
1051 if (early_init) {
1052 precond(AOTLinkedClassBulkLoader::is_initializing_classes_early());
1053 precond(is_linked());
1054 precond(init_thread() == nullptr);
1055 set_init_state(fully_initialized);
1056 fence_and_clear_init_lock();
1057 return;
1058 }
1059
1060 link_class(CHECK);
1061
1062 #ifdef ASSERT
1063 {
1064 Handle h_init_lock(THREAD, init_lock());
1065 ObjectLocker ol(h_init_lock, THREAD);
1066 assert(!is_initialized(), "sanity");
1067 assert(!is_being_initialized(), "sanity");
1068 assert(!is_in_error_state(), "sanity");
1069 }
1070 #endif
1071
1072 set_init_thread(THREAD);
1073 set_initialization_state_and_notify(fully_initialized, CHECK);
1074 }
1075 #endif
1076
1077 bool InstanceKlass::verify_code(TRAPS) {
1078 // 1) Verify the bytecodes
1079 return Verifier::verify(this, should_verify_class(), THREAD);
1080 }
1081
1082 static void load_classes_from_loadable_descriptors_attribute(InstanceKlass *ik, TRAPS) {
1083 if (ik->loadable_descriptors() != Universe::the_empty_short_array() && PreloadClasses) {
1084 ResourceMark rm(THREAD);
1085 HandleMark hm(THREAD);
1086 for (int i = 0; i < ik->loadable_descriptors()->length(); i++) {
1087 Symbol* sig = ik->constants()->symbol_at(ik->loadable_descriptors()->at(i));
1088 if (!Signature::has_envelope(sig)) continue;
1089 TempNewSymbol class_name = Signature::strip_envelope(sig);
1090 if (class_name == ik->name()) continue;
1091 log_info(class, preload)("Preloading of class %s during linking of class %s "
1092 "because the class is listed in the LoadableDescriptors attribute",
1093 sig->as_C_string(), ik->name()->as_C_string());
1094 oop loader = ik->class_loader();
1095 Klass* klass = nullptr;
1096
1097 if (CDSConfig::is_using_aot_linked_classes() && ik->in_aot_cache() && !ik->defined_by_other_loaders()) {
1098 // + We come to here during AOTLinkedClassBulkLoader::link_classes() and it's too early to
1099 // execute any Java code.
1100 // + All loadable descriptors that can be resolved would have been resolved during the AOT assembly
1101 // phase, and would have been loaded earlier by AOTLinkedClassBulkLoader, so they can be found in
1102 // the system dictionary.
1103 // + If no class of the given name have been loaded yet, it's most likely because the class
1104 // is missing from JAR files. Just ignore it.
1105 klass = SystemDictionary::find_instance_or_array_klass(THREAD, class_name, Handle(THREAD, loader));
1106 } else {
1107 klass = SystemDictionary::resolve_or_null(class_name,
1108 Handle(THREAD, loader), THREAD);
1109 }
1110 if (HAS_PENDING_EXCEPTION) {
1111 CLEAR_PENDING_EXCEPTION;
1112 }
1113 if (klass != nullptr) {
1114 log_info(class, preload)("Preloading of class %s during linking of class %s "
1115 "(cause: LoadableDescriptors attribute) succeeded",
1116 class_name->as_C_string(), ik->name()->as_C_string());
1117 if (!klass->is_value_klass()) {
1118 // Non value classes are allowed by the current spec, but it could be an indication
1119 // of an issue so let's log a warning
1120 log_info(class, preload)("Preloading of class %s during linking of class %s "
1121 "(cause: LoadableDescriptors attribute) but loaded class is not a value class",
1122 class_name->as_C_string(), ik->name()->as_C_string());
1123 }
1124 } else {
1125 log_info(class, preload)("Preloading of class %s during linking of class %s "
1126 "(cause: LoadableDescriptors attribute) failed",
1127 class_name->as_C_string(), ik->name()->as_C_string());
1128 }
1129 }
1130 }
1131 }
1132
1133 void InstanceKlass::link_class(TRAPS) {
1134 assert(is_loaded(), "must be loaded");
1135 if (!is_linked()) {
1136 link_class_impl(CHECK);
1137 }
1138 }
1139
1140 // Called to verify that a class can link during initialization, without
1141 // throwing a VerifyError.
1142 bool InstanceKlass::link_class_or_fail(TRAPS) {
1143 assert(is_loaded(), "must be loaded");
1144 if (!is_linked()) {
1145 link_class_impl(CHECK_false);
1146 }
1147 return is_linked();
1148 }
1149
1150 bool InstanceKlass::link_class_impl(TRAPS) {
1151 if (CDSConfig::is_dumping_static_archive() && AOTSystemDictionary::has_class_failed_verification(this)) {
1152 // This is for CDS static dump only -- we use the in_error_state to indicate that
1153 // the class has failed verification. Throwing the NoClassDefFoundError here is just
1154 // a convenient way to stop repeat attempts to verify the same (bad) class.
1155 //
1156 // Note that the NoClassDefFoundError is not part of the JLS, and should not be thrown
1157 // if we are executing Java code. This is not a problem for CDS dumping phase since
1158 // it doesn't execute any Java code.
1159 ResourceMark rm(THREAD);
1160 // Names are all known to be < 64k so we know this formatted message is not excessively large.
1161 Exceptions::fthrow(THREAD_AND_LOCATION,
1162 vmSymbols::java_lang_NoClassDefFoundError(),
1163 "Class %s, or one of its supertypes, failed class initialization",
1164 external_name());
1165 return false;
1166 }
1167 // return if already verified
1168 if (is_linked()) {
1169 return true;
1170 }
1171
1172 // Timing
1173 // timer handles recursion
1174 JavaThread* jt = THREAD;
1175
1176 // link super class before linking this class
1177 InstanceKlass* super_klass = super();
1178 if (super_klass != nullptr) {
1179 if (super_klass->is_interface()) { // check if super class is an interface
1180 ResourceMark rm(THREAD);
1181 // Names are all known to be < 64k so we know this formatted message is not excessively large.
1182 Exceptions::fthrow(
1183 THREAD_AND_LOCATION,
1184 vmSymbols::java_lang_IncompatibleClassChangeError(),
1185 "class %s has interface %s as super class",
1186 external_name(),
1187 super_klass->external_name()
1188 );
1189 return false;
1190 }
1191
1192 super_klass->link_class_impl(CHECK_false);
1193 }
1194
1195 // link all interfaces implemented by this class before linking this class
1196 Array<InstanceKlass*>* interfaces = local_interfaces();
1197 int num_interfaces = interfaces->length();
1198 for (int index = 0; index < num_interfaces; index++) {
1199 InstanceKlass* interk = interfaces->at(index);
1200 interk->link_class_impl(CHECK_false);
1201 }
1202
1203 if (Arguments::is_valhalla_enabled()) {
1204 // Aggressively preloading all classes from the LoadableDescriptors attribute
1205 // so value classes can be scalarized in the calling conventions computed below
1206 load_classes_from_loadable_descriptors_attribute(this, THREAD);
1207 assert(!HAS_PENDING_EXCEPTION, "Shouldn't have pending exceptions from call above");
1208 }
1209
1210 // in case the class is linked in the process of linking its superclasses
1211 if (is_linked()) {
1212 return true;
1213 }
1214
1215 // trace only the link time for this klass that includes
1216 // the verification time
1217 PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
1218 ClassLoader::perf_class_link_selftime(),
1219 ClassLoader::perf_classes_linked(),
1220 jt->get_thread_stat()->perf_recursion_counts_addr(),
1221 jt->get_thread_stat()->perf_timers_addr(),
1222 PerfClassTraceTime::CLASS_LINK);
1223
1224 // verification & rewriting
1225 {
1226 HandleMark hm(THREAD);
1227 Handle h_init_lock(THREAD, init_lock());
1228 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE_false);
1229 // Don't allow preemption if we link/initialize classes below,
1230 // since that would release this monitor while we are in the
1231 // middle of linking this class.
1232 NoPreemptMark npm(THREAD);
1233
1234 // rewritten will have been set if loader constraint error found
1235 // on an earlier link attempt
1236 // don't verify or rewrite if already rewritten
1237 //
1238
1239 if (!is_linked()) {
1240 if (!is_rewritten()) {
1241 if (in_aot_cache()) {
1242 assert(!verified_at_dump_time(), "must be");
1243 }
1244 {
1245 bool verify_ok = verify_code(THREAD);
1246 if (!verify_ok) {
1247 return false;
1248 }
1249 }
1250
1251 // Just in case a side-effect of verify linked this class already
1252 // (which can sometimes happen since the verifier loads classes
1253 // using custom class loaders, which are free to initialize things)
1254 if (is_linked()) {
1255 return true;
1256 }
1257
1258 // also sets rewritten
1259 rewrite_class(CHECK_false);
1260 } else if (in_aot_cache()) {
1261 AOTSystemDictionary::check_verification_constraints(this, CHECK_false);
1262 }
1263
1264 // relocate jsrs and link methods after they are all rewritten
1265 link_methods(CHECK_false);
1266
1267 // Initialize the vtable and interface table after
1268 // methods have been rewritten since rewrite may
1269 // fabricate new Method*s.
1270 // also does loader constraint checking
1271 //
1272 // initialize_vtable and initialize_itable need to be rerun
1273 // for a shared class if
1274 // 1) the class is loaded by custom class loader or
1275 // 2) the class is loaded by built-in class loader but failed to add archived loader constraints or
1276 // 3) the class was not verified during dump time
1277 bool need_init_table = true;
1278 if (in_aot_cache() && verified_at_dump_time() &&
1279 AOTSystemDictionary::check_linking_constraints(THREAD, this)) {
1280 need_init_table = false;
1281 }
1282 if (need_init_table) {
1283 vtable().initialize_vtable_and_check_constraints(CHECK_false);
1284 itable().initialize_itable_and_check_constraints(CHECK_false);
1285 }
1286 #ifdef ASSERT
1287 vtable().verify(tty, true);
1288 // In case itable verification is ever added.
1289 // itable().verify(tty, true);
1290 #endif
1291 if (Universe::is_fully_initialized()) {
1292 DeoptimizationScope deopt_scope;
1293 {
1294 // Now mark all code that assumes the class is not linked.
1295 // Set state under the Compile_lock also.
1296 MutexLocker ml(THREAD, Compile_lock);
1297
1298 set_init_state(linked);
1299 CodeCache::mark_dependents_on(&deopt_scope, this);
1300 }
1301 // Perform the deopt handshake outside Compile_lock.
1302 deopt_scope.deoptimize_marked();
1303 } else {
1304 set_init_state(linked);
1305 }
1306 if (JvmtiExport::should_post_class_prepare()) {
1307 JvmtiExport::post_class_prepare(THREAD, this);
1308 }
1309 }
1310 }
1311
1312 if (log_is_enabled(Info, class, link)) {
1313 ResourceMark rm(THREAD);
1314 log_info(class, link)("Linked class %s", external_name());
1315 }
1316
1317 return true;
1318 }
1319
1320 // Rewrite the byte codes of all of the methods of a class.
1321 // The rewriter must be called exactly once. Rewriting must happen after
1322 // verification but before the first method of the class is executed.
1323 void InstanceKlass::rewrite_class(TRAPS) {
1324 assert(is_loaded(), "must be loaded");
1325 if (is_rewritten()) {
1326 assert(in_aot_cache(), "rewriting an unshared class?");
1327 return;
1328 }
1329 Rewriter::rewrite(this, CHECK);
1330 set_rewritten();
1331 }
1332
1333 // Now relocate and link method entry points after class is rewritten.
1334 // This is outside is_rewritten flag. In case of an exception, it can be
1335 // executed more than once.
1336 void InstanceKlass::link_methods(TRAPS) {
1337 PerfTraceTime timer(ClassLoader::perf_ik_link_methods_time());
1338
1339 int len = methods()->length();
1340 for (int i = len-1; i >= 0; i--) {
1341 methodHandle m(THREAD, methods()->at(i));
1342
1343 // Set up method entry points for compiler and interpreter .
1344 m->link_method(m, CHECK);
1345 }
1346 }
1347
1348 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
1349 void InstanceKlass::initialize_super_interfaces(TRAPS) {
1350 assert (has_nonstatic_concrete_methods(), "caller should have checked this");
1351 for (int i = 0; i < local_interfaces()->length(); ++i) {
1352 InstanceKlass* ik = local_interfaces()->at(i);
1353
1354 // Initialization is depth first search ie. we start with top of the inheritance tree
1355 // has_nonstatic_concrete_methods drives searching superinterfaces since it
1356 // means has_nonstatic_concrete_methods in its superinterface hierarchy
1357 if (ik->has_nonstatic_concrete_methods()) {
1358 ik->initialize_super_interfaces(CHECK);
1359 }
1360
1361 // Only initialize() interfaces that "declare" concrete methods.
1362 if (ik->should_be_initialized() && ik->declares_nonstatic_concrete_methods()) {
1363 ik->initialize(CHECK);
1364 }
1365 }
1366 }
1367
1368 using InitializationErrorTable = HashTable<const InstanceKlass*, OopHandle, 107, AnyObj::C_HEAP, mtClass>;
1369 static InitializationErrorTable* _initialization_error_table;
1370
1371 void InstanceKlass::add_initialization_error(JavaThread* current, Handle exception) {
1372 // Create the same exception with a message indicating the thread name,
1373 // and the StackTraceElements.
1374 Handle init_error = java_lang_Throwable::create_initialization_error(current, exception);
1375 ResourceMark rm(current);
1376 if (init_error.is_null()) {
1377 log_trace(class, init)("Unable to create the desired initialization error for class %s", external_name());
1378
1379 // We failed to create the new exception, most likely due to either out-of-memory or
1380 // a stackoverflow error. If the original exception was either of those then we save
1381 // the shared, pre-allocated, stackless, instance of that exception.
1382 if (exception->klass() == vmClasses::StackOverflowError_klass()) {
1383 log_debug(class, init)("Using shared StackOverflowError as initialization error for class %s", external_name());
1384 init_error = Handle(current, Universe::class_init_stack_overflow_error());
1385 } else if (exception->klass() == vmClasses::OutOfMemoryError_klass()) {
1386 log_debug(class, init)("Using shared OutOfMemoryError as initialization error for class %s", external_name());
1387 init_error = Handle(current, Universe::class_init_out_of_memory_error());
1388 } else {
1389 return;
1390 }
1391 }
1392
1393 MutexLocker ml(current, ClassInitError_lock);
1394 OopHandle elem = OopHandle(Universe::vm_global(), init_error());
1395 bool created;
1396 if (_initialization_error_table == nullptr) {
1397 _initialization_error_table = new (mtClass) InitializationErrorTable();
1398 }
1399 _initialization_error_table->put_if_absent(this, elem, &created);
1400 assert(created, "Initialization is single threaded");
1401 log_trace(class, init)("Initialization error added for class %s", external_name());
1402 }
1403
1404 oop InstanceKlass::get_initialization_error(JavaThread* current) {
1405 MutexLocker ml(current, ClassInitError_lock);
1406 if (_initialization_error_table == nullptr) {
1407 return nullptr;
1408 }
1409 OopHandle* h = _initialization_error_table->get(this);
1410 return (h != nullptr) ? h->resolve() : nullptr;
1411 }
1412
1413 // Need to remove entries for unloaded classes.
1414 void InstanceKlass::clean_initialization_error_table() {
1415 struct InitErrorTableCleaner {
1416 bool do_entry(const InstanceKlass* ik, OopHandle h) {
1417 if (!ik->is_loader_alive()) {
1418 h.release(Universe::vm_global());
1419 return true;
1420 } else {
1421 return false;
1422 }
1423 }
1424 };
1425
1426 assert_locked_or_safepoint(ClassInitError_lock);
1427 InitErrorTableCleaner cleaner;
1428 if (_initialization_error_table != nullptr) {
1429 _initialization_error_table->unlink(&cleaner);
1430 }
1431 }
1432
1433 class ThreadWaitingForClassInit : public StackObj {
1434 JavaThread* _thread;
1435 public:
1436 ThreadWaitingForClassInit(JavaThread* thread, InstanceKlass* ik) : _thread(thread) {
1437 _thread->set_class_to_be_initialized(ik);
1438 }
1439 ~ThreadWaitingForClassInit() {
1440 _thread->set_class_to_be_initialized(nullptr);
1441 }
1442 };
1443
1444 void InstanceKlass::initialize_impl(TRAPS) {
1445 HandleMark hm(THREAD);
1446
1447 // Make sure klass is linked (verified) before initialization
1448 // A class could already be verified, since it has been reflected upon.
1449 link_class(CHECK);
1450
1451 DTRACE_CLASSINIT_PROBE(required, -1);
1452
1453 bool wait = false;
1454
1455 JavaThread* jt = THREAD;
1456
1457 bool debug_logging_enabled = log_is_enabled(Debug, class, init);
1458
1459 // refer to the JVM book page 47 for description of steps
1460 // Step 1
1461 {
1462 Handle h_init_lock(THREAD, init_lock());
1463 ObjectLocker ol(h_init_lock, CHECK_PREEMPTABLE);
1464
1465 // Step 2
1466 // If we were to use wait() instead of waitInterruptibly() then
1467 // we might end up throwing IE from link/symbol resolution sites
1468 // that aren't expected to throw. This would wreak havoc. See 6320309.
1469 while (is_being_initialized() && !is_reentrant_initialization(jt)) {
1470 if (debug_logging_enabled) {
1471 ResourceMark rm(jt);
1472 log_debug(class, init)("Thread \"%s\" waiting for initialization of %s by thread \"%s\"",
1473 jt->name(), external_name(), init_thread_name());
1474 }
1475 wait = true;
1476 ThreadWaitingForClassInit twcl(THREAD, this);
1477 ol.wait_uninterruptibly(CHECK_PREEMPTABLE);
1478 }
1479
1480 // Step 3
1481 if (is_being_initialized() && is_reentrant_initialization(jt)) {
1482 if (debug_logging_enabled) {
1483 ResourceMark rm(jt);
1484 log_debug(class, init)("Thread \"%s\" recursively initializing %s",
1485 jt->name(), external_name());
1486 }
1487 DTRACE_CLASSINIT_PROBE_WAIT(recursive, -1, wait);
1488 return;
1489 }
1490
1491 // Step 4
1492 if (is_initialized()) {
1493 if (debug_logging_enabled) {
1494 ResourceMark rm(jt);
1495 log_debug(class, init)("Thread \"%s\" found %s already initialized",
1496 jt->name(), external_name());
1497 }
1498 DTRACE_CLASSINIT_PROBE_WAIT(concurrent, -1, wait);
1499 return;
1500 }
1501
1502 // Step 5
1503 if (is_in_error_state()) {
1504 if (debug_logging_enabled) {
1505 ResourceMark rm(jt);
1506 log_debug(class, init)("Thread \"%s\" found %s is in error state",
1507 jt->name(), external_name());
1508 }
1509
1510 DTRACE_CLASSINIT_PROBE_WAIT(erroneous, -1, wait);
1511 ResourceMark rm(THREAD);
1512 Handle cause(THREAD, get_initialization_error(THREAD));
1513
1514 stringStream ss;
1515 ss.print("Could not initialize class %s", external_name());
1516 if (cause.is_null()) {
1517 THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), ss.as_string());
1518 } else {
1519 THROW_MSG_CAUSE(vmSymbols::java_lang_NoClassDefFoundError(),
1520 ss.as_string(), cause);
1521 }
1522 } else {
1523
1524 // Step 6
1525 set_init_state(being_initialized);
1526 set_init_thread(jt);
1527 if (debug_logging_enabled) {
1528 ResourceMark rm(jt);
1529 log_debug(class, init)("Thread \"%s\" is initializing %s",
1530 jt->name(), external_name());
1531 }
1532 }
1533 }
1534
1535 // Block preemption once we are the initializer thread. Unmounting now
1536 // would complicate the reentrant case (identity is platform thread).
1537 NoPreemptMark npm(THREAD);
1538
1539 // Pre-allocating an all-zero value to be used to reset nullable flat storages
1540 if (is_value_klass()) {
1541 ValueKlass* vk = ValueKlass::cast(this);
1542 if (vk->supports_nullable_layouts()) {
1543 oop val = vk->allocate_instance(THREAD);
1544 if (HAS_PENDING_EXCEPTION) {
1545 Handle e(THREAD, PENDING_EXCEPTION);
1546 CLEAR_PENDING_EXCEPTION;
1547 {
1548 EXCEPTION_MARK;
1549 add_initialization_error(THREAD, e);
1550 // Locks object, set state, and notify all waiting threads
1551 set_initialization_state_and_notify(initialization_error, THREAD);
1552 CLEAR_PENDING_EXCEPTION;
1553 }
1554 THROW_OOP(e());
1555 }
1556 vk->set_null_reset_value(val);
1557 }
1558 }
1559
1560 // Step 7
1561 // Next, if C is a class rather than an interface, initialize it's super class and super
1562 // interfaces.
1563 if (!is_interface()) {
1564 Klass* super_klass = super();
1565 if (super_klass != nullptr && super_klass->should_be_initialized()) {
1566 super_klass->initialize(THREAD);
1567 }
1568 // If C implements any interface that declares a non-static, concrete method,
1569 // the initialization of C triggers initialization of its super interfaces.
1570 // Only need to recurse if has_nonstatic_concrete_methods which includes declaring and
1571 // having a superinterface that declares, non-static, concrete methods
1572 if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1573 initialize_super_interfaces(THREAD);
1574 }
1575
1576 // If any exceptions, complete abruptly, throwing the same exception as above.
1577 if (HAS_PENDING_EXCEPTION) {
1578 Handle e(THREAD, PENDING_EXCEPTION);
1579 CLEAR_PENDING_EXCEPTION;
1580 {
1581 EXCEPTION_MARK;
1582 add_initialization_error(THREAD, e);
1583 // Locks object, set state, and notify all waiting threads
1584 set_initialization_state_and_notify(initialization_error, THREAD);
1585 CLEAR_PENDING_EXCEPTION;
1586 }
1587 DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1588 THROW_OOP(e());
1589 }
1590 }
1591
1592
1593 // Step 8
1594 {
1595 DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1596 if (class_initializer() != nullptr) {
1597 // Timer includes any side effects of class initialization (resolution,
1598 // etc), but not recursive entry into call_class_initializer().
1599 PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1600 ClassLoader::perf_class_init_selftime(),
1601 ClassLoader::perf_classes_inited(),
1602 jt->get_thread_stat()->perf_recursion_counts_addr(),
1603 jt->get_thread_stat()->perf_timers_addr(),
1604 PerfClassTraceTime::CLASS_CLINIT);
1605 call_class_initializer(THREAD);
1606 } else {
1607 // The elapsed time is so small it's not worth counting.
1608 if (UsePerfData) {
1609 ClassLoader::perf_classes_inited()->inc();
1610 }
1611 call_class_initializer(THREAD);
1612 }
1613
1614 if (has_strict_static_fields() && !HAS_PENDING_EXCEPTION && !ReplayCompiles) {
1615 // Step 9 also verifies that strict static fields have been initialized.
1616 // Status bits were set in ClassFileParser::post_process_parsed_stream.
1617 // After <clinit>, bits must all be clear, or else we must throw an error.
1618 // This is an extremely fast check, so we won't bother with a timer.
1619 assert(fields_status() != nullptr, "");
1620 Symbol* bad_strict_static = nullptr;
1621 for (int index = 0; index < fields_status()->length(); index++) {
1622 // Very fast loop over single byte array looking for a set bit.
1623 if (fields_status()->adr_at(index)->is_strict_static_unset()) {
1624 // This strict static field has not been set by the class initializer.
1625 // Note that in the common no-error case, we read no field metadata.
1626 // We only unpack it when we need to report an error.
1627 FieldInfo fi = field(index);
1628 bad_strict_static = fi.name(constants());
1629 if (debug_logging_enabled) {
1630 ResourceMark rm(jt);
1631 const char* msg = format_strict_static_message(bad_strict_static);
1632 log_debug(class, init)("%s", msg);
1633 } else {
1634 // If we are not logging, do not bother to look for a second offense.
1635 break;
1636 }
1637 }
1638 }
1639 if (bad_strict_static != nullptr) {
1640 throw_strict_static_exception(bad_strict_static, "is unset after initialization of", THREAD);
1641 }
1642 }
1643 }
1644
1645 // Step 9
1646 if (!HAS_PENDING_EXCEPTION) {
1647 set_initialization_state_and_notify(fully_initialized, CHECK);
1648 DEBUG_ONLY(vtable().verify(tty, true);)
1649 CompilationPolicy::replay_training_at_init(this, THREAD);
1650 }
1651 else {
1652 // Step 10 and 11
1653 Handle e(THREAD, PENDING_EXCEPTION);
1654 CLEAR_PENDING_EXCEPTION;
1655 // JVMTI has already reported the pending exception
1656 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1657 JvmtiExport::clear_detected_exception(jt);
1658 {
1659 EXCEPTION_MARK;
1660 add_initialization_error(THREAD, e);
1661 set_initialization_state_and_notify(initialization_error, THREAD);
1662 CLEAR_PENDING_EXCEPTION; // ignore any exception thrown, class initialization error is thrown below
1663 // JVMTI has already reported the pending exception
1664 // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1665 JvmtiExport::clear_detected_exception(jt);
1666 }
1667 DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1668 if (e->is_a(vmClasses::Error_klass())) {
1669 THROW_OOP(e());
1670 } else {
1671 JavaCallArguments args(e);
1672 THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1673 vmSymbols::throwable_void_signature(),
1674 &args);
1675 }
1676 }
1677 DTRACE_CLASSINIT_PROBE_WAIT(end, -1, wait);
1678 }
1679
1680
1681 void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
1682 Handle h_init_lock(THREAD, init_lock());
1683 if (h_init_lock() != nullptr) {
1684 ObjectLocker ol(h_init_lock, THREAD);
1685 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1686 set_init_state(state);
1687 fence_and_clear_init_lock();
1688 ol.notify_all(CHECK);
1689 } else {
1690 assert(h_init_lock() != nullptr, "The initialization state should never be set twice");
1691 set_init_thread(nullptr); // reset _init_thread before changing _init_state
1692 set_init_state(state);
1693 }
1694 }
1695
1696 void InstanceKlass::notify_strict_static_access(int field_index, bool is_writing, TRAPS) {
1697 guarantee(field_index >= 0 && field_index < fields_status()->length(), "valid field index");
1698 DEBUG_ONLY(FieldInfo debugfi = field(field_index));
1699 assert(debugfi.access_flags().is_strict(), "");
1700 assert(debugfi.access_flags().is_static(), "");
1701 FieldStatus& fs = *fields_status()->adr_at(field_index);
1702 LogTarget(Trace, class, init) lt;
1703 if (lt.is_enabled()) {
1704 ResourceMark rm(THREAD);
1705 LogStream ls(lt);
1706 FieldInfo fi = field(field_index);
1707 ls.print("notify %s %s %s%s ",
1708 external_name(), is_writing? "Write" : "Read",
1709 fs.is_strict_static_unset() ? "Unset" : "(set)",
1710 fs.is_strict_static_unread() ? "+Unread" : "");
1711 fi.print(&ls, constants());
1712 }
1713 if (fs.is_strict_static_unset()) {
1714 assert(fs.is_strict_static_unread(), "ClassFileParser resp.");
1715 // If it is not set, there are only two reasonable things we can do here:
1716 // - mark it set if this is putstatic
1717 // - throw an error (Read-Before-Write) if this is getstatic
1718
1719 // The unset state is (or should be) transient, and observable only in one
1720 // thread during the execution of <clinit>. Something is wrong here as this
1721 // should not be possible
1722 guarantee(is_reentrant_initialization(THREAD), "unscoped access to strict static");
1723 if (is_writing) {
1724 // clear the "unset" bit, since the field is actually going to be written
1725 fs.update_strict_static_unset(false);
1726 } else {
1727 // throw an IllegalStateException, since we are reading before writing
1728 // see also InstanceKlass::initialize_impl, Step 8 (at end)
1729 Symbol* bad_strict_static = field(field_index).name(constants());
1730 throw_strict_static_exception(bad_strict_static, "is unset before first read in", CHECK);
1731 }
1732 } else {
1733 // Ensure no write after read for final strict statics
1734 FieldInfo fi = field(field_index);
1735 bool is_final = fi.access_flags().is_final();
1736 if (is_final) {
1737 // no final write after read, so observing a constant freezes it, as if <clinit> ended early
1738 // (maybe we could trust the constant a little earlier, before <clinit> ends)
1739 if (is_writing && !fs.is_strict_static_unread()) {
1740 Symbol* bad_strict_static = fi.name(constants());
1741 throw_strict_static_exception(bad_strict_static, "is set after read (as final) in", CHECK);
1742 } else if (!is_writing && fs.is_strict_static_unread()) {
1743 fs.update_strict_static_unread(false);
1744 }
1745 }
1746 }
1747 }
1748
1749 void InstanceKlass::throw_strict_static_exception(Symbol* field_name, const char* when, TRAPS) {
1750 ResourceMark rm(THREAD);
1751 const char* msg = format_strict_static_message(field_name, when);
1752 THROW_MSG(vmSymbols::java_lang_IllegalStateException(), msg);
1753 }
1754
1755 const char* InstanceKlass::format_strict_static_message(Symbol* field_name, const char* when) {
1756 stringStream ss;
1757 ss.print("Strict static \"%s\" %s %s",
1758 field_name->as_C_string(),
1759 when == nullptr ? "is unset in" : when,
1760 external_name());
1761 return ss.as_string();
1762 }
1763
1764 bool InstanceKlass::has_strict_instance_fields_in_hierarchy() const {
1765 for (const InstanceKlass* ik = this; ik != nullptr; ik = ik->java_super()) {
1766 if (ik->has_strict_instance_fields()) {
1767 return true;
1768 }
1769 }
1770 return false;
1771 }
1772
1773 // Update hierarchy. This is done before the new klass has been added to the SystemDictionary. The Compile_lock
1774 // is grabbed, to ensure that the compiler is not using the class hierarchy.
1775 void InstanceKlass::add_to_hierarchy(JavaThread* current) {
1776 assert(!SafepointSynchronize::is_at_safepoint(), "must NOT be at safepoint");
1777
1778 DeoptimizationScope deopt_scope;
1779 {
1780 MutexLocker ml(current, Compile_lock);
1781
1782 set_init_state(InstanceKlass::loaded);
1783 ClassLoadingService::notify_class_loaded(this, in_aot_cache());
1784 // make sure init_state store is already done.
1785 // The compiler reads the hierarchy outside of the Compile_lock.
1786 // Access ordering is used to add to hierarchy.
1787
1788 // Link into hierarchy.
1789 append_to_sibling_list(); // add to superklass/sibling list
1790 process_interfaces(); // handle all "implements" declarations
1791
1792 // Now mark all code that depended on old class hierarchy.
1793 // Note: must be done *after* linking k into the hierarchy (was bug 12/9/97)
1794 if (Universe::is_fully_initialized()) {
1795 CodeCache::mark_dependents_on(&deopt_scope, this);
1796 }
1797 }
1798 // Perform the deopt handshake outside Compile_lock.
1799 deopt_scope.deoptimize_marked();
1800 }
1801
1802
1803 InstanceKlass* InstanceKlass::implementor() const {
1804 InstanceKlass* volatile* ik = adr_implementor();
1805 if (ik == nullptr) {
1806 return nullptr;
1807 } else {
1808 // This load races with inserts, and therefore needs acquire.
1809 InstanceKlass* ikls = AtomicAccess::load_acquire(ik);
1810 if (ikls != nullptr && !ikls->is_loader_alive()) {
1811 return nullptr; // don't return unloaded class
1812 } else {
1813 return ikls;
1814 }
1815 }
1816 }
1817
1818
1819 void InstanceKlass::set_implementor(InstanceKlass* ik) {
1820 assert_locked_or_safepoint(Compile_lock);
1821 assert(is_interface(), "not interface");
1822 InstanceKlass* volatile* addr = adr_implementor();
1823 assert(addr != nullptr, "null addr");
1824 if (addr != nullptr) {
1825 AtomicAccess::release_store(addr, ik);
1826 }
1827 }
1828
1829 int InstanceKlass::nof_implementors() const {
1830 InstanceKlass* ik = implementor();
1831 if (ik == nullptr) {
1832 return 0;
1833 } else if (ik != this) {
1834 return 1;
1835 } else {
1836 return 2;
1837 }
1838 }
1839
1840 // The embedded _implementor field can only record one implementor.
1841 // When there are more than one implementors, the _implementor field
1842 // is set to the interface Klass* itself. Following are the possible
1843 // values for the _implementor field:
1844 // null - no implementor
1845 // implementor Klass* - one implementor
1846 // self - more than one implementor
1847 //
1848 // The _implementor field only exists for interfaces.
1849 void InstanceKlass::add_implementor(InstanceKlass* ik) {
1850 if (Universe::is_fully_initialized()) {
1851 assert_lock_strong(Compile_lock);
1852 }
1853 assert(is_interface(), "not interface");
1854 // Filter out my subinterfaces.
1855 // (Note: Interfaces are never on the subklass list.)
1856 if (ik->is_interface()) return;
1857
1858 // Filter out subclasses whose supers already implement me.
1859 // (Note: CHA must walk subclasses of direct implementors
1860 // in order to locate indirect implementors.)
1861 InstanceKlass* super_ik = ik->super();
1862 if (super_ik != nullptr && super_ik->implements_interface(this))
1863 // We only need to check one immediate superclass, since the
1864 // implements_interface query looks at transitive_interfaces.
1865 // Any supers of the super have the same (or fewer) transitive_interfaces.
1866 return;
1867
1868 InstanceKlass* iklass = implementor();
1869 if (iklass == nullptr) {
1870 set_implementor(ik);
1871 } else if (iklass != this && iklass != ik) {
1872 // There is already an implementor. Use itself as an indicator of
1873 // more than one implementors.
1874 set_implementor(this);
1875 }
1876
1877 // The implementor also implements the transitive_interfaces
1878 for (int index = 0; index < local_interfaces()->length(); index++) {
1879 local_interfaces()->at(index)->add_implementor(ik);
1880 }
1881 }
1882
1883 void InstanceKlass::init_implementor() {
1884 if (is_interface()) {
1885 set_implementor(nullptr);
1886 }
1887 }
1888
1889
1890 void InstanceKlass::process_interfaces() {
1891 // link this class into the implementors list of every interface it implements
1892 for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
1893 assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
1894 InstanceKlass* interf = local_interfaces()->at(i);
1895 assert(interf->is_interface(), "expected interface");
1896 interf->add_implementor(this);
1897 }
1898 }
1899
1900 bool InstanceKlass::can_be_primary_super_slow() const {
1901 if (is_interface())
1902 return false;
1903 else
1904 return Klass::can_be_primary_super_slow();
1905 }
1906
1907 GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots,
1908 Array<InstanceKlass*>* transitive_interfaces) {
1909 // The secondaries are the implemented interfaces.
1910 // We need the cast because Array<Klass*> is NOT a supertype of Array<InstanceKlass*>,
1911 // (but it's safe to do here because we won't write into _secondary_supers from this point on).
1912 Array<Klass*>* interfaces = (Array<Klass*>*)(address)transitive_interfaces;
1913 int num_secondaries = num_extra_slots + interfaces->length();
1914 if (num_secondaries == 0) {
1915 // Must share this for correct bootstrapping!
1916 set_secondary_supers(Universe::the_empty_klass_array(), Universe::the_empty_klass_bitmap());
1917 return nullptr;
1918 } else if (num_extra_slots == 0 && interfaces->length() <= 1) {
1919 // We will reuse the transitive interfaces list if we're certain
1920 // it's in hash order.
1921 uintx bitmap = compute_secondary_supers_bitmap(interfaces);
1922 set_secondary_supers(interfaces, bitmap);
1923 return nullptr;
1924 }
1925 // Copy transitive interfaces to a temporary growable array to be constructed
1926 // into the secondary super list with extra slots.
1927 GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
1928 for (int i = 0; i < interfaces->length(); i++) {
1929 secondaries->push(interfaces->at(i));
1930 }
1931 return secondaries;
1932 }
1933
1934 bool InstanceKlass::implements_interface(Klass* k) const {
1935 if (this == k) return true;
1936 assert(k->is_interface(), "should be an interface class");
1937 for (int i = 0; i < transitive_interfaces()->length(); i++) {
1938 if (transitive_interfaces()->at(i) == k) {
1939 return true;
1940 }
1941 }
1942 return false;
1943 }
1944
1945 bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1946 // Verify direct super interface
1947 if (this == k) return true;
1948 assert(k->is_interface(), "should be an interface class");
1949 for (int i = 0; i < local_interfaces()->length(); i++) {
1950 if (local_interfaces()->at(i) == k) {
1951 return true;
1952 }
1953 }
1954 return false;
1955 }
1956
1957 instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1958 if (TraceFinalizerRegistration) {
1959 tty->print("Registered ");
1960 i->print_value_on(tty);
1961 tty->print_cr(" (" PTR_FORMAT ") as finalizable", p2i(i));
1962 }
1963 instanceHandle h_i(THREAD, i);
1964 // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1965 JavaValue result(T_VOID);
1966 JavaCallArguments args(h_i);
1967 methodHandle mh(THREAD, Universe::finalizer_register_method());
1968 JavaCalls::call(&result, mh, &args, CHECK_NULL);
1969 MANAGEMENT_ONLY(FinalizerService::on_register(h_i(), THREAD);)
1970 return h_i();
1971 }
1972
1973 instanceOop InstanceKlass::allocate_instance(TRAPS) {
1974 assert(!is_abstract() && !is_interface(), "Should not create this object");
1975 size_t size = size_helper(); // Query before forming handle.
1976 return (instanceOop)Universe::heap()->obj_allocate(this, size, THREAD);
1977 }
1978
1979 instanceOop InstanceKlass::allocate_instance(oop java_class, TRAPS) {
1980 Klass* k = java_lang_Class::as_Klass(java_class);
1981 if (k == nullptr) {
1982 ResourceMark rm(THREAD);
1983 THROW_(vmSymbols::java_lang_InstantiationException(), nullptr);
1984 }
1985 InstanceKlass* ik = cast(k);
1986 ik->check_valid_for_instantiation(false, CHECK_NULL);
1987 ik->initialize(CHECK_NULL);
1988 return ik->allocate_instance(THREAD);
1989 }
1990
1991 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1992 return instanceHandle(THREAD, allocate_instance(THREAD));
1993 }
1994
1995 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1996 if (is_interface() || is_abstract()) {
1997 ResourceMark rm(THREAD);
1998 THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1999 : vmSymbols::java_lang_InstantiationException(), external_name());
2000 }
2001 if (this == vmClasses::Class_klass()) {
2002 ResourceMark rm(THREAD);
2003 THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
2004 : vmSymbols::java_lang_IllegalAccessException(), external_name());
2005 }
2006 }
2007
2008 ArrayKlass* InstanceKlass::array_klass(int n, TRAPS) {
2009 // Need load-acquire for lock-free read
2010 if (array_klasses_acquire() == nullptr) {
2011
2012 // Recursively lock array allocation
2013 RecursiveLocker rl(MultiArray_lock, THREAD);
2014
2015 // Check if another thread created the array klass while we were waiting for the lock.
2016 if (array_klasses() == nullptr) {
2017 ObjArrayKlass* k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
2018 // use 'release' to pair with lock-free load
2019 release_set_array_klasses(k);
2020 }
2021 }
2022
2023 // array_klasses() will always be set at this point
2024 ObjArrayKlass* ak = array_klasses();
2025 assert(ak != nullptr, "should be set");
2026 return ak->array_klass(n, THREAD);
2027 }
2028
2029 ArrayKlass* InstanceKlass::array_klass_or_null(int n) {
2030 // Need load-acquire for lock-free read
2031 ObjArrayKlass* oak = array_klasses_acquire();
2032 if (oak == nullptr) {
2033 return nullptr;
2034 } else {
2035 return oak->array_klass_or_null(n);
2036 }
2037 }
2038
2039 ArrayKlass* InstanceKlass::array_klass(TRAPS) {
2040 return array_klass(1, THREAD);
2041 }
2042
2043 ArrayKlass* InstanceKlass::array_klass_or_null() {
2044 return array_klass_or_null(1);
2045 }
2046
2047 Method* InstanceKlass::class_initializer() const {
2048 Method* clinit = find_method(
2049 vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
2050 if (clinit != nullptr && clinit->is_class_initializer()) {
2051 return clinit;
2052 }
2053 return nullptr;
2054 }
2055
2056 void InstanceKlass::call_class_initializer(TRAPS) {
2057 if (ReplayCompiles &&
2058 (ReplaySuppressInitializers == 1 ||
2059 (ReplaySuppressInitializers >= 2 && class_loader() != nullptr))) {
2060 // Hide the existence of the initializer for the purpose of replaying the compile
2061 return;
2062 }
2063
2064 #if INCLUDE_CDS
2065 // This is needed to ensure the consistency of the archived heap objects.
2066 if (has_aot_initialized_mirror() && CDSConfig::is_loading_heap()) {
2067 AOTClassInitializer::call_runtime_setup(THREAD, this);
2068 return;
2069 } else if (has_archived_enum_objs()) {
2070 assert(in_aot_cache(), "must be");
2071 bool initialized = CDSEnumKlass::initialize_enum_klass(this, CHECK);
2072 if (initialized) {
2073 return;
2074 }
2075 }
2076 #endif
2077
2078 methodHandle h_method(THREAD, class_initializer());
2079 assert(!is_initialized(), "we cannot initialize twice");
2080 LogTarget(Info, class, init) lt;
2081 if (lt.is_enabled()) {
2082 ResourceMark rm(THREAD);
2083 LogStream ls(lt);
2084 ls.print("%d Initializing ", call_class_initializer_counter++);
2085 name()->print_value_on(&ls);
2086 ls.print_cr("%s (" PTR_FORMAT ") by thread \"%s\"",
2087 h_method() == nullptr ? "(no method)" : "", p2i(this),
2088 THREAD->name());
2089 }
2090 if (h_method() != nullptr) {
2091 ThreadInClassInitializer ticl(THREAD, this); // Track class being initialized
2092 JavaCallArguments args; // No arguments
2093 JavaValue result(T_VOID);
2094 JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
2095 }
2096 }
2097
2098 // If a class that implements this interface is initialized, is the JVM required
2099 // to first execute a <clinit> method declared in this interface,
2100 // or (if also_check_supers==true) any of the super types of this interface?
2101 //
2102 // JVMS 5.5. Initialization, step 7: Next, if C is a class rather than
2103 // an interface, then let SC be its superclass and let SI1, ..., SIn
2104 // be all superinterfaces of C (whether direct or indirect) that
2105 // declare at least one non-abstract, non-static method.
2106 //
2107 // So when an interface is initialized, it does not look at its
2108 // supers. But a proper class will ensure that all of its supers have
2109 // run their <clinit> methods, except that it disregards interfaces
2110 // that lack a non-static concrete method (i.e., a default method).
2111 // Therefore, you should probably call this method only when the
2112 // current class is a super of some proper class, not an interface.
2113 bool InstanceKlass::interface_needs_clinit_execution_as_super(bool also_check_supers) const {
2114 assert(is_interface(), "must be");
2115
2116 if (!has_nonstatic_concrete_methods()) {
2117 // quick check: no nonstatic concrete methods are declared by this or any super interfaces
2118 return false;
2119 }
2120
2121 // JVMS 5.5. Initialization
2122 // ...If C is an interface that declares a non-abstract,
2123 // non-static method, the initialization of a class that
2124 // implements C directly or indirectly.
2125 if (declares_nonstatic_concrete_methods() && class_initializer() != nullptr) {
2126 return true;
2127 }
2128 if (also_check_supers) {
2129 Array<InstanceKlass*>* all_ifs = transitive_interfaces();
2130 for (int i = 0; i < all_ifs->length(); ++i) {
2131 InstanceKlass* super_intf = all_ifs->at(i);
2132 if (super_intf->declares_nonstatic_concrete_methods() && super_intf->class_initializer() != nullptr) {
2133 return true;
2134 }
2135 }
2136 }
2137 return false;
2138 }
2139
2140 void InstanceKlass::mask_for(const methodHandle& method, int bci,
2141 InterpreterOopMap* entry_for) {
2142 // Lazily create the _oop_map_cache at first request.
2143 // Load_acquire is needed to safely get instance published with CAS by another thread.
2144 OopMapCache* oop_map_cache = AtomicAccess::load_acquire(&_oop_map_cache);
2145 if (oop_map_cache == nullptr) {
2146 // Try to install new instance atomically.
2147 oop_map_cache = new OopMapCache();
2148 OopMapCache* other = AtomicAccess::cmpxchg(&_oop_map_cache, (OopMapCache*)nullptr, oop_map_cache);
2149 if (other != nullptr) {
2150 // Someone else managed to install before us, ditch local copy and use the existing one.
2151 delete oop_map_cache;
2152 oop_map_cache = other;
2153 }
2154 }
2155 // _oop_map_cache is constant after init; lookup below does its own locking.
2156 oop_map_cache->lookup(method, bci, entry_for);
2157 }
2158
2159
2160 FieldInfo InstanceKlass::field(int index) const {
2161 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2162 if (fs.index() == index) {
2163 return fs.to_FieldInfo();
2164 }
2165 }
2166 fatal("Field not found");
2167 return FieldInfo();
2168 }
2169
2170 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2171 JavaFieldStream fs(this);
2172 if (fs.lookup(name, sig)) {
2173 assert(fs.name() == name, "name must match");
2174 assert(fs.signature() == sig, "signature must match");
2175 fd->reinitialize(this, fs.to_FieldInfo());
2176 return true;
2177 }
2178 return false;
2179 }
2180
2181 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd, bool also_internal) const {
2182 if (!also_internal) {
2183 return find_local_field( name, sig, fd);
2184 }
2185
2186 for (AllFieldStream fs(this); !fs.done(); fs.next()) {
2187 if (fs.name() == name && fs.signature() == sig) {
2188 fd->reinitialize(this, fs.to_FieldInfo());
2189 return true;
2190 }
2191 }
2192 return false;
2193 }
2194
2195 Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2196 const int n = local_interfaces()->length();
2197 for (int i = 0; i < n; i++) {
2198 InstanceKlass* intf1 = local_interfaces()->at(i);
2199 assert(intf1->is_interface(), "just checking type");
2200 // search for field in current interface
2201 if (intf1->find_local_field(name, sig, fd)) {
2202 assert(fd->is_static(), "interface field must be static");
2203 return intf1;
2204 }
2205 // search for field in direct superinterfaces
2206 Klass* intf2 = intf1->find_interface_field(name, sig, fd);
2207 if (intf2 != nullptr) return intf2;
2208 }
2209 // otherwise field lookup fails
2210 return nullptr;
2211 }
2212
2213
2214 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
2215 // search order according to newest JVM spec (5.4.3.2, p.167).
2216 // 1) search for field in current klass
2217 if (find_local_field(name, sig, fd)) {
2218 return const_cast<InstanceKlass*>(this);
2219 }
2220 // 2) search for field recursively in direct superinterfaces
2221 { Klass* intf = find_interface_field(name, sig, fd);
2222 if (intf != nullptr) return intf;
2223 }
2224 // 3) apply field lookup recursively if superclass exists
2225 { InstanceKlass* supr = super();
2226 if (supr != nullptr) return supr->find_field(name, sig, fd);
2227 }
2228 // 4) otherwise field lookup fails
2229 return nullptr;
2230 }
2231
2232
2233 Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
2234 // search order according to newest JVM spec (5.4.3.2, p.167).
2235 // 1) search for field in current klass
2236 if (find_local_field(name, sig, fd)) {
2237 if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
2238 }
2239 // 2) search for field recursively in direct superinterfaces
2240 if (is_static) {
2241 Klass* intf = find_interface_field(name, sig, fd);
2242 if (intf != nullptr) return intf;
2243 }
2244 // 3) apply field lookup recursively if superclass exists
2245 { InstanceKlass* supr = super();
2246 if (supr != nullptr) return supr->find_field(name, sig, is_static, fd);
2247 }
2248 // 4) otherwise field lookup fails
2249 return nullptr;
2250 }
2251
2252 bool InstanceKlass::contains_field_offset(int offset) {
2253 if (this->is_value_klass()) {
2254 ValueKlass* vk = ValueKlass::cast(this);
2255 return offset >= vk->payload_offset() && offset < (vk->payload_offset() + vk->payload_size_in_bytes());
2256 } else {
2257 fieldDescriptor fd;
2258 return find_field_from_offset(offset, false, &fd);
2259 }
2260 }
2261
2262 bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2263 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2264 if (fs.offset() == offset) {
2265 fd->reinitialize(const_cast<InstanceKlass*>(this), fs.to_FieldInfo());
2266 if (fd->is_static() == is_static) return true;
2267 }
2268 }
2269 return false;
2270 }
2271
2272
2273 bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
2274 const InstanceKlass* klass = this;
2275 while (klass != nullptr) {
2276 if (klass->find_local_field_from_offset(offset, is_static, fd)) {
2277 return true;
2278 }
2279 klass = klass->super();
2280 }
2281 return false;
2282 }
2283
2284 bool InstanceKlass::find_local_flat_field_containing_offset(int offset, fieldDescriptor* fd) const {
2285 for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
2286 if (!fs.is_flat()) {
2287 continue;
2288 }
2289
2290 if (fs.offset() > offset) {
2291 continue;
2292 }
2293
2294 const int offset_in_flat_field = offset - fs.offset();
2295 const ValueFieldInfo vfi = value_field_info(fs.index());
2296 const int field_size = vfi.klass()->layout_size_in_bytes(vfi.flat_layout_kind());
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 (AOTSystemDictionary::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() && !defined_by_other_loaders()) {
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 // AOTSystemDictionary::check_verification_constraints() will not work for this class.
3323 return false;
3324 }
3325
3326 if (CDSConfig::is_dumping_aot_cache() && 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 AOTSystemDictionary::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 AOTSystemDictionary::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 }