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