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