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