1 /*
   2  * Copyright (c) 1997, 2015, 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.hpp"
  29 #include "classfile/stringTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "gc/shared/collectedHeap.inline.hpp"
  32 #include "gc/shared/gcLocker.inline.hpp"
  33 #include "memory/allocation.inline.hpp"
  34 #include "memory/filemap.hpp"
  35 #include "oops/oop.inline.hpp"
  36 #include "runtime/atomic.inline.hpp"
  37 #include "runtime/mutexLocker.hpp"
  38 #include "utilities/hashtable.inline.hpp"
  39 #include "utilities/macros.hpp"
  40 #if INCLUDE_ALL_GCS
  41 #include "gc/g1/g1CollectedHeap.hpp"
  42 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  43 #include "gc/g1/g1StringDedup.hpp"
  44 #endif
  45 
  46 // the number of buckets a thread claims
  47 const int ClaimChunkSize = 32;
  48 
  49 #ifdef ASSERT
  50 class StableMemoryChecker : public StackObj {
  51   enum { _bufsize = wordSize*4 };
  52 
  53   address _region;
  54   jint    _size;
  55   u1      _save_buf[_bufsize];
  56 
  57   int sample(u1* save_buf) {
  58     if (_size <= _bufsize) {
  59       memcpy(save_buf, _region, _size);
  60       return _size;
  61     } else {
  62       // copy head and tail
  63       memcpy(&save_buf[0],          _region,                      _bufsize/2);
  64       memcpy(&save_buf[_bufsize/2], _region + _size - _bufsize/2, _bufsize/2);
  65       return (_bufsize/2)*2;
  66     }
  67   }
  68 
  69  public:
  70   StableMemoryChecker(const void* region, jint size) {
  71     _region = (address) region;
  72     _size   = size;
  73     sample(_save_buf);
  74   }
  75 
  76   bool verify() {
  77     u1 check_buf[sizeof(_save_buf)];
  78     int check_size = sample(check_buf);
  79     return (0 == memcmp(_save_buf, check_buf, check_size));
  80   }
  81 
  82   void set_region(const void* region) { _region = (address) region; }
  83 };
  84 #endif
  85 
  86 
  87 // --------------------------------------------------------------------------
  88 StringTable* StringTable::_the_table = NULL;
  89 bool StringTable::_ignore_shared_strings = false;
  90 bool StringTable::_needs_rehashing = false;
  91 
  92 volatile int StringTable::_parallel_claimed_idx = 0;
  93 
  94 CompactHashtable<oop, char> StringTable::_shared_table;
  95 
  96 // Pick hashing algorithm
  97 unsigned int StringTable::hash_string(const jchar* s, int len) {
  98   return use_alternate_hashcode() ? AltHashing::murmur3_32(seed(), s, len) :
  99                                     java_lang_String::hash_code(s, len);
 100 }
 101 
 102 oop StringTable::lookup_shared(jchar* name, int len) {
 103   // java_lang_String::hash_code() was used to compute hash values in the shared table. Don't
 104   // use the hash value from StringTable::hash_string() as it might use alternate hashcode.
 105   return _shared_table.lookup((const char*)name,
 106                               java_lang_String::hash_code(name, len), len);
 107 }
 108 
 109 oop StringTable::lookup_in_main_table(int index, jchar* name,
 110                                 int len, unsigned int hash) {
 111   int count = 0;
 112   for (HashtableEntry<oop, mtSymbol>* l = bucket(index); l != NULL; l = l->next()) {
 113     count++;
 114     if (l->hash() == hash) {
 115       if (java_lang_String::equals(l->literal(), name, len)) {
 116         return l->literal();
 117       }
 118     }
 119   }
 120   // If the bucket size is too deep check if this hash code is insufficient.
 121   if (count >= rehash_count && !needs_rehashing()) {
 122     _needs_rehashing = check_rehash_table(count);
 123   }
 124   return NULL;
 125 }
 126 
 127 
 128 oop StringTable::basic_add(int index_arg, Handle string, jchar* name,
 129                            int len, unsigned int hashValue_arg, TRAPS) {
 130 
 131   assert(java_lang_String::equals(string(), name, len),
 132          "string must be properly initialized");
 133   // Cannot hit a safepoint in this function because the "this" pointer can move.
 134   No_Safepoint_Verifier nsv;
 135 
 136   // Check if the symbol table has been rehashed, if so, need to recalculate
 137   // the hash value and index before second lookup.
 138   unsigned int hashValue;
 139   int index;
 140   if (use_alternate_hashcode()) {
 141     hashValue = hash_string(name, len);
 142     index = hash_to_index(hashValue);
 143   } else {
 144     hashValue = hashValue_arg;
 145     index = index_arg;
 146   }
 147 
 148   // Since look-up was done lock-free, we need to check if another
 149   // thread beat us in the race to insert the symbol.
 150 
 151   // No need to lookup the shared table from here since the caller (intern()) already did
 152   oop test = lookup_in_main_table(index, name, len, hashValue); // calls lookup(u1*, int)
 153   if (test != NULL) {
 154     // Entry already added
 155     return test;
 156   }
 157 
 158   HashtableEntry<oop, mtSymbol>* entry = new_entry(hashValue, string());
 159   add_entry(index, entry);
 160   return string();
 161 }
 162 
 163 
 164 oop StringTable::lookup(Symbol* symbol) {
 165   ResourceMark rm;
 166   int length;
 167   jchar* chars = symbol->as_unicode(length);
 168   return lookup(chars, length);
 169 }
 170 
 171 // Tell the GC that this string was looked up in the StringTable.
 172 static void ensure_string_alive(oop string) {
 173   // A lookup in the StringTable could return an object that was previously
 174   // considered dead. The SATB part of G1 needs to get notified about this
 175   // potential resurrection, otherwise the marking might not find the object.
 176 #if INCLUDE_ALL_GCS
 177   if (UseG1GC && string != NULL) {
 178     G1SATBCardTableModRefBS::enqueue(string);
 179   }
 180 #endif
 181 }
 182 
 183 oop StringTable::lookup(jchar* name, int len) {
 184   oop string = lookup_shared(name, len);
 185   if (string != NULL) {
 186     return string;
 187   }
 188 
 189   unsigned int hash = hash_string(name, len);
 190   int index = the_table()->hash_to_index(hash);
 191   string = the_table()->lookup_in_main_table(index, name, len, hash);
 192 
 193   ensure_string_alive(string);
 194 
 195   return string;
 196 }
 197 
 198 
 199 oop StringTable::intern(Handle string_or_null, jchar* name,
 200                         int len, TRAPS) {
 201   oop found_string = lookup_shared(name, len);
 202   if (found_string != NULL) {
 203     return found_string;
 204   }
 205 
 206   unsigned int hashValue = hash_string(name, len);
 207   int index = the_table()->hash_to_index(hashValue);
 208   found_string = the_table()->lookup_in_main_table(index, name, len, hashValue);
 209 
 210   // Found
 211   if (found_string != NULL) {
 212     ensure_string_alive(found_string);
 213     return found_string;
 214   }
 215 
 216   debug_only(StableMemoryChecker smc(name, len * sizeof(name[0])));
 217   assert(!Universe::heap()->is_in_reserved(name),
 218          "proposed name of symbol must be stable");
 219 
 220   Handle string;
 221   // try to reuse the string if possible
 222   if (!string_or_null.is_null()) {
 223     string = string_or_null;
 224   } else {
 225     string = java_lang_String::create_from_unicode(name, len, CHECK_NULL);
 226   }
 227 
 228 #if INCLUDE_ALL_GCS
 229   if (G1StringDedup::is_enabled()) {
 230     // Deduplicate the string before it is interned. Note that we should never
 231     // deduplicate a string after it has been interned. Doing so will counteract
 232     // compiler optimizations done on e.g. interned string literals.
 233     G1StringDedup::deduplicate(string());
 234   }
 235 #endif
 236 
 237   // Grab the StringTable_lock before getting the_table() because it could
 238   // change at safepoint.
 239   oop added_or_found;
 240   {
 241     MutexLocker ml(StringTable_lock, THREAD);
 242     // Otherwise, add to symbol to table
 243     added_or_found = the_table()->basic_add(index, string, name, len,
 244                                   hashValue, CHECK_NULL);
 245   }
 246 
 247   ensure_string_alive(added_or_found);
 248 
 249   return added_or_found;
 250 }
 251 
 252 oop StringTable::intern(Symbol* symbol, TRAPS) {
 253   if (symbol == NULL) return NULL;
 254   ResourceMark rm(THREAD);
 255   int length;
 256   jchar* chars = symbol->as_unicode(length);
 257   Handle string;
 258   oop result = intern(string, chars, length, CHECK_NULL);
 259   return result;
 260 }
 261 
 262 
 263 oop StringTable::intern(oop string, TRAPS)
 264 {
 265   if (string == NULL) return NULL;
 266   ResourceMark rm(THREAD);
 267   int length;
 268   Handle h_string (THREAD, string);
 269   jchar* chars = java_lang_String::as_unicode_string(string, length, CHECK_NULL);
 270   oop result = intern(h_string, chars, length, CHECK_NULL);
 271   return result;
 272 }
 273 
 274 
 275 oop StringTable::intern(const char* utf8_string, TRAPS) {
 276   if (utf8_string == NULL) return NULL;
 277   ResourceMark rm(THREAD);
 278   int length = UTF8::unicode_length(utf8_string);
 279   jchar* chars = NEW_RESOURCE_ARRAY(jchar, length);
 280   UTF8::convert_to_unicode(utf8_string, chars, length);
 281   Handle string;
 282   oop result = intern(string, chars, length, CHECK_NULL);
 283   return result;
 284 }
 285 
 286 void StringTable::unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int* processed, int* removed) {
 287   buckets_unlink_or_oops_do(is_alive, f, 0, the_table()->table_size(), processed, removed);
 288 }
 289 
 290 void StringTable::possibly_parallel_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int* processed, int* removed) {
 291   // Readers of the table are unlocked, so we should only be removing
 292   // entries at a safepoint.
 293   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 294   const int limit = the_table()->table_size();
 295 
 296   for (;;) {
 297     // Grab next set of buckets to scan
 298     int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
 299     if (start_idx >= limit) {
 300       // End of table
 301       break;
 302     }
 303 
 304     int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
 305     buckets_unlink_or_oops_do(is_alive, f, start_idx, end_idx, processed, removed);
 306   }
 307 }
 308 
 309 void StringTable::buckets_oops_do(OopClosure* f, int start_idx, int end_idx) {
 310   const int limit = the_table()->table_size();
 311 
 312   assert(0 <= start_idx && start_idx <= limit,
 313          "start_idx (%d) is out of bounds", start_idx);
 314   assert(0 <= end_idx && end_idx <= limit,
 315          "end_idx (%d) is out of bounds", end_idx);
 316   assert(start_idx <= end_idx,
 317          "Index ordering: start_idx=%d, end_idx=%d",
 318          start_idx, end_idx);
 319 
 320   for (int i = start_idx; i < end_idx; i += 1) {
 321     HashtableEntry<oop, mtSymbol>* entry = the_table()->bucket(i);
 322     while (entry != NULL) {
 323       assert(!entry->is_shared(), "CDS not used for the StringTable");
 324 
 325       f->do_oop((oop*)entry->literal_addr());
 326 
 327       entry = entry->next();
 328     }
 329   }
 330 }
 331 
 332 void StringTable::buckets_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int start_idx, int end_idx, int* processed, int* removed) {
 333   const int limit = the_table()->table_size();
 334 
 335   assert(0 <= start_idx && start_idx <= limit,
 336          "start_idx (%d) is out of bounds", start_idx);
 337   assert(0 <= end_idx && end_idx <= limit,
 338          "end_idx (%d) is out of bounds", end_idx);
 339   assert(start_idx <= end_idx,
 340          "Index ordering: start_idx=%d, end_idx=%d",
 341          start_idx, end_idx);
 342 
 343   for (int i = start_idx; i < end_idx; ++i) {
 344     HashtableEntry<oop, mtSymbol>** p = the_table()->bucket_addr(i);
 345     HashtableEntry<oop, mtSymbol>* entry = the_table()->bucket(i);
 346     while (entry != NULL) {
 347       assert(!entry->is_shared(), "CDS not used for the StringTable");
 348 
 349       if (is_alive->do_object_b(entry->literal())) {
 350         if (f != NULL) {
 351           f->do_oop((oop*)entry->literal_addr());
 352         }
 353         p = entry->next_addr();
 354       } else {
 355         *p = entry->next();
 356         the_table()->free_entry(entry);
 357         (*removed)++;
 358       }
 359       (*processed)++;
 360       entry = *p;
 361     }
 362   }
 363 }
 364 
 365 void StringTable::oops_do(OopClosure* f) {
 366   buckets_oops_do(f, 0, the_table()->table_size());
 367 }
 368 
 369 void StringTable::possibly_parallel_oops_do(OopClosure* f) {
 370   const int limit = the_table()->table_size();
 371 
 372   for (;;) {
 373     // Grab next set of buckets to scan
 374     int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
 375     if (start_idx >= limit) {
 376       // End of table
 377       break;
 378     }
 379 
 380     int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
 381     buckets_oops_do(f, start_idx, end_idx);
 382   }
 383 }
 384 
 385 // This verification is part of Universe::verify() and needs to be quick.
 386 // See StringTable::verify_and_compare() below for exhaustive verification.
 387 void StringTable::verify() {
 388   for (int i = 0; i < the_table()->table_size(); ++i) {
 389     HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
 390     for ( ; p != NULL; p = p->next()) {
 391       oop s = p->literal();
 392       guarantee(s != NULL, "interned string is NULL");
 393       unsigned int h = java_lang_String::hash_string(s);
 394       guarantee(p->hash() == h, "broken hash in string table entry");
 395       guarantee(the_table()->hash_to_index(h) == i,
 396                 "wrong index in string table");
 397     }
 398   }
 399 }
 400 
 401 void StringTable::dump(outputStream* st, bool verbose) {
 402   if (!verbose) {
 403     the_table()->dump_table(st, "StringTable");
 404   } else {
 405     Thread* THREAD = Thread::current();
 406     st->print_cr("VERSION: 1.1");
 407     for (int i = 0; i < the_table()->table_size(); ++i) {
 408       HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
 409       for ( ; p != NULL; p = p->next()) {
 410         oop s = p->literal();
 411         typeArrayOop value  = java_lang_String::value(s);
 412         int          offset = java_lang_String::offset(s);
 413         int          length = java_lang_String::length(s);
 414 
 415         if (length <= 0) {
 416           st->print("%d: ", length);
 417         } else {
 418           ResourceMark rm(THREAD);
 419           jchar* chars = (jchar*)value->char_at_addr(offset);
 420           int utf8_length = UNICODE::utf8_length(chars, length);
 421           char* utf8_string = NEW_RESOURCE_ARRAY(char, utf8_length + 1);
 422           UNICODE::convert_to_utf8(chars, length, utf8_string);
 423 
 424           st->print("%d: ", utf8_length);
 425           HashtableTextDump::put_utf8(st, utf8_string, utf8_length);
 426         }
 427         st->cr();
 428       }
 429     }
 430   }
 431 }
 432 
 433 StringTable::VerifyRetTypes StringTable::compare_entries(
 434                                       int bkt1, int e_cnt1,
 435                                       HashtableEntry<oop, mtSymbol>* e_ptr1,
 436                                       int bkt2, int e_cnt2,
 437                                       HashtableEntry<oop, mtSymbol>* e_ptr2) {
 438   // These entries are sanity checked by verify_and_compare_entries()
 439   // before this function is called.
 440   oop str1 = e_ptr1->literal();
 441   oop str2 = e_ptr2->literal();
 442 
 443   if (str1 == str2) {
 444     tty->print_cr("ERROR: identical oop values (0x" PTR_FORMAT ") "
 445                   "in entry @ bucket[%d][%d] and entry @ bucket[%d][%d]",
 446                   p2i(str1), bkt1, e_cnt1, bkt2, e_cnt2);
 447     return _verify_fail_continue;
 448   }
 449 
 450   if (java_lang_String::equals(str1, str2)) {
 451     tty->print_cr("ERROR: identical String values in entry @ "
 452                   "bucket[%d][%d] and entry @ bucket[%d][%d]",
 453                   bkt1, e_cnt1, bkt2, e_cnt2);
 454     return _verify_fail_continue;
 455   }
 456 
 457   return _verify_pass;
 458 }
 459 
 460 StringTable::VerifyRetTypes StringTable::verify_entry(int bkt, int e_cnt,
 461                                       HashtableEntry<oop, mtSymbol>* e_ptr,
 462                                       StringTable::VerifyMesgModes mesg_mode) {
 463 
 464   VerifyRetTypes ret = _verify_pass;  // be optimistic
 465 
 466   oop str = e_ptr->literal();
 467   if (str == NULL) {
 468     if (mesg_mode == _verify_with_mesgs) {
 469       tty->print_cr("ERROR: NULL oop value in entry @ bucket[%d][%d]", bkt,
 470                     e_cnt);
 471     }
 472     // NULL oop means no more verifications are possible
 473     return _verify_fail_done;
 474   }
 475 
 476   if (str->klass() != SystemDictionary::String_klass()) {
 477     if (mesg_mode == _verify_with_mesgs) {
 478       tty->print_cr("ERROR: oop is not a String in entry @ bucket[%d][%d]",
 479                     bkt, e_cnt);
 480     }
 481     // not a String means no more verifications are possible
 482     return _verify_fail_done;
 483   }
 484 
 485   unsigned int h = java_lang_String::hash_string(str);
 486   if (e_ptr->hash() != h) {
 487     if (mesg_mode == _verify_with_mesgs) {
 488       tty->print_cr("ERROR: broken hash value in entry @ bucket[%d][%d], "
 489                     "bkt_hash=%d, str_hash=%d", bkt, e_cnt, e_ptr->hash(), h);
 490     }
 491     ret = _verify_fail_continue;
 492   }
 493 
 494   if (the_table()->hash_to_index(h) != bkt) {
 495     if (mesg_mode == _verify_with_mesgs) {
 496       tty->print_cr("ERROR: wrong index value for entry @ bucket[%d][%d], "
 497                     "str_hash=%d, hash_to_index=%d", bkt, e_cnt, h,
 498                     the_table()->hash_to_index(h));
 499     }
 500     ret = _verify_fail_continue;
 501   }
 502 
 503   return ret;
 504 }
 505 
 506 // See StringTable::verify() above for the quick verification that is
 507 // part of Universe::verify(). This verification is exhaustive and
 508 // reports on every issue that is found. StringTable::verify() only
 509 // reports on the first issue that is found.
 510 //
 511 // StringTable::verify_entry() checks:
 512 // - oop value != NULL (same as verify())
 513 // - oop value is a String
 514 // - hash(String) == hash in entry (same as verify())
 515 // - index for hash == index of entry (same as verify())
 516 //
 517 // StringTable::compare_entries() checks:
 518 // - oops are unique across all entries
 519 // - String values are unique across all entries
 520 //
 521 int StringTable::verify_and_compare_entries() {
 522   assert(StringTable_lock->is_locked(), "sanity check");
 523 
 524   int  fail_cnt = 0;
 525 
 526   // first, verify all the entries individually:
 527   for (int bkt = 0; bkt < the_table()->table_size(); bkt++) {
 528     HashtableEntry<oop, mtSymbol>* e_ptr = the_table()->bucket(bkt);
 529     for (int e_cnt = 0; e_ptr != NULL; e_ptr = e_ptr->next(), e_cnt++) {
 530       VerifyRetTypes ret = verify_entry(bkt, e_cnt, e_ptr, _verify_with_mesgs);
 531       if (ret != _verify_pass) {
 532         fail_cnt++;
 533       }
 534     }
 535   }
 536 
 537   // Optimization: if the above check did not find any failures, then
 538   // the comparison loop below does not need to call verify_entry()
 539   // before calling compare_entries(). If there were failures, then we
 540   // have to call verify_entry() to see if the entry can be passed to
 541   // compare_entries() safely. When we call verify_entry() in the loop
 542   // below, we do so quietly to void duplicate messages and we don't
 543   // increment fail_cnt because the failures have already been counted.
 544   bool need_entry_verify = (fail_cnt != 0);
 545 
 546   // second, verify all entries relative to each other:
 547   for (int bkt1 = 0; bkt1 < the_table()->table_size(); bkt1++) {
 548     HashtableEntry<oop, mtSymbol>* e_ptr1 = the_table()->bucket(bkt1);
 549     for (int e_cnt1 = 0; e_ptr1 != NULL; e_ptr1 = e_ptr1->next(), e_cnt1++) {
 550       if (need_entry_verify) {
 551         VerifyRetTypes ret = verify_entry(bkt1, e_cnt1, e_ptr1,
 552                                           _verify_quietly);
 553         if (ret == _verify_fail_done) {
 554           // cannot use the current entry to compare against other entries
 555           continue;
 556         }
 557       }
 558 
 559       for (int bkt2 = bkt1; bkt2 < the_table()->table_size(); bkt2++) {
 560         HashtableEntry<oop, mtSymbol>* e_ptr2 = the_table()->bucket(bkt2);
 561         int e_cnt2;
 562         for (e_cnt2 = 0; e_ptr2 != NULL; e_ptr2 = e_ptr2->next(), e_cnt2++) {
 563           if (bkt1 == bkt2 && e_cnt2 <= e_cnt1) {
 564             // skip the entries up to and including the one that
 565             // we're comparing against
 566             continue;
 567           }
 568 
 569           if (need_entry_verify) {
 570             VerifyRetTypes ret = verify_entry(bkt2, e_cnt2, e_ptr2,
 571                                               _verify_quietly);
 572             if (ret == _verify_fail_done) {
 573               // cannot compare against this entry
 574               continue;
 575             }
 576           }
 577 
 578           // compare two entries, report and count any failures:
 579           if (compare_entries(bkt1, e_cnt1, e_ptr1, bkt2, e_cnt2, e_ptr2)
 580               != _verify_pass) {
 581             fail_cnt++;
 582           }
 583         }
 584       }
 585     }
 586   }
 587   return fail_cnt;
 588 }
 589 
 590 // Create a new table and using alternate hash code, populate the new table
 591 // with the existing strings.   Set flag to use the alternate hash code afterwards.
 592 void StringTable::rehash_table() {
 593   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 594   // This should never happen with -Xshare:dump but it might in testing mode.
 595   if (DumpSharedSpaces) return;
 596   StringTable* new_table = new StringTable();
 597 
 598   // Rehash the table
 599   the_table()->move_to(new_table);
 600 
 601   // Delete the table and buckets (entries are reused in new table).
 602   delete _the_table;
 603   // Don't check if we need rehashing until the table gets unbalanced again.
 604   // Then rehash with a new global seed.
 605   _needs_rehashing = false;
 606   _the_table = new_table;
 607 }
 608 
 609 // Utility for dumping strings
 610 StringtableDCmd::StringtableDCmd(outputStream* output, bool heap) :
 611                                  DCmdWithParser(output, heap),
 612   _verbose("-verbose", "Dump the content of each string in the table",
 613            "BOOLEAN", false, "false") {
 614   _dcmdparser.add_dcmd_option(&_verbose);
 615 }
 616 
 617 void StringtableDCmd::execute(DCmdSource source, TRAPS) {
 618   VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpStrings,
 619                          _verbose.value());
 620   VMThread::execute(&dumper);
 621 }
 622 
 623 int StringtableDCmd::num_arguments() {
 624   ResourceMark rm;
 625   StringtableDCmd* dcmd = new StringtableDCmd(NULL, false);
 626   if (dcmd != NULL) {
 627     DCmdMark mark(dcmd);
 628     return dcmd->_dcmdparser.num_arguments();
 629   } else {
 630     return 0;
 631   }
 632 }
 633 
 634 // Sharing
 635 bool StringTable::copy_shared_string(GrowableArray<MemRegion> *string_space,
 636                                      CompactHashtableWriter* ch_table) {
 637 #if INCLUDE_CDS && INCLUDE_ALL_GCS && defined(_LP64) && !defined(_WINDOWS)
 638   assert(UseG1GC, "Only support G1 GC");
 639   assert(UseCompressedOops && UseCompressedClassPointers,
 640          "Only support UseCompressedOops and UseCompressedClassPointers enabled");
 641 
 642   Thread* THREAD = Thread::current();
 643   G1CollectedHeap::heap()->begin_archive_alloc_range();
 644   for (int i = 0; i < the_table()->table_size(); ++i) {
 645     HashtableEntry<oop, mtSymbol>* bucket = the_table()->bucket(i);
 646     for ( ; bucket != NULL; bucket = bucket->next()) {
 647       oop s = bucket->literal();
 648       unsigned int hash = java_lang_String::hash_code(s);
 649       if (hash == 0) {
 650         continue;
 651       }
 652 
 653       // allocate the new 'value' array first
 654       typeArrayOop v = java_lang_String::value(s);
 655       int v_len = v->size();
 656       typeArrayOop new_v;
 657       if (G1CollectedHeap::heap()->is_archive_alloc_too_large(v_len)) {
 658         continue; // skip the current String. The 'value' array is too large to handle
 659       } else {
 660         new_v = (typeArrayOop)G1CollectedHeap::heap()->archive_mem_allocate(v_len);
 661         if (new_v == NULL) {
 662           return false; // allocation failed
 663         }
 664       }
 665       // now allocate the new String object
 666       int s_len = s->size();
 667       oop new_s = (oop)G1CollectedHeap::heap()->archive_mem_allocate(s_len);
 668       if (new_s == NULL) {
 669         return false;
 670       }
 671 
 672       s->identity_hash();
 673       v->identity_hash();
 674 
 675       // copy the objects' data
 676       Copy::aligned_disjoint_words((HeapWord*)s, (HeapWord*)new_s, s_len);
 677       Copy::aligned_disjoint_words((HeapWord*)v, (HeapWord*)new_v, v_len);
 678 
 679       // adjust the pointer to the 'value' field in the new String oop. Also pre-compute and set the
 680       // 'hash' field. That avoids "write" to the shared strings at runtime by the deduplication process.
 681       java_lang_String::set_value_raw(new_s, new_v);
 682       if (java_lang_String::hash(new_s) == 0) {
 683         java_lang_String::set_hash(new_s, hash);
 684       }
 685 
 686       // add to the compact table
 687       ch_table->add(hash, new_s);
 688     }
 689   }
 690 
 691   G1CollectedHeap::heap()->end_archive_alloc_range(string_space, os::vm_allocation_granularity());
 692   assert(string_space->length() <= 2, "sanity");
 693 #endif
 694   return true;
 695 }
 696 
 697 bool StringTable::copy_compact_table(char** top, char *end, GrowableArray<MemRegion> *string_space,
 698                                      size_t* space_size) {
 699 #if INCLUDE_CDS && defined(_LP64) && !defined(_WINDOWS)
 700   if (!(UseG1GC && UseCompressedOops && UseCompressedClassPointers)) {
 701     if (PrintSharedSpaces) {
 702       tty->print_cr("Shared strings are excluded from the archive as UseG1GC, "
 703                     "UseCompressedOops and UseCompressedClassPointers are required.");
 704     }
 705     return true;
 706   }
 707 
 708   CompactHashtableWriter ch_table(CompactHashtable<oop, char>::_string_table,
 709                                   the_table()->number_of_entries(),
 710                                   &MetaspaceShared::stats()->string);
 711 
 712   // Copy the interned strings into the "string space" within the java heap
 713   if (!copy_shared_string(string_space, &ch_table)) {
 714     return false;
 715   }
 716 
 717   for (int i = 0; i < string_space->length(); i++) {
 718     *space_size += string_space->at(i).byte_size();
 719   }
 720 
 721   // Now dump the compact table
 722   if (*top + ch_table.get_required_bytes() > end) {
 723     // not enough space left
 724     return false;
 725   }
 726   ch_table.dump(top, end);
 727   *top = (char*)align_pointer_up(*top, sizeof(void*));
 728 
 729 #endif
 730   return true;
 731 }
 732 
 733 void StringTable::shared_oops_do(OopClosure* f) {
 734 #if INCLUDE_CDS && defined(_LP64) && !defined(_WINDOWS)
 735   _shared_table.oops_do(f);
 736 #endif
 737 }
 738 
 739 const char* StringTable::init_shared_table(FileMapInfo *mapinfo, char *buffer) {
 740 #if INCLUDE_CDS && defined(_LP64) && !defined(_WINDOWS)
 741   if (mapinfo->space_capacity(MetaspaceShared::first_string) == 0) {
 742     // no shared string data
 743     return buffer;
 744   }
 745 
 746   // initialize the shared table
 747   juint *p = (juint*)buffer;
 748   const char* end = _shared_table.init(
 749           CompactHashtable<oop, char>::_string_table, (char*)p);
 750   const char* aligned_end = (const char*)align_pointer_up(end, sizeof(void*));
 751 
 752   if (_ignore_shared_strings) {
 753     _shared_table.reset();
 754   }
 755 
 756   return aligned_end;
 757 #endif
 758 
 759   return buffer;
 760 }