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