1 /*
   2  * Copyright (c) 1997, 2016, 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 "classfile/dictionary.hpp"
  27 #include "classfile/javaClasses.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "memory/heapInspection.hpp"
  32 #include "memory/metadataFactory.hpp"
  33 #include "memory/oopFactory.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "oops/instanceKlass.hpp"
  36 #include "oops/klass.inline.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "runtime/atomic.inline.hpp"
  39 #include "runtime/orderAccess.inline.hpp"
  40 #include "trace/traceMacros.hpp"
  41 #include "utilities/macros.hpp"
  42 #include "utilities/stack.inline.hpp"
  43 #include "logging/log.hpp"
  44 #if INCLUDE_ALL_GCS
  45 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  46 #endif // INCLUDE_ALL_GCS
  47 
  48 void Klass::set_name(Symbol* n) {
  49   _name = n;
  50   if (_name != NULL) _name->increment_refcount();
  51 }
  52 
  53 bool Klass::is_subclass_of(const Klass* k) const {
  54   // Run up the super chain and check
  55   if (this == k) return true;
  56 
  57   Klass* t = const_cast<Klass*>(this)->super();
  58 
  59   while (t != NULL) {
  60     if (t == k) return true;
  61     t = t->super();
  62   }
  63   return false;
  64 }
  65 
  66 bool Klass::search_secondary_supers(Klass* k) const {
  67   // Put some extra logic here out-of-line, before the search proper.
  68   // This cuts down the size of the inline method.
  69 
  70   // This is necessary, since I am never in my own secondary_super list.
  71   if (this == k)
  72     return true;
  73   // Scan the array-of-objects for a match
  74   int cnt = secondary_supers()->length();
  75   for (int i = 0; i < cnt; i++) {
  76     if (secondary_supers()->at(i) == k) {
  77       ((Klass*)this)->set_secondary_super_cache(k);
  78       return true;
  79     }
  80   }
  81   return false;
  82 }
  83 
  84 // Return self, except for abstract classes with exactly 1
  85 // implementor.  Then return the 1 concrete implementation.
  86 Klass *Klass::up_cast_abstract() {
  87   Klass *r = this;
  88   while( r->is_abstract() ) {   // Receiver is abstract?
  89     Klass *s = r->subklass();   // Check for exactly 1 subklass
  90     if( !s || s->next_sibling() ) // Oops; wrong count; give up
  91       return this;              // Return 'this' as a no-progress flag
  92     r = s;                    // Loop till find concrete class
  93   }
  94   return r;                   // Return the 1 concrete class
  95 }
  96 
  97 // Find LCA in class hierarchy
  98 Klass *Klass::LCA( Klass *k2 ) {
  99   Klass *k1 = this;
 100   while( 1 ) {
 101     if( k1->is_subtype_of(k2) ) return k2;
 102     if( k2->is_subtype_of(k1) ) return k1;
 103     k1 = k1->super();
 104     k2 = k2->super();
 105   }
 106 }
 107 
 108 
 109 void Klass::check_valid_for_instantiation(bool throwError, TRAPS) {
 110   ResourceMark rm(THREAD);
 111   THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
 112             : vmSymbols::java_lang_InstantiationException(), external_name());
 113 }
 114 
 115 
 116 void Klass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos, int length, TRAPS) {
 117   THROW(vmSymbols::java_lang_ArrayStoreException());
 118 }
 119 
 120 
 121 void Klass::initialize(TRAPS) {
 122   ShouldNotReachHere();
 123 }
 124 
 125 bool Klass::compute_is_subtype_of(Klass* k) {
 126   assert(k->is_klass(), "argument must be a class");
 127   return is_subclass_of(k);
 128 }
 129 
 130 Klass* Klass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
 131 #ifdef ASSERT
 132   tty->print_cr("Error: find_field called on a klass oop."
 133                 " Likely error: reflection method does not correctly"
 134                 " wrap return value in a mirror object.");
 135 #endif
 136   ShouldNotReachHere();
 137   return NULL;
 138 }
 139 
 140 Method* Klass::uncached_lookup_method(const Symbol* name, const Symbol* signature, OverpassLookupMode overpass_mode) const {
 141 #ifdef ASSERT
 142   tty->print_cr("Error: uncached_lookup_method called on a klass oop."
 143                 " Likely error: reflection method does not correctly"
 144                 " wrap return value in a mirror object.");
 145 #endif
 146   ShouldNotReachHere();
 147   return NULL;
 148 }
 149 
 150 void* Klass::operator new(size_t size, ClassLoaderData* loader_data, size_t word_size, TRAPS) throw() {
 151   return Metaspace::allocate(loader_data, word_size, /*read_only*/false,
 152                              MetaspaceObj::ClassType, THREAD);
 153 }
 154 
 155 // "Normal" instantiation is preceeded by a MetaspaceObj allocation
 156 // which zeros out memory - calloc equivalent.
 157 // The constructor is also used from init_self_patching_vtbl_list,
 158 // which doesn't zero out the memory before calling the constructor.
 159 // Need to set the _java_mirror field explicitly to not hit an assert that the field
 160 // should be NULL before setting it.
 161 Klass::Klass() : _prototype_header(markOopDesc::prototype()),
 162                  _shared_class_path_index(-1),
 163                  _java_mirror(NULL) {
 164 
 165   _primary_supers[0] = this;
 166   set_super_check_offset(in_bytes(primary_supers_offset()));
 167 }
 168 
 169 jint Klass::array_layout_helper(BasicType etype) {
 170   assert(etype >= T_BOOLEAN && etype <= T_OBJECT, "valid etype");
 171   // Note that T_ARRAY is not allowed here.
 172   int  hsize = arrayOopDesc::base_offset_in_bytes(etype);
 173   int  esize = type2aelembytes(etype);
 174   bool isobj = (etype == T_OBJECT);
 175   int  tag   =  isobj ? _lh_array_tag_obj_value : _lh_array_tag_type_value;
 176   int lh = array_layout_helper(tag, hsize, etype, exact_log2(esize));
 177 
 178   assert(lh < (int)_lh_neutral_value, "must look like an array layout");
 179   assert(layout_helper_is_array(lh), "correct kind");
 180   assert(layout_helper_is_objArray(lh) == isobj, "correct kind");
 181   assert(layout_helper_is_typeArray(lh) == !isobj, "correct kind");
 182   assert(layout_helper_header_size(lh) == hsize, "correct decode");
 183   assert(layout_helper_element_type(lh) == etype, "correct decode");
 184   assert(1 << layout_helper_log2_element_size(lh) == esize, "correct decode");
 185 
 186   return lh;
 187 }
 188 
 189 bool Klass::can_be_primary_super_slow() const {
 190   if (super() == NULL)
 191     return true;
 192   else if (super()->super_depth() >= primary_super_limit()-1)
 193     return false;
 194   else
 195     return true;
 196 }
 197 
 198 void Klass::initialize_supers(Klass* k, TRAPS) {
 199   if (FastSuperclassLimit == 0) {
 200     // None of the other machinery matters.
 201     set_super(k);
 202     return;
 203   }
 204   if (k == NULL) {
 205     set_super(NULL);
 206     _primary_supers[0] = this;
 207     assert(super_depth() == 0, "Object must already be initialized properly");
 208   } else if (k != super() || k == SystemDictionary::Object_klass()) {
 209     assert(super() == NULL || super() == SystemDictionary::Object_klass(),
 210            "initialize this only once to a non-trivial value");
 211     set_super(k);
 212     Klass* sup = k;
 213     int sup_depth = sup->super_depth();
 214     juint my_depth  = MIN2(sup_depth + 1, (int)primary_super_limit());
 215     if (!can_be_primary_super_slow())
 216       my_depth = primary_super_limit();
 217     for (juint i = 0; i < my_depth; i++) {
 218       _primary_supers[i] = sup->_primary_supers[i];
 219     }
 220     Klass* *super_check_cell;
 221     if (my_depth < primary_super_limit()) {
 222       _primary_supers[my_depth] = this;
 223       super_check_cell = &_primary_supers[my_depth];
 224     } else {
 225       // Overflow of the primary_supers array forces me to be secondary.
 226       super_check_cell = &_secondary_super_cache;
 227     }
 228     set_super_check_offset((address)super_check_cell - (address) this);
 229 
 230 #ifdef ASSERT
 231     {
 232       juint j = super_depth();
 233       assert(j == my_depth, "computed accessor gets right answer");
 234       Klass* t = this;
 235       while (!t->can_be_primary_super()) {
 236         t = t->super();
 237         j = t->super_depth();
 238       }
 239       for (juint j1 = j+1; j1 < primary_super_limit(); j1++) {
 240         assert(primary_super_of_depth(j1) == NULL, "super list padding");
 241       }
 242       while (t != NULL) {
 243         assert(primary_super_of_depth(j) == t, "super list initialization");
 244         t = t->super();
 245         --j;
 246       }
 247       assert(j == (juint)-1, "correct depth count");
 248     }
 249 #endif
 250   }
 251 
 252   if (secondary_supers() == NULL) {
 253     KlassHandle this_kh (THREAD, this);
 254 
 255     // Now compute the list of secondary supertypes.
 256     // Secondaries can occasionally be on the super chain,
 257     // if the inline "_primary_supers" array overflows.
 258     int extras = 0;
 259     Klass* p;
 260     for (p = super(); !(p == NULL || p->can_be_primary_super()); p = p->super()) {
 261       ++extras;
 262     }
 263 
 264     ResourceMark rm(THREAD);  // need to reclaim GrowableArrays allocated below
 265 
 266     // Compute the "real" non-extra secondaries.
 267     GrowableArray<Klass*>* secondaries = compute_secondary_supers(extras);
 268     if (secondaries == NULL) {
 269       // secondary_supers set by compute_secondary_supers
 270       return;
 271     }
 272 
 273     GrowableArray<Klass*>* primaries = new GrowableArray<Klass*>(extras);
 274 
 275     for (p = this_kh->super(); !(p == NULL || p->can_be_primary_super()); p = p->super()) {
 276       int i;                    // Scan for overflow primaries being duplicates of 2nd'arys
 277 
 278       // This happens frequently for very deeply nested arrays: the
 279       // primary superclass chain overflows into the secondary.  The
 280       // secondary list contains the element_klass's secondaries with
 281       // an extra array dimension added.  If the element_klass's
 282       // secondary list already contains some primary overflows, they
 283       // (with the extra level of array-ness) will collide with the
 284       // normal primary superclass overflows.
 285       for( i = 0; i < secondaries->length(); i++ ) {
 286         if( secondaries->at(i) == p )
 287           break;
 288       }
 289       if( i < secondaries->length() )
 290         continue;               // It's a dup, don't put it in
 291       primaries->push(p);
 292     }
 293     // Combine the two arrays into a metadata object to pack the array.
 294     // The primaries are added in the reverse order, then the secondaries.
 295     int new_length = primaries->length() + secondaries->length();
 296     Array<Klass*>* s2 = MetadataFactory::new_array<Klass*>(
 297                                        class_loader_data(), new_length, CHECK);
 298     int fill_p = primaries->length();
 299     for (int j = 0; j < fill_p; j++) {
 300       s2->at_put(j, primaries->pop());  // add primaries in reverse order.
 301     }
 302     for( int j = 0; j < secondaries->length(); j++ ) {
 303       s2->at_put(j+fill_p, secondaries->at(j));  // add secondaries on the end.
 304     }
 305 
 306   #ifdef ASSERT
 307       // We must not copy any NULL placeholders left over from bootstrap.
 308     for (int j = 0; j < s2->length(); j++) {
 309       assert(s2->at(j) != NULL, "correct bootstrapping order");
 310     }
 311   #endif
 312 
 313     this_kh->set_secondary_supers(s2);
 314   }
 315 }
 316 
 317 GrowableArray<Klass*>* Klass::compute_secondary_supers(int num_extra_slots) {
 318   assert(num_extra_slots == 0, "override for complex klasses");
 319   set_secondary_supers(Universe::the_empty_klass_array());
 320   return NULL;
 321 }
 322 
 323 
 324 InstanceKlass* Klass::superklass() const {
 325   assert(super() == NULL || super()->is_instance_klass(), "must be instance klass");
 326   return _super == NULL ? NULL : InstanceKlass::cast(_super);
 327 }
 328 
 329 void Klass::set_subklass(Klass* s) {
 330   assert(s != this, "sanity check");
 331   _subklass = s;
 332 }
 333 
 334 void Klass::set_next_sibling(Klass* s) {
 335   assert(s != this, "sanity check");
 336   _next_sibling = s;
 337 }
 338 
 339 void Klass::append_to_sibling_list() {
 340   debug_only(verify();)
 341   // add ourselves to superklass' subklass list
 342   InstanceKlass* super = superklass();
 343   if (super == NULL) return;        // special case: class Object
 344   assert((!super->is_interface()    // interfaces cannot be supers
 345           && (super->superklass() == NULL || !is_interface())),
 346          "an interface can only be a subklass of Object");
 347   Klass* prev_first_subklass = super->subklass();
 348   if (prev_first_subklass != NULL) {
 349     // set our sibling to be the superklass' previous first subklass
 350     set_next_sibling(prev_first_subklass);
 351   }
 352   // make ourselves the superklass' first subklass
 353   super->set_subklass(this);
 354   debug_only(verify();)
 355 }
 356 
 357 bool Klass::is_loader_alive(BoolObjectClosure* is_alive) {
 358 #ifdef ASSERT
 359   // The class is alive iff the class loader is alive.
 360   oop loader = class_loader();
 361   bool loader_alive = (loader == NULL) || is_alive->do_object_b(loader);
 362 #endif // ASSERT
 363 
 364   // The class is alive if it's mirror is alive (which should be marked if the
 365   // loader is alive) unless it's an anoymous class.
 366   bool mirror_alive = is_alive->do_object_b(java_mirror());
 367   assert(!mirror_alive || loader_alive, "loader must be alive if the mirror is"
 368                         " but not the other way around with anonymous classes");
 369   return mirror_alive;
 370 }
 371 
 372 void Klass::clean_weak_klass_links(BoolObjectClosure* is_alive, bool clean_alive_klasses) {
 373   if (!ClassUnloading) {
 374     return;
 375   }
 376 
 377   Klass* root = SystemDictionary::Object_klass();
 378   Stack<Klass*, mtGC> stack;
 379 
 380   stack.push(root);
 381   while (!stack.is_empty()) {
 382     Klass* current = stack.pop();
 383 
 384     assert(current->is_loader_alive(is_alive), "just checking, this should be live");
 385 
 386     // Find and set the first alive subklass
 387     Klass* sub = current->subklass();
 388     while (sub != NULL && !sub->is_loader_alive(is_alive)) {
 389 #ifndef PRODUCT
 390       if (log_is_enabled(Trace, classunload)) {
 391         ResourceMark rm;
 392         log_trace(classunload)("[Unlinking class (subclass) %s]", sub->external_name());
 393       }
 394 #endif
 395       sub = sub->next_sibling();
 396     }
 397     current->set_subklass(sub);
 398     if (sub != NULL) {
 399       stack.push(sub);
 400     }
 401 
 402     // Find and set the first alive sibling
 403     Klass* sibling = current->next_sibling();
 404     while (sibling != NULL && !sibling->is_loader_alive(is_alive)) {
 405       if (log_is_enabled(Trace, classunload)) {
 406         ResourceMark rm;
 407         log_trace(classunload)("[Unlinking class (sibling) %s]", sibling->external_name());
 408       }
 409       sibling = sibling->next_sibling();
 410     }
 411     current->set_next_sibling(sibling);
 412     if (sibling != NULL) {
 413       stack.push(sibling);
 414     }
 415 
 416     // Clean the implementors list and method data.
 417     if (clean_alive_klasses && current->is_instance_klass()) {
 418       InstanceKlass* ik = InstanceKlass::cast(current);
 419       ik->clean_weak_instanceklass_links(is_alive);
 420     }
 421   }
 422 }
 423 
 424 void Klass::klass_update_barrier_set(oop v) {
 425   record_modified_oops();
 426 }
 427 
 428 // This barrier is used by G1 to remember the old oop values, so
 429 // that we don't forget any objects that were live at the snapshot at
 430 // the beginning. This function is only used when we write oops into Klasses.
 431 void Klass::klass_update_barrier_set_pre(oop* p, oop v) {
 432 #if INCLUDE_ALL_GCS
 433   if (UseG1GC) {
 434     oop obj = *p;
 435     if (obj != NULL) {
 436       G1SATBCardTableModRefBS::enqueue(obj);
 437     }
 438   }
 439 #endif
 440 }
 441 
 442 void Klass::klass_oop_store(oop* p, oop v) {
 443   assert(!Universe::heap()->is_in_reserved((void*)p), "Should store pointer into metadata");
 444   assert(v == NULL || Universe::heap()->is_in_reserved((void*)v), "Should store pointer to an object");
 445 
 446   // do the store
 447   if (always_do_update_barrier) {
 448     klass_oop_store((volatile oop*)p, v);
 449   } else {
 450     klass_update_barrier_set_pre(p, v);
 451     *p = v;
 452     klass_update_barrier_set(v);
 453   }
 454 }
 455 
 456 void Klass::klass_oop_store(volatile oop* p, oop v) {
 457   assert(!Universe::heap()->is_in_reserved((void*)p), "Should store pointer into metadata");
 458   assert(v == NULL || Universe::heap()->is_in_reserved((void*)v), "Should store pointer to an object");
 459 
 460   klass_update_barrier_set_pre((oop*)p, v); // Cast away volatile.
 461   OrderAccess::release_store_ptr(p, v);
 462   klass_update_barrier_set(v);
 463 }
 464 
 465 void Klass::oops_do(OopClosure* cl) {
 466   cl->do_oop(&_java_mirror);
 467 }
 468 
 469 void Klass::remove_unshareable_info() {
 470   assert (DumpSharedSpaces, "only called for DumpSharedSpaces");
 471 
 472   set_subklass(NULL);
 473   set_next_sibling(NULL);
 474   // Clear the java mirror
 475   set_java_mirror(NULL);
 476   set_next_link(NULL);
 477 
 478   // Null out class_loader_data because we don't share that yet.
 479   set_class_loader_data(NULL);
 480 }
 481 
 482 void Klass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
 483   TRACE_INIT_ID(this);
 484   // If an exception happened during CDS restore, some of these fields may already be
 485   // set.  We leave the class on the CLD list, even if incomplete so that we don't
 486   // modify the CLD list outside a safepoint.
 487   if (class_loader_data() == NULL) {
 488     // Restore class_loader_data to the null class loader data
 489     set_class_loader_data(loader_data);
 490 
 491     // Add to null class loader list first before creating the mirror
 492     // (same order as class file parsing)
 493     loader_data->add_class(this);
 494   }
 495 
 496   // Recreate the class mirror.
 497   // Only recreate it if not present.  A previous attempt to restore may have
 498   // gotten an OOM later but keep the mirror if it was created.
 499   if (java_mirror() == NULL) {
 500     Handle loader = loader_data->class_loader();
 501     java_lang_Class::create_mirror(this, loader, protection_domain, CHECK);
 502   }
 503 }
 504 
 505 Klass* Klass::array_klass_or_null(int rank) {
 506   EXCEPTION_MARK;
 507   // No exception can be thrown by array_klass_impl when called with or_null == true.
 508   // (In anycase, the execption mark will fail if it do so)
 509   return array_klass_impl(true, rank, THREAD);
 510 }
 511 
 512 
 513 Klass* Klass::array_klass_or_null() {
 514   EXCEPTION_MARK;
 515   // No exception can be thrown by array_klass_impl when called with or_null == true.
 516   // (In anycase, the execption mark will fail if it do so)
 517   return array_klass_impl(true, THREAD);
 518 }
 519 
 520 
 521 Klass* Klass::array_klass_impl(bool or_null, int rank, TRAPS) {
 522   fatal("array_klass should be dispatched to InstanceKlass, ObjArrayKlass or TypeArrayKlass");
 523   return NULL;
 524 }
 525 
 526 
 527 Klass* Klass::array_klass_impl(bool or_null, TRAPS) {
 528   fatal("array_klass should be dispatched to InstanceKlass, ObjArrayKlass or TypeArrayKlass");
 529   return NULL;
 530 }
 531 
 532 oop Klass::class_loader() const { return class_loader_data()->class_loader(); }
 533 
 534 // In product mode, this function doesn't have virtual function calls so
 535 // there might be some performance advantage to handling InstanceKlass here.
 536 const char* Klass::external_name() const {
 537   if (is_instance_klass()) {
 538     const InstanceKlass* ik = static_cast<const InstanceKlass*>(this);
 539     if (ik->is_anonymous()) {
 540       intptr_t hash = 0;
 541       if (ik->java_mirror() != NULL) {
 542         // java_mirror might not be created yet, return 0 as hash.
 543         hash = ik->java_mirror()->identity_hash();
 544       }
 545       char     hash_buf[40];
 546       sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
 547       size_t   hash_len = strlen(hash_buf);
 548 
 549       size_t result_len = name()->utf8_length();
 550       char*  result     = NEW_RESOURCE_ARRAY(char, result_len + hash_len + 1);
 551       name()->as_klass_external_name(result, (int) result_len + 1);
 552       assert(strlen(result) == result_len, "");
 553       strcpy(result + result_len, hash_buf);
 554       assert(strlen(result) == result_len + hash_len, "");
 555       return result;
 556     }
 557   }
 558   if (name() == NULL)  return "<unknown>";
 559   return name()->as_klass_external_name();
 560 }
 561 
 562 
 563 const char* Klass::signature_name() const {
 564   if (name() == NULL)  return "<unknown>";
 565   return name()->as_C_string();
 566 }
 567 
 568 // Unless overridden, modifier_flags is 0.
 569 jint Klass::compute_modifier_flags(TRAPS) const {
 570   return 0;
 571 }
 572 
 573 int Klass::atomic_incr_biased_lock_revocation_count() {
 574   return (int) Atomic::add(1, &_biased_lock_revocation_count);
 575 }
 576 
 577 // Unless overridden, jvmti_class_status has no flags set.
 578 jint Klass::jvmti_class_status() const {
 579   return 0;
 580 }
 581 
 582 
 583 // Printing
 584 
 585 void Klass::print_on(outputStream* st) const {
 586   ResourceMark rm;
 587   // print title
 588   st->print("%s", internal_name());
 589   print_address_on(st);
 590   st->cr();
 591 }
 592 
 593 void Klass::oop_print_on(oop obj, outputStream* st) {
 594   ResourceMark rm;
 595   // print title
 596   st->print_cr("%s ", internal_name());
 597   obj->print_address_on(st);
 598 
 599   if (WizardMode) {
 600      // print header
 601      obj->mark()->print_on(st);
 602   }
 603 
 604   // print class
 605   st->print(" - klass: ");
 606   obj->klass()->print_value_on(st);
 607   st->cr();
 608 }
 609 
 610 void Klass::oop_print_value_on(oop obj, outputStream* st) {
 611   // print title
 612   ResourceMark rm;              // Cannot print in debug mode without this
 613   st->print("%s", internal_name());
 614   obj->print_address_on(st);
 615 }
 616 
 617 #if INCLUDE_SERVICES
 618 // Size Statistics
 619 void Klass::collect_statistics(KlassSizeStats *sz) const {
 620   sz->_klass_bytes = sz->count(this);
 621   sz->_mirror_bytes = sz->count(java_mirror());
 622   sz->_secondary_supers_bytes = sz->count_array(secondary_supers());
 623 
 624   sz->_ro_bytes += sz->_secondary_supers_bytes;
 625   sz->_rw_bytes += sz->_klass_bytes + sz->_mirror_bytes;
 626 }
 627 #endif // INCLUDE_SERVICES
 628 
 629 // Verification
 630 
 631 void Klass::verify_on(outputStream* st) {
 632 
 633   // This can be expensive, but it is worth checking that this klass is actually
 634   // in the CLD graph but not in production.
 635   assert(Metaspace::contains((address)this), "Should be");
 636 
 637   guarantee(this->is_klass(),"should be klass");
 638 
 639   if (super() != NULL) {
 640     guarantee(super()->is_klass(), "should be klass");
 641   }
 642   if (secondary_super_cache() != NULL) {
 643     Klass* ko = secondary_super_cache();
 644     guarantee(ko->is_klass(), "should be klass");
 645   }
 646   for ( uint i = 0; i < primary_super_limit(); i++ ) {
 647     Klass* ko = _primary_supers[i];
 648     if (ko != NULL) {
 649       guarantee(ko->is_klass(), "should be klass");
 650     }
 651   }
 652 
 653   if (java_mirror() != NULL) {
 654     guarantee(java_mirror()->is_oop(), "should be instance");
 655   }
 656 }
 657 
 658 void Klass::oop_verify_on(oop obj, outputStream* st) {
 659   guarantee(obj->is_oop(),  "should be oop");
 660   guarantee(obj->klass()->is_klass(), "klass field is not a klass");
 661 }
 662 
 663 #ifndef PRODUCT
 664 
 665 bool Klass::verify_vtable_index(int i) {
 666   int limit = vtable_length()/vtableEntry::size();
 667   assert(i >= 0 && i < limit, "index %d out of bounds %d", i, limit);
 668   return true;
 669 }
 670 
 671 bool Klass::verify_itable_index(int i) {
 672   assert(is_instance_klass(), "");
 673   int method_count = klassItable::method_count_for_interface(this);
 674   assert(i >= 0 && i < method_count, "index out of bounds");
 675   return true;
 676 }
 677 
 678 #endif
 679 
 680 /////////////// Unit tests ///////////////
 681 
 682 #ifndef PRODUCT
 683 
 684 class TestKlass {
 685  public:
 686   static void test_oop_is_instanceClassLoader() {
 687     Klass* klass = SystemDictionary::ClassLoader_klass();
 688     guarantee(klass->is_instance_klass(), "assert");
 689     guarantee(InstanceKlass::cast(klass)->is_class_loader_instance_klass(), "test failed");
 690 
 691     klass = SystemDictionary::String_klass();
 692     guarantee(!klass->is_instance_klass() ||
 693               !InstanceKlass::cast(klass)->is_class_loader_instance_klass(),
 694               "test failed");
 695   }
 696 };
 697 
 698 void TestKlass_test() {
 699   TestKlass::test_oop_is_instanceClassLoader();
 700 }
 701 
 702 #endif  // PRODUCT