1 /*
   2  * Copyright (c) 1997, 2012, 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/javaClasses.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "gc_interface/collectedHeap.inline.hpp"
  31 #include "memory/allocation.inline.hpp"
  32 #include "memory/filemap.hpp"
  33 #include "memory/gcLocker.inline.hpp"
  34 #include "oops/oop.inline.hpp"
  35 #include "oops/oop.inline2.hpp"
  36 #include "runtime/mutexLocker.hpp"
  37 #include "utilities/hashtable.inline.hpp"
  38 #include "utilities/numberSeq.hpp"
  39 
  40 // --------------------------------------------------------------------------
  41 
  42 SymbolTable* SymbolTable::_the_table = NULL;
  43 // Static arena for symbols that are not deallocated
  44 Arena* SymbolTable::_arena = NULL;
  45 bool SymbolTable::_needs_rehashing = false;
  46 
  47 Symbol* SymbolTable::allocate_symbol(const u1* name, int len, bool c_heap, TRAPS) {
  48   assert (len <= Symbol::max_length(), "should be checked by caller");
  49 
  50   Symbol* sym;
  51   // Allocate symbols in the C heap when dumping shared spaces in case there
  52   // are temporary symbols we can remove.
  53   if (c_heap || DumpSharedSpaces) {
  54     // refcount starts as 1
  55     sym = new (len, THREAD) Symbol(name, len, 1);
  56   } else {
  57     sym = new (len, arena(), THREAD) Symbol(name, len, -1);
  58   }
  59   assert(sym != NULL, "new should call vm_exit_out_of_memory if C_HEAP is exhausted");
  60   return sym;
  61 }
  62 
  63 void SymbolTable::initialize_symbols(int arena_alloc_size) {
  64   // Initialize the arena for global symbols, size passed in depends on CDS.
  65   if (arena_alloc_size == 0) {
  66     _arena = new (mtSymbol) Arena();
  67   } else {
  68     _arena = new (mtSymbol) Arena(arena_alloc_size);
  69   }
  70 }
  71 
  72 // Call function for all symbols in the symbol table.
  73 void SymbolTable::symbols_do(SymbolClosure *cl) {
  74   const int n = the_table()->table_size();
  75   for (int i = 0; i < n; i++) {
  76     for (HashtableEntry<Symbol*, mtSymbol>* p = the_table()->bucket(i);
  77          p != NULL;
  78          p = p->next()) {
  79       cl->do_symbol(p->literal_addr());
  80     }
  81   }
  82 }
  83 
  84 int SymbolTable::symbols_removed = 0;
  85 int SymbolTable::symbols_counted = 0;
  86 
  87 // Remove unreferenced symbols from the symbol table
  88 // This is done late during GC.
  89 void SymbolTable::unlink() {
  90   int removed = 0;
  91   int total = 0;
  92   size_t memory_total = 0;
  93   for (int i = 0; i < the_table()->table_size(); ++i) {
  94     HashtableEntry<Symbol*, mtSymbol>** p = the_table()->bucket_addr(i);
  95     HashtableEntry<Symbol*, mtSymbol>* entry = the_table()->bucket(i);
  96     while (entry != NULL) {
  97       // Shared entries are normally at the end of the bucket and if we run into
  98       // a shared entry, then there is nothing more to remove. However, if we
  99       // have rehashed the table, then the shared entries are no longer at the
 100       // end of the bucket.
 101       if (entry->is_shared() && !use_alternate_hashcode()) {
 102         break;
 103       }
 104       Symbol* s = entry->literal();
 105       memory_total += s->object_size();
 106       total++;
 107       assert(s != NULL, "just checking");
 108       // If reference count is zero, remove.
 109       if (s->refcount() == 0) {
 110         assert(!entry->is_shared(), "shared entries should be kept live");
 111         delete s;
 112         removed++;
 113         *p = entry->next();
 114         the_table()->free_entry(entry);
 115       } else {
 116         p = entry->next_addr();
 117       }
 118       // get next entry
 119       entry = (HashtableEntry<Symbol*, mtSymbol>*)HashtableEntry<Symbol*, mtSymbol>::make_ptr(*p);
 120     }
 121   }
 122   symbols_removed += removed;
 123   symbols_counted += total;
 124   // Exclude printing for normal PrintGCDetails because people parse
 125   // this output.
 126   if (PrintGCDetails && Verbose && WizardMode) {
 127     gclog_or_tty->print(" [Symbols=%d size=" SIZE_FORMAT "K] ", total,
 128                         (memory_total*HeapWordSize)/1024);
 129   }
 130 }
 131 
 132 // Create a new table and using alternate hash code, populate the new table
 133 // with the existing strings.   Set flag to use the alternate hash code afterwards.
 134 void SymbolTable::rehash_table() {
 135   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 136   // This should never happen with -Xshare:dump but it might in testing mode.
 137   if (DumpSharedSpaces) return;
 138   // Create a new symbol table
 139   SymbolTable* new_table = new SymbolTable();
 140 
 141   the_table()->move_to(new_table);
 142 
 143   // Delete the table and buckets (entries are reused in new table).
 144   delete _the_table;
 145   // Don't check if we need rehashing until the table gets unbalanced again.
 146   // Then rehash with a new global seed.
 147   _needs_rehashing = false;
 148   _the_table = new_table;
 149 }
 150 
 151 // Lookup a symbol in a bucket.
 152 
 153 Symbol* SymbolTable::lookup(int index, const char* name,
 154                               int len, unsigned int hash) {
 155   int count = 0;
 156   for (HashtableEntry<Symbol*, mtSymbol>* e = bucket(index); e != NULL; e = e->next()) {
 157     count++;  // count all entries in this bucket, not just ones with same hash
 158     if (e->hash() == hash) {
 159       Symbol* sym = e->literal();
 160       if (sym->equals(name, len)) {
 161         // something is referencing this symbol now.
 162         sym->increment_refcount();
 163         return sym;
 164       }
 165     }
 166   }
 167   // If the bucket size is too deep check if this hash code is insufficient.
 168   if (count >= BasicHashtable<mtSymbol>::rehash_count && !needs_rehashing()) {
 169     _needs_rehashing = check_rehash_table(count);
 170   }
 171   return NULL;
 172 }
 173 
 174 // Pick hashing algorithm.
 175 unsigned int SymbolTable::hash_symbol(const char* s, int len) {
 176   return use_alternate_hashcode() ?
 177            AltHashing::murmur3_32(seed(), (const jbyte*)s, len) :
 178            java_lang_String::to_hash(s, len);
 179 }
 180 
 181 
 182 // We take care not to be blocking while holding the
 183 // SymbolTable_lock. Otherwise, the system might deadlock, since the
 184 // symboltable is used during compilation (VM_thread) The lock free
 185 // synchronization is simplified by the fact that we do not delete
 186 // entries in the symbol table during normal execution (only during
 187 // safepoints).
 188 
 189 Symbol* SymbolTable::lookup(const char* name, int len, TRAPS) {
 190   unsigned int hashValue = hash_symbol(name, len);
 191   int index = the_table()->hash_to_index(hashValue);
 192 
 193   Symbol* s = the_table()->lookup(index, name, len, hashValue);
 194 
 195   // Found
 196   if (s != NULL) return s;
 197 
 198   // Grab SymbolTable_lock first.
 199   MutexLocker ml(SymbolTable_lock, THREAD);
 200 
 201   // Otherwise, add to symbol to table
 202   return the_table()->basic_add(index, (u1*)name, len, hashValue, true, CHECK_NULL);
 203 }
 204 
 205 Symbol* SymbolTable::lookup(const Symbol* sym, int begin, int end, TRAPS) {
 206   char* buffer;
 207   int index, len;
 208   unsigned int hashValue;
 209   char* name;
 210   {
 211     debug_only(No_Safepoint_Verifier nsv;)
 212 
 213     name = (char*)sym->base() + begin;
 214     len = end - begin;
 215     hashValue = hash_symbol(name, len);
 216     index = the_table()->hash_to_index(hashValue);
 217     Symbol* s = the_table()->lookup(index, name, len, hashValue);
 218 
 219     // Found
 220     if (s != NULL) return s;
 221   }
 222 
 223   // Otherwise, add to symbol to table. Copy to a C string first.
 224   char stack_buf[128];
 225   ResourceMark rm(THREAD);
 226   if (len <= 128) {
 227     buffer = stack_buf;
 228   } else {
 229     buffer = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
 230   }
 231   for (int i=0; i<len; i++) {
 232     buffer[i] = name[i];
 233   }
 234   // Make sure there is no safepoint in the code above since name can't move.
 235   // We can't include the code in No_Safepoint_Verifier because of the
 236   // ResourceMark.
 237 
 238   // Grab SymbolTable_lock first.
 239   MutexLocker ml(SymbolTable_lock, THREAD);
 240 
 241   return the_table()->basic_add(index, (u1*)buffer, len, hashValue, true, CHECK_NULL);
 242 }
 243 
 244 Symbol* SymbolTable::lookup_only(const char* name, int len,
 245                                    unsigned int& hash) {
 246   hash = hash_symbol(name, len);
 247   int index = the_table()->hash_to_index(hash);
 248 
 249   Symbol* s = the_table()->lookup(index, name, len, hash);
 250   return s;
 251 }
 252 
 253 // Look up the address of the literal in the SymbolTable for this Symbol*
 254 // Do not create any new symbols
 255 // Do not increment the reference count to keep this alive
 256 Symbol** SymbolTable::lookup_symbol_addr(Symbol* sym){
 257   unsigned int hash = hash_symbol((char*)sym->bytes(), sym->utf8_length());
 258   int index = the_table()->hash_to_index(hash);
 259 
 260   for (HashtableEntry<Symbol*, mtSymbol>* e = the_table()->bucket(index); e != NULL; e = e->next()) {
 261     if (e->hash() == hash) {
 262       Symbol* literal_sym = e->literal();
 263       if (sym == literal_sym) {
 264         return e->literal_addr();
 265       }
 266     }
 267   }
 268   return NULL;
 269 }
 270 
 271 // Suggestion: Push unicode-based lookup all the way into the hashing
 272 // and probing logic, so there is no need for convert_to_utf8 until
 273 // an actual new Symbol* is created.
 274 Symbol* SymbolTable::lookup_unicode(const jchar* name, int utf16_length, TRAPS) {
 275   int utf8_length = UNICODE::utf8_length((jchar*) name, utf16_length);
 276   char stack_buf[128];
 277   if (utf8_length < (int) sizeof(stack_buf)) {
 278     char* chars = stack_buf;
 279     UNICODE::convert_to_utf8(name, utf16_length, chars);
 280     return lookup(chars, utf8_length, THREAD);
 281   } else {
 282     ResourceMark rm(THREAD);
 283     char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);;
 284     UNICODE::convert_to_utf8(name, utf16_length, chars);
 285     return lookup(chars, utf8_length, THREAD);
 286   }
 287 }
 288 
 289 Symbol* SymbolTable::lookup_only_unicode(const jchar* name, int utf16_length,
 290                                            unsigned int& hash) {
 291   int utf8_length = UNICODE::utf8_length((jchar*) name, utf16_length);
 292   char stack_buf[128];
 293   if (utf8_length < (int) sizeof(stack_buf)) {
 294     char* chars = stack_buf;
 295     UNICODE::convert_to_utf8(name, utf16_length, chars);
 296     return lookup_only(chars, utf8_length, hash);
 297   } else {
 298     ResourceMark rm;
 299     char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);;
 300     UNICODE::convert_to_utf8(name, utf16_length, chars);
 301     return lookup_only(chars, utf8_length, hash);
 302   }
 303 }
 304 
 305 void SymbolTable::add(Handle class_loader, constantPoolHandle cp,
 306                       int names_count,
 307                       const char** names, int* lengths, int* cp_indices,
 308                       unsigned int* hashValues, TRAPS) {
 309   // Grab SymbolTable_lock first.
 310   MutexLocker ml(SymbolTable_lock, THREAD);
 311 
 312   SymbolTable* table = the_table();
 313   bool added = table->basic_add(class_loader, cp, names_count, names, lengths,
 314                                 cp_indices, hashValues, CHECK);
 315   if (!added) {
 316     // do it the hard way
 317     for (int i=0; i<names_count; i++) {
 318       int index = table->hash_to_index(hashValues[i]);
 319       bool c_heap = class_loader() != NULL;
 320       Symbol* sym = table->basic_add(index, (u1*)names[i], lengths[i], hashValues[i], c_heap, CHECK);
 321       cp->symbol_at_put(cp_indices[i], sym);
 322     }
 323   }
 324 }
 325 
 326 Symbol* SymbolTable::new_permanent_symbol(const char* name, TRAPS) {
 327   unsigned int hash;
 328   Symbol* result = SymbolTable::lookup_only((char*)name, (int)strlen(name), hash);
 329   if (result != NULL) {
 330     return result;
 331   }
 332   // Grab SymbolTable_lock first.
 333   MutexLocker ml(SymbolTable_lock, THREAD);
 334 
 335   SymbolTable* table = the_table();
 336   int index = table->hash_to_index(hash);
 337   return table->basic_add(index, (u1*)name, (int)strlen(name), hash, false, THREAD);
 338 }
 339 
 340 Symbol* SymbolTable::basic_add(int index_arg, u1 *name, int len,
 341                                unsigned int hashValue_arg, bool c_heap, TRAPS) {
 342   assert(!Universe::heap()->is_in_reserved(name) || GC_locker::is_active(),
 343          "proposed name of symbol must be stable");
 344 
 345   // Don't allow symbols to be created which cannot fit in a Symbol*.
 346   if (len > Symbol::max_length()) {
 347     THROW_MSG_0(vmSymbols::java_lang_InternalError(),
 348                 "name is too long to represent");
 349   }
 350 
 351   // Cannot hit a safepoint in this function because the "this" pointer can move.
 352   No_Safepoint_Verifier nsv;
 353 
 354   // Check if the symbol table has been rehashed, if so, need to recalculate
 355   // the hash value and index.
 356   unsigned int hashValue;
 357   int index;
 358   if (use_alternate_hashcode()) {
 359     hashValue = hash_symbol((const char*)name, len);
 360     index = hash_to_index(hashValue);
 361   } else {
 362     hashValue = hashValue_arg;
 363     index = index_arg;
 364   }
 365 
 366   // Since look-up was done lock-free, we need to check if another
 367   // thread beat us in the race to insert the symbol.
 368   Symbol* test = lookup(index, (char*)name, len, hashValue);
 369   if (test != NULL) {
 370     // A race occurred and another thread introduced the symbol.
 371     assert(test->refcount() != 0, "lookup should have incremented the count");
 372     return test;
 373   }
 374 
 375   // Create a new symbol.
 376   Symbol* sym = allocate_symbol(name, len, c_heap, CHECK_NULL);
 377   assert(sym->equals((char*)name, len), "symbol must be properly initialized");
 378 
 379   HashtableEntry<Symbol*, mtSymbol>* entry = new_entry(hashValue, sym);
 380   add_entry(index, entry);
 381   return sym;
 382 }
 383 
 384 // This version of basic_add adds symbols in batch from the constant pool
 385 // parsing.
 386 bool SymbolTable::basic_add(Handle class_loader, constantPoolHandle cp,
 387                             int names_count,
 388                             const char** names, int* lengths,
 389                             int* cp_indices, unsigned int* hashValues,
 390                             TRAPS) {
 391 
 392   // Check symbol names are not too long.  If any are too long, don't add any.
 393   for (int i = 0; i< names_count; i++) {
 394     if (lengths[i] > Symbol::max_length()) {
 395       THROW_MSG_0(vmSymbols::java_lang_InternalError(),
 396                   "name is too long to represent");
 397     }
 398   }
 399 
 400   // Cannot hit a safepoint in this function because the "this" pointer can move.
 401   No_Safepoint_Verifier nsv;
 402 
 403   for (int i=0; i<names_count; i++) {
 404     // Check if the symbol table has been rehashed, if so, need to recalculate
 405     // the hash value.
 406     unsigned int hashValue;
 407     if (use_alternate_hashcode()) {
 408       hashValue = hash_symbol(names[i], lengths[i]);
 409     } else {
 410       hashValue = hashValues[i];
 411     }
 412     // Since look-up was done lock-free, we need to check if another
 413     // thread beat us in the race to insert the symbol.
 414     int index = hash_to_index(hashValue);
 415     Symbol* test = lookup(index, names[i], lengths[i], hashValue);
 416     if (test != NULL) {
 417       // A race occurred and another thread introduced the symbol, this one
 418       // will be dropped and collected. Use test instead.
 419       cp->symbol_at_put(cp_indices[i], test);
 420       assert(test->refcount() != 0, "lookup should have incremented the count");
 421     } else {
 422       // Create a new symbol.  The null class loader is never unloaded so these
 423       // are allocated specially in a permanent arena.
 424       bool c_heap = class_loader() != NULL;
 425       Symbol* sym = allocate_symbol((const u1*)names[i], lengths[i], c_heap, CHECK_(false));
 426       assert(sym->equals(names[i], lengths[i]), "symbol must be properly initialized");  // why wouldn't it be???
 427       HashtableEntry<Symbol*, mtSymbol>* entry = new_entry(hashValue, sym);
 428       add_entry(index, entry);
 429       cp->symbol_at_put(cp_indices[i], sym);
 430     }
 431   }
 432   return true;
 433 }
 434 
 435 
 436 void SymbolTable::verify() {
 437   for (int i = 0; i < the_table()->table_size(); ++i) {
 438     HashtableEntry<Symbol*, mtSymbol>* p = the_table()->bucket(i);
 439     for ( ; p != NULL; p = p->next()) {
 440       Symbol* s = (Symbol*)(p->literal());
 441       guarantee(s != NULL, "symbol is NULL");
 442       unsigned int h = hash_symbol((char*)s->bytes(), s->utf8_length());
 443       guarantee(p->hash() == h, "broken hash in symbol table entry");
 444       guarantee(the_table()->hash_to_index(h) == i,
 445                 "wrong index in symbol table");
 446     }
 447   }
 448 }
 449 
 450 void SymbolTable::dump(outputStream* st) {
 451   NumberSeq summary;
 452   for (int i = 0; i < the_table()->table_size(); ++i) {
 453     int count = 0;
 454     for (HashtableEntry<Symbol*, mtSymbol>* e = the_table()->bucket(i);
 455        e != NULL; e = e->next()) {
 456       count++;
 457     }
 458     summary.add((double)count);
 459   }
 460   st->print_cr("SymbolTable statistics:");
 461   st->print_cr("Number of buckets       : %7d", summary.num());
 462   st->print_cr("Average bucket size     : %7.0f", summary.avg());
 463   st->print_cr("Variance of bucket size : %7.0f", summary.variance());
 464   st->print_cr("Std. dev. of bucket size: %7.0f", summary.sd());
 465   st->print_cr("Maximum bucket size     : %7.0f", summary.maximum());
 466 }
 467 
 468 
 469 //---------------------------------------------------------------------------
 470 // Non-product code
 471 
 472 #ifndef PRODUCT
 473 
 474 void SymbolTable::print_histogram() {
 475   MutexLocker ml(SymbolTable_lock);
 476   const int results_length = 100;
 477   int results[results_length];
 478   int i,j;
 479 
 480   // initialize results to zero
 481   for (j = 0; j < results_length; j++) {
 482     results[j] = 0;
 483   }
 484 
 485   int total = 0;
 486   int max_symbols = 0;
 487   int out_of_range = 0;
 488   int memory_total = 0;
 489   int count = 0;
 490   for (i = 0; i < the_table()->table_size(); i++) {
 491     HashtableEntry<Symbol*, mtSymbol>* p = the_table()->bucket(i);
 492     for ( ; p != NULL; p = p->next()) {
 493       memory_total += p->literal()->object_size();
 494       count++;
 495       int counter = p->literal()->utf8_length();
 496       total += counter;
 497       if (counter < results_length) {
 498         results[counter]++;
 499       } else {
 500         out_of_range++;
 501       }
 502       max_symbols = MAX2(max_symbols, counter);
 503     }
 504   }
 505   tty->print_cr("Symbol Table:");
 506   tty->print_cr("Total number of symbols  %5d", count);
 507   tty->print_cr("Total size in memory     %5dK",
 508           (memory_total*HeapWordSize)/1024);
 509   tty->print_cr("Total counted            %5d", symbols_counted);
 510   tty->print_cr("Total removed            %5d", symbols_removed);
 511   if (symbols_counted > 0) {
 512     tty->print_cr("Percent removed          %3.2f",
 513           ((float)symbols_removed/(float)symbols_counted)* 100);
 514   }
 515   tty->print_cr("Reference counts         %5d", Symbol::_total_count);
 516   tty->print_cr("Symbol arena size        %5d used %5d",
 517                  arena()->size_in_bytes(), arena()->used());
 518   tty->print_cr("Histogram of symbol length:");
 519   tty->print_cr("%8s %5d", "Total  ", total);
 520   tty->print_cr("%8s %5d", "Maximum", max_symbols);
 521   tty->print_cr("%8s %3.2f", "Average",
 522           ((float) total / (float) the_table()->table_size()));
 523   tty->print_cr("%s", "Histogram:");
 524   tty->print_cr(" %s %29s", "Length", "Number chains that length");
 525   for (i = 0; i < results_length; i++) {
 526     if (results[i] > 0) {
 527       tty->print_cr("%6d %10d", i, results[i]);
 528     }
 529   }
 530   if (Verbose) {
 531     int line_length = 70;
 532     tty->print_cr("%s %30s", " Length", "Number chains that length");
 533     for (i = 0; i < results_length; i++) {
 534       if (results[i] > 0) {
 535         tty->print("%4d", i);
 536         for (j = 0; (j < results[i]) && (j < line_length);  j++) {
 537           tty->print("%1s", "*");
 538         }
 539         if (j == line_length) {
 540           tty->print("%1s", "+");
 541         }
 542         tty->cr();
 543       }
 544     }
 545   }
 546   tty->print_cr(" %s %d: %d\n", "Number chains longer than",
 547                     results_length, out_of_range);
 548 }
 549 
 550 void SymbolTable::print() {
 551   for (int i = 0; i < the_table()->table_size(); ++i) {
 552     HashtableEntry<Symbol*, mtSymbol>** p = the_table()->bucket_addr(i);
 553     HashtableEntry<Symbol*, mtSymbol>* entry = the_table()->bucket(i);
 554     if (entry != NULL) {
 555       while (entry != NULL) {
 556         tty->print(PTR_FORMAT " ", entry->literal());
 557         entry->literal()->print();
 558         tty->print(" %d", entry->literal()->refcount());
 559         p = entry->next_addr();
 560         entry = (HashtableEntry<Symbol*, mtSymbol>*)HashtableEntry<Symbol*, mtSymbol>::make_ptr(*p);
 561       }
 562       tty->cr();
 563     }
 564   }
 565 }
 566 #endif // PRODUCT
 567 
 568 // --------------------------------------------------------------------------
 569 
 570 #ifdef ASSERT
 571 class StableMemoryChecker : public StackObj {
 572   enum { _bufsize = wordSize*4 };
 573 
 574   address _region;
 575   jint    _size;
 576   u1      _save_buf[_bufsize];
 577 
 578   int sample(u1* save_buf) {
 579     if (_size <= _bufsize) {
 580       memcpy(save_buf, _region, _size);
 581       return _size;
 582     } else {
 583       // copy head and tail
 584       memcpy(&save_buf[0],          _region,                      _bufsize/2);
 585       memcpy(&save_buf[_bufsize/2], _region + _size - _bufsize/2, _bufsize/2);
 586       return (_bufsize/2)*2;
 587     }
 588   }
 589 
 590  public:
 591   StableMemoryChecker(const void* region, jint size) {
 592     _region = (address) region;
 593     _size   = size;
 594     sample(_save_buf);
 595   }
 596 
 597   bool verify() {
 598     u1 check_buf[sizeof(_save_buf)];
 599     int check_size = sample(check_buf);
 600     return (0 == memcmp(_save_buf, check_buf, check_size));
 601   }
 602 
 603   void set_region(const void* region) { _region = (address) region; }
 604 };
 605 #endif
 606 
 607 
 608 // --------------------------------------------------------------------------
 609 StringTable* StringTable::_the_table = NULL;
 610 
 611 bool StringTable::_needs_rehashing = false;
 612 
 613 volatile int StringTable::_parallel_claimed_idx = 0;
 614 
 615 // Pick hashing algorithm
 616 unsigned int StringTable::hash_string(const jchar* s, int len) {
 617   return use_alternate_hashcode() ? AltHashing::murmur3_32(seed(), s, len) :
 618                                     java_lang_String::to_hash(s, len);
 619 }
 620 
 621 oop StringTable::lookup(int index, jchar* name,
 622                         int len, unsigned int hash) {
 623   int count = 0;
 624   for (HashtableEntry<oop, mtSymbol>* l = bucket(index); l != NULL; l = l->next()) {
 625     count++;
 626     if (l->hash() == hash) {
 627       if (java_lang_String::equals(l->literal(), name, len)) {
 628         return l->literal();
 629       }
 630     }
 631   }
 632   // If the bucket size is too deep check if this hash code is insufficient.
 633   if (count >= BasicHashtable<mtSymbol>::rehash_count && !needs_rehashing()) {
 634     _needs_rehashing = check_rehash_table(count);
 635   }
 636   return NULL;
 637 }
 638 
 639 
 640 oop StringTable::basic_add(int index_arg, Handle string, jchar* name,
 641                            int len, unsigned int hashValue_arg, TRAPS) {
 642 
 643   assert(java_lang_String::equals(string(), name, len),
 644          "string must be properly initialized");
 645   // Cannot hit a safepoint in this function because the "this" pointer can move.
 646   No_Safepoint_Verifier nsv;
 647 
 648   // Check if the symbol table has been rehashed, if so, need to recalculate
 649   // the hash value and index before second lookup.
 650   unsigned int hashValue;
 651   int index;
 652   if (use_alternate_hashcode()) {
 653     hashValue = hash_string(name, len);
 654     index = hash_to_index(hashValue);
 655   } else {
 656     hashValue = hashValue_arg;
 657     index = index_arg;
 658   }
 659 
 660   // Since look-up was done lock-free, we need to check if another
 661   // thread beat us in the race to insert the symbol.
 662 
 663   oop test = lookup(index, name, len, hashValue); // calls lookup(u1*, int)
 664   if (test != NULL) {
 665     // Entry already added
 666     return test;
 667   }
 668 
 669   HashtableEntry<oop, mtSymbol>* entry = new_entry(hashValue, string());
 670   add_entry(index, entry);
 671   return string();
 672 }
 673 
 674 
 675 oop StringTable::lookup(Symbol* symbol) {
 676   ResourceMark rm;
 677   int length;
 678   jchar* chars = symbol->as_unicode(length);
 679   unsigned int hashValue = hash_string(chars, length);
 680   int index = the_table()->hash_to_index(hashValue);
 681   return the_table()->lookup(index, chars, length, hashValue);
 682 }
 683 
 684 
 685 oop StringTable::intern(Handle string_or_null, jchar* name,
 686                         int len, TRAPS) {
 687   unsigned int hashValue = hash_string(name, len);
 688   int index = the_table()->hash_to_index(hashValue);
 689   oop found_string = the_table()->lookup(index, name, len, hashValue);
 690 
 691   // Found
 692   if (found_string != NULL) return found_string;
 693 
 694   debug_only(StableMemoryChecker smc(name, len * sizeof(name[0])));
 695   assert(!Universe::heap()->is_in_reserved(name) || GC_locker::is_active(),
 696          "proposed name of symbol must be stable");
 697 
 698   Handle string;
 699   // try to reuse the string if possible
 700   if (!string_or_null.is_null() && (!JavaObjectsInPerm || string_or_null()->is_perm())) {
 701     string = string_or_null;
 702   } else {
 703     string = java_lang_String::create_tenured_from_unicode(name, len, CHECK_NULL);
 704   }
 705 
 706   // Grab the StringTable_lock before getting the_table() because it could
 707   // change at safepoint.
 708   MutexLocker ml(StringTable_lock, THREAD);
 709 
 710   // Otherwise, add to symbol to table
 711   return the_table()->basic_add(index, string, name, len,
 712                                 hashValue, CHECK_NULL);
 713 }
 714 
 715 oop StringTable::intern(Symbol* symbol, TRAPS) {
 716   if (symbol == NULL) return NULL;
 717   ResourceMark rm(THREAD);
 718   int length;
 719   jchar* chars = symbol->as_unicode(length);
 720   Handle string;
 721   oop result = intern(string, chars, length, CHECK_NULL);
 722   return result;
 723 }
 724 
 725 
 726 oop StringTable::intern(oop string, TRAPS)
 727 {
 728   if (string == NULL) return NULL;
 729   ResourceMark rm(THREAD);
 730   int length;
 731   Handle h_string (THREAD, string);
 732   jchar* chars = java_lang_String::as_unicode_string(string, length);
 733   oop result = intern(h_string, chars, length, CHECK_NULL);
 734   return result;
 735 }
 736 
 737 
 738 oop StringTable::intern(const char* utf8_string, TRAPS) {
 739   if (utf8_string == NULL) return NULL;
 740   ResourceMark rm(THREAD);
 741   int length = UTF8::unicode_length(utf8_string);
 742   jchar* chars = NEW_RESOURCE_ARRAY(jchar, length);
 743   UTF8::convert_to_unicode(utf8_string, chars, length);
 744   Handle string;
 745   oop result = intern(string, chars, length, CHECK_NULL);
 746   return result;
 747 }
 748 
 749 void StringTable::unlink(BoolObjectClosure* is_alive) {
 750   // Readers of the table are unlocked, so we should only be removing
 751   // entries at a safepoint.
 752   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 753   for (int i = 0; i < the_table()->table_size(); ++i) {
 754     HashtableEntry<oop, mtSymbol>** p = the_table()->bucket_addr(i);
 755     HashtableEntry<oop, mtSymbol>* entry = the_table()->bucket(i);
 756     while (entry != NULL) {
 757       // Shared entries are normally at the end of the bucket and if we run into
 758       // a shared entry, then there is nothing more to remove. However, if we
 759       // have rehashed the table, then the shared entries are no longer at the
 760       // end of the bucket.
 761       if (entry->is_shared() && !use_alternate_hashcode()) {
 762         break;
 763       }
 764       assert(entry->literal() != NULL, "just checking");
 765       if (entry->is_shared() || is_alive->do_object_b(entry->literal())) {
 766         p = entry->next_addr();
 767       } else {
 768         *p = entry->next();
 769         the_table()->free_entry(entry);
 770       }
 771       entry = (HashtableEntry<oop, mtSymbol>*)HashtableEntry<oop, mtSymbol>::make_ptr(*p);
 772     }
 773   }
 774 }
 775 
 776 void StringTable::buckets_do(OopClosure* f, int start_idx, int end_idx) {
 777   const int limit = the_table()->table_size();
 778 
 779   assert(0 <= start_idx && start_idx <= limit,
 780          err_msg("start_idx (" INT32_FORMAT ") oob?", start_idx));
 781   assert(0 <= end_idx && end_idx <= limit,
 782          err_msg("end_idx (" INT32_FORMAT ") oob?", end_idx));
 783   assert(start_idx <= end_idx,
 784          err_msg("Ordering: start_idx=" INT32_FORMAT", end_idx=" INT32_FORMAT,
 785                  start_idx, end_idx));
 786 
 787   for (int i = start_idx; i < end_idx; i += 1) {
 788     HashtableEntry<oop, mtSymbol>** p = the_table()->bucket_addr(i);
 789     HashtableEntry<oop, mtSymbol>* entry = the_table()->bucket(i);
 790     while (entry != NULL) {
 791       f->do_oop((oop*)entry->literal_addr());
 792 
 793       // Did the closure remove the literal from the table?
 794       if (entry->literal() == NULL) {
 795         assert(!entry->is_shared(), "immutable hashtable entry?");
 796         *p = entry->next();
 797         the_table()->free_entry(entry);
 798       } else {
 799         p = entry->next_addr();
 800       }
 801       entry = (HashtableEntry<oop, mtSymbol>*)HashtableEntry<oop, mtSymbol>::make_ptr(*p);
 802     }
 803   }
 804 }
 805 
 806 void StringTable::oops_do(OopClosure* f) {
 807   buckets_do(f, 0, the_table()->table_size());
 808 }
 809 
 810 void StringTable::possibly_parallel_oops_do(OopClosure* f) {
 811   const int ClaimChunkSize = 32;
 812   const int limit = the_table()->table_size();
 813 
 814   for (;;) {
 815     // Grab next set of buckets to scan
 816     int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
 817     if (start_idx >= limit) {
 818       // End of table
 819       break;
 820     }
 821 
 822     int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
 823     buckets_do(f, start_idx, end_idx);
 824   }
 825 }
 826 
 827 void StringTable::verify() {
 828   for (int i = 0; i < the_table()->table_size(); ++i) {
 829     HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
 830     for ( ; p != NULL; p = p->next()) {
 831       oop s = p->literal();
 832       guarantee(s != NULL, "interned string is NULL");
 833       guarantee(s->is_perm() || !JavaObjectsInPerm, "interned string not in permspace");
 834       unsigned int h = java_lang_String::hash_string(s);
 835       guarantee(p->hash() == h, "broken hash in string table entry");
 836       guarantee(the_table()->hash_to_index(h) == i,
 837                 "wrong index in string table");
 838     }
 839   }
 840 }
 841 
 842 void StringTable::dump(outputStream* st) {
 843   NumberSeq summary;
 844   for (int i = 0; i < the_table()->table_size(); ++i) {
 845     HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
 846     int count = 0;
 847     for ( ; p != NULL; p = p->next()) {
 848       count++;
 849     }
 850     summary.add((double)count);
 851   }
 852   st->print_cr("StringTable statistics:");
 853   st->print_cr("Number of buckets       : %7d", summary.num());
 854   st->print_cr("Average bucket size     : %7.0f", summary.avg());
 855   st->print_cr("Variance of bucket size : %7.0f", summary.variance());
 856   st->print_cr("Std. dev. of bucket size: %7.0f", summary.sd());
 857   st->print_cr("Maximum bucket size     : %7.0f", summary.maximum());
 858 }
 859 
 860 
 861 // Create a new table and using alternate hash code, populate the new table
 862 // with the existing strings.   Set flag to use the alternate hash code afterwards.
 863 void StringTable::rehash_table() {
 864   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 865   // This should never happen with -Xshare:dump but it might in testing mode.
 866   if (DumpSharedSpaces) return;
 867   StringTable* new_table = new StringTable();
 868 
 869   // Rehash the table
 870   the_table()->move_to(new_table);
 871 
 872   // Delete the table and buckets (entries are reused in new table).
 873   delete _the_table;
 874   // Don't check if we need rehashing until the table gets unbalanced again.
 875   // Then rehash with a new global seed.
 876   _needs_rehashing = false;
 877   _the_table = new_table;
 878 }