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