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