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