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