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