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