1 /*
   2  * Copyright (c) 2003, 2017, 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/classLoaderData.inline.hpp"
  27 #include "classfile/sharedClassUtil.hpp"
  28 #include "classfile/dictionary.hpp"
  29 #include "classfile/protectionDomainCache.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/systemDictionaryShared.hpp"
  32 #include "logging/log.hpp"
  33 #include "logging/logStream.hpp"
  34 #include "memory/iterator.hpp"
  35 #include "memory/metaspaceClosure.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "oops/oop.inline.hpp"
  38 #include "runtime/orderAccess.inline.hpp"
  39 #include "utilities/hashtable.inline.hpp"
  40 
  41 DictionaryEntry*  Dictionary::_current_class_entry = NULL;
  42 int               Dictionary::_current_class_index =    0;
  43 
  44 size_t Dictionary::entry_size() {
  45   if (DumpSharedSpaces) {
  46     return SystemDictionaryShared::dictionary_entry_size();
  47   } else {
  48     return sizeof(DictionaryEntry);
  49   }
  50 }
  51 
  52 Dictionary::Dictionary(int table_size)
  53   : TwoOopHashtable<InstanceKlass*, mtClass>(table_size, (int)entry_size()) {
  54   _current_class_index = 0;
  55   _current_class_entry = NULL;
  56   _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize);
  57 };
  58 
  59 
  60 Dictionary::Dictionary(int table_size, HashtableBucket<mtClass>* t,
  61                        int number_of_entries)
  62   : TwoOopHashtable<InstanceKlass*, mtClass>(table_size, (int)entry_size(), t, number_of_entries) {
  63   _current_class_index = 0;
  64   _current_class_entry = NULL;
  65   _pd_cache_table = new ProtectionDomainCacheTable(defaultProtectionDomainCacheSize);
  66 };
  67 
  68 ProtectionDomainCacheEntry* Dictionary::cache_get(Handle protection_domain) {
  69   return _pd_cache_table->get(protection_domain);
  70 }
  71 
  72 DictionaryEntry* Dictionary::new_entry(unsigned int hash, InstanceKlass* klass,
  73                                        ClassLoaderData* loader_data) {
  74   DictionaryEntry* entry = (DictionaryEntry*)Hashtable<InstanceKlass*, mtClass>::new_entry(hash, klass);
  75   entry->set_loader_data(loader_data);
  76   entry->set_pd_set(NULL);
  77   assert(klass->is_instance_klass(), "Must be");
  78   if (DumpSharedSpaces) {
  79     SystemDictionaryShared::init_shared_dictionary_entry(klass, entry);
  80   }
  81   return entry;
  82 }
  83 
  84 
  85 void Dictionary::free_entry(DictionaryEntry* entry) {
  86   // avoid recursion when deleting linked list
  87   while (entry->pd_set() != NULL) {
  88     ProtectionDomainEntry* to_delete = entry->pd_set();
  89     entry->set_pd_set(to_delete->next());
  90     delete to_delete;
  91   }
  92   Hashtable<InstanceKlass*, mtClass>::free_entry(entry);
  93 }
  94 
  95 
  96 bool DictionaryEntry::contains_protection_domain(oop protection_domain) const {
  97 #ifdef ASSERT
  98   if (protection_domain == klass()->protection_domain()) {
  99     // Ensure this doesn't show up in the pd_set (invariant)
 100     bool in_pd_set = false;
 101     for (ProtectionDomainEntry* current = _pd_set;
 102                                 current != NULL;
 103                                 current = current->next()) {
 104       if (current->protection_domain() == protection_domain) {
 105         in_pd_set = true;
 106         break;
 107       }
 108     }
 109     if (in_pd_set) {
 110       assert(false, "A klass's protection domain should not show up "
 111                     "in its sys. dict. PD set");
 112     }
 113   }
 114 #endif /* ASSERT */
 115 
 116   if (protection_domain == klass()->protection_domain()) {
 117     // Succeeds trivially
 118     return true;
 119   }
 120 
 121   for (ProtectionDomainEntry* current = _pd_set;
 122                               current != NULL;
 123                               current = current->next()) {
 124     if (current->protection_domain() == protection_domain) return true;
 125   }
 126   return false;
 127 }
 128 
 129 
 130 void DictionaryEntry::add_protection_domain(Dictionary* dict, Handle protection_domain) {
 131   assert_locked_or_safepoint(SystemDictionary_lock);
 132   if (!contains_protection_domain(protection_domain())) {
 133     ProtectionDomainCacheEntry* entry = dict->cache_get(protection_domain);
 134     ProtectionDomainEntry* new_head =
 135                 new ProtectionDomainEntry(entry, _pd_set);
 136     // Warning: Preserve store ordering.  The SystemDictionary is read
 137     //          without locks.  The new ProtectionDomainEntry must be
 138     //          complete before other threads can be allowed to see it
 139     //          via a store to _pd_set.
 140     OrderAccess::release_store_ptr(&_pd_set, new_head);
 141   }
 142   LogTarget(Trace, protectiondomain) lt;
 143   if (lt.is_enabled()) {
 144     LogStream ls(lt);
 145     print_count(&ls);
 146   }
 147 }
 148 
 149 
 150 void Dictionary::do_unloading() {
 151   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 152 
 153   // Remove unloadable entries and classes from system dictionary
 154   DictionaryEntry* probe = NULL;
 155   for (int index = 0; index < table_size(); index++) {
 156     for (DictionaryEntry** p = bucket_addr(index); *p != NULL; ) {
 157       probe = *p;
 158       Klass* e = probe->klass();
 159       ClassLoaderData* loader_data = probe->loader_data();
 160 
 161       InstanceKlass* ik = InstanceKlass::cast(e);
 162 
 163       // Only unload classes that are not strongly reachable
 164       if (!is_strongly_reachable(loader_data, e)) {
 165         // Entry was not visited in phase1 (negated test from phase1)
 166         assert(!loader_data->is_the_null_class_loader_data(), "unloading entry with null class loader");
 167         ClassLoaderData* k_def_class_loader_data = ik->class_loader_data();
 168 
 169         // Do we need to delete this system dictionary entry?
 170         bool purge_entry = false;
 171 
 172         // Do we need to delete this system dictionary entry?
 173         if (loader_data->is_unloading()) {
 174           // If the loader is not live this entry should always be
 175           // removed (will never be looked up again).
 176           purge_entry = true;
 177         } else {
 178           // The loader in this entry is alive. If the klass is dead,
 179           // (determined by checking the defining class loader)
 180           // the loader must be an initiating loader (rather than the
 181           // defining loader). Remove this entry.
 182           if (k_def_class_loader_data->is_unloading()) {
 183             // If we get here, the class_loader_data must not be the defining
 184             // loader, it must be an initiating one.
 185             assert(k_def_class_loader_data != loader_data,
 186                    "cannot have live defining loader and unreachable klass");
 187             // Loader is live, but class and its defining loader are dead.
 188             // Remove the entry. The class is going away.
 189             purge_entry = true;
 190           }
 191         }
 192 
 193         if (purge_entry) {
 194           *p = probe->next();
 195           if (probe == _current_class_entry) {
 196             _current_class_entry = NULL;
 197           }
 198           free_entry(probe);
 199           continue;
 200         }
 201       }
 202       p = probe->next_addr();
 203     }
 204   }
 205 }
 206 
 207 void Dictionary::roots_oops_do(OopClosure* strong, OopClosure* weak) {
 208   // Do strong roots marking if the closures are the same.
 209   if (strong == weak || !ClassUnloading) {
 210     // Only the protection domain oops contain references into the heap. Iterate
 211     // over all of them.
 212     _pd_cache_table->oops_do(strong);
 213   } else {
 214    if (weak != NULL) {
 215      _pd_cache_table->oops_do(weak);
 216    }
 217   }
 218 }
 219 
 220 
 221 void Dictionary::remove_classes_in_error_state() {
 222   assert(DumpSharedSpaces, "supported only when dumping");
 223   DictionaryEntry* probe = NULL;
 224   for (int index = 0; index < table_size(); index++) {
 225     for (DictionaryEntry** p = bucket_addr(index); *p != NULL; ) {
 226       probe = *p;
 227       InstanceKlass* ik = InstanceKlass::cast(probe->klass());
 228       if (ik->is_in_error_state()) { // purge this entry
 229         *p = probe->next();
 230         if (probe == _current_class_entry) {
 231           _current_class_entry = NULL;
 232         }
 233         free_entry(probe);
 234         ResourceMark rm;
 235         tty->print_cr("Preload Warning: Removed error class: %s", ik->external_name());
 236         continue;
 237       }
 238 
 239       p = probe->next_addr();
 240     }
 241   }
 242 }
 243 
 244 //   Just the classes from defining class loaders
 245 void Dictionary::classes_do(void f(Klass*)) {
 246   for (int index = 0; index < table_size(); index++) {
 247     for (DictionaryEntry* probe = bucket(index);
 248                           probe != NULL;
 249                           probe = probe->next()) {
 250       Klass* k = probe->klass();
 251       if (probe->loader_data() == k->class_loader_data()) {
 252         f(k);
 253       }
 254     }
 255   }
 256 }
 257 
 258 // Added for initialize_itable_for_klass to handle exceptions
 259 //   Just the classes from defining class loaders
 260 void Dictionary::classes_do(void f(Klass*, TRAPS), TRAPS) {
 261   for (int index = 0; index < table_size(); index++) {
 262     for (DictionaryEntry* probe = bucket(index);
 263                           probe != NULL;
 264                           probe = probe->next()) {
 265       Klass* k = probe->klass();
 266       if (probe->loader_data() == k->class_loader_data()) {
 267         f(k, CHECK);
 268       }
 269     }
 270   }
 271 }
 272 
 273 //   All classes, and their class loaders
 274 // Don't iterate over placeholders
 275 void Dictionary::classes_do(void f(Klass*, ClassLoaderData*)) {
 276   for (int index = 0; index < table_size(); index++) {
 277     for (DictionaryEntry* probe = bucket(index);
 278                           probe != NULL;
 279                           probe = probe->next()) {
 280       Klass* k = probe->klass();
 281       f(k, probe->loader_data());
 282     }
 283   }
 284 }
 285 
 286 // Used to scan and relocate the classes during CDS archive dump.
 287 void Dictionary::classes_do(MetaspaceClosure* it) {
 288   for (int index = 0; index < table_size(); index++) {
 289     for (DictionaryEntry* probe = bucket(index);
 290                           probe != NULL;
 291                           probe = probe->next()) {
 292       it->push(probe->klass_addr());
 293       if (DumpSharedSpaces) {
 294         ((SharedDictionaryEntry*)probe)->metaspace_pointers_do(it);
 295       }
 296     }
 297   }
 298 }
 299 
 300 
 301 void Dictionary::oops_do(OopClosure* f) {
 302   // Only the protection domain oops contain references into the heap. Iterate
 303   // over all of them.
 304   _pd_cache_table->oops_do(f);
 305 }
 306 
 307 void Dictionary::unlink(BoolObjectClosure* is_alive) {
 308   // Only the protection domain cache table may contain references to the heap
 309   // that need to be unlinked.
 310   _pd_cache_table->unlink(is_alive);
 311 }
 312 
 313 InstanceKlass* Dictionary::try_get_next_class() {
 314   while (true) {
 315     if (_current_class_entry != NULL) {
 316       InstanceKlass* k = _current_class_entry->klass();
 317       _current_class_entry = _current_class_entry->next();
 318       return k;
 319     }
 320     _current_class_index = (_current_class_index + 1) % table_size();
 321     _current_class_entry = bucket(_current_class_index);
 322   }
 323   // never reached
 324 }
 325 
 326 // Add a loaded class to the system dictionary.
 327 // Readers of the SystemDictionary aren't always locked, so _buckets
 328 // is volatile. The store of the next field in the constructor is
 329 // also cast to volatile;  we do this to ensure store order is maintained
 330 // by the compilers.
 331 
 332 void Dictionary::add_klass(Symbol* class_name, ClassLoaderData* loader_data,
 333                            InstanceKlass* obj) {
 334   assert_locked_or_safepoint(SystemDictionary_lock);
 335   assert(obj != NULL, "adding NULL obj");
 336   assert(obj->name() == class_name, "sanity check on name");
 337   assert(loader_data != NULL, "Must be non-NULL");
 338 
 339   unsigned int hash = compute_hash(class_name, loader_data);
 340   int index = hash_to_index(hash);
 341   DictionaryEntry* entry = new_entry(hash, obj, loader_data);
 342   add_entry(index, entry);
 343 }
 344 
 345 
 346 // This routine does not lock the system dictionary.
 347 //
 348 // Since readers don't hold a lock, we must make sure that system
 349 // dictionary entries are only removed at a safepoint (when only one
 350 // thread is running), and are added to in a safe way (all links must
 351 // be updated in an MT-safe manner).
 352 //
 353 // Callers should be aware that an entry could be added just after
 354 // _buckets[index] is read here, so the caller will not see the new entry.
 355 DictionaryEntry* Dictionary::get_entry(int index, unsigned int hash,
 356                                        Symbol* class_name,
 357                                        ClassLoaderData* loader_data) {
 358   for (DictionaryEntry* entry = bucket(index);
 359                         entry != NULL;
 360                         entry = entry->next()) {
 361     if (entry->hash() == hash && entry->equals(class_name, loader_data)) {
 362       return entry;
 363     }
 364   }
 365   return NULL;
 366 }
 367 
 368 
 369 InstanceKlass* Dictionary::find(int index, unsigned int hash, Symbol* name,
 370                                 ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
 371   DictionaryEntry* entry = get_entry(index, hash, name, loader_data);
 372   if (entry != NULL && entry->is_valid_protection_domain(protection_domain)) {
 373     return entry->klass();
 374   } else {
 375     return NULL;
 376   }
 377 }
 378 
 379 
 380 InstanceKlass* Dictionary::find_class(int index, unsigned int hash,
 381                                       Symbol* name, ClassLoaderData* loader_data) {
 382   assert_locked_or_safepoint(SystemDictionary_lock);
 383   assert (index == index_for(name, loader_data), "incorrect index?");
 384 
 385   DictionaryEntry* entry = get_entry(index, hash, name, loader_data);
 386   return (entry != NULL) ? entry->klass() : NULL;
 387 }
 388 
 389 
 390 // Variant of find_class for shared classes.  No locking required, as
 391 // that table is static.
 392 
 393 InstanceKlass* Dictionary::find_shared_class(int index, unsigned int hash,
 394                                              Symbol* name) {
 395   assert (index == index_for(name, NULL), "incorrect index?");
 396 
 397   DictionaryEntry* entry = get_entry(index, hash, name, NULL);
 398   return (entry != NULL) ? entry->klass() : NULL;
 399 }
 400 
 401 
 402 void Dictionary::add_protection_domain(int index, unsigned int hash,
 403                                        InstanceKlass* klass,
 404                                        ClassLoaderData* loader_data, Handle protection_domain,
 405                                        TRAPS) {
 406   Symbol*  klass_name = klass->name();
 407   DictionaryEntry* entry = get_entry(index, hash, klass_name, loader_data);
 408 
 409   assert(entry != NULL,"entry must be present, we just created it");
 410   assert(protection_domain() != NULL,
 411          "real protection domain should be present");
 412 
 413   entry->add_protection_domain(this, protection_domain);
 414 
 415   assert(entry->contains_protection_domain(protection_domain()),
 416          "now protection domain should be present");
 417 }
 418 
 419 
 420 bool Dictionary::is_valid_protection_domain(int index, unsigned int hash,
 421                                             Symbol* name,
 422                                             ClassLoaderData* loader_data,
 423                                             Handle protection_domain) {
 424   DictionaryEntry* entry = get_entry(index, hash, name, loader_data);
 425   return entry->is_valid_protection_domain(protection_domain);
 426 }
 427 
 428 
 429 void Dictionary::reorder_dictionary_for_sharing() {
 430 
 431   // Copy all the dictionary entries into a single master list.
 432 
 433   DictionaryEntry* master_list = NULL;
 434   for (int i = 0; i < table_size(); ++i) {
 435     DictionaryEntry* p = bucket(i);
 436     while (p != NULL) {
 437       DictionaryEntry* tmp;
 438       tmp = p->next();
 439       p->set_next(master_list);
 440       master_list = p;
 441       p = tmp;
 442     }
 443     set_entry(i, NULL);
 444   }
 445 
 446   // Add the dictionary entries back to the list in the correct buckets.
 447   while (master_list != NULL) {
 448     DictionaryEntry* p = master_list;
 449     master_list = master_list->next();
 450     p->set_next(NULL);
 451     Symbol* class_name = p->klass()->name();
 452     // Since the null class loader data isn't copied to the CDS archive,
 453     // compute the hash with NULL for loader data.
 454     unsigned int hash = compute_hash(class_name, NULL);
 455     int index = hash_to_index(hash);
 456     p->set_hash(hash);
 457     p->set_loader_data(NULL);   // loader_data isn't copied to CDS
 458     p->set_next(bucket(index));
 459     set_entry(index, p);
 460   }
 461 }
 462 
 463 
 464 SymbolPropertyTable::SymbolPropertyTable(int table_size)
 465   : Hashtable<Symbol*, mtSymbol>(table_size, sizeof(SymbolPropertyEntry))
 466 {
 467 }
 468 SymbolPropertyTable::SymbolPropertyTable(int table_size, HashtableBucket<mtSymbol>* t,
 469                                          int number_of_entries)
 470   : Hashtable<Symbol*, mtSymbol>(table_size, sizeof(SymbolPropertyEntry), t, number_of_entries)
 471 {
 472 }
 473 
 474 
 475 SymbolPropertyEntry* SymbolPropertyTable::find_entry(int index, unsigned int hash,
 476                                                      Symbol* sym,
 477                                                      intptr_t sym_mode) {
 478   assert(index == index_for(sym, sym_mode), "incorrect index?");
 479   for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
 480     if (p->hash() == hash && p->symbol() == sym && p->symbol_mode() == sym_mode) {
 481       return p;
 482     }
 483   }
 484   return NULL;
 485 }
 486 
 487 
 488 SymbolPropertyEntry* SymbolPropertyTable::add_entry(int index, unsigned int hash,
 489                                                     Symbol* sym, intptr_t sym_mode) {
 490   assert_locked_or_safepoint(SystemDictionary_lock);
 491   assert(index == index_for(sym, sym_mode), "incorrect index?");
 492   assert(find_entry(index, hash, sym, sym_mode) == NULL, "no double entry");
 493 
 494   SymbolPropertyEntry* p = new_entry(hash, sym, sym_mode);
 495   Hashtable<Symbol*, mtSymbol>::add_entry(index, p);
 496   return p;
 497 }
 498 
 499 void SymbolPropertyTable::oops_do(OopClosure* f) {
 500   for (int index = 0; index < table_size(); index++) {
 501     for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
 502       if (p->method_type() != NULL) {
 503         f->do_oop(p->method_type_addr());
 504       }
 505     }
 506   }
 507 }
 508 
 509 void SymbolPropertyTable::methods_do(void f(Method*)) {
 510   for (int index = 0; index < table_size(); index++) {
 511     for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
 512       Method* prop = p->method();
 513       if (prop != NULL) {
 514         f((Method*)prop);
 515       }
 516     }
 517   }
 518 }
 519 
 520 
 521 // ----------------------------------------------------------------------------
 522 
 523 void Dictionary::print(bool details) {
 524   ResourceMark rm;
 525 
 526   if (details) {
 527     tty->print_cr("Java system dictionary (table_size=%d, classes=%d)",
 528                    table_size(), number_of_entries());
 529     tty->print_cr("^ indicates that initiating loader is different from "
 530                   "defining loader");
 531   }
 532 
 533   for (int index = 0; index < table_size(); index++) {
 534     for (DictionaryEntry* probe = bucket(index);
 535                           probe != NULL;
 536                           probe = probe->next()) {
 537       Klass* e = probe->klass();
 538       ClassLoaderData* loader_data =  probe->loader_data();
 539       bool is_defining_class =
 540          (loader_data == e->class_loader_data());
 541       if (details) {
 542         tty->print("%4d: ", index);
 543       }
 544       tty->print("%s%s", ((!details) || is_defining_class) ? " " : "^",
 545                  e->external_name());
 546 
 547       if (details) {
 548         tty->print(", loader ");
 549         if (loader_data != NULL) {
 550           loader_data->print_value();
 551         } else {
 552           tty->print("NULL");
 553         }
 554       }
 555       tty->cr();
 556     }
 557   }
 558 
 559   if (details) {
 560     tty->cr();
 561     _pd_cache_table->print();
 562   }
 563   tty->cr();
 564 }
 565 
 566 void DictionaryEntry::verify() {
 567   Klass* e = klass();
 568   ClassLoaderData* cld = loader_data();
 569   guarantee(e->is_instance_klass(),
 570                           "Verify of system dictionary failed");
 571   // class loader must be present;  a null class loader is the
 572   // boostrap loader
 573   guarantee(cld != NULL || DumpSharedSpaces ||
 574             cld->class_loader() == NULL ||
 575             cld->class_loader()->is_instance(),
 576             "checking type of class_loader");
 577   e->verify();
 578   verify_protection_domain_set();
 579 }
 580 
 581 void Dictionary::verify() {
 582   guarantee(number_of_entries() >= 0, "Verify of system dictionary failed");
 583   verify_table<DictionaryEntry>("System Dictionary");
 584   _pd_cache_table->verify();
 585 }
 586