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