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