1 /*
   2  * Copyright (c) 2003, 2018, 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/dictionary.inline.hpp"
  28 #include "classfile/protectionDomainCache.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "logging/log.hpp"
  31 #include "logging/logStream.hpp"
  32 #include "memory/iterator.hpp"
  33 #include "memory/metaspaceClosure.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "runtime/atomic.hpp"
  37 #include "runtime/orderAccess.hpp"
  38 #include "runtime/safepointVerifiers.hpp"
  39 #include "utilities/hashtable.inline.hpp"
  40 
  41 // Optimization: if any dictionary needs resizing, we set this flag,
  42 // so that we dont't have to walk all dictionaries to check if any actually
  43 // needs resizing, which is costly to do at Safepoint.
  44 bool Dictionary::_some_dictionary_needs_resizing = false;
  45 
  46 Dictionary::Dictionary(ClassLoaderData* loader_data, int table_size, bool resizable)
  47   : Hashtable<InstanceKlass*, mtClass>(table_size, (int)sizeof(DictionaryEntry)),
  48     _resizable(resizable), _needs_resizing(false), _loader_data(loader_data) {
  49 };
  50 
  51 
  52 Dictionary::Dictionary(ClassLoaderData* loader_data,
  53                        int table_size, HashtableBucket<mtClass>* t,
  54                        int number_of_entries, bool resizable)
  55   : Hashtable<InstanceKlass*, mtClass>(table_size, (int)sizeof(DictionaryEntry), t, number_of_entries),
  56     _resizable(resizable), _needs_resizing(false), _loader_data(loader_data) {
  57 };
  58 
  59 Dictionary::~Dictionary() {
  60   DictionaryEntry* probe = NULL;
  61   for (int index = 0; index < table_size(); index++) {
  62     for (DictionaryEntry** p = bucket_addr(index); *p != NULL; ) {
  63       probe = *p;
  64       *p = probe->next();
  65       free_entry(probe);
  66     }
  67   }
  68   assert(number_of_entries() == 0, "should have removed all entries");
  69   assert(new_entry_free_list() == NULL, "entry present on Dictionary's free list");
  70   free_buckets();
  71 }
  72 
  73 DictionaryEntry* Dictionary::new_entry(unsigned int hash, InstanceKlass* klass) {
  74   DictionaryEntry* entry = (DictionaryEntry*)Hashtable<InstanceKlass*, mtClass>::allocate_new_entry(hash, klass);
  75   entry->set_pd_set(NULL);
  76   assert(klass->is_instance_klass(), "Must be");
  77   return entry;
  78 }
  79 
  80 
  81 void Dictionary::free_entry(DictionaryEntry* entry) {
  82   // avoid recursion when deleting linked list
  83   // pd_set is accessed during a safepoint.
  84   while (entry->pd_set() != NULL) {
  85     ProtectionDomainEntry* to_delete = entry->pd_set();
  86     entry->set_pd_set(to_delete->next());
  87     delete to_delete;
  88   }
  89   // Unlink from the Hashtable prior to freeing
  90   unlink_entry(entry);
  91   FREE_C_HEAP_ARRAY(char, entry);
  92 }
  93 
  94 const int _resize_load_trigger = 5;       // load factor that will trigger the resize
  95 const double _resize_factor    = 2.0;     // by how much we will resize using current number of entries
  96 const int _resize_max_size     = 40423;   // the max dictionary size allowed
  97 const int _primelist[] = {107, 1009, 2017, 4049, 5051, 10103, 20201, _resize_max_size};
  98 const int _prime_array_size = sizeof(_primelist)/sizeof(int);
  99 
 100 // Calculate next "good" dictionary size based on requested count
 101 static int calculate_dictionary_size(int requested) {
 102   int newsize = _primelist[0];
 103   int index = 0;
 104   for (newsize = _primelist[index]; index < (_prime_array_size - 1);
 105        newsize = _primelist[++index]) {
 106     if (requested <= newsize) {
 107       break;
 108     }
 109   }
 110   return newsize;
 111 }
 112 
 113 bool Dictionary::does_any_dictionary_needs_resizing() {
 114   return Dictionary::_some_dictionary_needs_resizing;
 115 }
 116 
 117 void Dictionary::check_if_needs_resize() {
 118   if (_resizable == true) {
 119     if (number_of_entries() > (_resize_load_trigger*table_size())) {
 120       _needs_resizing = true;
 121       Dictionary::_some_dictionary_needs_resizing = true;
 122     }
 123   }
 124 }
 125 
 126 bool Dictionary::resize_if_needed() {
 127   int desired_size = 0;
 128   if (_needs_resizing == true) {
 129     desired_size = calculate_dictionary_size((int)(_resize_factor*number_of_entries()));
 130     if (desired_size >= _resize_max_size) {
 131       desired_size = _resize_max_size;
 132       // We have reached the limit, turn resizing off
 133       _resizable = false;
 134     }
 135     if ((desired_size != 0) && (desired_size != table_size())) {
 136       if (!resize(desired_size)) {
 137         // Something went wrong, turn resizing off
 138         _resizable = false;
 139       }
 140     }
 141   }
 142 
 143   _needs_resizing = false;
 144   Dictionary::_some_dictionary_needs_resizing = false;
 145 
 146   return (desired_size != 0);
 147 }
 148 
 149 bool DictionaryEntry::contains_protection_domain(oop protection_domain) const {
 150 #ifdef ASSERT
 151   if (oopDesc::equals(protection_domain, instance_klass()->protection_domain())) {
 152     // Ensure this doesn't show up in the pd_set (invariant)
 153     bool in_pd_set = false;
 154     for (ProtectionDomainEntry* current = pd_set_acquire();
 155                                 current != NULL;
 156                                 current = current->next()) {
 157       if (oopDesc::equals(current->object_no_keepalive(), protection_domain)) {
 158         in_pd_set = true;
 159         break;
 160       }
 161     }
 162     if (in_pd_set) {
 163       assert(false, "A klass's protection domain should not show up "
 164                     "in its sys. dict. PD set");
 165     }
 166   }
 167 #endif /* ASSERT */
 168 
 169   if (oopDesc::equals(protection_domain, instance_klass()->protection_domain())) {
 170     // Succeeds trivially
 171     return true;
 172   }
 173 
 174   for (ProtectionDomainEntry* current = pd_set_acquire();
 175                               current != NULL;
 176                               current = current->next()) {
 177     if (oopDesc::equals(current->object_no_keepalive(), protection_domain)) return true;
 178   }
 179   return false;
 180 }
 181 
 182 
 183 void DictionaryEntry::add_protection_domain(Dictionary* dict, Handle protection_domain) {
 184   assert_locked_or_safepoint(SystemDictionary_lock);
 185   if (!contains_protection_domain(protection_domain())) {
 186     ProtectionDomainCacheEntry* entry = SystemDictionary::cache_get(protection_domain);
 187     ProtectionDomainEntry* new_head =
 188                 new ProtectionDomainEntry(entry, pd_set());
 189     // Warning: Preserve store ordering.  The SystemDictionary is read
 190     //          without locks.  The new ProtectionDomainEntry must be
 191     //          complete before other threads can be allowed to see it
 192     //          via a store to _pd_set.
 193     release_set_pd_set(new_head);
 194   }
 195   LogTarget(Trace, protectiondomain) lt;
 196   if (lt.is_enabled()) {
 197     LogStream ls(lt);
 198     print_count(&ls);
 199   }
 200 }
 201 
 202 // During class loading we may have cached a protection domain that has
 203 // since been unreferenced, so this entry should be cleared.
 204 void Dictionary::clean_cached_protection_domains(DictionaryEntry* probe) {
 205   assert_locked_or_safepoint(SystemDictionary_lock);
 206 
 207   ProtectionDomainEntry* current = probe->pd_set();
 208   ProtectionDomainEntry* prev = NULL;
 209   while (current != NULL) {
 210     if (current->object_no_keepalive() == NULL) {
 211       LogTarget(Debug, protectiondomain) lt;
 212       if (lt.is_enabled()) {
 213         ResourceMark rm;
 214         // Print out trace information
 215         LogStream ls(lt);
 216         ls.print_cr("PD in set is not alive:");
 217         ls.print("class loader: "); loader_data()->class_loader()->print_value_on(&ls);
 218         ls.print(" loading: "); probe->instance_klass()->print_value_on(&ls);
 219         ls.cr();
 220       }
 221       if (probe->pd_set() == current) {
 222         probe->set_pd_set(current->next());
 223       } else {
 224         assert(prev != NULL, "should be set by alive entry");
 225         prev->set_next(current->next());
 226       }
 227       ProtectionDomainEntry* to_delete = current;
 228       current = current->next();
 229       delete to_delete;
 230     } else {
 231       prev = current;
 232       current = current->next();
 233     }
 234   }
 235 }
 236 
 237 
 238 void Dictionary::do_unloading() {
 239   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 240 
 241   // The NULL class loader doesn't initiate loading classes from other class loaders
 242   if (loader_data() == ClassLoaderData::the_null_class_loader_data()) {
 243     return;
 244   }
 245 
 246   // Remove unloaded entries and classes from this dictionary
 247   DictionaryEntry* probe = NULL;
 248   for (int index = 0; index < table_size(); index++) {
 249     for (DictionaryEntry** p = bucket_addr(index); *p != NULL; ) {
 250       probe = *p;
 251       InstanceKlass* ik = probe->instance_klass();
 252       ClassLoaderData* k_def_class_loader_data = ik->class_loader_data();
 253 
 254       // If the klass that this loader initiated is dead,
 255       // (determined by checking the defining class loader)
 256       // remove this entry.
 257       if (k_def_class_loader_data->is_unloading()) {
 258         assert(k_def_class_loader_data != loader_data(),
 259                "cannot have live defining loader and unreachable klass");
 260         *p = probe->next();
 261         free_entry(probe);
 262         continue;
 263       }
 264       // Clean pd_set
 265       clean_cached_protection_domains(probe);
 266       p = probe->next_addr();
 267     }
 268   }
 269 }
 270 
 271 //   Just the classes from defining class loaders
 272 void Dictionary::classes_do(void f(InstanceKlass*)) {
 273   for (int index = 0; index < table_size(); index++) {
 274     for (DictionaryEntry* probe = bucket(index);
 275                           probe != NULL;
 276                           probe = probe->next()) {
 277       InstanceKlass* k = probe->instance_klass();
 278       if (loader_data() == k->class_loader_data()) {
 279         f(k);
 280       }
 281     }
 282   }
 283 }
 284 
 285 // Added for initialize_itable_for_klass to handle exceptions
 286 //   Just the classes from defining class loaders
 287 void Dictionary::classes_do(void f(InstanceKlass*, TRAPS), TRAPS) {
 288   for (int index = 0; index < table_size(); index++) {
 289     for (DictionaryEntry* probe = bucket(index);
 290                           probe != NULL;
 291                           probe = probe->next()) {
 292       InstanceKlass* k = probe->instance_klass();
 293       if (loader_data() == k->class_loader_data()) {
 294         f(k, CHECK);
 295       }
 296     }
 297   }
 298 }
 299 
 300 // All classes, and their class loaders, including initiating class loaders
 301 void Dictionary::all_entries_do(KlassClosure* closure) {
 302   for (int index = 0; index < table_size(); index++) {
 303     for (DictionaryEntry* probe = bucket(index);
 304                           probe != NULL;
 305                           probe = probe->next()) {
 306       InstanceKlass* k = probe->instance_klass();
 307       closure->do_klass(k);
 308     }
 309   }
 310 }
 311 
 312 // Used to scan and relocate the classes during CDS archive dump.
 313 void Dictionary::classes_do(MetaspaceClosure* it) {
 314   assert(DumpSharedSpaces, "dump-time only");
 315   for (int index = 0; index < table_size(); index++) {
 316     for (DictionaryEntry* probe = bucket(index);
 317                           probe != NULL;
 318                           probe = probe->next()) {
 319       it->push(probe->klass_addr());
 320     }
 321   }
 322 }
 323 
 324 
 325 
 326 // Add a loaded class to the 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(unsigned int hash, Symbol* class_name,
 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 
 338   DictionaryEntry* entry = new_entry(hash, obj);
 339   int index = hash_to_index(hash);
 340   add_entry(index, entry);
 341   check_if_needs_resize();
 342 }
 343 
 344 
 345 // This routine does not lock the dictionary.
 346 //
 347 // Since readers don't hold a lock, we must make sure that system
 348 // dictionary entries are only removed at a safepoint (when only one
 349 // thread is running), and are added to in a safe way (all links must
 350 // be updated in an MT-safe manner).
 351 //
 352 // Callers should be aware that an entry could be added just after
 353 // _buckets[index] is read here, so the caller will not see the new entry.
 354 DictionaryEntry* Dictionary::get_entry(int index, unsigned int hash,
 355                                        Symbol* class_name) {
 356   for (DictionaryEntry* entry = bucket(index);
 357                         entry != NULL;
 358                         entry = entry->next()) {
 359     if (entry->hash() == hash && entry->equals(class_name)) {
 360       return entry;
 361     }
 362   }
 363   return NULL;
 364 }
 365 
 366 
 367 InstanceKlass* Dictionary::find(unsigned int hash, Symbol* name,
 368                                 Handle protection_domain) {
 369   NoSafepointVerifier nsv;
 370 
 371   int index = hash_to_index(hash);
 372   DictionaryEntry* entry = get_entry(index, hash, name);
 373   if (entry != NULL && entry->is_valid_protection_domain(protection_domain)) {
 374     return entry->instance_klass();
 375   } else {
 376     return NULL;
 377   }
 378 }
 379 
 380 
 381 InstanceKlass* Dictionary::find_class(int index, unsigned int hash,
 382                                       Symbol* name) {
 383   assert_locked_or_safepoint(SystemDictionary_lock);
 384   assert (index == index_for(name), "incorrect index?");
 385 
 386   DictionaryEntry* entry = get_entry(index, hash, name);
 387   return (entry != NULL) ? entry->instance_klass() : NULL;
 388 }
 389 
 390 
 391 void Dictionary::add_protection_domain(int index, unsigned int hash,
 392                                        InstanceKlass* klass,
 393                                        Handle protection_domain,
 394                                        TRAPS) {
 395   Symbol*  klass_name = klass->name();
 396   DictionaryEntry* entry = get_entry(index, hash, klass_name);
 397 
 398   assert(entry != NULL,"entry must be present, we just created it");
 399   assert(protection_domain() != NULL,
 400          "real protection domain should be present");
 401 
 402   entry->add_protection_domain(this, protection_domain);
 403 
 404 #ifdef ASSERT
 405   assert(loader_data() != ClassLoaderData::the_null_class_loader_data(), "doesn't make sense");
 406 #endif
 407 
 408   assert(entry->contains_protection_domain(protection_domain()),
 409          "now protection domain should be present");
 410 }
 411 
 412 
 413 bool Dictionary::is_valid_protection_domain(unsigned int hash,
 414                                             Symbol* name,
 415                                             Handle protection_domain) {
 416   int index = hash_to_index(hash);
 417   DictionaryEntry* entry = get_entry(index, hash, name);
 418   return entry->is_valid_protection_domain(protection_domain);
 419 }
 420 
 421 SymbolPropertyTable::SymbolPropertyTable(int table_size)
 422   : Hashtable<Symbol*, mtSymbol>(table_size, sizeof(SymbolPropertyEntry))
 423 {
 424 }
 425 SymbolPropertyTable::SymbolPropertyTable(int table_size, HashtableBucket<mtSymbol>* t,
 426                                          int number_of_entries)
 427   : Hashtable<Symbol*, mtSymbol>(table_size, sizeof(SymbolPropertyEntry), t, number_of_entries)
 428 {
 429 }
 430 
 431 
 432 SymbolPropertyEntry* SymbolPropertyTable::find_entry(int index, unsigned int hash,
 433                                                      Symbol* sym,
 434                                                      intptr_t sym_mode) {
 435   assert(index == index_for(sym, sym_mode), "incorrect index?");
 436   for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
 437     if (p->hash() == hash && p->symbol() == sym && p->symbol_mode() == sym_mode) {
 438       return p;
 439     }
 440   }
 441   return NULL;
 442 }
 443 
 444 
 445 SymbolPropertyEntry* SymbolPropertyTable::add_entry(int index, unsigned int hash,
 446                                                     Symbol* sym, intptr_t sym_mode) {
 447   assert_locked_or_safepoint(SystemDictionary_lock);
 448   assert(index == index_for(sym, sym_mode), "incorrect index?");
 449   assert(find_entry(index, hash, sym, sym_mode) == NULL, "no double entry");
 450 
 451   SymbolPropertyEntry* p = new_entry(hash, sym, sym_mode);
 452   Hashtable<Symbol*, mtSymbol>::add_entry(index, p);
 453   return p;
 454 }
 455 
 456 void SymbolPropertyTable::oops_do(OopClosure* f) {
 457   for (int index = 0; index < table_size(); index++) {
 458     for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
 459       if (p->method_type() != NULL) {
 460         f->do_oop(p->method_type_addr());
 461       }
 462     }
 463   }
 464 }
 465 
 466 void SymbolPropertyTable::methods_do(void f(Method*)) {
 467   for (int index = 0; index < table_size(); index++) {
 468     for (SymbolPropertyEntry* p = bucket(index); p != NULL; p = p->next()) {
 469       Method* prop = p->method();
 470       if (prop != NULL) {
 471         f((Method*)prop);
 472       }
 473     }
 474   }
 475 }
 476 
 477 
 478 // ----------------------------------------------------------------------------
 479 
 480 void Dictionary::print_on(outputStream* st) const {
 481   ResourceMark rm;
 482 
 483   assert(loader_data() != NULL, "loader data should not be null");
 484   st->print_cr("Java dictionary (table_size=%d, classes=%d, resizable=%s)",
 485                table_size(), number_of_entries(), BOOL_TO_STR(_resizable));
 486   st->print_cr("^ indicates that initiating loader is different from defining loader");
 487 
 488   for (int index = 0; index < table_size(); index++) {
 489     for (DictionaryEntry* probe = bucket(index);
 490                           probe != NULL;
 491                           probe = probe->next()) {
 492       Klass* e = probe->instance_klass();
 493       bool is_defining_class =
 494          (loader_data() == e->class_loader_data());
 495       st->print("%4d: %s%s", index, is_defining_class ? " " : "^", e->external_name());
 496       ClassLoaderData* cld = e->class_loader_data();
 497       if (!loader_data()->is_the_null_class_loader_data()) {
 498         // Class loader output for the dictionary for the null class loader data is
 499         // redundant and obvious.
 500         st->print(", ");
 501         cld->print_value_on(st);
 502       }
 503       st->cr();
 504     }
 505   }
 506   tty->cr();
 507 }
 508 
 509 void DictionaryEntry::verify() {
 510   Klass* e = instance_klass();
 511   guarantee(e->is_instance_klass(),
 512                           "Verify of dictionary failed");
 513   e->verify();
 514   verify_protection_domain_set();
 515 }
 516 
 517 void Dictionary::verify() {
 518   guarantee(number_of_entries() >= 0, "Verify of dictionary failed");
 519 
 520   ClassLoaderData* cld = loader_data();
 521   // class loader must be present;  a null class loader is the
 522   // boostrap loader
 523   guarantee(cld != NULL ||
 524             cld->class_loader() == NULL ||
 525             cld->class_loader()->is_instance(),
 526             "checking type of class_loader");
 527 
 528   ResourceMark rm;
 529   stringStream tempst;
 530   tempst.print("System Dictionary for %s class loader", cld->loader_name_and_id());
 531   verify_table<DictionaryEntry>(tempst.as_string());
 532 }