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