1 /*
   2  * Copyright (c) 1997, 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/altHashing.hpp"
  27 #include "classfile/compactHashtable.hpp"
  28 #include "classfile/javaClasses.inline.hpp"
  29 #include "classfile/stringTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "gc/shared/collectedHeap.hpp"
  32 #include "gc/shared/oopStorage.inline.hpp"
  33 #include "gc/shared/oopStorageParState.inline.hpp"
  34 #include "logging/log.hpp"
  35 #include "logging/logStream.hpp"
  36 #include "memory/allocation.inline.hpp"
  37 #include "memory/filemap.hpp"
  38 #include "memory/heapShared.inline.hpp"
  39 #include "memory/metaspaceShared.inline.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "memory/universe.hpp"
  42 #include "oops/access.inline.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "oops/typeArrayOop.inline.hpp"
  45 #include "oops/weakHandle.inline.hpp"
  46 #include "runtime/atomic.hpp"
  47 #include "runtime/handles.inline.hpp"
  48 #include "runtime/mutexLocker.hpp"
  49 #include "runtime/safepointVerifiers.hpp"
  50 #include "runtime/timerTrace.hpp"
  51 #include "runtime/interfaceSupport.inline.hpp"
  52 #include "services/diagnosticCommand.hpp"
  53 #include "utilities/concurrentHashTable.inline.hpp"
  54 #include "utilities/concurrentHashTableTasks.inline.hpp"
  55 #include "utilities/macros.hpp"
  56 
  57 // We prefer short chains of avg 2
  58 #define PREF_AVG_LIST_LEN   2
  59 // 2^24 is max size
  60 #define END_SIZE           24
  61 // If a chain gets to 32 something might be wrong
  62 #define REHASH_LEN         32
  63 // If we have as many dead items as 50% of the number of bucket
  64 #define CLEAN_DEAD_HIGH_WATER_MARK 0.5
  65 
  66 // --------------------------------------------------------------------------
  67 inline oop read_string_from_compact_hashtable(address base_address, u4 offset) {
  68   assert(sizeof(narrowOop) == sizeof(offset), "must be");
  69   narrowOop v = (narrowOop)offset;
  70   return HeapShared::decode_from_archive(v);
  71 }
  72 
  73 inline bool string_equals_compact_hashtable_entry(oop value, const jchar* key, int len) {
  74   return java_lang_String::equals(value, (jchar*)key, len);
  75 }
  76 
  77 static CompactHashtable<
  78   const jchar*, oop,
  79   read_string_from_compact_hashtable,
  80   string_equals_compact_hashtable_entry
  81 > _shared_table;
  82 
  83 // --------------------------------------------------------------------------
  84 StringTable* StringTable::_the_table = NULL;
  85 volatile bool StringTable::_shared_string_mapped = false;
  86 volatile bool StringTable::_alt_hash = false;
  87 
  88 static juint murmur_seed = 0;
  89 
  90 uintx hash_string(const jchar* s, int len, bool useAlt) {
  91   return  useAlt ?
  92     AltHashing::murmur3_32(murmur_seed, s, len) :
  93     java_lang_String::hash_code(s, len);
  94 }
  95 
  96 class StringTableConfig : public StringTableHash::BaseConfig {
  97  private:
  98  public:
  99   static uintx get_hash(WeakHandle<vm_string_table_data> const& value,
 100                         bool* is_dead) {
 101     EXCEPTION_MARK;
 102     oop val_oop = value.peek();
 103     if (val_oop == NULL) {
 104       *is_dead = true;
 105       return 0;
 106     }
 107     *is_dead = false;
 108     ResourceMark rm(THREAD);
 109     // All String oops are hashed as unicode
 110     int length;
 111     jchar* chars = java_lang_String::as_unicode_string(val_oop, length, THREAD);
 112     if (chars != NULL) {
 113       return hash_string(chars, length, StringTable::_alt_hash);
 114     }
 115     vm_exit_out_of_memory(length, OOM_MALLOC_ERROR, "get hash from oop");
 116     return 0;
 117   }
 118   // We use default allocation/deallocation but counted
 119   static void* allocate_node(size_t size,
 120                              WeakHandle<vm_string_table_data> const& value) {
 121     StringTable::item_added();
 122     return StringTableHash::BaseConfig::allocate_node(size, value);
 123   }
 124   static void free_node(void* memory,
 125                         WeakHandle<vm_string_table_data> const& value) {
 126     value.release();
 127     StringTableHash::BaseConfig::free_node(memory, value);
 128     StringTable::item_removed();
 129   }
 130 };
 131 
 132 class StringTableLookupJchar : StackObj {
 133  private:
 134   Thread* _thread;
 135   uintx _hash;
 136   int _len;
 137   const jchar* _str;
 138   Handle _found;
 139 
 140  public:
 141   StringTableLookupJchar(Thread* thread, uintx hash, const jchar* key, int len)
 142     : _thread(thread), _hash(hash), _len(len), _str(key) {
 143   }
 144   uintx get_hash() const {
 145     return _hash;
 146   }
 147   bool equals(WeakHandle<vm_string_table_data>* value, bool* is_dead) {
 148     oop val_oop = value->peek();
 149     if (val_oop == NULL) {
 150       // dead oop, mark this hash dead for cleaning
 151       *is_dead = true;
 152       return false;
 153     }
 154     bool equals = java_lang_String::equals(val_oop, (jchar*)_str, _len);
 155     if (!equals) {
 156       return false;
 157     }
 158     // Need to resolve weak handle and Handleize through possible safepoint.
 159      _found = Handle(_thread, value->resolve());
 160     return true;
 161   }
 162 };
 163 
 164 class StringTableLookupOop : public StackObj {
 165  private:
 166   Thread* _thread;
 167   uintx _hash;
 168   Handle _find;
 169   Handle _found;  // Might be a different oop with the same value that's already
 170                   // in the table, which is the point.
 171  public:
 172   StringTableLookupOop(Thread* thread, uintx hash, Handle handle)
 173     : _thread(thread), _hash(hash), _find(handle) { }
 174 
 175   uintx get_hash() const {
 176     return _hash;
 177   }
 178 
 179   bool equals(WeakHandle<vm_string_table_data>* value, bool* is_dead) {
 180     oop val_oop = value->peek();
 181     if (val_oop == NULL) {
 182       // dead oop, mark this hash dead for cleaning
 183       *is_dead = true;
 184       return false;
 185     }
 186     bool equals = java_lang_String::equals(_find(), val_oop);
 187     if (!equals) {
 188       return false;
 189     }
 190     // Need to resolve weak handle and Handleize through possible safepoint.
 191     _found = Handle(_thread, value->resolve());
 192     return true;
 193   }
 194 };
 195 
 196 static size_t ceil_log2(size_t val) {
 197   size_t ret;
 198   for (ret = 1; ((size_t)1 << ret) < val; ++ret);
 199   return ret;
 200 }
 201 
 202 StringTable::StringTable() : _local_table(NULL), _current_size(0), _has_work(0),
 203   _needs_rehashing(false), _weak_handles(NULL), _items_count(0), _uncleaned_items_count(0) {
 204   _weak_handles = new OopStorage("StringTable weak",
 205                                  StringTableWeakAlloc_lock,
 206                                  StringTableWeakActive_lock);
 207   size_t start_size_log_2 = ceil_log2(StringTableSize);
 208   _current_size = ((size_t)1) << start_size_log_2;
 209   log_trace(stringtable)("Start size: " SIZE_FORMAT " (" SIZE_FORMAT ")",
 210                          _current_size, start_size_log_2);
 211   _local_table = new StringTableHash(start_size_log_2, END_SIZE, REHASH_LEN);
 212 }
 213 
 214 size_t StringTable::item_added() {
 215   return Atomic::add((size_t)1, &(the_table()->_items_count));
 216 }
 217 
 218 size_t StringTable::add_items_count_to_clean(size_t ndead) {
 219   size_t total = Atomic::add((size_t)ndead, &(the_table()->_uncleaned_items_count));
 220   log_trace(stringtable)(
 221      "Uncleaned items:" SIZE_FORMAT " added: " SIZE_FORMAT " total:" SIZE_FORMAT,
 222      the_table()->_uncleaned_items_count, ndead, total);
 223   return total;
 224 }
 225 
 226 void StringTable::item_removed() {
 227   Atomic::add((size_t)-1, &(the_table()->_items_count));
 228 }
 229 
 230 double StringTable::get_load_factor() {
 231   return (double)_items_count/_current_size;
 232 }
 233 
 234 double StringTable::get_dead_factor() {
 235   return (double)_uncleaned_items_count/_current_size;
 236 }
 237 
 238 size_t StringTable::table_size() {
 239   return ((size_t)1) << _local_table->get_size_log2(Thread::current());
 240 }
 241 
 242 void StringTable::trigger_concurrent_work() {
 243   MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
 244   the_table()->_has_work = true;
 245   Service_lock->notify_all();
 246 }
 247 
 248 // Probing
 249 oop StringTable::lookup(Symbol* symbol) {
 250   ResourceMark rm;
 251   int length;
 252   jchar* chars = symbol->as_unicode(length);
 253   return lookup(chars, length);
 254 }
 255 
 256 oop StringTable::lookup(jchar* name, int len) {
 257   unsigned int hash = java_lang_String::hash_code(name, len);
 258   oop string = StringTable::the_table()->lookup_shared(name, len, hash);
 259   if (string != NULL) {
 260     return string;
 261   }
 262   if (StringTable::_alt_hash) {
 263     hash = hash_string(name, len, true);
 264   }
 265   return StringTable::the_table()->do_lookup(name, len, hash);
 266 }
 267 
 268 class StringTableGet : public StackObj {
 269   Thread* _thread;
 270   Handle  _return;
 271  public:
 272   StringTableGet(Thread* thread) : _thread(thread) {}
 273   void operator()(WeakHandle<vm_string_table_data>* val) {
 274     oop result = val->resolve();
 275     assert(result != NULL, "Result should be reachable");
 276     _return = Handle(_thread, result);
 277   }
 278   oop get_res_oop() {
 279     return _return();
 280   }
 281 };
 282 
 283 oop StringTable::do_lookup(jchar* name, int len, uintx hash) {
 284   Thread* thread = Thread::current();
 285   StringTableLookupJchar lookup(thread, hash, name, len);
 286   StringTableGet stg(thread);
 287   bool rehash_warning;
 288   _local_table->get(thread, lookup, stg, &rehash_warning);
 289   if (rehash_warning) {
 290     _needs_rehashing = true;
 291   }
 292   return stg.get_res_oop();
 293 }
 294 
 295 // Interning
 296 oop StringTable::intern(Symbol* symbol, TRAPS) {
 297   if (symbol == NULL) return NULL;
 298   ResourceMark rm(THREAD);
 299   int length;
 300   jchar* chars = symbol->as_unicode(length);
 301   Handle string;
 302   oop result = intern(string, chars, length, CHECK_NULL);
 303   return result;
 304 }
 305 
 306 oop StringTable::intern(oop string, TRAPS) {
 307   if (string == NULL) return NULL;
 308   ResourceMark rm(THREAD);
 309   int length;
 310   Handle h_string (THREAD, string);
 311   jchar* chars = java_lang_String::as_unicode_string(string, length,
 312                                                      CHECK_NULL);
 313   oop result = intern(h_string, chars, length, CHECK_NULL);
 314   return result;
 315 }
 316 
 317 oop StringTable::intern(const char* utf8_string, TRAPS) {
 318   if (utf8_string == NULL) return NULL;
 319   ResourceMark rm(THREAD);
 320   int length = UTF8::unicode_length(utf8_string);
 321   jchar* chars = NEW_RESOURCE_ARRAY(jchar, length);
 322   UTF8::convert_to_unicode(utf8_string, chars, length);
 323   Handle string;
 324   oop result = intern(string, chars, length, CHECK_NULL);
 325   return result;
 326 }
 327 
 328 oop StringTable::intern(Handle string_or_null_h, jchar* name, int len, TRAPS) {
 329   // shared table always uses java_lang_String::hash_code
 330   unsigned int hash = java_lang_String::hash_code(name, len);
 331   oop found_string = StringTable::the_table()->lookup_shared(name, len, hash);
 332   if (found_string != NULL) {
 333     return found_string;
 334   }
 335   if (StringTable::_alt_hash) {
 336     hash = hash_string(name, len, true);
 337   }
 338   return StringTable::the_table()->do_intern(string_or_null_h, name, len,
 339                                              hash, CHECK_NULL);
 340 }
 341 
 342 class StringTableCreateEntry : public StackObj {
 343  private:
 344    Thread* _thread;
 345    Handle  _return;
 346    Handle  _store;
 347  public:
 348   StringTableCreateEntry(Thread* thread, Handle store)
 349     : _thread(thread), _store(store) {}
 350 
 351   WeakHandle<vm_string_table_data> operator()() { // No dups found
 352     WeakHandle<vm_string_table_data> wh =
 353       WeakHandle<vm_string_table_data>::create(_store);
 354     return wh;
 355   }
 356   void operator()(bool inserted, WeakHandle<vm_string_table_data>* val) {
 357     oop result = val->resolve();
 358     assert(result != NULL, "Result should be reachable");
 359     _return = Handle(_thread, result);
 360   }
 361   oop get_return() const {
 362     return _return();
 363   }
 364 };
 365 
 366 oop StringTable::do_intern(Handle string_or_null_h, jchar* name,
 367                            int len, uintx hash, TRAPS) {
 368   HandleMark hm(THREAD);  // cleanup strings created
 369   Handle string_h;
 370 
 371   if (!string_or_null_h.is_null()) {
 372     string_h = string_or_null_h;
 373   } else {
 374     string_h = java_lang_String::create_from_unicode(name, len, CHECK_NULL);
 375   }
 376 
 377   // Deduplicate the string before it is interned. Note that we should never
 378   // deduplicate a string after it has been interned. Doing so will counteract
 379   // compiler optimizations done on e.g. interned string literals.
 380   Universe::heap()->deduplicate_string(string_h());
 381 
 382   assert(java_lang_String::equals(string_h(), name, len),
 383          "string must be properly initialized");
 384   assert(len == java_lang_String::length(string_h()), "Must be same length");
 385   StringTableLookupOop lookup(THREAD, hash, string_h);
 386   StringTableCreateEntry stc(THREAD, string_h);
 387 
 388   bool rehash_warning;
 389   _local_table->get_insert_lazy(THREAD, lookup, stc, stc, &rehash_warning);
 390   if (rehash_warning) {
 391     _needs_rehashing = true;
 392   }
 393   return stc.get_return();
 394 }
 395 
 396 // GC support
 397 class StringTableIsAliveCounter : public BoolObjectClosure {
 398   BoolObjectClosure* _real_boc;
 399  public:
 400   size_t _count;
 401   size_t _count_total;
 402   StringTableIsAliveCounter(BoolObjectClosure* boc) : _real_boc(boc), _count(0),
 403                                                       _count_total(0) {}
 404   bool do_object_b(oop obj) {
 405     bool ret = _real_boc->do_object_b(obj);
 406     if (!ret) {
 407       ++_count;
 408     }
 409     ++_count_total;
 410     return ret;
 411   }
 412 };
 413 
 414 void StringTable::unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f,
 415                                     size_t* processed, size_t* removed) {
 416   DoNothingClosure dnc;
 417   assert(is_alive != NULL, "No closure");
 418   StringTableIsAliveCounter stiac(is_alive);
 419   OopClosure* tmp = f != NULL ? f : &dnc;
 420 
 421   StringTable::the_table()->_weak_handles->weak_oops_do(&stiac, tmp);
 422 
 423   // This is the serial case without ParState.
 424   // Just set the correct number and check for a cleaning phase.
 425   the_table()->_uncleaned_items_count = stiac._count;
 426   StringTable::the_table()->check_concurrent_work();
 427 
 428   if (processed != NULL) {
 429     *processed = stiac._count_total;
 430   }
 431   if (removed != NULL) {
 432     *removed = stiac._count;
 433   }
 434 }
 435 
 436 void StringTable::oops_do(OopClosure* f) {
 437   assert(f != NULL, "No closure");
 438   StringTable::the_table()->_weak_handles->oops_do(f);
 439 }
 440 
 441 void StringTable::possibly_parallel_unlink(
 442    OopStorage::ParState<false, false>* _par_state_string, BoolObjectClosure* cl,
 443    size_t* processed, size_t* removed)
 444 {
 445   DoNothingClosure dnc;
 446   assert(cl != NULL, "No closure");
 447   StringTableIsAliveCounter stiac(cl);
 448 
 449   _par_state_string->weak_oops_do(&stiac, &dnc);
 450 
 451   // Accumulate the dead strings.
 452   the_table()->add_items_count_to_clean(stiac._count);
 453 
 454   *processed = stiac._count_total;
 455   *removed = stiac._count;
 456 }
 457 
 458 void StringTable::possibly_parallel_oops_do(
 459    OopStorage::ParState<false /* concurrent */, false /* const */>*
 460    _par_state_string, OopClosure* f)
 461 {
 462   assert(f != NULL, "No closure");
 463   _par_state_string->oops_do(f);
 464 }
 465 
 466 // Concurrent work
 467 void StringTable::grow(JavaThread* jt) {
 468   StringTableHash::GrowTask gt(_local_table);
 469   if (!gt.prepare(jt)) {
 470     return;
 471   }
 472   log_trace(stringtable)("Started to grow");
 473   {
 474     TraceTime timer("Grow", TRACETIME_LOG(Debug, stringtable, perf));
 475     while (gt.do_task(jt)) {
 476       gt.pause(jt);
 477       {
 478         ThreadBlockInVM tbivm(jt);
 479       }
 480       gt.cont(jt);
 481     }
 482   }
 483   gt.done(jt);
 484   _current_size = table_size();
 485   log_debug(stringtable)("Grown to size:" SIZE_FORMAT, _current_size);
 486 }
 487 
 488 struct StringTableDoDelete : StackObj {
 489   void operator()(WeakHandle<vm_string_table_data>* val) {
 490     /* do nothing */
 491   }
 492 };
 493 
 494 struct StringTableDeleteCheck : StackObj {
 495   long _count;
 496   long _item;
 497   StringTableDeleteCheck() : _count(0), _item(0) {}
 498   bool operator()(WeakHandle<vm_string_table_data>* val) {
 499     ++_item;
 500     oop tmp = val->peek();
 501     if (tmp == NULL) {
 502       ++_count;
 503       return true;
 504     } else {
 505       return false;
 506     }
 507   }
 508 };
 509 
 510 void StringTable::clean_dead_entries(JavaThread* jt) {
 511   StringTableHash::BulkDeleteTask bdt(_local_table);
 512   if (!bdt.prepare(jt)) {
 513     return;
 514   }
 515 
 516   StringTableDeleteCheck stdc;
 517   StringTableDoDelete stdd;
 518   {
 519     TraceTime timer("Clean", TRACETIME_LOG(Debug, stringtable, perf));
 520     while(bdt.do_task(jt, stdc, stdd)) {
 521       bdt.pause(jt);
 522       {
 523         ThreadBlockInVM tbivm(jt);
 524       }
 525       bdt.cont(jt);
 526     }
 527     bdt.done(jt);
 528   }
 529   log_debug(stringtable)("Cleaned %ld of %ld", stdc._count, stdc._item);
 530 }
 531 
 532 void StringTable::check_concurrent_work() {
 533   if (_has_work) {
 534     return;
 535   }
 536 
 537   double load_factor = StringTable::get_load_factor();
 538   double dead_factor = StringTable::get_dead_factor();
 539   // We should clean/resize if we have more dead than alive,
 540   // more items than preferred load factor or
 541   // more dead items than water mark.
 542   if ((dead_factor > load_factor) ||
 543       (load_factor > PREF_AVG_LIST_LEN) ||
 544       (dead_factor > CLEAN_DEAD_HIGH_WATER_MARK)) {
 545     log_debug(stringtable)("Concurrent work triggered, live factor:%g dead factor:%g",
 546                            load_factor, dead_factor);
 547     trigger_concurrent_work();
 548   }
 549 }
 550 
 551 void StringTable::concurrent_work(JavaThread* jt) {
 552   _has_work = false;
 553   double load_factor = get_load_factor();
 554   log_debug(stringtable, perf)("Concurrent work, live factor: %g", load_factor);
 555   // We prefer growing, since that also removes dead items
 556   if (load_factor > PREF_AVG_LIST_LEN && !_local_table->is_max_size_reached()) {
 557     grow(jt);
 558   } else {
 559     clean_dead_entries(jt);
 560   }
 561 }
 562 
 563 void StringTable::do_concurrent_work(JavaThread* jt) {
 564   StringTable::the_table()->concurrent_work(jt);
 565 }
 566 
 567 // Rehash
 568 bool StringTable::do_rehash() {
 569   if (!_local_table->is_safepoint_safe()) {
 570     return false;
 571   }
 572 
 573   // We use max size
 574   StringTableHash* new_table = new StringTableHash(END_SIZE, END_SIZE, REHASH_LEN);
 575   // Use alt hash from now on
 576   _alt_hash = true;
 577   if (!_local_table->try_move_nodes_to(Thread::current(), new_table)) {
 578     _alt_hash = false;
 579     delete new_table;
 580     return false;
 581   }
 582 
 583   // free old table
 584   delete _local_table;
 585   _local_table = new_table;
 586 
 587   return true;
 588 }
 589 
 590 void StringTable::try_rehash_table() {
 591   static bool rehashed = false;
 592   log_debug(stringtable)("Table imbalanced, rehashing called.");
 593 
 594   // Grow instead of rehash.
 595   if (get_load_factor() > PREF_AVG_LIST_LEN &&
 596       !_local_table->is_max_size_reached()) {
 597     log_debug(stringtable)("Choosing growing over rehashing.");
 598     trigger_concurrent_work();
 599     _needs_rehashing = false;
 600     return;
 601   }
 602   // Already rehashed.
 603   if (rehashed) {
 604     log_warning(stringtable)("Rehashing already done, still long lists.");
 605     trigger_concurrent_work();
 606     _needs_rehashing = false;
 607     return;
 608   }
 609 
 610   murmur_seed = AltHashing::compute_seed();
 611   {
 612     if (do_rehash()) {
 613       rehashed = true;
 614     } else {
 615       log_info(stringtable)("Resizes in progress rehashing skipped.");
 616     }
 617   }
 618   _needs_rehashing = false;
 619 }
 620 
 621 void StringTable::rehash_table() {
 622   StringTable::the_table()->try_rehash_table();
 623 }
 624 
 625 // Statistics
 626 static int literal_size(oop obj) {
 627   // NOTE: this would over-count if (pre-JDK8)
 628   // java_lang_Class::has_offset_field() is true and the String.value array is
 629   // shared by several Strings. However, starting from JDK8, the String.value
 630   // array is not shared anymore.
 631   if (obj == NULL) {
 632     return 0;
 633   } else if (obj->klass() == SystemDictionary::String_klass()) {
 634     return (obj->size() + java_lang_String::value(obj)->size()) * HeapWordSize;
 635   } else {
 636     return obj->size();
 637   }
 638 }
 639 
 640 struct SizeFunc : StackObj {
 641   size_t operator()(WeakHandle<vm_string_table_data>* val) {
 642     oop s = val->peek();
 643     if (s == NULL) {
 644       // Dead
 645       return 0;
 646     }
 647     return literal_size(s);
 648   };
 649 };
 650 
 651 void StringTable::print_table_statistics(outputStream* st,
 652                                          const char* table_name) {
 653   SizeFunc sz;
 654   _local_table->statistics_to(Thread::current(), sz, st, table_name);
 655 }
 656 
 657 // Verification
 658 class VerifyStrings : StackObj {
 659  public:
 660   bool operator()(WeakHandle<vm_string_table_data>* val) {
 661     oop s = val->peek();
 662     if (s != NULL) {
 663       assert(java_lang_String::length(s) >= 0, "Length on string must work.");
 664     }
 665     return true;
 666   };
 667 };
 668 
 669 // This verification is part of Universe::verify() and needs to be quick.
 670 void StringTable::verify() {
 671   Thread* thr = Thread::current();
 672   VerifyStrings vs;
 673   if (!the_table()->_local_table->try_scan(thr, vs)) {
 674     log_info(stringtable)("verify unavailable at this moment");
 675   }
 676 }
 677 
 678 // Verification and comp
 679 class VerifyCompStrings : StackObj {
 680   GrowableArray<oop>* _oops;
 681  public:
 682   size_t _errors;
 683   VerifyCompStrings(GrowableArray<oop>* oops) : _oops(oops), _errors(0) {}
 684   bool operator()(WeakHandle<vm_string_table_data>* val) {
 685     oop s = val->resolve();
 686     if (s == NULL) {
 687       return true;
 688     }
 689     int len = _oops->length();
 690     for (int i = 0; i < len; i++) {
 691       bool eq = java_lang_String::equals(s, _oops->at(i));
 692       assert(!eq, "Duplicate strings");
 693       if (eq) {
 694         _errors++;
 695       }
 696     }
 697     _oops->push(s);
 698     return true;
 699   };
 700 };
 701 
 702 size_t StringTable::verify_and_compare_entries() {
 703   Thread* thr = Thread::current();
 704   GrowableArray<oop>* oops =
 705     new (ResourceObj::C_HEAP, mtInternal)
 706       GrowableArray<oop>((int)the_table()->_current_size, true);
 707 
 708   VerifyCompStrings vcs(oops);
 709   if (!the_table()->_local_table->try_scan(thr, vcs)) {
 710     log_info(stringtable)("verify unavailable at this moment");
 711   }
 712   delete oops;
 713   return vcs._errors;
 714 }
 715 
 716 // Dumping
 717 class PrintString : StackObj {
 718   Thread* _thr;
 719   outputStream* _st;
 720  public:
 721   PrintString(Thread* thr, outputStream* st) : _thr(thr), _st(st) {}
 722   bool operator()(WeakHandle<vm_string_table_data>* val) {
 723     oop s = val->peek();
 724     if (s == NULL) {
 725       return true;
 726     }
 727     typeArrayOop value     = java_lang_String::value_no_keepalive(s);
 728     int          length    = java_lang_String::length(s);
 729     bool         is_latin1 = java_lang_String::is_latin1(s);
 730 
 731     if (length <= 0) {
 732       _st->print("%d: ", length);
 733     } else {
 734       ResourceMark rm(_thr);
 735       int utf8_length = length;
 736       char* utf8_string;
 737 
 738       if (!is_latin1) {
 739         jchar* chars = value->char_at_addr(0);
 740         utf8_string = UNICODE::as_utf8(chars, utf8_length);
 741       } else {
 742         jbyte* bytes = value->byte_at_addr(0);
 743         utf8_string = UNICODE::as_utf8(bytes, utf8_length);
 744       }
 745 
 746       _st->print("%d: ", utf8_length);
 747       HashtableTextDump::put_utf8(_st, utf8_string, utf8_length);
 748     }
 749     _st->cr();
 750     return true;
 751   };
 752 };
 753 
 754 void StringTable::dump(outputStream* st, bool verbose) {
 755   if (!verbose) {
 756     the_table()->print_table_statistics(st, "StringTable");
 757   } else {
 758     Thread* thr = Thread::current();
 759     ResourceMark rm(thr);
 760     st->print_cr("VERSION: 1.1");
 761     PrintString ps(thr, st);
 762     if (!the_table()->_local_table->try_scan(thr, ps)) {
 763       st->print_cr("dump unavailable at this moment");
 764     }
 765   }
 766 }
 767 
 768 // Utility for dumping strings
 769 StringtableDCmd::StringtableDCmd(outputStream* output, bool heap) :
 770                                  DCmdWithParser(output, heap),
 771   _verbose("-verbose", "Dump the content of each string in the table",
 772            "BOOLEAN", false, "false") {
 773   _dcmdparser.add_dcmd_option(&_verbose);
 774 }
 775 
 776 void StringtableDCmd::execute(DCmdSource source, TRAPS) {
 777   VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpStrings,
 778                          _verbose.value());
 779   VMThread::execute(&dumper);
 780 }
 781 
 782 int StringtableDCmd::num_arguments() {
 783   ResourceMark rm;
 784   StringtableDCmd* dcmd = new StringtableDCmd(NULL, false);
 785   if (dcmd != NULL) {
 786     DCmdMark mark(dcmd);
 787     return dcmd->_dcmdparser.num_arguments();
 788   } else {
 789     return 0;
 790   }
 791 }
 792 
 793 // Sharing
 794 #if INCLUDE_CDS_JAVA_HEAP
 795 oop StringTable::lookup_shared(jchar* name, int len, unsigned int hash) {
 796   assert(hash == java_lang_String::hash_code(name, len),
 797          "hash must be computed using java_lang_String::hash_code");
 798   return _shared_table.lookup(name, hash, len);
 799 }
 800 
 801 oop StringTable::create_archived_string(oop s, Thread* THREAD) {
 802   assert(DumpSharedSpaces, "this function is only used with -Xshare:dump");
 803 
 804   if (MetaspaceShared::is_archive_object(s)) {
 805     return s;
 806   }
 807 
 808   oop new_s = NULL;
 809   typeArrayOop v = java_lang_String::value_no_keepalive(s);
 810   typeArrayOop new_v =
 811     (typeArrayOop)MetaspaceShared::archive_heap_object(v, THREAD);
 812   if (new_v == NULL) {
 813     return NULL;
 814   }
 815   new_s = MetaspaceShared::archive_heap_object(s, THREAD);
 816   if (new_s == NULL) {
 817     return NULL;
 818   }
 819 
 820   // adjust the pointer to the 'value' field in the new String oop
 821   java_lang_String::set_value_raw(new_s, new_v);
 822   return new_s;
 823 }
 824 
 825 class CompactStringTableWriter: public CompactHashtableWriter {
 826 public:
 827   CompactStringTableWriter(int num_entries, CompactHashtableStats* stats) :
 828     CompactHashtableWriter(num_entries, stats) {}
 829   void add(unsigned int hash, oop string) {
 830     CompactHashtableWriter::add(hash, CompressedOops::encode(string));
 831   }
 832 };
 833 
 834 struct CopyToArchive : StackObj {
 835   CompactStringTableWriter* _writer;
 836   CopyToArchive(CompactStringTableWriter* writer) : _writer(writer) {}
 837   bool operator()(WeakHandle<vm_string_table_data>* val) {
 838     oop s = val->peek();
 839     if (s == NULL) {
 840       return true;
 841     }
 842     unsigned int hash = java_lang_String::hash_code(s);
 843     if (hash == 0) {
 844       return true;
 845     }
 846 
 847     java_lang_String::set_hash(s, hash);
 848     oop new_s = StringTable::create_archived_string(s, Thread::current());
 849     if (new_s == NULL) {
 850       return true;
 851     }
 852 
 853     val->replace(new_s);
 854     // add to the compact table
 855     _writer->add(hash, new_s);
 856     return true;
 857   }
 858 };
 859 
 860 void StringTable::copy_shared_string_table(CompactStringTableWriter* writer) {
 861   assert(MetaspaceShared::is_heap_object_archiving_allowed(), "must be");
 862 
 863   CopyToArchive copy(writer);
 864   StringTable::the_table()->_local_table->do_scan(Thread::current(), copy);
 865 }
 866 
 867 void StringTable::write_to_archive() {
 868   assert(MetaspaceShared::is_heap_object_archiving_allowed(), "must be");
 869 
 870   _shared_table.reset();
 871   int num_buckets = the_table()->_items_count / SharedSymbolTableBucketSize;
 872   // calculation of num_buckets can result in zero buckets, we need at least one
 873   CompactStringTableWriter writer(num_buckets > 1 ? num_buckets : 1,
 874                                   &MetaspaceShared::stats()->string);
 875 
 876   // Copy the interned strings into the "string space" within the java heap
 877   copy_shared_string_table(&writer);
 878   writer.dump(&_shared_table, "string");
 879 }
 880 
 881 void StringTable::serialize(SerializeClosure* soc) {
 882   _shared_table.serialize(soc);
 883 
 884   if (soc->writing()) {
 885     // Sanity. Make sure we don't use the shared table at dump time
 886     _shared_table.reset();
 887   } else if (!_shared_string_mapped) {
 888     _shared_table.reset();
 889   }
 890 }
 891 
 892 class SharedStringIterator {
 893   OopClosure* _oop_closure;
 894 public:
 895   SharedStringIterator(OopClosure* f) : _oop_closure(f) {}
 896   void do_value(oop string) {
 897     _oop_closure->do_oop(&string);
 898   }
 899 };
 900 
 901 void StringTable::shared_oops_do(OopClosure* f) {
 902   SharedStringIterator iter(f);
 903   _shared_table.iterate(&iter);
 904 }
 905 #endif //INCLUDE_CDS_JAVA_HEAP