1 /*
2  * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "jvm.h"
27 #include "classfile/classLoaderDataGraph.hpp"
28 #include "classfile/javaClasses.hpp"
29 #include "classfile/systemDictionary.hpp"
30 #include "classfile/vmSymbols.hpp"
31 #include "interpreter/linkResolver.hpp"
32 #include "logging/log.hpp"
33 #include "logging/logStream.hpp"
34 #include "memory/metaspaceShared.hpp"
35 #include "memory/resourceArea.hpp"
36 #include "memory/universe.hpp"
37 #include "oops/instanceKlass.hpp"
38 #include "oops/klassVtable.hpp"
39 #include "oops/method.hpp"
40 #include "oops/objArrayOop.hpp"
41 #include "oops/oop.inline.hpp"
42 #include "runtime/arguments.hpp"
43 #include "runtime/flags/flagSetting.hpp"
44 #include "runtime/handles.inline.hpp"
45 #include "runtime/safepointVerifiers.hpp"
46 #include "utilities/copy.hpp"
47 
ik() const48 inline InstanceKlass* klassVtable::ik() const {
49   return InstanceKlass::cast(_klass);
50 }
51 
is_preinitialized_vtable()52 bool klassVtable::is_preinitialized_vtable() {
53   return _klass->is_shared() && !MetaspaceShared::remapped_readwrite();
54 }
55 
56 
57 // this function computes the vtable size (including the size needed for miranda
58 // methods) and the number of miranda methods in this class.
59 // Note on Miranda methods: Let's say there is a class C that implements
60 // interface I, and none of C's superclasses implements I.
61 // Let's say there is an abstract method m in I that neither C
62 // nor any of its super classes implement (i.e there is no method of any access,
63 // with the same name and signature as m), then m is a Miranda method which is
64 // entered as a public abstract method in C's vtable.  From then on it should
65 // treated as any other public method in C for method over-ride purposes.
compute_vtable_size_and_num_mirandas(int * vtable_length_ret,int * num_new_mirandas,GrowableArray<Method * > * all_mirandas,const Klass * super,Array<Method * > * methods,AccessFlags class_flags,u2 major_version,Handle classloader,Symbol * classname,Array<InstanceKlass * > * local_interfaces,TRAPS)66 void klassVtable::compute_vtable_size_and_num_mirandas(
67     int* vtable_length_ret, int* num_new_mirandas,
68     GrowableArray<Method*>* all_mirandas, const Klass* super,
69     Array<Method*>* methods, AccessFlags class_flags, u2 major_version,
70     Handle classloader, Symbol* classname, Array<InstanceKlass*>* local_interfaces,
71     TRAPS) {
72   NoSafepointVerifier nsv;
73 
74   // set up default result values
75   int vtable_length = 0;
76 
77   // start off with super's vtable length
78   vtable_length = super == NULL ? 0 : super->vtable_length();
79 
80   // go thru each method in the methods table to see if it needs a new entry
81   int len = methods->length();
82   for (int i = 0; i < len; i++) {
83     assert(methods->at(i)->is_method(), "must be a Method*");
84     methodHandle mh(THREAD, methods->at(i));
85 
86     if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, major_version, THREAD)) {
87       assert(!methods->at(i)->is_private(), "private methods should not need a vtable entry");
88       vtable_length += vtableEntry::size(); // we need a new entry
89     }
90   }
91 
92   GrowableArray<Method*> new_mirandas(20);
93   // compute the number of mirandas methods that must be added to the end
94   get_mirandas(&new_mirandas, all_mirandas, super, methods, NULL, local_interfaces,
95                class_flags.is_interface());
96   *num_new_mirandas = new_mirandas.length();
97 
98   // Interfaces do not need interface methods in their vtables
99   // This includes miranda methods and during later processing, default methods
100   if (!class_flags.is_interface()) {
101      vtable_length += *num_new_mirandas * vtableEntry::size();
102   }
103 
104   if (Universe::is_bootstrapping() && vtable_length == 0) {
105     // array classes don't have their superclass set correctly during
106     // bootstrapping
107     vtable_length = Universe::base_vtable_size();
108   }
109 
110   if (super == NULL && vtable_length != Universe::base_vtable_size()) {
111     if (Universe::is_bootstrapping()) {
112       // Someone is attempting to override java.lang.Object incorrectly on the
113       // bootclasspath.  The JVM cannot recover from this error including throwing
114       // an exception
115       vm_exit_during_initialization("Incompatible definition of java.lang.Object");
116     } else {
117       // Someone is attempting to redefine java.lang.Object incorrectly.  The
118       // only way this should happen is from
119       // SystemDictionary::resolve_from_stream(), which will detect this later
120       // and throw a security exception.  So don't assert here to let
121       // the exception occur.
122       vtable_length = Universe::base_vtable_size();
123     }
124   }
125   assert(vtable_length % vtableEntry::size() == 0, "bad vtable length");
126   assert(vtable_length >= Universe::base_vtable_size(), "vtable too small");
127 
128   *vtable_length_ret = vtable_length;
129 }
130 
131 // Copy super class's vtable to the first part (prefix) of this class's vtable,
132 // and return the number of entries copied.  Expects that 'super' is the Java
133 // super class (arrays can have "array" super classes that must be skipped).
initialize_from_super(Klass * super)134 int klassVtable::initialize_from_super(Klass* super) {
135   if (super == NULL) {
136     return 0;
137   } else if (is_preinitialized_vtable()) {
138     // A shared class' vtable is preinitialized at dump time. No need to copy
139     // methods from super class for shared class, as that was already done
140     // during archiving time. However, if Jvmti has redefined a class,
141     // copy super class's vtable in case the super class has changed.
142     return super->vtable().length();
143   } else {
144     // copy methods from superKlass
145     klassVtable superVtable = super->vtable();
146     assert(superVtable.length() <= _length, "vtable too short");
147 #ifdef ASSERT
148     superVtable.verify(tty, true);
149 #endif
150     superVtable.copy_vtable_to(table());
151     if (log_develop_is_enabled(Trace, vtables)) {
152       ResourceMark rm;
153       log_develop_trace(vtables)("copy vtable from %s to %s size %d",
154                                  super->internal_name(), klass()->internal_name(),
155                                  _length);
156     }
157     return superVtable.length();
158   }
159 }
160 
161 //
162 // Revised lookup semantics   introduced 1.3 (Kestrel beta)
initialize_vtable(bool checkconstraints,TRAPS)163 void klassVtable::initialize_vtable(bool checkconstraints, TRAPS) {
164 
165   // Note:  Arrays can have intermediate array supers.  Use java_super to skip them.
166   InstanceKlass* super = _klass->java_super();
167 
168   bool is_shared = _klass->is_shared();
169 
170   if (!_klass->is_array_klass()) {
171     ResourceMark rm(THREAD);
172     log_develop_debug(vtables)("Initializing: %s", _klass->name()->as_C_string());
173   }
174 
175 #ifdef ASSERT
176   oop* end_of_obj = (oop*)_klass + _klass->size();
177   oop* end_of_vtable = (oop*)&table()[_length];
178   assert(end_of_vtable <= end_of_obj, "vtable extends beyond end");
179 #endif
180 
181   if (Universe::is_bootstrapping()) {
182     assert(!is_shared, "sanity");
183     // just clear everything
184     for (int i = 0; i < _length; i++) table()[i].clear();
185     return;
186   }
187 
188   int super_vtable_len = initialize_from_super(super);
189   if (_klass->is_array_klass()) {
190     assert(super_vtable_len == _length, "arrays shouldn't introduce new methods");
191   } else {
192     assert(_klass->is_instance_klass(), "must be InstanceKlass");
193 
194     Array<Method*>* methods = ik()->methods();
195     int len = methods->length();
196     int initialized = super_vtable_len;
197 
198     // Check each of this class's methods against super;
199     // if override, replace in copy of super vtable, otherwise append to end
200     for (int i = 0; i < len; i++) {
201       // update_inherited_vtable can stop for gc - ensure using handles
202       HandleMark hm(THREAD);
203       assert(methods->at(i)->is_method(), "must be a Method*");
204       methodHandle mh(THREAD, methods->at(i));
205 
206       bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, -1, checkconstraints, CHECK);
207 
208       if (needs_new_entry) {
209         put_method_at(mh(), initialized);
210         mh()->set_vtable_index(initialized); // set primary vtable index
211         initialized++;
212       }
213     }
214 
215     // update vtable with default_methods
216     Array<Method*>* default_methods = ik()->default_methods();
217     if (default_methods != NULL) {
218       len = default_methods->length();
219       if (len > 0) {
220         Array<int>* def_vtable_indices = NULL;
221         if ((def_vtable_indices = ik()->default_vtable_indices()) == NULL) {
222           assert(!is_shared, "shared class def_vtable_indices does not exist");
223           def_vtable_indices = ik()->create_new_default_vtable_indices(len, CHECK);
224         } else {
225           assert(def_vtable_indices->length() == len, "reinit vtable len?");
226         }
227         for (int i = 0; i < len; i++) {
228           HandleMark hm(THREAD);
229           assert(default_methods->at(i)->is_method(), "must be a Method*");
230           methodHandle mh(THREAD, default_methods->at(i));
231           assert(!mh->is_private(), "private interface method in the default method list");
232           bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, i, checkconstraints, CHECK);
233 
234           // needs new entry
235           if (needs_new_entry) {
236             put_method_at(mh(), initialized);
237             if (is_preinitialized_vtable()) {
238               // At runtime initialize_vtable is rerun for a shared class
239               // (loaded by the non-boot loader) as part of link_class_impl().
240               // The dumptime vtable index should be the same as the runtime index.
241               assert(def_vtable_indices->at(i) == initialized,
242                      "dump time vtable index is different from runtime index");
243             } else {
244               def_vtable_indices->at_put(i, initialized); //set vtable index
245             }
246             initialized++;
247           }
248         }
249       }
250     }
251 
252     // add miranda methods; it will also return the updated initialized
253     // Interfaces do not need interface methods in their vtables
254     // This includes miranda methods and during later processing, default methods
255     if (!ik()->is_interface()) {
256       initialized = fill_in_mirandas(initialized, THREAD);
257     }
258 
259     // In class hierarchies where the accessibility is not increasing (i.e., going from private ->
260     // package_private -> public/protected), the vtable might actually be smaller than our initial
261     // calculation, for classfile versions for which we do not do transitive override
262     // calculations.
263     if (ik()->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION) {
264       assert(initialized == _length, "vtable initialization failed");
265     } else {
266       assert(initialized <= _length, "vtable initialization failed");
267       for(;initialized < _length; initialized++) {
268         table()[initialized].clear();
269       }
270     }
271     NOT_PRODUCT(verify(tty, true));
272   }
273 }
274 
275 // Called for cases where a method does not override its superclass' vtable entry
276 // For bytecodes not produced by javac together it is possible that a method does not override
277 // the superclass's method, but might indirectly override a super-super class's vtable entry
278 // If none found, return a null superk, else return the superk of the method this does override
279 // For public and protected methods: if they override a superclass, they will
280 // also be overridden themselves appropriately.
281 // Private methods do not override, and are not overridden and are not in the vtable.
282 // Package Private methods are trickier:
283 // e.g. P1.A, pub m
284 // P2.B extends A, package private m
285 // P1.C extends B, public m
286 // P1.C.m needs to override P1.A.m and can not override P2.B.m
287 // Therefore: all package private methods need their own vtable entries for
288 // them to be the root of an inheritance overriding decision
289 // Package private methods may also override other vtable entries
find_transitive_override(InstanceKlass * initialsuper,const methodHandle & target_method,int vtable_index,Handle target_loader,Symbol * target_classname,Thread * THREAD)290 InstanceKlass* klassVtable::find_transitive_override(InstanceKlass* initialsuper, const methodHandle& target_method,
291                             int vtable_index, Handle target_loader, Symbol* target_classname, Thread * THREAD) {
292   InstanceKlass* superk = initialsuper;
293   while (superk != NULL && superk->super() != NULL) {
294     klassVtable ssVtable = (superk->super())->vtable();
295     if (vtable_index < ssVtable.length()) {
296       Method* super_method = ssVtable.method_at(vtable_index);
297       // get the class holding the matching method
298       // make sure you use that class for is_override
299       InstanceKlass* supermethodholder = super_method->method_holder();
300 #ifndef PRODUCT
301       Symbol* name= target_method()->name();
302       Symbol* signature = target_method()->signature();
303       assert(super_method->name() == name && super_method->signature() == signature, "vtable entry name/sig mismatch");
304 #endif
305 
306       if (supermethodholder->is_override(methodHandle(THREAD, super_method), target_loader, target_classname, THREAD)) {
307         if (log_develop_is_enabled(Trace, vtables)) {
308           ResourceMark rm(THREAD);
309           LogTarget(Trace, vtables) lt;
310           LogStream ls(lt);
311           char* sig = target_method()->name_and_sig_as_C_string();
312           ls.print("transitive overriding superclass %s with %s index %d, original flags: ",
313                        supermethodholder->internal_name(),
314                        sig, vtable_index);
315           super_method->print_linkage_flags(&ls);
316           ls.print("overriders flags: ");
317           target_method->print_linkage_flags(&ls);
318           ls.cr();
319         }
320 
321         break; // return found superk
322       }
323     } else  {
324       // super class has no vtable entry here, stop transitive search
325       superk = (InstanceKlass*)NULL;
326       break;
327     }
328     // if no override found yet, continue to search up
329     superk = superk->super() == NULL ? NULL : InstanceKlass::cast(superk->super());
330   }
331 
332   return superk;
333 }
334 
log_vtables(int i,bool overrides,const methodHandle & target_method,Klass * target_klass,Method * super_method,Thread * thread)335 static void log_vtables(int i, bool overrides, const methodHandle& target_method,
336                         Klass* target_klass, Method* super_method,
337                         Thread* thread) {
338 #ifndef PRODUCT
339   if (log_develop_is_enabled(Trace, vtables)) {
340     ResourceMark rm(thread);
341     LogTarget(Trace, vtables) lt;
342     LogStream ls(lt);
343     char* sig = target_method()->name_and_sig_as_C_string();
344     if (overrides) {
345       ls.print("overriding with %s index %d, original flags: ",
346                    sig, i);
347     } else {
348       ls.print("NOT overriding with %s index %d, original flags: ",
349                    sig, i);
350     }
351     super_method->print_linkage_flags(&ls);
352     ls.print("overriders flags: ");
353     target_method->print_linkage_flags(&ls);
354     ls.cr();
355   }
356 #endif
357 }
358 
359 // Update child's copy of super vtable for overrides
360 // OR return true if a new vtable entry is required.
361 // Only called for InstanceKlass's, i.e. not for arrays
362 // If that changed, could not use _klass as handle for klass
update_inherited_vtable(InstanceKlass * klass,const methodHandle & target_method,int super_vtable_len,int default_index,bool checkconstraints,TRAPS)363 bool klassVtable::update_inherited_vtable(InstanceKlass* klass, const methodHandle& target_method,
364                                           int super_vtable_len, int default_index,
365                                           bool checkconstraints, TRAPS) {
366   ResourceMark rm(THREAD);
367   bool allocate_new = true;
368   assert(klass->is_instance_klass(), "must be InstanceKlass");
369 
370   Array<int>* def_vtable_indices = NULL;
371   bool is_default = false;
372 
373   // default methods are non-private concrete methods in superinterfaces which are added
374   // to the vtable with their real method_holder.
375   // Since vtable and itable indices share the same storage, don't touch
376   // the default method's real vtable/itable index.
377   // default_vtable_indices stores the vtable value relative to this inheritor
378   if (default_index >= 0 ) {
379     is_default = true;
380     def_vtable_indices = klass->default_vtable_indices();
381     assert(!target_method()->is_private(), "private interface method flagged as default");
382     assert(def_vtable_indices != NULL, "def vtable alloc?");
383     assert(default_index <= def_vtable_indices->length(), "def vtable len?");
384   } else {
385     assert(klass == target_method()->method_holder(), "caller resp.");
386     // Initialize the method's vtable index to "nonvirtual".
387     // If we allocate a vtable entry, we will update it to a non-negative number.
388     target_method()->set_vtable_index(Method::nonvirtual_vtable_index);
389   }
390 
391   // Private, static and <init> methods are never in
392   if (target_method()->is_private() || target_method()->is_static() ||
393       (target_method()->name()->fast_compare(vmSymbols::object_initializer_name()) == 0)) {
394     return false;
395   }
396 
397   if (target_method->is_final_method(klass->access_flags())) {
398     // a final method never needs a new entry; final methods can be statically
399     // resolved and they have to be present in the vtable only if they override
400     // a super's method, in which case they re-use its entry
401     allocate_new = false;
402   } else if (klass->is_interface()) {
403     allocate_new = false;  // see note below in needs_new_vtable_entry
404     // An interface never allocates new vtable slots, only inherits old ones.
405     // This method will either be assigned its own itable index later,
406     // or be assigned an inherited vtable index in the loop below.
407     // default methods inherited by classes store their vtable indices
408     // in the inheritor's default_vtable_indices.
409     // default methods inherited by interfaces may already have a
410     // valid itable index, if so, don't change it.
411     // Overpass methods in an interface will be assigned an itable index later
412     // by an inheriting class.
413     if ((!is_default || !target_method()->has_itable_index())) {
414       target_method()->set_vtable_index(Method::pending_itable_index);
415     }
416   }
417 
418   // we need a new entry if there is no superclass
419   Klass* super = klass->super();
420   if (super == NULL) {
421     return allocate_new;
422   }
423 
424   // search through the vtable and update overridden entries
425   // Since check_signature_loaders acquires SystemDictionary_lock
426   // which can block for gc, once we are in this loop, use handles
427   // For classfiles built with >= jdk7, we now look for transitive overrides
428 
429   Symbol* name = target_method()->name();
430   Symbol* signature = target_method()->signature();
431 
432   Klass* target_klass = target_method()->method_holder();
433   if (target_klass == NULL) {
434     target_klass = _klass;
435   }
436 
437   Handle target_loader(THREAD, target_klass->class_loader());
438 
439   Symbol* target_classname = target_klass->name();
440   for(int i = 0; i < super_vtable_len; i++) {
441     Method* super_method;
442     if (is_preinitialized_vtable()) {
443       // If this is a shared class, the vtable is already in the final state (fully
444       // initialized). Need to look at the super's vtable.
445       klassVtable superVtable = super->vtable();
446       super_method = superVtable.method_at(i);
447     } else {
448       super_method = method_at(i);
449     }
450     // Check if method name matches.  Ignore match if klass is an interface and the
451     // matching method is a non-public java.lang.Object method.  (See JVMS 5.4.3.4)
452     // This is safe because the method at this slot should never get invoked.
453     // (TBD: put in a method to throw NoSuchMethodError if this slot is ever used.)
454     if (super_method->name() == name && super_method->signature() == signature &&
455         (!_klass->is_interface() ||
456          !SystemDictionary::is_nonpublic_Object_method(super_method))) {
457 
458       // get super_klass for method_holder for the found method
459       InstanceKlass* super_klass =  super_method->method_holder();
460 
461       // Whether the method is being overridden
462       bool overrides = false;
463 
464       // private methods are also never overridden
465       if (!super_method->is_private() &&
466           (is_default
467           || ((super_klass->is_override(methodHandle(THREAD, super_method), target_loader, target_classname, THREAD))
468           || ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION)
469           && ((super_klass = find_transitive_override(super_klass,
470                              target_method, i, target_loader,
471                              target_classname, THREAD))
472                              != (InstanceKlass*)NULL)))))
473         {
474         // Package private methods always need a new entry to root their own
475         // overriding. They may also override other methods.
476         if (!target_method()->is_package_private()) {
477           allocate_new = false;
478         }
479 
480         // Do not check loader constraints for overpass methods because overpass
481         // methods are created by the jvm to throw exceptions.
482         if (checkconstraints && !target_method()->is_overpass()) {
483           // Override vtable entry if passes loader constraint check
484           // if loader constraint checking requested
485           // No need to visit his super, since he and his super
486           // have already made any needed loader constraints.
487           // Since loader constraints are transitive, it is enough
488           // to link to the first super, and we get all the others.
489           Handle super_loader(THREAD, super_klass->class_loader());
490 
491           if (target_loader() != super_loader()) {
492             ResourceMark rm(THREAD);
493             Symbol* failed_type_symbol =
494               SystemDictionary::check_signature_loaders(signature, _klass,
495                                                         target_loader, super_loader,
496                                                         true, CHECK_(false));
497             if (failed_type_symbol != NULL) {
498               stringStream ss;
499               ss.print("loader constraint violation for class %s: when selecting "
500                        "overriding method '", klass->external_name());
501               target_method()->print_external_name(&ss),
502               ss.print("' the class loader %s of the "
503                        "selected method's type %s, and the class loader %s for its super "
504                        "type %s have different Class objects for the type %s used in the signature (%s; %s)",
505                        target_klass->class_loader_data()->loader_name_and_id(),
506                        target_klass->external_name(),
507                        super_klass->class_loader_data()->loader_name_and_id(),
508                        super_klass->external_name(),
509                        failed_type_symbol->as_klass_external_name(),
510                        target_klass->class_in_module_of_loader(false, true),
511                        super_klass->class_in_module_of_loader(false, true));
512               THROW_MSG_(vmSymbols::java_lang_LinkageError(), ss.as_string(), false);
513             }
514           }
515         }
516 
517         put_method_at(target_method(), i);
518         overrides = true;
519         if (!is_default) {
520           target_method()->set_vtable_index(i);
521         } else {
522           if (def_vtable_indices != NULL) {
523             if (is_preinitialized_vtable()) {
524               // At runtime initialize_vtable is rerun as part of link_class_impl()
525               // for a shared class loaded by the non-boot loader.
526               // The dumptime vtable index should be the same as the runtime index.
527               assert(def_vtable_indices->at(default_index) == i,
528                      "dump time vtable index is different from runtime index");
529             } else {
530               def_vtable_indices->at_put(default_index, i);
531             }
532           }
533           assert(super_method->is_default_method() || super_method->is_overpass()
534                  || super_method->is_abstract(), "default override error");
535         }
536       } else {
537         overrides = false;
538       }
539       log_vtables(i, overrides, target_method, target_klass, super_method, THREAD);
540     }
541   }
542   return allocate_new;
543 }
544 
put_method_at(Method * m,int index)545 void klassVtable::put_method_at(Method* m, int index) {
546   assert(!m->is_private(), "private methods should not be in vtable");
547   if (is_preinitialized_vtable()) {
548     // At runtime initialize_vtable is rerun as part of link_class_impl()
549     // for shared class loaded by the non-boot loader to obtain the loader
550     // constraints based on the runtime classloaders' context. The dumptime
551     // method at the vtable index should be the same as the runtime method.
552     assert(table()[index].method() == m,
553            "archived method is different from the runtime method");
554   } else {
555     if (log_develop_is_enabled(Trace, vtables)) {
556       ResourceMark rm;
557       LogTarget(Trace, vtables) lt;
558       LogStream ls(lt);
559       const char* sig = (m != NULL) ? m->name_and_sig_as_C_string() : "<NULL>";
560       ls.print("adding %s at index %d, flags: ", sig, index);
561       if (m != NULL) {
562         m->print_linkage_flags(&ls);
563       }
564       ls.cr();
565     }
566     table()[index].set(m);
567   }
568 }
569 
570 // Find out if a method "m" with superclass "super", loader "classloader" and
571 // name "classname" needs a new vtable entry.  Let P be a class package defined
572 // by "classloader" and "classname".
573 // NOTE: The logic used here is very similar to the one used for computing
574 // the vtables indices for a method. We cannot directly use that function because,
575 // we allocate the InstanceKlass at load time, and that requires that the
576 // superclass has been loaded.
577 // However, the vtable entries are filled in at link time, and therefore
578 // the superclass' vtable may not yet have been filled in.
needs_new_vtable_entry(const methodHandle & target_method,const Klass * super,Handle classloader,Symbol * classname,AccessFlags class_flags,u2 major_version,TRAPS)579 bool klassVtable::needs_new_vtable_entry(const methodHandle& target_method,
580                                          const Klass* super,
581                                          Handle classloader,
582                                          Symbol* classname,
583                                          AccessFlags class_flags,
584                                          u2 major_version,
585                                          TRAPS) {
586   if (class_flags.is_interface()) {
587     // Interfaces do not use vtables, except for java.lang.Object methods,
588     // so there is no point to assigning
589     // a vtable index to any of their local methods.  If we refrain from doing this,
590     // we can use Method::_vtable_index to hold the itable index
591     return false;
592   }
593 
594   if (target_method->is_final_method(class_flags) ||
595       // a final method never needs a new entry; final methods can be statically
596       // resolved and they have to be present in the vtable only if they override
597       // a super's method, in which case they re-use its entry
598       (target_method()->is_private()) ||
599       // private methods don't need to be in vtable
600       (target_method()->is_static()) ||
601       // static methods don't need to be in vtable
602       (target_method()->name()->fast_compare(vmSymbols::object_initializer_name()) == 0)
603       // <init> is never called dynamically-bound
604       ) {
605     return false;
606   }
607 
608   // Concrete interface methods do not need new entries, they override
609   // abstract method entries using default inheritance rules
610   if (target_method()->method_holder() != NULL &&
611       target_method()->method_holder()->is_interface()  &&
612       !target_method()->is_abstract()) {
613     assert(target_method()->is_default_method(),
614            "unexpected interface method type");
615     return false;
616   }
617 
618   // we need a new entry if there is no superclass
619   if (super == NULL) {
620     return true;
621   }
622 
623   // Package private methods always need a new entry to root their own
624   // overriding. This allows transitive overriding to work.
625   if (target_method()->is_package_private()) {
626     return true;
627   }
628 
629   // search through the super class hierarchy to see if we need
630   // a new entry
631   ResourceMark rm(THREAD);
632   Symbol* name = target_method()->name();
633   Symbol* signature = target_method()->signature();
634   const Klass* k = super;
635   Method* super_method = NULL;
636   InstanceKlass *holder = NULL;
637   Method* recheck_method =  NULL;
638   bool found_pkg_prvt_method = false;
639   while (k != NULL) {
640     // lookup through the hierarchy for a method with matching name and sign.
641     super_method = InstanceKlass::cast(k)->lookup_method(name, signature);
642     if (super_method == NULL) {
643       break; // we still have to search for a matching miranda method
644     }
645     // get the class holding the matching method
646     // make sure you use that class for is_override
647     InstanceKlass* superk = super_method->method_holder();
648     // we want only instance method matches
649     // ignore private methods found via lookup_method since they do not participate in overriding,
650     // and since we do override around them: e.g. a.m pub/b.m private/c.m pub,
651     // ignore private, c.m pub does override a.m pub
652     // For classes that were not javac'd together, we also do transitive overriding around
653     // methods that have less accessibility
654     if ((!super_method->is_static()) &&
655        (!super_method->is_private())) {
656       if (superk->is_override(methodHandle(THREAD, super_method), classloader, classname, THREAD)) {
657         return false;
658       // else keep looking for transitive overrides
659       }
660       // If we get here then one of the super classes has a package private method
661       // that will not get overridden because it is in a different package.  But,
662       // that package private method does "override" any matching methods in super
663       // interfaces, so there will be no miranda vtable entry created.  So, set flag
664       // to TRUE for use below, in case there are no methods in super classes that
665       // this target method overrides.
666       assert(super_method->is_package_private(), "super_method must be package private");
667       assert(!superk->is_same_class_package(classloader(), classname),
668              "Must be different packages");
669       found_pkg_prvt_method = true;
670     }
671 
672     // Start with lookup result and continue to search up, for versions supporting transitive override
673     if (major_version >= VTABLE_TRANSITIVE_OVERRIDE_VERSION) {
674       k = superk->super(); // haven't found an override match yet; continue to look
675     } else {
676       break;
677     }
678   }
679 
680   // If found_pkg_prvt_method is set, then the ONLY matching method in the
681   // superclasses is package private in another package. That matching method will
682   // prevent a miranda vtable entry from being created. Because the target method can not
683   // override the package private method in another package, then it needs to be the root
684   // for its own vtable entry.
685   if (found_pkg_prvt_method) {
686      return true;
687   }
688 
689   // if the target method is public or protected it may have a matching
690   // miranda method in the super, whose entry it should re-use.
691   // Actually, to handle cases that javac would not generate, we need
692   // this check for all access permissions.
693   const InstanceKlass *sk = InstanceKlass::cast(super);
694   if (sk->has_miranda_methods()) {
695     if (sk->lookup_method_in_all_interfaces(name, signature, Klass::find_defaults) != NULL) {
696       return false; // found a matching miranda; we do not need a new entry
697     }
698   }
699   return true; // found no match; we need a new entry
700 }
701 
702 // Support for miranda methods
703 
704 // get the vtable index of a miranda method with matching "name" and "signature"
index_of_miranda(Symbol * name,Symbol * signature)705 int klassVtable::index_of_miranda(Symbol* name, Symbol* signature) {
706   // search from the bottom, might be faster
707   for (int i = (length() - 1); i >= 0; i--) {
708     Method* m = table()[i].method();
709     if (is_miranda_entry_at(i) &&
710         m->name() == name && m->signature() == signature) {
711       return i;
712     }
713   }
714   return Method::invalid_vtable_index;
715 }
716 
717 // check if an entry at an index is miranda
718 // requires that method m at entry be declared ("held") by an interface.
is_miranda_entry_at(int i)719 bool klassVtable::is_miranda_entry_at(int i) {
720   Method* m = method_at(i);
721   Klass* method_holder = m->method_holder();
722   InstanceKlass *mhk = InstanceKlass::cast(method_holder);
723 
724   // miranda methods are public abstract instance interface methods in a class's vtable
725   if (mhk->is_interface()) {
726     assert(m->is_public(), "should be public");
727     assert(ik()->implements_interface(method_holder) , "this class should implement the interface");
728     if (is_miranda(m, ik()->methods(), ik()->default_methods(), ik()->super(), klass()->is_interface())) {
729       return true;
730     }
731   }
732   return false;
733 }
734 
735 // Check if a method is a miranda method, given a class's methods array,
736 // its default_method table and its super class.
737 // "Miranda" means an abstract non-private method that would not be
738 // overridden for the local class.
739 // A "miranda" method should only include non-private interface
740 // instance methods, i.e. not private methods, not static methods,
741 // not default methods (concrete interface methods), not overpass methods.
742 // If a given class already has a local (including overpass) method, a
743 // default method, or any of its superclasses has the same which would have
744 // overridden an abstract method, then this is not a miranda method.
745 //
746 // Miranda methods are checked multiple times.
747 // Pass 1: during class load/class file parsing: before vtable size calculation:
748 // include superinterface abstract and default methods (non-private instance).
749 // We include potential default methods to give them space in the vtable.
750 // During the first run, the current instanceKlass has not yet been
751 // created, the superclasses and superinterfaces do have instanceKlasses
752 // but may not have vtables, the default_methods list is empty, no overpasses.
753 // Default method generation uses the all_mirandas array as the starter set for
754 // maximally-specific default method calculation.  So, for both classes and
755 // interfaces, it is necessary that the first pass will find all non-private
756 // interface instance methods, whether or not they are concrete.
757 //
758 // Pass 2: recalculated during vtable initialization: only include abstract methods.
759 // The goal of pass 2 is to walk through the superinterfaces to see if any of
760 // the superinterface methods (which were all abstract pre-default methods)
761 // need to be added to the vtable.
762 // With the addition of default methods, we have three new challenges:
763 // overpasses, static interface methods and private interface methods.
764 // Static and private interface methods do not get added to the vtable and
765 // are not seen by the method resolution process, so we skip those.
766 // Overpass methods are already in the vtable, so vtable lookup will
767 // find them and we don't need to add a miranda method to the end of
768 // the vtable. So we look for overpass methods and if they are found we
769 // return false. Note that we inherit our superclasses vtable, so
770 // the superclass' search also needs to use find_overpass so that if
771 // one is found we return false.
772 // False means - we don't need a miranda method added to the vtable.
773 //
774 // During the second run, default_methods is set up, so concrete methods from
775 // superinterfaces with matching names/signatures to default_methods are already
776 // in the default_methods list and do not need to be appended to the vtable
777 // as mirandas. Abstract methods may already have been handled via
778 // overpasses - either local or superclass overpasses, which may be
779 // in the vtable already.
780 //
781 // Pass 3: They are also checked by link resolution and selection,
782 // for invocation on a method (not interface method) reference that
783 // resolves to a method with an interface as its method_holder.
784 // Used as part of walking from the bottom of the vtable to find
785 // the vtable index for the miranda method.
786 //
787 // Part of the Miranda Rights in the US mean that if you do not have
788 // an attorney one will be appointed for you.
is_miranda(Method * m,Array<Method * > * class_methods,Array<Method * > * default_methods,const Klass * super,bool is_interface)789 bool klassVtable::is_miranda(Method* m, Array<Method*>* class_methods,
790                              Array<Method*>* default_methods, const Klass* super,
791                              bool is_interface) {
792   if (m->is_static() || m->is_private() || m->is_overpass()) {
793     return false;
794   }
795   Symbol* name = m->name();
796   Symbol* signature = m->signature();
797 
798   // First look in local methods to see if already covered
799   if (InstanceKlass::find_local_method(class_methods, name, signature,
800               Klass::find_overpass, Klass::skip_static, Klass::skip_private) != NULL)
801   {
802     return false;
803   }
804 
805   // Check local default methods
806   if ((default_methods != NULL) &&
807     (InstanceKlass::find_method(default_methods, name, signature) != NULL))
808    {
809      return false;
810    }
811 
812   // Iterate on all superclasses, which should be InstanceKlasses.
813   // Note that we explicitly look for overpasses at each level.
814   // Overpasses may or may not exist for supers for pass 1,
815   // they should have been created for pass 2 and later.
816 
817   for (const Klass* cursuper = super; cursuper != NULL; cursuper = cursuper->super())
818   {
819      Method* found_mth = InstanceKlass::cast(cursuper)->find_local_method(name, signature,
820        Klass::find_overpass, Klass::skip_static, Klass::skip_private);
821      // Ignore non-public methods in java.lang.Object if klass is an interface.
822      if (found_mth != NULL && (!is_interface ||
823          !SystemDictionary::is_nonpublic_Object_method(found_mth))) {
824        return false;
825      }
826   }
827 
828   return true;
829 }
830 
831 // Scans current_interface_methods for miranda methods that do not
832 // already appear in new_mirandas, or default methods,  and are also not defined-and-non-private
833 // in super (superclass).  These mirandas are added to all_mirandas if it is
834 // not null; in addition, those that are not duplicates of miranda methods
835 // inherited by super from its interfaces are added to new_mirandas.
836 // Thus, new_mirandas will be the set of mirandas that this class introduces,
837 // all_mirandas will be the set of all mirandas applicable to this class
838 // including all defined in superclasses.
add_new_mirandas_to_lists(GrowableArray<Method * > * new_mirandas,GrowableArray<Method * > * all_mirandas,Array<Method * > * current_interface_methods,Array<Method * > * class_methods,Array<Method * > * default_methods,const Klass * super,bool is_interface)839 void klassVtable::add_new_mirandas_to_lists(
840     GrowableArray<Method*>* new_mirandas, GrowableArray<Method*>* all_mirandas,
841     Array<Method*>* current_interface_methods, Array<Method*>* class_methods,
842     Array<Method*>* default_methods, const Klass* super, bool is_interface) {
843 
844   // iterate thru the current interface's method to see if it a miranda
845   int num_methods = current_interface_methods->length();
846   for (int i = 0; i < num_methods; i++) {
847     Method* im = current_interface_methods->at(i);
848     bool is_duplicate = false;
849     int num_of_current_mirandas = new_mirandas->length();
850     // check for duplicate mirandas in different interfaces we implement
851     for (int j = 0; j < num_of_current_mirandas; j++) {
852       Method* miranda = new_mirandas->at(j);
853       if ((im->name() == miranda->name()) &&
854           (im->signature() == miranda->signature())) {
855         is_duplicate = true;
856         break;
857       }
858     }
859 
860     if (!is_duplicate) { // we don't want duplicate miranda entries in the vtable
861       if (is_miranda(im, class_methods, default_methods, super, is_interface)) { // is it a miranda at all?
862         const InstanceKlass *sk = InstanceKlass::cast(super);
863         // check if it is a duplicate of a super's miranda
864         if (sk->lookup_method_in_all_interfaces(im->name(), im->signature(), Klass::find_defaults) == NULL) {
865           new_mirandas->append(im);
866         }
867         if (all_mirandas != NULL) {
868           all_mirandas->append(im);
869         }
870       }
871     }
872   }
873 }
874 
get_mirandas(GrowableArray<Method * > * new_mirandas,GrowableArray<Method * > * all_mirandas,const Klass * super,Array<Method * > * class_methods,Array<Method * > * default_methods,Array<InstanceKlass * > * local_interfaces,bool is_interface)875 void klassVtable::get_mirandas(GrowableArray<Method*>* new_mirandas,
876                                GrowableArray<Method*>* all_mirandas,
877                                const Klass* super,
878                                Array<Method*>* class_methods,
879                                Array<Method*>* default_methods,
880                                Array<InstanceKlass*>* local_interfaces,
881                                bool is_interface) {
882   assert((new_mirandas->length() == 0) , "current mirandas must be 0");
883 
884   // iterate thru the local interfaces looking for a miranda
885   int num_local_ifs = local_interfaces->length();
886   for (int i = 0; i < num_local_ifs; i++) {
887     InstanceKlass *ik = InstanceKlass::cast(local_interfaces->at(i));
888     add_new_mirandas_to_lists(new_mirandas, all_mirandas,
889                               ik->methods(), class_methods,
890                               default_methods, super, is_interface);
891     // iterate thru each local's super interfaces
892     Array<InstanceKlass*>* super_ifs = ik->transitive_interfaces();
893     int num_super_ifs = super_ifs->length();
894     for (int j = 0; j < num_super_ifs; j++) {
895       InstanceKlass *sik = super_ifs->at(j);
896       add_new_mirandas_to_lists(new_mirandas, all_mirandas,
897                                 sik->methods(), class_methods,
898                                 default_methods, super, is_interface);
899     }
900   }
901 }
902 
903 // Discover miranda methods ("miranda" = "interface abstract, no binding"),
904 // and append them into the vtable starting at index initialized,
905 // return the new value of initialized.
906 // Miranda methods use vtable entries, but do not get assigned a vtable_index
907 // The vtable_index is discovered by searching from the end of the vtable
fill_in_mirandas(int initialized,TRAPS)908 int klassVtable::fill_in_mirandas(int initialized, TRAPS) {
909   ResourceMark rm(THREAD);
910   GrowableArray<Method*> mirandas(20);
911   get_mirandas(&mirandas, NULL, ik()->super(), ik()->methods(),
912                ik()->default_methods(), ik()->local_interfaces(),
913                klass()->is_interface());
914   for (int i = 0; i < mirandas.length(); i++) {
915     if (log_develop_is_enabled(Trace, vtables)) {
916       Method* meth = mirandas.at(i);
917       LogTarget(Trace, vtables) lt;
918       LogStream ls(lt);
919       if (meth != NULL) {
920         char* sig = meth->name_and_sig_as_C_string();
921         ls.print("fill in mirandas with %s index %d, flags: ",
922                      sig, initialized);
923         meth->print_linkage_flags(&ls);
924         ls.cr();
925       }
926     }
927     put_method_at(mirandas.at(i), initialized);
928     ++initialized;
929   }
930   return initialized;
931 }
932 
933 // Copy this class's vtable to the vtable beginning at start.
934 // Used to copy superclass vtable to prefix of subclass's vtable.
copy_vtable_to(vtableEntry * start)935 void klassVtable::copy_vtable_to(vtableEntry* start) {
936   Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size());
937 }
938 
939 #if INCLUDE_JVMTI
adjust_default_method(int vtable_index,Method * old_method,Method * new_method)940 bool klassVtable::adjust_default_method(int vtable_index, Method* old_method, Method* new_method) {
941   // If old_method is default, find this vtable index in default_vtable_indices
942   // and replace that method in the _default_methods list
943   bool updated = false;
944 
945   Array<Method*>* default_methods = ik()->default_methods();
946   if (default_methods != NULL) {
947     int len = default_methods->length();
948     for (int idx = 0; idx < len; idx++) {
949       if (vtable_index == ik()->default_vtable_indices()->at(idx)) {
950         if (default_methods->at(idx) == old_method) {
951           default_methods->at_put(idx, new_method);
952           updated = true;
953         }
954         break;
955       }
956     }
957   }
958   return updated;
959 }
960 
961 // search the vtable for uses of either obsolete or EMCP methods
adjust_method_entries(bool * trace_name_printed)962 void klassVtable::adjust_method_entries(bool * trace_name_printed) {
963   int prn_enabled = 0;
964   ResourceMark rm;
965 
966   for (int index = 0; index < length(); index++) {
967     Method* old_method = unchecked_method_at(index);
968     if (old_method == NULL || !old_method->is_old()) {
969       continue; // skip uninteresting entries
970     }
971     assert(!old_method->is_deleted(), "vtable methods may not be deleted");
972 
973     Method* new_method = old_method->get_new_method();
974     put_method_at(new_method, index);
975 
976     // For default methods, need to update the _default_methods array
977     // which can only have one method entry for a given signature
978     bool updated_default = false;
979     if (old_method->is_default_method()) {
980       updated_default = adjust_default_method(index, old_method, new_method);
981     }
982 
983     if (!(*trace_name_printed)) {
984       log_info(redefine, class, update)
985         ("adjust: klassname=%s for methods from name=%s",
986          _klass->external_name(), old_method->method_holder()->external_name());
987       *trace_name_printed = true;
988     }
989     log_trace(redefine, class, update, vtables)
990       ("vtable method update: class: %s method: %s, updated default = %s",
991        _klass->external_name(), new_method->external_name(), updated_default ? "true" : "false");
992   }
993 }
994 
995 // a vtable should never contain old or obsolete methods
check_no_old_or_obsolete_entries()996 bool klassVtable::check_no_old_or_obsolete_entries() {
997   ResourceMark rm;
998 
999   for (int i = 0; i < length(); i++) {
1000     Method* m = unchecked_method_at(i);
1001     if (m != NULL &&
1002         (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
1003       log_trace(redefine, class, update, vtables)
1004         ("vtable check found old method entry: class: %s old: %d obsolete: %d, method: %s",
1005          _klass->external_name(), m->is_old(), m->is_obsolete(), m->external_name());
1006       return false;
1007     }
1008   }
1009   return true;
1010 }
1011 
dump_vtable()1012 void klassVtable::dump_vtable() {
1013   tty->print_cr("vtable dump --");
1014   for (int i = 0; i < length(); i++) {
1015     Method* m = unchecked_method_at(i);
1016     if (m != NULL) {
1017       tty->print("      (%5d)  ", i);
1018       m->access_flags().print_on(tty);
1019       if (m->is_default_method()) {
1020         tty->print("default ");
1021       }
1022       if (m->is_overpass()) {
1023         tty->print("overpass");
1024       }
1025       tty->print(" --  ");
1026       m->print_name(tty);
1027       tty->cr();
1028     }
1029   }
1030 }
1031 #endif // INCLUDE_JVMTI
1032 
1033 //-----------------------------------------------------------------------------------------
1034 // Itable code
1035 
1036 // Initialize a itableMethodEntry
initialize(Method * m)1037 void itableMethodEntry::initialize(Method* m) {
1038   if (m == NULL) return;
1039 
1040 #ifdef ASSERT
1041   if (MetaspaceShared::is_in_shared_metaspace((void*)&_method) &&
1042      !MetaspaceShared::remapped_readwrite()) {
1043     // At runtime initialize_itable is rerun as part of link_class_impl()
1044     // for a shared class loaded by the non-boot loader.
1045     // The dumptime itable method entry should be the same as the runtime entry.
1046     assert(_method == m, "sanity");
1047   }
1048 #endif
1049   _method = m;
1050 }
1051 
klassItable(InstanceKlass * klass)1052 klassItable::klassItable(InstanceKlass* klass) {
1053   _klass = klass;
1054 
1055   if (klass->itable_length() > 0) {
1056     itableOffsetEntry* offset_entry = (itableOffsetEntry*)klass->start_of_itable();
1057     if (offset_entry  != NULL && offset_entry->interface_klass() != NULL) { // Check that itable is initialized
1058       // First offset entry points to the first method_entry
1059       intptr_t* method_entry  = (intptr_t *)(((address)klass) + offset_entry->offset());
1060       intptr_t* end         = klass->end_of_itable();
1061 
1062       _table_offset      = (intptr_t*)offset_entry - (intptr_t*)klass;
1063       _size_offset_table = (method_entry - ((intptr_t*)offset_entry)) / itableOffsetEntry::size();
1064       _size_method_table = (end - method_entry)                  / itableMethodEntry::size();
1065       assert(_table_offset >= 0 && _size_offset_table >= 0 && _size_method_table >= 0, "wrong computation");
1066       return;
1067     }
1068   }
1069 
1070   // The length of the itable was either zero, or it has not yet been initialized.
1071   _table_offset      = 0;
1072   _size_offset_table = 0;
1073   _size_method_table = 0;
1074 }
1075 
1076 static int initialize_count = 0;
1077 
1078 // Initialization
initialize_itable(bool checkconstraints,TRAPS)1079 void klassItable::initialize_itable(bool checkconstraints, TRAPS) {
1080   if (_klass->is_interface()) {
1081     // This needs to go after vtable indices are assigned but
1082     // before implementors need to know the number of itable indices.
1083     assign_itable_indices_for_interface(InstanceKlass::cast(_klass), THREAD);
1084   }
1085 
1086   // Cannot be setup doing bootstrapping, interfaces don't have
1087   // itables, and klass with only ones entry have empty itables
1088   if (Universe::is_bootstrapping() ||
1089       _klass->is_interface() ||
1090       _klass->itable_length() == itableOffsetEntry::size()) return;
1091 
1092   // There's alway an extra itable entry so we can null-terminate it.
1093   guarantee(size_offset_table() >= 1, "too small");
1094   int num_interfaces = size_offset_table() - 1;
1095   if (num_interfaces > 0) {
1096     ResourceMark rm(THREAD);
1097     log_develop_debug(itables)("%3d: Initializing itables for %s", ++initialize_count,
1098                        _klass->name()->as_C_string());
1099 
1100 
1101     // Iterate through all interfaces
1102     int i;
1103     for(i = 0; i < num_interfaces; i++) {
1104       itableOffsetEntry* ioe = offset_entry(i);
1105       HandleMark hm(THREAD);
1106       Klass* interf = ioe->interface_klass();
1107       assert(interf != NULL && ioe->offset() != 0, "bad offset entry in itable");
1108       initialize_itable_for_interface(ioe->offset(), InstanceKlass::cast(interf), checkconstraints, CHECK);
1109     }
1110 
1111   }
1112   // Check that the last entry is empty
1113   itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1);
1114   guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing");
1115 }
1116 
1117 
interface_method_needs_itable_index(Method * m)1118 inline bool interface_method_needs_itable_index(Method* m) {
1119   if (m->is_static())           return false;   // e.g., Stream.empty
1120   if (m->is_initializer())      return false;   // <init> or <clinit>
1121   if (m->is_private())          return false;   // uses direct call
1122   // If an interface redeclares a method from java.lang.Object,
1123   // it should already have a vtable index, don't touch it.
1124   // e.g., CharSequence.toString (from initialize_vtable)
1125   // if (m->has_vtable_index())  return false; // NO!
1126   return true;
1127 }
1128 
assign_itable_indices_for_interface(InstanceKlass * klass,TRAPS)1129 int klassItable::assign_itable_indices_for_interface(InstanceKlass* klass, TRAPS) {
1130   // an interface does not have an itable, but its methods need to be numbered
1131   ResourceMark rm(THREAD);
1132   log_develop_debug(itables)("%3d: Initializing itable indices for interface %s",
1133                              ++initialize_count, klass->name()->as_C_string());
1134   Array<Method*>* methods = klass->methods();
1135   int nof_methods = methods->length();
1136   int ime_num = 0;
1137   for (int i = 0; i < nof_methods; i++) {
1138     Method* m = methods->at(i);
1139     if (interface_method_needs_itable_index(m)) {
1140       assert(!m->is_final_method(), "no final interface methods");
1141       // If m is already assigned a vtable index, do not disturb it.
1142       if (log_develop_is_enabled(Trace, itables)) {
1143         LogTarget(Trace, itables) lt;
1144         LogStream ls(lt);
1145         assert(m != NULL, "methods can never be null");
1146         const char* sig = m->name_and_sig_as_C_string();
1147         if (m->has_vtable_index()) {
1148           ls.print("vtable index %d for method: %s, flags: ", m->vtable_index(), sig);
1149         } else {
1150           ls.print("itable index %d for method: %s, flags: ", ime_num, sig);
1151         }
1152         m->print_linkage_flags(&ls);
1153         ls.cr();
1154       }
1155       if (!m->has_vtable_index()) {
1156         // A shared method could have an initialized itable_index that
1157         // is < 0.
1158         assert(m->vtable_index() == Method::pending_itable_index ||
1159                m->is_shared(),
1160                "set by initialize_vtable");
1161         m->set_itable_index(ime_num);
1162         // Progress to next itable entry
1163         ime_num++;
1164       }
1165     }
1166   }
1167   assert(ime_num == method_count_for_interface(klass), "proper sizing");
1168   return ime_num;
1169 }
1170 
method_count_for_interface(InstanceKlass * interf)1171 int klassItable::method_count_for_interface(InstanceKlass* interf) {
1172   assert(interf->is_interface(), "must be");
1173   Array<Method*>* methods = interf->methods();
1174   int nof_methods = methods->length();
1175   int length = 0;
1176   while (nof_methods > 0) {
1177     Method* m = methods->at(nof_methods-1);
1178     if (m->has_itable_index()) {
1179       length = m->itable_index() + 1;
1180       break;
1181     }
1182     nof_methods -= 1;
1183   }
1184 #ifdef ASSERT
1185   int nof_methods_copy = nof_methods;
1186   while (nof_methods_copy > 0) {
1187     Method* mm = methods->at(--nof_methods_copy);
1188     assert(!mm->has_itable_index() || mm->itable_index() < length, "");
1189   }
1190 #endif //ASSERT
1191   // return the rightmost itable index, plus one; or 0 if no methods have
1192   // itable indices
1193   return length;
1194 }
1195 
1196 
initialize_itable_for_interface(int method_table_offset,InstanceKlass * interf,bool checkconstraints,TRAPS)1197 void klassItable::initialize_itable_for_interface(int method_table_offset, InstanceKlass* interf, bool checkconstraints, TRAPS) {
1198   assert(interf->is_interface(), "must be");
1199   Array<Method*>* methods = interf->methods();
1200   int nof_methods = methods->length();
1201   HandleMark hm;
1202   Handle interface_loader (THREAD, interf->class_loader());
1203 
1204   int ime_count = method_count_for_interface(interf);
1205   for (int i = 0; i < nof_methods; i++) {
1206     Method* m = methods->at(i);
1207     Method* target = NULL;
1208     if (m->has_itable_index()) {
1209       // This search must match the runtime resolution, i.e. selection search for invokeinterface
1210       // to correctly enforce loader constraints for interface method inheritance.
1211       // Private methods are skipped as a private class method can never be the implementation
1212       // of an interface method.
1213       // Invokespecial does not perform selection based on the receiver, so it does not use
1214       // the cached itable.
1215       target = LinkResolver::lookup_instance_method_in_klasses(_klass, m->name(), m->signature(),
1216                                                                Klass::skip_private, CHECK);
1217     }
1218     if (target == NULL || !target->is_public() || target->is_abstract() || target->is_overpass()) {
1219       assert(target == NULL || !target->is_overpass() || target->is_public(),
1220              "Non-public overpass method!");
1221       // Entry does not resolve. Leave it empty for AbstractMethodError or other error.
1222       if (!(target == NULL) && !target->is_public()) {
1223         // Stuff an IllegalAccessError throwing method in there instead.
1224         itableOffsetEntry::method_entry(_klass, method_table_offset)[m->itable_index()].
1225             initialize(Universe::throw_illegal_access_error());
1226       }
1227     } else {
1228       // Entry did resolve, check loader constraints before initializing
1229       // if checkconstraints requested
1230       if (checkconstraints) {
1231         Handle method_holder_loader (THREAD, target->method_holder()->class_loader());
1232         InstanceKlass* method_holder = target->method_holder();
1233         if (method_holder_loader() != interface_loader()) {
1234           ResourceMark rm(THREAD);
1235           Symbol* failed_type_symbol =
1236             SystemDictionary::check_signature_loaders(m->signature(),
1237                                                       _klass,
1238                                                       method_holder_loader,
1239                                                       interface_loader,
1240                                                       true, CHECK);
1241           if (failed_type_symbol != NULL) {
1242             stringStream ss;
1243             ss.print("loader constraint violation in interface itable"
1244                      " initialization for class %s: when selecting method '",
1245                      _klass->external_name());
1246             m->print_external_name(&ss),
1247             ss.print("' the class loader %s for super interface %s, and the class"
1248                      " loader %s of the selected method's %s, %s have"
1249                      " different Class objects for the type %s used in the signature (%s; %s)",
1250                      interf->class_loader_data()->loader_name_and_id(),
1251                      interf->external_name(),
1252                      method_holder->class_loader_data()->loader_name_and_id(),
1253                      method_holder->external_kind(),
1254                      method_holder->external_name(),
1255                      failed_type_symbol->as_klass_external_name(),
1256                      interf->class_in_module_of_loader(false, true),
1257                      method_holder->class_in_module_of_loader(false, true));
1258             THROW_MSG(vmSymbols::java_lang_LinkageError(), ss.as_string());
1259           }
1260         }
1261       }
1262 
1263       // ime may have moved during GC so recalculate address
1264       int ime_num = m->itable_index();
1265       assert(ime_num < ime_count, "oob");
1266       itableOffsetEntry::method_entry(_klass, method_table_offset)[ime_num].initialize(target);
1267       if (log_develop_is_enabled(Trace, itables)) {
1268         ResourceMark rm(THREAD);
1269         if (target != NULL) {
1270           LogTarget(Trace, itables) lt;
1271           LogStream ls(lt);
1272           char* sig = target->name_and_sig_as_C_string();
1273           ls.print("interface: %s, ime_num: %d, target: %s, method_holder: %s ",
1274                        interf->internal_name(), ime_num, sig,
1275                        target->method_holder()->internal_name());
1276           ls.print("target_method flags: ");
1277           target->print_linkage_flags(&ls);
1278           ls.cr();
1279         }
1280       }
1281     }
1282   }
1283 }
1284 
1285 #if INCLUDE_JVMTI
1286 // search the itable for uses of either obsolete or EMCP methods
adjust_method_entries(bool * trace_name_printed)1287 void klassItable::adjust_method_entries(bool * trace_name_printed) {
1288   ResourceMark rm;
1289   itableMethodEntry* ime = method_entry(0);
1290 
1291   for (int i = 0; i < _size_method_table; i++, ime++) {
1292     Method* old_method = ime->method();
1293     if (old_method == NULL || !old_method->is_old()) {
1294       continue; // skip uninteresting entries
1295     }
1296     assert(!old_method->is_deleted(), "itable methods may not be deleted");
1297     Method* new_method = old_method->get_new_method();
1298     ime->initialize(new_method);
1299 
1300     if (!(*trace_name_printed)) {
1301       log_info(redefine, class, update)("adjust: name=%s", old_method->method_holder()->external_name());
1302       *trace_name_printed = true;
1303     }
1304     log_trace(redefine, class, update, itables)
1305       ("itable method update: class: %s method: %s", _klass->external_name(), new_method->external_name());
1306   }
1307 }
1308 
1309 // an itable should never contain old or obsolete methods
check_no_old_or_obsolete_entries()1310 bool klassItable::check_no_old_or_obsolete_entries() {
1311   ResourceMark rm;
1312   itableMethodEntry* ime = method_entry(0);
1313 
1314   for (int i = 0; i < _size_method_table; i++) {
1315     Method* m = ime->method();
1316     if (m != NULL &&
1317         (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
1318       log_trace(redefine, class, update, itables)
1319         ("itable check found old method entry: class: %s old: %d obsolete: %d, method: %s",
1320          _klass->external_name(), m->is_old(), m->is_obsolete(), m->external_name());
1321       return false;
1322     }
1323     ime++;
1324   }
1325   return true;
1326 }
1327 
dump_itable()1328 void klassItable::dump_itable() {
1329   itableMethodEntry* ime = method_entry(0);
1330   tty->print_cr("itable dump --");
1331   for (int i = 0; i < _size_method_table; i++) {
1332     Method* m = ime->method();
1333     if (m != NULL) {
1334       tty->print("      (%5d)  ", i);
1335       m->access_flags().print_on(tty);
1336       if (m->is_default_method()) {
1337         tty->print("default ");
1338       }
1339       tty->print(" --  ");
1340       m->print_name(tty);
1341       tty->cr();
1342     }
1343     ime++;
1344   }
1345 }
1346 #endif // INCLUDE_JVMTI
1347 
1348 // Setup
1349 class InterfaceVisiterClosure : public StackObj {
1350  public:
1351   virtual void doit(InstanceKlass* intf, int method_count) = 0;
1352 };
1353 
1354 // Visit all interfaces with at least one itable method
visit_all_interfaces(Array<InstanceKlass * > * transitive_intf,InterfaceVisiterClosure * blk)1355 void visit_all_interfaces(Array<InstanceKlass*>* transitive_intf, InterfaceVisiterClosure *blk) {
1356   // Handle array argument
1357   for(int i = 0; i < transitive_intf->length(); i++) {
1358     InstanceKlass* intf = transitive_intf->at(i);
1359     assert(intf->is_interface(), "sanity check");
1360 
1361     // Find no. of itable methods
1362     int method_count = 0;
1363     // method_count = klassItable::method_count_for_interface(intf);
1364     Array<Method*>* methods = intf->methods();
1365     if (methods->length() > 0) {
1366       for (int i = methods->length(); --i >= 0; ) {
1367         if (interface_method_needs_itable_index(methods->at(i))) {
1368           method_count++;
1369         }
1370       }
1371     }
1372 
1373     // Visit all interfaces which either have any methods or can participate in receiver type check.
1374     // We do not bother to count methods in transitive interfaces, although that would allow us to skip
1375     // this step in the rare case of a zero-method interface extending another zero-method interface.
1376     if (method_count > 0 || intf->transitive_interfaces()->length() > 0) {
1377       blk->doit(intf, method_count);
1378     }
1379   }
1380 }
1381 
1382 class CountInterfacesClosure : public InterfaceVisiterClosure {
1383  private:
1384   int _nof_methods;
1385   int _nof_interfaces;
1386  public:
CountInterfacesClosure()1387    CountInterfacesClosure() { _nof_methods = 0; _nof_interfaces = 0; }
1388 
nof_methods() const1389    int nof_methods() const    { return _nof_methods; }
nof_interfaces() const1390    int nof_interfaces() const { return _nof_interfaces; }
1391 
doit(InstanceKlass * intf,int method_count)1392    void doit(InstanceKlass* intf, int method_count) { _nof_methods += method_count; _nof_interfaces++; }
1393 };
1394 
1395 class SetupItableClosure : public InterfaceVisiterClosure  {
1396  private:
1397   itableOffsetEntry* _offset_entry;
1398   itableMethodEntry* _method_entry;
1399   address            _klass_begin;
1400  public:
SetupItableClosure(address klass_begin,itableOffsetEntry * offset_entry,itableMethodEntry * method_entry)1401   SetupItableClosure(address klass_begin, itableOffsetEntry* offset_entry, itableMethodEntry* method_entry) {
1402     _klass_begin  = klass_begin;
1403     _offset_entry = offset_entry;
1404     _method_entry = method_entry;
1405   }
1406 
method_entry() const1407   itableMethodEntry* method_entry() const { return _method_entry; }
1408 
doit(InstanceKlass * intf,int method_count)1409   void doit(InstanceKlass* intf, int method_count) {
1410     int offset = ((address)_method_entry) - _klass_begin;
1411     _offset_entry->initialize(intf, offset);
1412     _offset_entry++;
1413     _method_entry += method_count;
1414   }
1415 };
1416 
compute_itable_size(Array<InstanceKlass * > * transitive_interfaces)1417 int klassItable::compute_itable_size(Array<InstanceKlass*>* transitive_interfaces) {
1418   // Count no of interfaces and total number of interface methods
1419   CountInterfacesClosure cic;
1420   visit_all_interfaces(transitive_interfaces, &cic);
1421 
1422   // There's alway an extra itable entry so we can null-terminate it.
1423   int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods());
1424 
1425   // Statistics
1426   update_stats(itable_size * wordSize);
1427 
1428   return itable_size;
1429 }
1430 
1431 
1432 // Fill out offset table and interface klasses into the itable space
setup_itable_offset_table(InstanceKlass * klass)1433 void klassItable::setup_itable_offset_table(InstanceKlass* klass) {
1434   if (klass->itable_length() == 0) return;
1435   assert(!klass->is_interface(), "Should have zero length itable");
1436 
1437   // Count no of interfaces and total number of interface methods
1438   CountInterfacesClosure cic;
1439   visit_all_interfaces(klass->transitive_interfaces(), &cic);
1440   int nof_methods    = cic.nof_methods();
1441   int nof_interfaces = cic.nof_interfaces();
1442 
1443   // Add one extra entry so we can null-terminate the table
1444   nof_interfaces++;
1445 
1446   assert(compute_itable_size(klass->transitive_interfaces()) ==
1447          calc_itable_size(nof_interfaces, nof_methods),
1448          "mismatch calculation of itable size");
1449 
1450   // Fill-out offset table
1451   itableOffsetEntry* ioe = (itableOffsetEntry*)klass->start_of_itable();
1452   itableMethodEntry* ime = (itableMethodEntry*)(ioe + nof_interfaces);
1453   intptr_t* end               = klass->end_of_itable();
1454   assert((oop*)(ime + nof_methods) <= (oop*)klass->start_of_nonstatic_oop_maps(), "wrong offset calculation (1)");
1455   assert((oop*)(end) == (oop*)(ime + nof_methods),                      "wrong offset calculation (2)");
1456 
1457   // Visit all interfaces and initialize itable offset table
1458   SetupItableClosure sic((address)klass, ioe, ime);
1459   visit_all_interfaces(klass->transitive_interfaces(), &sic);
1460 
1461 #ifdef ASSERT
1462   ime  = sic.method_entry();
1463   oop* v = (oop*) klass->end_of_itable();
1464   assert( (oop*)(ime) == v, "wrong offset calculation (2)");
1465 #endif
1466 }
1467 
verify(outputStream * st,bool forced)1468 void klassVtable::verify(outputStream* st, bool forced) {
1469   // make sure table is initialized
1470   if (!Universe::is_fully_initialized()) return;
1471 #ifndef PRODUCT
1472   // avoid redundant verifies
1473   if (!forced && _verify_count == Universe::verify_count()) return;
1474   _verify_count = Universe::verify_count();
1475 #endif
1476   oop* end_of_obj = (oop*)_klass + _klass->size();
1477   oop* end_of_vtable = (oop *)&table()[_length];
1478   if (end_of_vtable > end_of_obj) {
1479     ResourceMark rm;
1480     fatal("klass %s: klass object too short (vtable extends beyond end)",
1481           _klass->internal_name());
1482   }
1483 
1484   for (int i = 0; i < _length; i++) table()[i].verify(this, st);
1485   // verify consistency with superKlass vtable
1486   Klass* super = _klass->super();
1487   if (super != NULL) {
1488     InstanceKlass* sk = InstanceKlass::cast(super);
1489     klassVtable vt = sk->vtable();
1490     for (int i = 0; i < vt.length(); i++) {
1491       verify_against(st, &vt, i);
1492     }
1493   }
1494 }
1495 
verify_against(outputStream * st,klassVtable * vt,int index)1496 void klassVtable::verify_against(outputStream* st, klassVtable* vt, int index) {
1497   vtableEntry* vte = &vt->table()[index];
1498   if (vte->method()->name()      != table()[index].method()->name() ||
1499       vte->method()->signature() != table()[index].method()->signature()) {
1500     fatal("mismatched name/signature of vtable entries");
1501   }
1502 }
1503 
1504 #ifndef PRODUCT
print()1505 void klassVtable::print() {
1506   ResourceMark rm;
1507   tty->print("klassVtable for klass %s (length %d):\n", _klass->internal_name(), length());
1508   for (int i = 0; i < length(); i++) {
1509     table()[i].print();
1510     tty->cr();
1511   }
1512 }
1513 #endif
1514 
verify(klassVtable * vt,outputStream * st)1515 void vtableEntry::verify(klassVtable* vt, outputStream* st) {
1516   Klass* vtklass = vt->klass();
1517   if (vtklass->is_instance_klass() &&
1518      (InstanceKlass::cast(vtklass)->major_version() >= klassVtable::VTABLE_TRANSITIVE_OVERRIDE_VERSION)) {
1519     assert(method() != NULL, "must have set method");
1520   }
1521   if (method() != NULL) {
1522     method()->verify();
1523     // we sub_type, because it could be a miranda method
1524     if (!vtklass->is_subtype_of(method()->method_holder())) {
1525 #ifndef PRODUCT
1526       print();
1527 #endif
1528       fatal("vtableEntry " PTR_FORMAT ": method is from subclass", p2i(this));
1529     }
1530  }
1531 }
1532 
1533 #ifndef PRODUCT
1534 
print()1535 void vtableEntry::print() {
1536   ResourceMark rm;
1537   tty->print("vtableEntry %s: ", method()->name()->as_C_string());
1538   if (Verbose) {
1539     tty->print("m " PTR_FORMAT " ", p2i(method()));
1540   }
1541 }
1542 
1543 class VtableStats : AllStatic {
1544  public:
1545   static int no_klasses;                // # classes with vtables
1546   static int no_array_klasses;          // # array classes
1547   static int no_instance_klasses;       // # instanceKlasses
1548   static int sum_of_vtable_len;         // total # of vtable entries
1549   static int sum_of_array_vtable_len;   // total # of vtable entries in array klasses only
1550   static int fixed;                     // total fixed overhead in bytes
1551   static int filler;                    // overhead caused by filler bytes
1552   static int entries;                   // total bytes consumed by vtable entries
1553   static int array_entries;             // total bytes consumed by array vtable entries
1554 
do_class(Klass * k)1555   static void do_class(Klass* k) {
1556     Klass* kl = k;
1557     klassVtable vt = kl->vtable();
1558     no_klasses++;
1559     if (kl->is_instance_klass()) {
1560       no_instance_klasses++;
1561       kl->array_klasses_do(do_class);
1562     }
1563     if (kl->is_array_klass()) {
1564       no_array_klasses++;
1565       sum_of_array_vtable_len += vt.length();
1566     }
1567     sum_of_vtable_len += vt.length();
1568   }
1569 
compute()1570   static void compute() {
1571     LockedClassesDo locked_do_class(&do_class);
1572     ClassLoaderDataGraph::classes_do(&locked_do_class);
1573     fixed  = no_klasses * oopSize;      // vtable length
1574     // filler size is a conservative approximation
1575     filler = oopSize * (no_klasses - no_instance_klasses) * (sizeof(InstanceKlass) - sizeof(ArrayKlass) - 1);
1576     entries = sizeof(vtableEntry) * sum_of_vtable_len;
1577     array_entries = sizeof(vtableEntry) * sum_of_array_vtable_len;
1578   }
1579 };
1580 
1581 int VtableStats::no_klasses = 0;
1582 int VtableStats::no_array_klasses = 0;
1583 int VtableStats::no_instance_klasses = 0;
1584 int VtableStats::sum_of_vtable_len = 0;
1585 int VtableStats::sum_of_array_vtable_len = 0;
1586 int VtableStats::fixed = 0;
1587 int VtableStats::filler = 0;
1588 int VtableStats::entries = 0;
1589 int VtableStats::array_entries = 0;
1590 
print_statistics()1591 void klassVtable::print_statistics() {
1592   ResourceMark rm;
1593   HandleMark hm;
1594   VtableStats::compute();
1595   tty->print_cr("vtable statistics:");
1596   tty->print_cr("%6d classes (%d instance, %d array)", VtableStats::no_klasses, VtableStats::no_instance_klasses, VtableStats::no_array_klasses);
1597   int total = VtableStats::fixed + VtableStats::filler + VtableStats::entries;
1598   tty->print_cr("%6d bytes fixed overhead (refs + vtable object header)", VtableStats::fixed);
1599   tty->print_cr("%6d bytes filler overhead", VtableStats::filler);
1600   tty->print_cr("%6d bytes for vtable entries (%d for arrays)", VtableStats::entries, VtableStats::array_entries);
1601   tty->print_cr("%6d bytes total", total);
1602 }
1603 
1604 int  klassItable::_total_classes;   // Total no. of classes with itables
1605 long klassItable::_total_size;      // Total no. of bytes used for itables
1606 
print_statistics()1607 void klassItable::print_statistics() {
1608  tty->print_cr("itable statistics:");
1609  tty->print_cr("%6d classes with itables", _total_classes);
1610  tty->print_cr("%6lu K uses for itables (average by class: %ld bytes)", _total_size / K, _total_size / _total_classes);
1611 }
1612 
1613 #endif // PRODUCT
1614