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