1 /*
   2  * Copyright (c) 1997, 2008, 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/_klass.cpp.incl"
  27 
  28 
  29 bool Klass::is_subclass_of(klassOop k) const {
  30   // Run up the super chain and check
  31   klassOop t = as_klassOop();
  32 
  33   if (t == k) return true;
  34   t = Klass::cast(t)->super();
  35 
  36   while (t != NULL) {
  37     if (t == k) return true;
  38     t = Klass::cast(t)->super();
  39   }
  40   return false;
  41 }
  42 
  43 bool Klass::search_secondary_supers(klassOop k) const {
  44   // Put some extra logic here out-of-line, before the search proper.
  45   // This cuts down the size of the inline method.
  46 
  47   // This is necessary, since I am never in my own secondary_super list.
  48   if (this->as_klassOop() == k)
  49     return true;
  50   // Scan the array-of-objects for a match
  51   int cnt = secondary_supers()->length();
  52   for (int i = 0; i < cnt; i++) {
  53     if (secondary_supers()->obj_at(i) == k) {
  54       ((Klass*)this)->set_secondary_super_cache(k);
  55       return true;
  56     }
  57   }
  58   return false;
  59 }
  60 
  61 // Return self, except for abstract classes with exactly 1
  62 // implementor.  Then return the 1 concrete implementation.
  63 Klass *Klass::up_cast_abstract() {
  64   Klass *r = this;
  65   while( r->is_abstract() ) {   // Receiver is abstract?
  66     Klass *s = r->subklass();   // Check for exactly 1 subklass
  67     if( !s || s->next_sibling() ) // Oops; wrong count; give up
  68       return this;              // Return 'this' as a no-progress flag
  69     r = s;                    // Loop till find concrete class
  70   }
  71   return r;                   // Return the 1 concrete class
  72 }
  73 
  74 // Find LCA in class hierarchy
  75 Klass *Klass::LCA( Klass *k2 ) {
  76   Klass *k1 = this;
  77   while( 1 ) {
  78     if( k1->is_subtype_of(k2->as_klassOop()) ) return k2;
  79     if( k2->is_subtype_of(k1->as_klassOop()) ) return k1;
  80     k1 = k1->super()->klass_part();
  81     k2 = k2->super()->klass_part();
  82   }
  83 }
  84 
  85 
  86 void Klass::check_valid_for_instantiation(bool throwError, TRAPS) {
  87   ResourceMark rm(THREAD);
  88   THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
  89             : vmSymbols::java_lang_InstantiationException(), external_name());
  90 }
  91 
  92 
  93 void Klass::copy_array(arrayOop s, int src_pos, arrayOop d, int dst_pos, int length, TRAPS) {
  94   THROW(vmSymbols::java_lang_ArrayStoreException());
  95 }
  96 
  97 
  98 void Klass::initialize(TRAPS) {
  99   ShouldNotReachHere();
 100 }
 101 
 102 bool Klass::compute_is_subtype_of(klassOop k) {
 103   assert(k->is_klass(), "argument must be a class");
 104   return is_subclass_of(k);
 105 }
 106 
 107 
 108 methodOop Klass::uncached_lookup_method(symbolOop name, symbolOop signature) const {
 109 #ifdef ASSERT
 110   tty->print_cr("Error: uncached_lookup_method called on a klass oop."
 111                 " Likely error: reflection method does not correctly"
 112                 " wrap return value in a mirror object.");
 113 #endif
 114   ShouldNotReachHere();
 115   return NULL;
 116 }
 117 
 118 klassOop Klass::base_create_klass_oop(KlassHandle& klass, int size,
 119                                       const Klass_vtbl& vtbl, TRAPS) {
 120   size = align_object_size(size);
 121   // allocate and initialize vtable
 122   Klass*   kl = (Klass*) vtbl.allocate_permanent(klass, size, CHECK_NULL);
 123   klassOop k  = kl->as_klassOop();
 124 
 125   { // Preinitialize supertype information.
 126     // A later call to initialize_supers() may update these settings:
 127     kl->set_super(NULL);
 128     for (juint i = 0; i < Klass::primary_super_limit(); i++) {
 129       kl->_primary_supers[i] = NULL;
 130     }
 131     kl->set_secondary_supers(NULL);
 132     oop_store_without_check((oop*) &kl->_primary_supers[0], k);
 133     kl->set_super_check_offset(primary_supers_offset_in_bytes() + sizeof(oopDesc));
 134   }
 135 
 136   kl->set_java_mirror(NULL);
 137   kl->set_modifier_flags(0);
 138   kl->set_layout_helper(Klass::_lh_neutral_value);
 139   kl->set_name(NULL);
 140   AccessFlags af;
 141   af.set_flags(0);
 142   kl->set_access_flags(af);
 143   kl->set_subklass(NULL);
 144   kl->set_next_sibling(NULL);
 145   kl->set_alloc_count(0);
 146   kl->set_alloc_size(0);
 147 
 148   kl->set_prototype_header(markOopDesc::prototype());
 149   kl->set_biased_lock_revocation_count(0);
 150   kl->set_last_biased_lock_bulk_revocation_time(0);
 151 
 152   return k;
 153 }
 154 
 155 KlassHandle Klass::base_create_klass(KlassHandle& klass, int size,
 156                                      const Klass_vtbl& vtbl, TRAPS) {
 157   klassOop ek = base_create_klass_oop(klass, size, vtbl, THREAD);
 158   return KlassHandle(THREAD, ek);
 159 }
 160 
 161 void Klass_vtbl::post_new_init_klass(KlassHandle& klass,
 162                                      klassOop new_klass,
 163                                      int size) const {
 164   assert(!new_klass->klass_part()->null_vtbl(), "Not a complete klass");
 165   CollectedHeap::post_allocation_install_obj_klass(klass, new_klass, size);
 166 }
 167 
 168 void* Klass_vtbl::operator new(size_t ignored, KlassHandle& klass,
 169                                int size, TRAPS) {
 170   // The vtable pointer is installed during the execution of
 171   // constructors in the call to permanent_obj_allocate().  Delay
 172   // the installation of the klass pointer into the new klass "k"
 173   // until after the vtable pointer has been installed (i.e., until
 174   // after the return of permanent_obj_allocate().
 175   klassOop k =
 176     (klassOop) CollectedHeap::permanent_obj_allocate_no_klass_install(klass,
 177       size, CHECK_NULL);
 178   return k->klass_part();
 179 }
 180 
 181 jint Klass::array_layout_helper(BasicType etype) {
 182   assert(etype >= T_BOOLEAN && etype <= T_OBJECT, "valid etype");
 183   // Note that T_ARRAY is not allowed here.
 184   int  hsize = arrayOopDesc::base_offset_in_bytes(etype);
 185   int  esize = type2aelembytes(etype);
 186   bool isobj = (etype == T_OBJECT);
 187   int  tag   =  isobj ? _lh_array_tag_obj_value : _lh_array_tag_type_value;
 188   int lh = array_layout_helper(tag, hsize, etype, exact_log2(esize));
 189 
 190   assert(lh < (int)_lh_neutral_value, "must look like an array layout");
 191   assert(layout_helper_is_javaArray(lh), "correct kind");
 192   assert(layout_helper_is_objArray(lh) == isobj, "correct kind");
 193   assert(layout_helper_is_typeArray(lh) == !isobj, "correct kind");
 194   assert(layout_helper_header_size(lh) == hsize, "correct decode");
 195   assert(layout_helper_element_type(lh) == etype, "correct decode");
 196   assert(1 << layout_helper_log2_element_size(lh) == esize, "correct decode");
 197 
 198   return lh;
 199 }
 200 
 201 bool Klass::can_be_primary_super_slow() const {
 202   if (super() == NULL)
 203     return true;
 204   else if (super()->klass_part()->super_depth() >= primary_super_limit()-1)
 205     return false;
 206   else
 207     return true;
 208 }
 209 
 210 void Klass::initialize_supers(klassOop k, TRAPS) {
 211   if (FastSuperclassLimit == 0) {
 212     // None of the other machinery matters.
 213     set_super(k);
 214     return;
 215   }
 216   if (k == NULL) {
 217     set_super(NULL);
 218     oop_store_without_check((oop*) &_primary_supers[0], (oop) this->as_klassOop());
 219     assert(super_depth() == 0, "Object must already be initialized properly");
 220   } else if (k != super() || k == SystemDictionary::Object_klass()) {
 221     assert(super() == NULL || super() == SystemDictionary::Object_klass(),
 222            "initialize this only once to a non-trivial value");
 223     set_super(k);
 224     Klass* sup = k->klass_part();
 225     int sup_depth = sup->super_depth();
 226     juint my_depth  = MIN2(sup_depth + 1, (int)primary_super_limit());
 227     if (!can_be_primary_super_slow())
 228       my_depth = primary_super_limit();
 229     for (juint i = 0; i < my_depth; i++) {
 230       oop_store_without_check((oop*) &_primary_supers[i], (oop) sup->_primary_supers[i]);
 231     }
 232     klassOop *super_check_cell;
 233     if (my_depth < primary_super_limit()) {
 234       oop_store_without_check((oop*) &_primary_supers[my_depth], (oop) this->as_klassOop());
 235       super_check_cell = &_primary_supers[my_depth];
 236     } else {
 237       // Overflow of the primary_supers array forces me to be secondary.
 238       super_check_cell = &_secondary_super_cache;
 239     }
 240     set_super_check_offset((address)super_check_cell - (address) this->as_klassOop());
 241 
 242 #ifdef ASSERT
 243     {
 244       juint j = super_depth();
 245       assert(j == my_depth, "computed accessor gets right answer");
 246       klassOop t = as_klassOop();
 247       while (!Klass::cast(t)->can_be_primary_super()) {
 248         t = Klass::cast(t)->super();
 249         j = Klass::cast(t)->super_depth();
 250       }
 251       for (juint j1 = j+1; j1 < primary_super_limit(); j1++) {
 252         assert(primary_super_of_depth(j1) == NULL, "super list padding");
 253       }
 254       while (t != NULL) {
 255         assert(primary_super_of_depth(j) == t, "super list initialization");
 256         t = Klass::cast(t)->super();
 257         --j;
 258       }
 259       assert(j == (juint)-1, "correct depth count");
 260     }
 261 #endif
 262   }
 263 
 264   if (secondary_supers() == NULL) {
 265     KlassHandle this_kh (THREAD, this);
 266 
 267     // Now compute the list of secondary supertypes.
 268     // Secondaries can occasionally be on the super chain,
 269     // if the inline "_primary_supers" array overflows.
 270     int extras = 0;
 271     klassOop p;
 272     for (p = super(); !(p == NULL || p->klass_part()->can_be_primary_super()); p = p->klass_part()->super()) {
 273       ++extras;
 274     }
 275 
 276     // Compute the "real" non-extra secondaries.
 277     objArrayOop secondary_oops = compute_secondary_supers(extras, CHECK);
 278     objArrayHandle secondaries (THREAD, secondary_oops);
 279 
 280     // Store the extra secondaries in the first array positions:
 281     int fillp = extras;
 282     for (p = this_kh->super(); !(p == NULL || p->klass_part()->can_be_primary_super()); p = p->klass_part()->super()) {
 283       int i;                    // Scan for overflow primaries being duplicates of 2nd'arys
 284 
 285       // This happens frequently for very deeply nested arrays: the
 286       // primary superclass chain overflows into the secondary.  The
 287       // secondary list contains the element_klass's secondaries with
 288       // an extra array dimension added.  If the element_klass's
 289       // secondary list already contains some primary overflows, they
 290       // (with the extra level of array-ness) will collide with the
 291       // normal primary superclass overflows.
 292       for( i = extras; i < secondaries->length(); i++ )
 293         if( secondaries->obj_at(i) == p )
 294           break;
 295       if( i < secondaries->length() )
 296         continue;               // It's a dup, don't put it in
 297       secondaries->obj_at_put(--fillp, p);
 298     }
 299     // See if we had some dup's, so the array has holes in it.
 300     if( fillp > 0 ) {
 301       // Pack the array.  Drop the old secondaries array on the floor
 302       // and let GC reclaim it.
 303       objArrayOop s2 = oopFactory::new_system_objArray(secondaries->length() - fillp, CHECK);
 304       for( int i = 0; i < s2->length(); i++ )
 305         s2->obj_at_put( i, secondaries->obj_at(i+fillp) );
 306       secondaries = objArrayHandle(THREAD, s2);
 307     }
 308 
 309   #ifdef ASSERT
 310     if (secondaries() != Universe::the_array_interfaces_array()) {
 311       // We must not copy any NULL placeholders left over from bootstrap.
 312       for (int j = 0; j < secondaries->length(); j++) {
 313         assert(secondaries->obj_at(j) != NULL, "correct bootstrapping order");
 314       }
 315     }
 316   #endif
 317 
 318     this_kh->set_secondary_supers(secondaries());
 319   }
 320 }
 321 
 322 objArrayOop Klass::compute_secondary_supers(int num_extra_slots, TRAPS) {
 323   assert(num_extra_slots == 0, "override for complex klasses");
 324   return Universe::the_empty_system_obj_array();
 325 }
 326 
 327 
 328 Klass* Klass::subklass() const {
 329   return _subklass == NULL ? NULL : Klass::cast(_subklass);
 330 }
 331 
 332 instanceKlass* Klass::superklass() const {
 333   assert(super() == NULL || super()->klass_part()->oop_is_instance(), "must be instance klass");
 334   return _super == NULL ? NULL : instanceKlass::cast(_super);
 335 }
 336 
 337 Klass* Klass::next_sibling() const {
 338   return _next_sibling == NULL ? NULL : Klass::cast(_next_sibling);
 339 }
 340 
 341 void Klass::set_subklass(klassOop s) {
 342   assert(s != as_klassOop(), "sanity check");
 343   oop_store_without_check((oop*)&_subklass, s);
 344 }
 345 
 346 void Klass::set_next_sibling(klassOop s) {
 347   assert(s != as_klassOop(), "sanity check");
 348   oop_store_without_check((oop*)&_next_sibling, s);
 349 }
 350 
 351 void Klass::append_to_sibling_list() {
 352   debug_only(if (!SharedSkipVerify) as_klassOop()->verify();)
 353   // add ourselves to superklass' subklass list
 354   instanceKlass* super = superklass();
 355   if (super == NULL) return;        // special case: class Object
 356   assert(SharedSkipVerify ||
 357          (!super->is_interface()    // interfaces cannot be supers
 358           && (super->superklass() == NULL || !is_interface())),
 359          "an interface can only be a subklass of Object");
 360   klassOop prev_first_subklass = super->subklass_oop();
 361   if (prev_first_subklass != NULL) {
 362     // set our sibling to be the superklass' previous first subklass
 363     set_next_sibling(prev_first_subklass);
 364   }
 365   // make ourselves the superklass' first subklass
 366   super->set_subklass(as_klassOop());
 367   debug_only(if (!SharedSkipVerify) as_klassOop()->verify();)
 368 }
 369 
 370 void Klass::remove_from_sibling_list() {
 371   // remove receiver from sibling list
 372   instanceKlass* super = superklass();
 373   assert(super != NULL || as_klassOop() == SystemDictionary::Object_klass(), "should have super");
 374   if (super == NULL) return;        // special case: class Object
 375   if (super->subklass() == this) {
 376     // first subklass
 377     super->set_subklass(_next_sibling);
 378   } else {
 379     Klass* sib = super->subklass();
 380     while (sib->next_sibling() != this) {
 381       sib = sib->next_sibling();
 382     };
 383     sib->set_next_sibling(_next_sibling);
 384   }
 385 }
 386 
 387 void Klass::follow_weak_klass_links( BoolObjectClosure* is_alive, OopClosure* keep_alive) {
 388   // This klass is alive but the subklass and siblings are not followed/updated.
 389   // We update the subklass link and the subklass' sibling links here.
 390   // Our own sibling link will be updated by our superclass (which must be alive
 391   // since we are).
 392   assert(is_alive->do_object_b(as_klassOop()), "just checking, this should be live");
 393   if (ClassUnloading) {
 394     klassOop sub = subklass_oop();
 395     if (sub != NULL && !is_alive->do_object_b(sub)) {
 396       // first subklass not alive, find first one alive
 397       do {
 398 #ifndef PRODUCT
 399         if (TraceClassUnloading && WizardMode) {
 400           ResourceMark rm;
 401           tty->print_cr("[Unlinking class (subclass) %s]", sub->klass_part()->external_name());
 402         }
 403 #endif
 404         sub = sub->klass_part()->next_sibling_oop();
 405       } while (sub != NULL && !is_alive->do_object_b(sub));
 406       set_subklass(sub);
 407     }
 408     // now update the subklass' sibling list
 409     while (sub != NULL) {
 410       klassOop next = sub->klass_part()->next_sibling_oop();
 411       if (next != NULL && !is_alive->do_object_b(next)) {
 412         // first sibling not alive, find first one alive
 413         do {
 414 #ifndef PRODUCT
 415           if (TraceClassUnloading && WizardMode) {
 416             ResourceMark rm;
 417             tty->print_cr("[Unlinking class (sibling) %s]", next->klass_part()->external_name());
 418           }
 419 #endif
 420           next = next->klass_part()->next_sibling_oop();
 421         } while (next != NULL && !is_alive->do_object_b(next));
 422         sub->klass_part()->set_next_sibling(next);
 423       }
 424       sub = next;
 425     }
 426   } else {
 427     // Always follow subklass and sibling link. This will prevent any klasses from
 428     // being unloaded (all classes are transitively linked from java.lang.Object).
 429     keep_alive->do_oop(adr_subklass());
 430     keep_alive->do_oop(adr_next_sibling());
 431   }
 432 }
 433 
 434 
 435 void Klass::remove_unshareable_info() {
 436   if (oop_is_instance()) {
 437     instanceKlass* ik = (instanceKlass*)this;
 438     if (ik->is_linked()) {
 439       ik->unlink_class();
 440     }
 441   }
 442   set_subklass(NULL);
 443   set_next_sibling(NULL);
 444 }
 445 
 446 
 447 klassOop Klass::array_klass_or_null(int rank) {
 448   EXCEPTION_MARK;
 449   // No exception can be thrown by array_klass_impl when called with or_null == true.
 450   // (In anycase, the execption mark will fail if it do so)
 451   return array_klass_impl(true, rank, THREAD);
 452 }
 453 
 454 
 455 klassOop Klass::array_klass_or_null() {
 456   EXCEPTION_MARK;
 457   // No exception can be thrown by array_klass_impl when called with or_null == true.
 458   // (In anycase, the execption mark will fail if it do so)
 459   return array_klass_impl(true, THREAD);
 460 }
 461 
 462 
 463 klassOop Klass::array_klass_impl(bool or_null, int rank, TRAPS) {
 464   fatal("array_klass should be dispatched to instanceKlass, objArrayKlass or typeArrayKlass");
 465   return NULL;
 466 }
 467 
 468 
 469 klassOop Klass::array_klass_impl(bool or_null, TRAPS) {
 470   fatal("array_klass should be dispatched to instanceKlass, objArrayKlass or typeArrayKlass");
 471   return NULL;
 472 }
 473 
 474 
 475 void Klass::with_array_klasses_do(void f(klassOop k)) {
 476   f(as_klassOop());
 477 }
 478 
 479 
 480 const char* Klass::external_name() const {
 481   if (oop_is_instance()) {
 482     instanceKlass* ik = (instanceKlass*) this;
 483     if (ik->is_anonymous()) {
 484       assert(AnonymousClasses, "");
 485       intptr_t hash = ik->java_mirror()->identity_hash();
 486       char     hash_buf[40];
 487       sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
 488       size_t   hash_len = strlen(hash_buf);
 489 
 490       size_t result_len = name()->utf8_length();
 491       char*  result     = NEW_RESOURCE_ARRAY(char, result_len + hash_len + 1);
 492       name()->as_klass_external_name(result, (int) result_len + 1);
 493       assert(strlen(result) == result_len, "");
 494       strcpy(result + result_len, hash_buf);
 495       assert(strlen(result) == result_len + hash_len, "");
 496       return result;
 497     }
 498   }
 499   if (name() == NULL)  return "<unknown>";
 500   return name()->as_klass_external_name();
 501 }
 502 
 503 
 504 const char* Klass::signature_name() const {
 505   if (name() == NULL)  return "<unknown>";
 506   return name()->as_C_string();
 507 }
 508 
 509 // Unless overridden, modifier_flags is 0.
 510 jint Klass::compute_modifier_flags(TRAPS) const {
 511   return 0;
 512 }
 513 
 514 int Klass::atomic_incr_biased_lock_revocation_count() {
 515   return (int) Atomic::add(1, &_biased_lock_revocation_count);
 516 }
 517 
 518 // Unless overridden, jvmti_class_status has no flags set.
 519 jint Klass::jvmti_class_status() const {
 520   return 0;
 521 }
 522 
 523 // Printing
 524 
 525 void Klass::oop_print_on(oop obj, outputStream* st) {
 526   ResourceMark rm;
 527   // print title
 528   st->print_cr("%s ", internal_name());
 529   obj->print_address_on(st);
 530 
 531   if (WizardMode) {
 532      // print header
 533      obj->mark()->print_on(st);
 534   }
 535 
 536   // print class
 537   st->print(" - klass: ");
 538   obj->klass()->print_value_on(st);
 539   st->cr();
 540 }
 541 
 542 void Klass::oop_print_value_on(oop obj, outputStream* st) {
 543   // print title
 544   ResourceMark rm;              // Cannot print in debug mode without this
 545   st->print("%s", internal_name());
 546   obj->print_address_on(st);
 547 }
 548 
 549 // Verification
 550 
 551 void Klass::oop_verify_on(oop obj, outputStream* st) {
 552   guarantee(obj->is_oop(),  "should be oop");
 553   guarantee(obj->klass()->is_perm(),  "should be in permspace");
 554   guarantee(obj->klass()->is_klass(), "klass field is not a klass");
 555 }
 556 
 557 
 558 void Klass::oop_verify_old_oop(oop obj, oop* p, bool allow_dirty) {
 559   /* $$$ I think this functionality should be handled by verification of
 560   RememberedSet::verify_old_oop(obj, p, allow_dirty, false);
 561   the card table. */
 562 }
 563 void Klass::oop_verify_old_oop(oop obj, narrowOop* p, bool allow_dirty) { }
 564 
 565 #ifndef PRODUCT
 566 
 567 void Klass::verify_vtable_index(int i) {
 568   assert(oop_is_instance() || oop_is_array(), "only instanceKlass and arrayKlass have vtables");
 569   if (oop_is_instance()) {
 570     assert(i>=0 && i<((instanceKlass*)this)->vtable_length()/vtableEntry::size(), "index out of bounds");
 571   } else {
 572     assert(i>=0 && i<((arrayKlass*)this)->vtable_length()/vtableEntry::size(), "index out of bounds");
 573   }
 574 }
 575 
 576 #endif