klassVtable.cpp revision 1472:c18cbe5936b8
1/*
2 * Copyright (c) 1997, 2009, 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 "incls/_precompiled.incl"
26#include "incls/_klassVtable.cpp.incl"
27
28inline instanceKlass* klassVtable::ik() const {
29  Klass* k = _klass()->klass_part();
30  assert(k->oop_is_instance(), "not an instanceKlass");
31  return (instanceKlass*)k;
32}
33
34
35// this function computes the vtable size (including the size needed for miranda
36// methods) and the number of miranda methods in this class
37// Note on Miranda methods: Let's say there is a class C that implements
38// interface I.  Let's say there is a method m in I that neither C nor any
39// of its super classes implement (i.e there is no method of any access, with
40// the same name and signature as m), then m is a Miranda method which is
41// entered as a public abstract method in C's vtable.  From then on it should
42// treated as any other public method in C for method over-ride purposes.
43void klassVtable::compute_vtable_size_and_num_mirandas(int &vtable_length,
44                                                       int &num_miranda_methods,
45                                                       klassOop super,
46                                                       objArrayOop methods,
47                                                       AccessFlags class_flags,
48                                                       Handle classloader,
49                                                       symbolHandle classname,
50                                                       objArrayOop local_interfaces,
51                                                       TRAPS
52                                                       ) {
53
54  No_Safepoint_Verifier nsv;
55
56  // set up default result values
57  vtable_length = 0;
58  num_miranda_methods = 0;
59
60  // start off with super's vtable length
61  instanceKlass* sk = (instanceKlass*)super->klass_part();
62  vtable_length = super == NULL ? 0 : sk->vtable_length();
63
64  // go thru each method in the methods table to see if it needs a new entry
65  int len = methods->length();
66  for (int i = 0; i < len; i++) {
67    assert(methods->obj_at(i)->is_method(), "must be a methodOop");
68    methodHandle mh(THREAD, methodOop(methods->obj_at(i)));
69
70    if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, THREAD)) {
71      vtable_length += vtableEntry::size(); // we need a new entry
72    }
73  }
74
75  // compute the number of mirandas methods that must be added to the end
76  num_miranda_methods = get_num_mirandas(super, methods, local_interfaces);
77  vtable_length += (num_miranda_methods * vtableEntry::size());
78
79  if (Universe::is_bootstrapping() && vtable_length == 0) {
80    // array classes don't have their superclass set correctly during
81    // bootstrapping
82    vtable_length = Universe::base_vtable_size();
83  }
84
85  if (super == NULL && !Universe::is_bootstrapping() &&
86      vtable_length != Universe::base_vtable_size()) {
87    // Someone is attempting to redefine java.lang.Object incorrectly.  The
88    // only way this should happen is from
89    // SystemDictionary::resolve_from_stream(), which will detect this later
90    // and throw a security exception.  So don't assert here to let
91    // the exception occur.
92    vtable_length = Universe::base_vtable_size();
93  }
94  assert(super != NULL || vtable_length == Universe::base_vtable_size(),
95         "bad vtable size for class Object");
96  assert(vtable_length % vtableEntry::size() == 0, "bad vtable length");
97  assert(vtable_length >= Universe::base_vtable_size(), "vtable too small");
98}
99
100int klassVtable::index_of(methodOop m, int len) const {
101  assert(m->vtable_index() >= 0, "do not ask this of non-vtable methods");
102  return m->vtable_index();
103}
104
105int klassVtable::initialize_from_super(KlassHandle super) {
106  if (super.is_null()) {
107    return 0;
108  } else {
109    // copy methods from superKlass
110    // can't inherit from array class, so must be instanceKlass
111    assert(super->oop_is_instance(), "must be instance klass");
112    instanceKlass* sk = (instanceKlass*)super()->klass_part();
113    klassVtable* superVtable = sk->vtable();
114    assert(superVtable->length() <= _length, "vtable too short");
115#ifdef ASSERT
116    superVtable->verify(tty, true);
117#endif
118    superVtable->copy_vtable_to(table());
119#ifndef PRODUCT
120    if (PrintVtables && Verbose) {
121      ResourceMark rm;
122      tty->print_cr("copy vtable from %s to %s size %d", sk->internal_name(), klass()->internal_name(), _length);
123    }
124#endif
125    return superVtable->length();
126  }
127}
128
129// Revised lookup semantics   introduced 1.3 (Kestral beta)
130void klassVtable::initialize_vtable(bool checkconstraints, TRAPS) {
131
132  // Note:  Arrays can have intermediate array supers.  Use java_super to skip them.
133  KlassHandle super (THREAD, klass()->java_super());
134  int nofNewEntries = 0;
135
136
137  if (PrintVtables && !klass()->oop_is_array()) {
138    ResourceMark rm(THREAD);
139    tty->print_cr("Initializing: %s", _klass->name()->as_C_string());
140  }
141
142#ifdef ASSERT
143  oop* end_of_obj = (oop*)_klass() + _klass()->size();
144  oop* end_of_vtable = (oop*)&table()[_length];
145  assert(end_of_vtable <= end_of_obj, "vtable extends beyond end");
146#endif
147
148  if (Universe::is_bootstrapping()) {
149    // just clear everything
150    for (int i = 0; i < _length; i++) table()[i].clear();
151    return;
152  }
153
154  int super_vtable_len = initialize_from_super(super);
155  if (klass()->oop_is_array()) {
156    assert(super_vtable_len == _length, "arrays shouldn't introduce new methods");
157  } else {
158    assert(_klass->oop_is_instance(), "must be instanceKlass");
159
160    objArrayHandle methods(THREAD, ik()->methods());
161    int len = methods()->length();
162    int initialized = super_vtable_len;
163
164    // update_inherited_vtable can stop for gc - ensure using handles
165    for (int i = 0; i < len; i++) {
166      HandleMark hm(THREAD);
167      assert(methods()->obj_at(i)->is_method(), "must be a methodOop");
168      methodHandle mh(THREAD, (methodOop)methods()->obj_at(i));
169
170      bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, checkconstraints, CHECK);
171
172      if (needs_new_entry) {
173        put_method_at(mh(), initialized);
174        mh()->set_vtable_index(initialized); // set primary vtable index
175        initialized++;
176      }
177    }
178
179    // add miranda methods; it will also update the value of initialized
180    fill_in_mirandas(initialized);
181
182    // In class hierarchies where the accessibility is not increasing (i.e., going from private ->
183    // package_private -> publicprotected), the vtable might actually be smaller than our initial
184    // calculation.
185    assert(initialized <= _length, "vtable initialization failed");
186    for(;initialized < _length; initialized++) {
187      put_method_at(NULL, initialized);
188    }
189    NOT_PRODUCT(verify(tty, true));
190  }
191}
192
193// Called for cases where a method does not override its superclass' vtable entry
194// For bytecodes not produced by javac together it is possible that a method does not override
195// the superclass's method, but might indirectly override a super-super class's vtable entry
196// If none found, return a null superk, else return the superk of the method this does override
197instanceKlass* klassVtable::find_transitive_override(instanceKlass* initialsuper, methodHandle target_method,
198                            int vtable_index, Handle target_loader, symbolHandle target_classname, Thread * THREAD) {
199  instanceKlass* superk = initialsuper;
200  while (superk != NULL && superk->super() != NULL) {
201    instanceKlass* supersuperklass = instanceKlass::cast(superk->super());
202    klassVtable* ssVtable = supersuperklass->vtable();
203    if (vtable_index < ssVtable->length()) {
204      methodOop super_method = ssVtable->method_at(vtable_index);
205#ifndef PRODUCT
206      symbolHandle name(THREAD,target_method()->name());
207      symbolHandle signature(THREAD,target_method()->signature());
208      assert(super_method->name() == name() && super_method->signature() == signature(), "vtable entry name/sig mismatch");
209#endif
210      if (supersuperklass->is_override(super_method, target_loader, target_classname, THREAD)) {
211#ifndef PRODUCT
212        if (PrintVtables && Verbose) {
213          ResourceMark rm(THREAD);
214          tty->print("transitive overriding superclass %s with %s::%s index %d, original flags: ",
215           supersuperklass->internal_name(),
216           _klass->internal_name(), (target_method() != NULL) ?
217           target_method()->name()->as_C_string() : "<NULL>", vtable_index);
218           super_method->access_flags().print_on(tty);
219           tty->print("overriders flags: ");
220           target_method->access_flags().print_on(tty);
221           tty->cr();
222        }
223#endif /*PRODUCT*/
224        break; // return found superk
225      }
226    } else  {
227      // super class has no vtable entry here, stop transitive search
228      superk = (instanceKlass*)NULL;
229      break;
230    }
231    // if no override found yet, continue to search up
232    superk = instanceKlass::cast(superk->super());
233  }
234
235  return superk;
236}
237
238
239// Update child's copy of super vtable for overrides
240// OR return true if a new vtable entry is required
241// Only called for instanceKlass's, i.e. not for arrays
242// If that changed, could not use _klass as handle for klass
243bool klassVtable::update_inherited_vtable(instanceKlass* klass, methodHandle target_method, int super_vtable_len,
244                  bool checkconstraints, TRAPS) {
245  ResourceMark rm;
246  bool allocate_new = true;
247  assert(klass->oop_is_instance(), "must be instanceKlass");
248
249  // Initialize the method's vtable index to "nonvirtual".
250  // If we allocate a vtable entry, we will update it to a non-negative number.
251  target_method()->set_vtable_index(methodOopDesc::nonvirtual_vtable_index);
252
253  // Static and <init> methods are never in
254  if (target_method()->is_static() || target_method()->name() ==  vmSymbols::object_initializer_name()) {
255    return false;
256  }
257
258  if (klass->is_final() || target_method()->is_final()) {
259    // a final method never needs a new entry; final methods can be statically
260    // resolved and they have to be present in the vtable only if they override
261    // a super's method, in which case they re-use its entry
262    allocate_new = false;
263  }
264
265  // we need a new entry if there is no superclass
266  if (klass->super() == NULL) {
267    return allocate_new;
268  }
269
270  // private methods always have a new entry in the vtable
271  // specification interpretation since classic has
272  // private methods not overriding
273  if (target_method()->is_private()) {
274    return allocate_new;
275  }
276
277  // search through the vtable and update overridden entries
278  // Since check_signature_loaders acquires SystemDictionary_lock
279  // which can block for gc, once we are in this loop, use handles
280  // For classfiles built with >= jdk7, we now look for transitive overrides
281
282  symbolHandle name(THREAD,target_method()->name());
283  symbolHandle signature(THREAD,target_method()->signature());
284  Handle target_loader(THREAD, _klass->class_loader());
285  symbolHandle target_classname(THREAD, _klass->name());
286  for(int i = 0; i < super_vtable_len; i++) {
287    methodOop super_method = method_at(i);
288    // Check if method name matches
289    if (super_method->name() == name() && super_method->signature() == signature()) {
290
291      // get super_klass for method_holder for the found method
292      instanceKlass* super_klass =  instanceKlass::cast(super_method->method_holder());
293
294      if ((super_klass->is_override(super_method, target_loader, target_classname, THREAD)) ||
295      ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION)
296        && ((super_klass = find_transitive_override(super_klass, target_method, i, target_loader,
297             target_classname, THREAD)) != (instanceKlass*)NULL))) {
298        // overriding, so no new entry
299        allocate_new = false;
300
301        if (checkconstraints) {
302        // Override vtable entry if passes loader constraint check
303        // if loader constraint checking requested
304        // No need to visit his super, since he and his super
305        // have already made any needed loader constraints.
306        // Since loader constraints are transitive, it is enough
307        // to link to the first super, and we get all the others.
308          Handle super_loader(THREAD, super_klass->class_loader());
309
310          if (target_loader() != super_loader()) {
311            ResourceMark rm(THREAD);
312            char* failed_type_name =
313              SystemDictionary::check_signature_loaders(signature, target_loader,
314                                                        super_loader, true,
315                                                        CHECK_(false));
316            if (failed_type_name != NULL) {
317              const char* msg = "loader constraint violation: when resolving "
318                "overridden method \"%s\" the class loader (instance"
319                " of %s) of the current class, %s, and its superclass loader "
320                "(instance of %s), have different Class objects for the type "
321                "%s used in the signature";
322              char* sig = target_method()->name_and_sig_as_C_string();
323              const char* loader1 = SystemDictionary::loader_name(target_loader());
324              char* current = _klass->name()->as_C_string();
325              const char* loader2 = SystemDictionary::loader_name(super_loader());
326              size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
327                strlen(current) + strlen(loader2) + strlen(failed_type_name);
328              char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
329              jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
330                           failed_type_name);
331              THROW_MSG_(vmSymbols::java_lang_LinkageError(), buf, false);
332            }
333          }
334       }
335
336        put_method_at(target_method(), i);
337        target_method()->set_vtable_index(i);
338#ifndef PRODUCT
339        if (PrintVtables && Verbose) {
340          tty->print("overriding with %s::%s index %d, original flags: ",
341           _klass->internal_name(), (target_method() != NULL) ?
342           target_method()->name()->as_C_string() : "<NULL>", i);
343           super_method->access_flags().print_on(tty);
344           tty->print("overriders flags: ");
345           target_method->access_flags().print_on(tty);
346           tty->cr();
347        }
348#endif /*PRODUCT*/
349      } else {
350        // allocate_new = true; default. We might override one entry,
351        // but not override another. Once we override one, not need new
352#ifndef PRODUCT
353        if (PrintVtables && Verbose) {
354          tty->print("NOT overriding with %s::%s index %d, original flags: ",
355           _klass->internal_name(), (target_method() != NULL) ?
356           target_method()->name()->as_C_string() : "<NULL>", i);
357           super_method->access_flags().print_on(tty);
358           tty->print("overriders flags: ");
359           target_method->access_flags().print_on(tty);
360           tty->cr();
361        }
362#endif /*PRODUCT*/
363      }
364    }
365  }
366  return allocate_new;
367}
368
369void klassVtable::put_method_at(methodOop m, int index) {
370  assert(m->is_oop_or_null(), "Not an oop or null");
371#ifndef PRODUCT
372  if (PrintVtables && Verbose) {
373    ResourceMark rm;
374    tty->print_cr("adding %s::%s at index %d", _klass->internal_name(),
375      (m != NULL) ? m->name()->as_C_string() : "<NULL>", index);
376  }
377  assert(unchecked_method_at(index)->is_oop_or_null(), "Not an oop or null");
378#endif
379  table()[index].set(m);
380}
381
382// Find out if a method "m" with superclass "super", loader "classloader" and
383// name "classname" needs a new vtable entry.  Let P be a class package defined
384// by "classloader" and "classname".
385// NOTE: The logic used here is very similar to the one used for computing
386// the vtables indices for a method. We cannot directly use that function because,
387// we allocate the instanceKlass at load time, and that requires that the
388// superclass has been loaded.
389// However, the vtable entries are filled in at link time, and therefore
390// the superclass' vtable may not yet have been filled in.
391bool klassVtable::needs_new_vtable_entry(methodHandle target_method,
392                                         klassOop super,
393                                         Handle classloader,
394                                         symbolHandle classname,
395                                         AccessFlags class_flags,
396                                         TRAPS) {
397  if ((class_flags.is_final() || target_method()->is_final()) ||
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      (target_method()->is_static()) ||
402      // static methods don't need to be in vtable
403      (target_method()->name() ==  vmSymbols::object_initializer_name())
404      // <init> is never called dynamically-bound
405      ) {
406    return false;
407  }
408
409  // we need a new entry if there is no superclass
410  if (super == NULL) {
411    return true;
412  }
413
414  // private methods always have a new entry in the vtable
415  // specification interpretation since classic has
416  // private methods not overriding
417  if (target_method()->is_private()) {
418    return true;
419  }
420
421  // search through the super class hierarchy to see if we need
422  // a new entry
423  ResourceMark rm;
424  symbolOop name = target_method()->name();
425  symbolOop signature = target_method()->signature();
426  klassOop k = super;
427  methodOop super_method = NULL;
428  instanceKlass *holder = NULL;
429  methodOop recheck_method =  NULL;
430  while (k != NULL) {
431    // lookup through the hierarchy for a method with matching name and sign.
432    super_method = instanceKlass::cast(k)->lookup_method(name, signature);
433    if (super_method == NULL) {
434      break; // we still have to search for a matching miranda method
435    }
436    // get the class holding the matching method
437    // make sure you use that class for is_override
438    instanceKlass* superk = instanceKlass::cast(super_method->method_holder());
439    // we want only instance method matches
440    // pretend private methods are not in the super vtable
441    // since we do override around them: e.g. a.m pub/b.m private/c.m pub,
442    // ignore private, c.m pub does override a.m pub
443    // For classes that were not javac'd together, we also do transitive overriding around
444    // methods that have less accessibility
445    if ((!super_method->is_static()) &&
446       (!super_method->is_private())) {
447      if (superk->is_override(super_method, classloader, classname, THREAD)) {
448        return false;
449      // else keep looking for transitive overrides
450      }
451    }
452
453    // Start with lookup result and continue to search up
454    k = superk->super(); // haven't found an override match yet; continue to look
455  }
456
457  // if the target method is public or protected it may have a matching
458  // miranda method in the super, whose entry it should re-use.
459  // Actually, to handle cases that javac would not generate, we need
460  // this check for all access permissions.
461  instanceKlass *sk = instanceKlass::cast(super);
462  if (sk->has_miranda_methods()) {
463    if (sk->lookup_method_in_all_interfaces(name, signature) != NULL) {
464      return false;  // found a matching miranda; we do not need a new entry
465    }
466  }
467  return true; // found no match; we need a new entry
468}
469
470// Support for miranda methods
471
472// get the vtable index of a miranda method with matching "name" and "signature"
473int klassVtable::index_of_miranda(symbolOop name, symbolOop signature) {
474  // search from the bottom, might be faster
475  for (int i = (length() - 1); i >= 0; i--) {
476    methodOop m = table()[i].method();
477    if (is_miranda_entry_at(i) &&
478        m->name() == name && m->signature() == signature) {
479      return i;
480    }
481  }
482  return methodOopDesc::invalid_vtable_index;
483}
484
485// check if an entry is miranda
486bool klassVtable::is_miranda_entry_at(int i) {
487  methodOop m = method_at(i);
488  klassOop method_holder = m->method_holder();
489  instanceKlass *mhk = instanceKlass::cast(method_holder);
490
491  // miranda methods are interface methods in a class's vtable
492  if (mhk->is_interface()) {
493    assert(m->is_public() && m->is_abstract(), "should be public and abstract");
494    assert(ik()->implements_interface(method_holder) , "this class should implement the interface");
495    assert(is_miranda(m, ik()->methods(), ik()->super()), "should be a miranda_method");
496    return true;
497  }
498  return false;
499}
500
501// check if a method is a miranda method, given a class's methods table and it's super
502// the caller must make sure that the method belongs to an interface implemented by the class
503bool klassVtable::is_miranda(methodOop m, objArrayOop class_methods, klassOop super) {
504  symbolOop name = m->name();
505  symbolOop signature = m->signature();
506  if (instanceKlass::find_method(class_methods, name, signature) == NULL) {
507     // did not find it in the method table of the current class
508    if (super == NULL) {
509      // super doesn't exist
510      return true;
511    } else {
512      if (instanceKlass::cast(super)->lookup_method(name, signature) == NULL) {
513        // super class hierarchy does not implement it
514        return true;
515      }
516    }
517  }
518  return false;
519}
520
521void klassVtable::add_new_mirandas_to_list(GrowableArray<methodOop>* list_of_current_mirandas,
522                                           objArrayOop current_interface_methods,
523                                           objArrayOop class_methods,
524                                           klassOop super) {
525  // iterate thru the current interface's method to see if it a miranda
526  int num_methods = current_interface_methods->length();
527  for (int i = 0; i < num_methods; i++) {
528    methodOop im = methodOop(current_interface_methods->obj_at(i));
529    bool is_duplicate = false;
530    int num_of_current_mirandas = list_of_current_mirandas->length();
531    // check for duplicate mirandas in different interfaces we implement
532    for (int j = 0; j < num_of_current_mirandas; j++) {
533      methodOop miranda = list_of_current_mirandas->at(j);
534      if ((im->name() == miranda->name()) &&
535          (im->signature() == miranda->signature())) {
536        is_duplicate = true;
537        break;
538      }
539    }
540
541    if (!is_duplicate) { // we don't want duplicate miranda entries in the vtable
542      if (is_miranda(im, class_methods, super)) { // is it a miranda at all?
543        instanceKlass *sk = instanceKlass::cast(super);
544        // check if it is a duplicate of a super's miranda
545        if (sk->lookup_method_in_all_interfaces(im->name(), im->signature()) == NULL) {
546          list_of_current_mirandas->append(im);
547        }
548      }
549    }
550  }
551}
552
553void klassVtable::get_mirandas(GrowableArray<methodOop>* mirandas,
554                               klassOop super, objArrayOop class_methods,
555                               objArrayOop local_interfaces) {
556  assert((mirandas->length() == 0) , "current mirandas must be 0");
557
558  // iterate thru the local interfaces looking for a miranda
559  int num_local_ifs = local_interfaces->length();
560  for (int i = 0; i < num_local_ifs; i++) {
561    instanceKlass *ik = instanceKlass::cast(klassOop(local_interfaces->obj_at(i)));
562    add_new_mirandas_to_list(mirandas, ik->methods(), class_methods, super);
563    // iterate thru each local's super interfaces
564    objArrayOop super_ifs = ik->transitive_interfaces();
565    int num_super_ifs = super_ifs->length();
566    for (int j = 0; j < num_super_ifs; j++) {
567      instanceKlass *sik = instanceKlass::cast(klassOop(super_ifs->obj_at(j)));
568      add_new_mirandas_to_list(mirandas, sik->methods(), class_methods, super);
569    }
570  }
571}
572
573// get number of mirandas
574int klassVtable::get_num_mirandas(klassOop super, objArrayOop class_methods, objArrayOop local_interfaces) {
575  ResourceMark rm;
576  GrowableArray<methodOop>* mirandas = new GrowableArray<methodOop>(20);
577  get_mirandas(mirandas, super, class_methods, local_interfaces);
578  return mirandas->length();
579}
580
581// fill in mirandas
582void klassVtable::fill_in_mirandas(int& initialized) {
583  ResourceMark rm;
584  GrowableArray<methodOop>* mirandas = new GrowableArray<methodOop>(20);
585  instanceKlass *this_ik = ik();
586  get_mirandas(mirandas, this_ik->super(), this_ik->methods(), this_ik->local_interfaces());
587  int num_mirandas = mirandas->length();
588  for (int i = 0; i < num_mirandas; i++) {
589    put_method_at(mirandas->at(i), initialized);
590    initialized++;
591  }
592}
593
594void klassVtable::copy_vtable_to(vtableEntry* start) {
595  Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size());
596}
597
598void klassVtable::adjust_method_entries(methodOop* old_methods, methodOop* new_methods,
599                                        int methods_length, bool * trace_name_printed) {
600  // search the vtable for uses of either obsolete or EMCP methods
601  for (int j = 0; j < methods_length; j++) {
602    methodOop old_method = old_methods[j];
603    methodOop new_method = new_methods[j];
604
605    // In the vast majority of cases we could get the vtable index
606    // by using:  old_method->vtable_index()
607    // However, there are rare cases, eg. sun.awt.X11.XDecoratedPeer.getX()
608    // in sun.awt.X11.XFramePeer where methods occur more than once in the
609    // vtable, so, alas, we must do an exhaustive search.
610    for (int index = 0; index < length(); index++) {
611      if (unchecked_method_at(index) == old_method) {
612        put_method_at(new_method, index);
613
614        if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
615          if (!(*trace_name_printed)) {
616            // RC_TRACE_MESG macro has an embedded ResourceMark
617            RC_TRACE_MESG(("adjust: name=%s",
618                           Klass::cast(old_method->method_holder())->external_name()));
619            *trace_name_printed = true;
620          }
621          // RC_TRACE macro has an embedded ResourceMark
622          RC_TRACE(0x00100000, ("vtable method update: %s(%s)",
623                                new_method->name()->as_C_string(),
624                                new_method->signature()->as_C_string()));
625        }
626      }
627    }
628  }
629}
630
631
632// Garbage collection
633void klassVtable::oop_follow_contents() {
634  int len = length();
635  for (int i = 0; i < len; i++) {
636    MarkSweep::mark_and_push(adr_method_at(i));
637  }
638}
639
640#ifndef SERIALGC
641void klassVtable::oop_follow_contents(ParCompactionManager* cm) {
642  int len = length();
643  for (int i = 0; i < len; i++) {
644    PSParallelCompact::mark_and_push(cm, adr_method_at(i));
645  }
646}
647#endif // SERIALGC
648
649void klassVtable::oop_adjust_pointers() {
650  int len = length();
651  for (int i = 0; i < len; i++) {
652    MarkSweep::adjust_pointer(adr_method_at(i));
653  }
654}
655
656#ifndef SERIALGC
657void klassVtable::oop_update_pointers(ParCompactionManager* cm) {
658  const int n = length();
659  for (int i = 0; i < n; i++) {
660    PSParallelCompact::adjust_pointer(adr_method_at(i));
661  }
662}
663
664void klassVtable::oop_update_pointers(ParCompactionManager* cm,
665                                      HeapWord* beg_addr, HeapWord* end_addr) {
666  const int n = length();
667  const int entry_size = vtableEntry::size();
668
669  int beg_idx = 0;
670  HeapWord* const method_0 = (HeapWord*)adr_method_at(0);
671  if (beg_addr > method_0) {
672    // it's safe to use cast, as we have guarantees on vtable size to be sane
673    beg_idx = int((pointer_delta(beg_addr, method_0) + entry_size - 1) / entry_size);
674  }
675
676  oop* const beg_oop = adr_method_at(beg_idx);
677  oop* const end_oop = MIN2((oop*)end_addr, adr_method_at(n));
678  for (oop* cur_oop = beg_oop; cur_oop < end_oop; cur_oop += entry_size) {
679    PSParallelCompact::adjust_pointer(cur_oop);
680  }
681}
682#endif // SERIALGC
683
684// Iterators
685void klassVtable::oop_oop_iterate(OopClosure* blk) {
686  int len = length();
687  for (int i = 0; i < len; i++) {
688    blk->do_oop(adr_method_at(i));
689  }
690}
691
692void klassVtable::oop_oop_iterate_m(OopClosure* blk, MemRegion mr) {
693  int len = length();
694  int i;
695  for (i = 0; i < len; i++) {
696    if ((HeapWord*)adr_method_at(i) >= mr.start()) break;
697  }
698  for (; i < len; i++) {
699    oop* adr = adr_method_at(i);
700    if ((HeapWord*)adr < mr.end()) blk->do_oop(adr);
701  }
702}
703
704//-----------------------------------------------------------------------------------------
705// Itable code
706
707// Initialize a itableMethodEntry
708void itableMethodEntry::initialize(methodOop m) {
709  if (m == NULL) return;
710
711  _method = m;
712}
713
714klassItable::klassItable(instanceKlassHandle klass) {
715  _klass = klass;
716
717  if (klass->itable_length() > 0) {
718    itableOffsetEntry* offset_entry = (itableOffsetEntry*)klass->start_of_itable();
719    if (offset_entry  != NULL && offset_entry->interface_klass() != NULL) { // Check that itable is initialized
720      // First offset entry points to the first method_entry
721      intptr_t* method_entry  = (intptr_t *)(((address)klass->as_klassOop()) + offset_entry->offset());
722      intptr_t* end         = klass->end_of_itable();
723
724      _table_offset      = (intptr_t*)offset_entry - (intptr_t*)klass->as_klassOop();
725      _size_offset_table = (method_entry - ((intptr_t*)offset_entry)) / itableOffsetEntry::size();
726      _size_method_table = (end - method_entry)                  / itableMethodEntry::size();
727      assert(_table_offset >= 0 && _size_offset_table >= 0 && _size_method_table >= 0, "wrong computation");
728      return;
729    }
730  }
731
732  // The length of the itable was either zero, or it has not yet been initialized.
733  _table_offset      = 0;
734  _size_offset_table = 0;
735  _size_method_table = 0;
736}
737
738// Garbage Collection
739
740void klassItable::oop_follow_contents() {
741  // offset table
742  itableOffsetEntry* ioe = offset_entry(0);
743  for(int i = 0; i < _size_offset_table; i++) {
744    MarkSweep::mark_and_push((oop*)&ioe->_interface);
745    ioe++;
746  }
747
748  // method table
749  itableMethodEntry* ime = method_entry(0);
750  for(int j = 0; j < _size_method_table; j++) {
751    MarkSweep::mark_and_push((oop*)&ime->_method);
752    ime++;
753  }
754}
755
756#ifndef SERIALGC
757void klassItable::oop_follow_contents(ParCompactionManager* cm) {
758  // offset table
759  itableOffsetEntry* ioe = offset_entry(0);
760  for(int i = 0; i < _size_offset_table; i++) {
761    PSParallelCompact::mark_and_push(cm, (oop*)&ioe->_interface);
762    ioe++;
763  }
764
765  // method table
766  itableMethodEntry* ime = method_entry(0);
767  for(int j = 0; j < _size_method_table; j++) {
768    PSParallelCompact::mark_and_push(cm, (oop*)&ime->_method);
769    ime++;
770  }
771}
772#endif // SERIALGC
773
774void klassItable::oop_adjust_pointers() {
775  // offset table
776  itableOffsetEntry* ioe = offset_entry(0);
777  for(int i = 0; i < _size_offset_table; i++) {
778    MarkSweep::adjust_pointer((oop*)&ioe->_interface);
779    ioe++;
780  }
781
782  // method table
783  itableMethodEntry* ime = method_entry(0);
784  for(int j = 0; j < _size_method_table; j++) {
785    MarkSweep::adjust_pointer((oop*)&ime->_method);
786    ime++;
787  }
788}
789
790#ifndef SERIALGC
791void klassItable::oop_update_pointers(ParCompactionManager* cm) {
792  // offset table
793  itableOffsetEntry* ioe = offset_entry(0);
794  for(int i = 0; i < _size_offset_table; i++) {
795    PSParallelCompact::adjust_pointer((oop*)&ioe->_interface);
796    ioe++;
797  }
798
799  // method table
800  itableMethodEntry* ime = method_entry(0);
801  for(int j = 0; j < _size_method_table; j++) {
802    PSParallelCompact::adjust_pointer((oop*)&ime->_method);
803    ime++;
804  }
805}
806
807void klassItable::oop_update_pointers(ParCompactionManager* cm,
808                                      HeapWord* beg_addr, HeapWord* end_addr) {
809  // offset table
810  itableOffsetEntry* ioe = offset_entry(0);
811  for(int i = 0; i < _size_offset_table; i++) {
812    oop* p = (oop*)&ioe->_interface;
813    PSParallelCompact::adjust_pointer(p, beg_addr, end_addr);
814    ioe++;
815  }
816
817  // method table
818  itableMethodEntry* ime = method_entry(0);
819  for(int j = 0; j < _size_method_table; j++) {
820    oop* p = (oop*)&ime->_method;
821    PSParallelCompact::adjust_pointer(p, beg_addr, end_addr);
822    ime++;
823  }
824}
825#endif // SERIALGC
826
827// Iterators
828void klassItable::oop_oop_iterate(OopClosure* blk) {
829  // offset table
830  itableOffsetEntry* ioe = offset_entry(0);
831  for(int i = 0; i < _size_offset_table; i++) {
832    blk->do_oop((oop*)&ioe->_interface);
833    ioe++;
834  }
835
836  // method table
837  itableMethodEntry* ime = method_entry(0);
838  for(int j = 0; j < _size_method_table; j++) {
839    blk->do_oop((oop*)&ime->_method);
840    ime++;
841  }
842}
843
844void klassItable::oop_oop_iterate_m(OopClosure* blk, MemRegion mr) {
845  // offset table
846  itableOffsetEntry* ioe = offset_entry(0);
847  for(int i = 0; i < _size_offset_table; i++) {
848    oop* adr = (oop*)&ioe->_interface;
849    if (mr.contains(adr)) blk->do_oop(adr);
850    ioe++;
851  }
852
853  // method table
854  itableMethodEntry* ime = method_entry(0);
855  for(int j = 0; j < _size_method_table; j++) {
856    oop* adr = (oop*)&ime->_method;
857    if (mr.contains(adr)) blk->do_oop(adr);
858    ime++;
859  }
860}
861
862
863static int initialize_count = 0;
864
865// Initialization
866void klassItable::initialize_itable(bool checkconstraints, TRAPS) {
867  // Cannot be setup doing bootstrapping, interfaces don't have
868  // itables, and klass with only ones entry have empty itables
869  if (Universe::is_bootstrapping() ||
870      _klass->is_interface() ||
871      _klass->itable_length() == itableOffsetEntry::size()) return;
872
873  // There's alway an extra itable entry so we can null-terminate it.
874  guarantee(size_offset_table() >= 1, "too small");
875  int num_interfaces = size_offset_table() - 1;
876  if (num_interfaces > 0) {
877    if (TraceItables) tty->print_cr("%3d: Initializing itables for %s", ++initialize_count,
878                                    _klass->name()->as_C_string());
879
880
881    // Iterate through all interfaces
882    int i;
883    for(i = 0; i < num_interfaces; i++) {
884      itableOffsetEntry* ioe = offset_entry(i);
885      KlassHandle interf_h (THREAD, ioe->interface_klass());
886      assert(interf_h() != NULL && ioe->offset() != 0, "bad offset entry in itable");
887      initialize_itable_for_interface(ioe->offset(), interf_h, checkconstraints, CHECK);
888    }
889
890  }
891  // Check that the last entry is empty
892  itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1);
893  guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing");
894}
895
896
897void klassItable::initialize_itable_for_interface(int method_table_offset, KlassHandle interf_h, bool checkconstraints, TRAPS) {
898  objArrayHandle methods(THREAD, instanceKlass::cast(interf_h())->methods());
899  int nof_methods = methods()->length();
900  HandleMark hm;
901  KlassHandle klass = _klass;
902  assert(nof_methods > 0, "at least one method must exist for interface to be in vtable");
903  Handle interface_loader (THREAD, instanceKlass::cast(interf_h())->class_loader());
904  int ime_num = 0;
905
906  // Skip first methodOop if it is a class initializer
907  int i = ((methodOop)methods()->obj_at(0))->name() != vmSymbols::class_initializer_name() ? 0 : 1;
908
909  // m, method_name, method_signature, klass reset each loop so they
910  // don't need preserving across check_signature_loaders call
911  // methods needs a handle in case of gc from check_signature_loaders
912  for(; i < nof_methods; i++) {
913    methodOop m = (methodOop)methods()->obj_at(i);
914    symbolOop method_name = m->name();
915    symbolOop method_signature = m->signature();
916
917    // This is same code as in Linkresolver::lookup_instance_method_in_klasses
918    methodOop target = klass->uncached_lookup_method(method_name, method_signature);
919    while (target != NULL && target->is_static()) {
920      // continue with recursive lookup through the superclass
921      klassOop super = Klass::cast(target->method_holder())->super();
922      target = (super == NULL) ? methodOop(NULL) : Klass::cast(super)->uncached_lookup_method(method_name, method_signature);
923    }
924    if (target == NULL || !target->is_public() || target->is_abstract()) {
925      // Entry do not resolve. Leave it empty
926    } else {
927      // Entry did resolve, check loader constraints before initializing
928      // if checkconstraints requested
929      methodHandle  target_h (THREAD, target); // preserve across gc
930      if (checkconstraints) {
931        Handle method_holder_loader (THREAD, instanceKlass::cast(target->method_holder())->class_loader());
932        if (method_holder_loader() != interface_loader()) {
933          ResourceMark rm(THREAD);
934          char* failed_type_name =
935            SystemDictionary::check_signature_loaders(method_signature,
936                                                      method_holder_loader,
937                                                      interface_loader,
938                                                      true, CHECK);
939          if (failed_type_name != NULL) {
940            const char* msg = "loader constraint violation in interface "
941              "itable initialization: when resolving method \"%s\" the class"
942              " loader (instance of %s) of the current class, %s, "
943              "and the class loader (instance of %s) for interface "
944              "%s have different Class objects for the type %s "
945              "used in the signature";
946            char* sig = target_h()->name_and_sig_as_C_string();
947            const char* loader1 = SystemDictionary::loader_name(method_holder_loader());
948            char* current = klass->name()->as_C_string();
949            const char* loader2 = SystemDictionary::loader_name(interface_loader());
950            char* iface = instanceKlass::cast(interf_h())->name()->as_C_string();
951            size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
952              strlen(current) + strlen(loader2) + strlen(iface) +
953              strlen(failed_type_name);
954            char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
955            jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
956                         iface, failed_type_name);
957            THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
958          }
959        }
960      }
961
962      // ime may have moved during GC so recalculate address
963      itableOffsetEntry::method_entry(_klass(), method_table_offset)[ime_num].initialize(target_h());
964    }
965    // Progress to next entry
966    ime_num++;
967  }
968}
969
970// Update entry for specific methodOop
971void klassItable::initialize_with_method(methodOop m) {
972  itableMethodEntry* ime = method_entry(0);
973  for(int i = 0; i < _size_method_table; i++) {
974    if (ime->method() == m) {
975      ime->initialize(m);
976    }
977    ime++;
978  }
979}
980
981void klassItable::adjust_method_entries(methodOop* old_methods, methodOop* new_methods,
982                                        int methods_length, bool * trace_name_printed) {
983  // search the itable for uses of either obsolete or EMCP methods
984  for (int j = 0; j < methods_length; j++) {
985    methodOop old_method = old_methods[j];
986    methodOop new_method = new_methods[j];
987    itableMethodEntry* ime = method_entry(0);
988
989    // The itable can describe more than one interface and the same
990    // method signature can be specified by more than one interface.
991    // This means we have to do an exhaustive search to find all the
992    // old_method references.
993    for (int i = 0; i < _size_method_table; i++) {
994      if (ime->method() == old_method) {
995        ime->initialize(new_method);
996
997        if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
998          if (!(*trace_name_printed)) {
999            // RC_TRACE_MESG macro has an embedded ResourceMark
1000            RC_TRACE_MESG(("adjust: name=%s",
1001              Klass::cast(old_method->method_holder())->external_name()));
1002            *trace_name_printed = true;
1003          }
1004          // RC_TRACE macro has an embedded ResourceMark
1005          RC_TRACE(0x00200000, ("itable method update: %s(%s)",
1006            new_method->name()->as_C_string(),
1007            new_method->signature()->as_C_string()));
1008        }
1009        break;
1010      }
1011      ime++;
1012    }
1013  }
1014}
1015
1016
1017// Setup
1018class InterfaceVisiterClosure : public StackObj {
1019 public:
1020  virtual void doit(klassOop intf, int method_count) = 0;
1021};
1022
1023// Visit all interfaces with at-least one method (excluding <clinit>)
1024void visit_all_interfaces(objArrayOop transitive_intf, InterfaceVisiterClosure *blk) {
1025  // Handle array argument
1026  for(int i = 0; i < transitive_intf->length(); i++) {
1027    klassOop intf = (klassOop)transitive_intf->obj_at(i);
1028    assert(Klass::cast(intf)->is_interface(), "sanity check");
1029
1030    // Find no. of methods excluding a <clinit>
1031    int method_count = instanceKlass::cast(intf)->methods()->length();
1032    if (method_count > 0) {
1033      methodOop m = (methodOop)instanceKlass::cast(intf)->methods()->obj_at(0);
1034      assert(m != NULL && m->is_method(), "sanity check");
1035      if (m->name() == vmSymbols::object_initializer_name()) {
1036        method_count--;
1037      }
1038    }
1039
1040    // Only count interfaces with at least one method
1041    if (method_count > 0) {
1042      blk->doit(intf, method_count);
1043    }
1044  }
1045}
1046
1047class CountInterfacesClosure : public InterfaceVisiterClosure {
1048 private:
1049  int _nof_methods;
1050  int _nof_interfaces;
1051 public:
1052   CountInterfacesClosure() { _nof_methods = 0; _nof_interfaces = 0; }
1053
1054   int nof_methods() const    { return _nof_methods; }
1055   int nof_interfaces() const { return _nof_interfaces; }
1056
1057   void doit(klassOop intf, int method_count) { _nof_methods += method_count; _nof_interfaces++; }
1058};
1059
1060class SetupItableClosure : public InterfaceVisiterClosure  {
1061 private:
1062  itableOffsetEntry* _offset_entry;
1063  itableMethodEntry* _method_entry;
1064  address            _klass_begin;
1065 public:
1066  SetupItableClosure(address klass_begin, itableOffsetEntry* offset_entry, itableMethodEntry* method_entry) {
1067    _klass_begin  = klass_begin;
1068    _offset_entry = offset_entry;
1069    _method_entry = method_entry;
1070  }
1071
1072  itableMethodEntry* method_entry() const { return _method_entry; }
1073
1074  void doit(klassOop intf, int method_count) {
1075    int offset = ((address)_method_entry) - _klass_begin;
1076    _offset_entry->initialize(intf, offset);
1077    _offset_entry++;
1078    _method_entry += method_count;
1079  }
1080};
1081
1082int klassItable::compute_itable_size(objArrayHandle transitive_interfaces) {
1083  // Count no of interfaces and total number of interface methods
1084  CountInterfacesClosure cic;
1085  visit_all_interfaces(transitive_interfaces(), &cic);
1086
1087  // There's alway an extra itable entry so we can null-terminate it.
1088  int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods());
1089
1090  // Statistics
1091  update_stats(itable_size * HeapWordSize);
1092
1093  return itable_size;
1094}
1095
1096
1097// Fill out offset table and interface klasses into the itable space
1098void klassItable::setup_itable_offset_table(instanceKlassHandle klass) {
1099  if (klass->itable_length() == 0) return;
1100  assert(!klass->is_interface(), "Should have zero length itable");
1101
1102  // Count no of interfaces and total number of interface methods
1103  CountInterfacesClosure cic;
1104  visit_all_interfaces(klass->transitive_interfaces(), &cic);
1105  int nof_methods    = cic.nof_methods();
1106  int nof_interfaces = cic.nof_interfaces();
1107
1108  // Add one extra entry so we can null-terminate the table
1109  nof_interfaces++;
1110
1111  assert(compute_itable_size(objArrayHandle(klass->transitive_interfaces())) ==
1112         calc_itable_size(nof_interfaces, nof_methods),
1113         "mismatch calculation of itable size");
1114
1115  // Fill-out offset table
1116  itableOffsetEntry* ioe = (itableOffsetEntry*)klass->start_of_itable();
1117  itableMethodEntry* ime = (itableMethodEntry*)(ioe + nof_interfaces);
1118  intptr_t* end               = klass->end_of_itable();
1119  assert((oop*)(ime + nof_methods) <= (oop*)klass->start_of_static_fields(), "wrong offset calculation (1)");
1120  assert((oop*)(end) == (oop*)(ime + nof_methods),                      "wrong offset calculation (2)");
1121
1122  // Visit all interfaces and initialize itable offset table
1123  SetupItableClosure sic((address)klass->as_klassOop(), ioe, ime);
1124  visit_all_interfaces(klass->transitive_interfaces(), &sic);
1125
1126#ifdef ASSERT
1127  ime  = sic.method_entry();
1128  oop* v = (oop*) klass->end_of_itable();
1129  assert( (oop*)(ime) == v, "wrong offset calculation (2)");
1130#endif
1131}
1132
1133
1134// m must be a method in an interface
1135int klassItable::compute_itable_index(methodOop m) {
1136  klassOop intf = m->method_holder();
1137  assert(instanceKlass::cast(intf)->is_interface(), "sanity check");
1138  objArrayOop methods = instanceKlass::cast(intf)->methods();
1139  int index = 0;
1140  while(methods->obj_at(index) != m) {
1141    index++;
1142    assert(index < methods->length(), "should find index for resolve_invoke");
1143  }
1144  // Adjust for <clinit>, which is left out of table if first method
1145  if (methods->length() > 0 && ((methodOop)methods->obj_at(0))->name() == vmSymbols::class_initializer_name()) {
1146    index--;
1147  }
1148  return index;
1149}
1150
1151
1152// inverse to compute_itable_index
1153methodOop klassItable::method_for_itable_index(klassOop intf, int itable_index) {
1154  assert(instanceKlass::cast(intf)->is_interface(), "sanity check");
1155  objArrayOop methods = instanceKlass::cast(intf)->methods();
1156
1157  int index = itable_index;
1158  // Adjust for <clinit>, which is left out of table if first method
1159  if (methods->length() > 0 && ((methodOop)methods->obj_at(0))->name() == vmSymbols::class_initializer_name()) {
1160    index++;
1161  }
1162
1163  if (itable_index < 0 || index >= methods->length())
1164    return NULL;                // help caller defend against bad indexes
1165
1166  methodOop m = (methodOop)methods->obj_at(index);
1167  assert(compute_itable_index(m) == itable_index, "correct inverse");
1168
1169  return m;
1170}
1171
1172void klassVtable::verify(outputStream* st, bool forced) {
1173  // make sure table is initialized
1174  if (!Universe::is_fully_initialized()) return;
1175#ifndef PRODUCT
1176  // avoid redundant verifies
1177  if (!forced && _verify_count == Universe::verify_count()) return;
1178  _verify_count = Universe::verify_count();
1179#endif
1180  oop* end_of_obj = (oop*)_klass() + _klass()->size();
1181  oop* end_of_vtable = (oop *)&table()[_length];
1182  if (end_of_vtable > end_of_obj) {
1183    fatal(err_msg("klass %s: klass object too short (vtable extends beyond "
1184                  "end)", _klass->internal_name()));
1185  }
1186
1187  for (int i = 0; i < _length; i++) table()[i].verify(this, st);
1188  // verify consistency with superKlass vtable
1189  klassOop super = _klass->super();
1190  if (super != NULL) {
1191    instanceKlass* sk = instanceKlass::cast(super);
1192    klassVtable* vt = sk->vtable();
1193    for (int i = 0; i < vt->length(); i++) {
1194      verify_against(st, vt, i);
1195    }
1196  }
1197}
1198
1199void klassVtable::verify_against(outputStream* st, klassVtable* vt, int index) {
1200  vtableEntry* vte = &vt->table()[index];
1201  if (vte->method()->name()      != table()[index].method()->name() ||
1202      vte->method()->signature() != table()[index].method()->signature()) {
1203    fatal("mismatched name/signature of vtable entries");
1204  }
1205}
1206
1207#ifndef PRODUCT
1208void klassVtable::print() {
1209  ResourceMark rm;
1210  tty->print("klassVtable for klass %s (length %d):\n", _klass->internal_name(), length());
1211  for (int i = 0; i < length(); i++) {
1212    table()[i].print();
1213    tty->cr();
1214  }
1215}
1216#endif
1217
1218void vtableEntry::verify(klassVtable* vt, outputStream* st) {
1219  NOT_PRODUCT(FlagSetting fs(IgnoreLockingAssertions, true));
1220  assert(method() != NULL, "must have set method");
1221  method()->verify();
1222  // we sub_type, because it could be a miranda method
1223  if (!vt->klass()->is_subtype_of(method()->method_holder())) {
1224#ifndef PRODUCT
1225    print();
1226#endif
1227    fatal(err_msg("vtableEntry " PTR_FORMAT ": method is from subclass", this));
1228  }
1229}
1230
1231#ifndef PRODUCT
1232
1233void vtableEntry::print() {
1234  ResourceMark rm;
1235  tty->print("vtableEntry %s: ", method()->name()->as_C_string());
1236  if (Verbose) {
1237    tty->print("m %#lx ", (address)method());
1238  }
1239}
1240
1241class VtableStats : AllStatic {
1242 public:
1243  static int no_klasses;                // # classes with vtables
1244  static int no_array_klasses;          // # array classes
1245  static int no_instance_klasses;       // # instanceKlasses
1246  static int sum_of_vtable_len;         // total # of vtable entries
1247  static int sum_of_array_vtable_len;   // total # of vtable entries in array klasses only
1248  static int fixed;                     // total fixed overhead in bytes
1249  static int filler;                    // overhead caused by filler bytes
1250  static int entries;                   // total bytes consumed by vtable entries
1251  static int array_entries;             // total bytes consumed by array vtable entries
1252
1253  static void do_class(klassOop k) {
1254    Klass* kl = k->klass_part();
1255    klassVtable* vt = kl->vtable();
1256    if (vt == NULL) return;
1257    no_klasses++;
1258    if (kl->oop_is_instance()) {
1259      no_instance_klasses++;
1260      kl->array_klasses_do(do_class);
1261    }
1262    if (kl->oop_is_array()) {
1263      no_array_klasses++;
1264      sum_of_array_vtable_len += vt->length();
1265    }
1266    sum_of_vtable_len += vt->length();
1267  }
1268
1269  static void compute() {
1270    SystemDictionary::classes_do(do_class);
1271    fixed  = no_klasses * oopSize;      // vtable length
1272    // filler size is a conservative approximation
1273    filler = oopSize * (no_klasses - no_instance_klasses) * (sizeof(instanceKlass) - sizeof(arrayKlass) - 1);
1274    entries = sizeof(vtableEntry) * sum_of_vtable_len;
1275    array_entries = sizeof(vtableEntry) * sum_of_array_vtable_len;
1276  }
1277};
1278
1279int VtableStats::no_klasses = 0;
1280int VtableStats::no_array_klasses = 0;
1281int VtableStats::no_instance_klasses = 0;
1282int VtableStats::sum_of_vtable_len = 0;
1283int VtableStats::sum_of_array_vtable_len = 0;
1284int VtableStats::fixed = 0;
1285int VtableStats::filler = 0;
1286int VtableStats::entries = 0;
1287int VtableStats::array_entries = 0;
1288
1289void klassVtable::print_statistics() {
1290  ResourceMark rm;
1291  HandleMark hm;
1292  VtableStats::compute();
1293  tty->print_cr("vtable statistics:");
1294  tty->print_cr("%6d classes (%d instance, %d array)", VtableStats::no_klasses, VtableStats::no_instance_klasses, VtableStats::no_array_klasses);
1295  int total = VtableStats::fixed + VtableStats::filler + VtableStats::entries;
1296  tty->print_cr("%6d bytes fixed overhead (refs + vtable object header)", VtableStats::fixed);
1297  tty->print_cr("%6d bytes filler overhead", VtableStats::filler);
1298  tty->print_cr("%6d bytes for vtable entries (%d for arrays)", VtableStats::entries, VtableStats::array_entries);
1299  tty->print_cr("%6d bytes total", total);
1300}
1301
1302bool klassVtable::check_no_old_entries() {
1303  // Check that there really is no entry
1304  for (int i = 0; i < length(); i++) {
1305    methodOop m = unchecked_method_at(i);
1306    if (m != NULL) {
1307        if (m->is_old()) {
1308            return false;
1309        }
1310    }
1311  }
1312  return true;
1313}
1314
1315void klassVtable::dump_vtable() {
1316  tty->print_cr("vtable dump --");
1317  for (int i = 0; i < length(); i++) {
1318    methodOop m = unchecked_method_at(i);
1319    if (m != NULL) {
1320      tty->print("      (%5d)  ", i);
1321      m->access_flags().print_on(tty);
1322      tty->print(" --  ");
1323      m->print_name(tty);
1324      tty->cr();
1325    }
1326  }
1327}
1328
1329int  klassItable::_total_classes;   // Total no. of classes with itables
1330long klassItable::_total_size;      // Total no. of bytes used for itables
1331
1332void klassItable::print_statistics() {
1333 tty->print_cr("itable statistics:");
1334 tty->print_cr("%6d classes with itables", _total_classes);
1335 tty->print_cr("%6d K uses for itables (average by class: %d bytes)", _total_size / K, _total_size / _total_classes);
1336}
1337
1338#endif // PRODUCT
1339