1 /*
  2  * Copyright (c) 1997, 2023, 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 "cds/archiveBuilder.hpp"
 27 #include "cds/cdsConfig.hpp"
 28 #include "cds/dynamicArchive.hpp"
 29 #include "classfile/altHashing.hpp"
 30 #include "classfile/classLoaderData.hpp"
 31 #include "classfile/compactHashtable.hpp"
 32 #include "classfile/javaClasses.hpp"
 33 #include "classfile/symbolTable.hpp"
 34 #include "memory/allocation.inline.hpp"
 35 #include "memory/metaspaceClosure.hpp"
 36 #include "memory/resourceArea.hpp"
 37 #include "oops/oop.inline.hpp"
 38 #include "runtime/atomic.hpp"
 39 #include "runtime/interfaceSupport.inline.hpp"
 40 #include "runtime/timerTrace.hpp"
 41 #include "runtime/trimNativeHeap.hpp"
 42 #include "services/diagnosticCommand.hpp"
 43 #include "utilities/concurrentHashTable.inline.hpp"
 44 #include "utilities/concurrentHashTableTasks.inline.hpp"
 45 #include "utilities/utf8.hpp"
 46 
 47 // We used to not resize at all, so let's be conservative
 48 // and not set it too short before we decide to resize,
 49 // to match previous startup behavior
 50 const double PREF_AVG_LIST_LEN = 8.0;
 51 // 2^24 is max size, like StringTable.
 52 const size_t END_SIZE = 24;
 53 // If a chain gets to 100 something might be wrong
 54 const size_t REHASH_LEN = 100;
 55 
 56 const size_t ON_STACK_BUFFER_LENGTH = 128;
 57 
 58 // --------------------------------------------------------------------------
 59 
 60 inline bool symbol_equals_compact_hashtable_entry(Symbol* value, const char* key, int len) {
 61   if (value->equals(key, len)) {
 62     return true;
 63   } else {
 64     return false;
 65   }
 66 }
 67 
 68 static OffsetCompactHashtable<
 69   const char*, Symbol*,
 70   symbol_equals_compact_hashtable_entry
 71 > _shared_table;
 72 
 73 static OffsetCompactHashtable<
 74   const char*, Symbol*,
 75   symbol_equals_compact_hashtable_entry
 76 > _dynamic_shared_table;
 77 
 78 // --------------------------------------------------------------------------
 79 
 80 typedef ConcurrentHashTable<SymbolTableConfig, mtSymbol> SymbolTableHash;
 81 static SymbolTableHash* _local_table = nullptr;
 82 
 83 volatile bool SymbolTable::_has_work = 0;
 84 volatile bool SymbolTable::_needs_rehashing = false;
 85 
 86 // For statistics
 87 static size_t _symbols_removed = 0;
 88 static size_t _symbols_counted = 0;
 89 static size_t _current_size = 0;
 90 
 91 static volatile size_t _items_count = 0;
 92 static volatile bool   _has_items_to_clean = false;
 93 
 94 
 95 static volatile bool _alt_hash = false;
 96 
 97 #ifdef USE_LIBRARY_BASED_TLS_ONLY
 98 static volatile bool _lookup_shared_first = false;
 99 #else
100 // "_lookup_shared_first" can get highly contended with many cores if multiple threads
101 // are updating "lookup success history" in a global shared variable. If built-in TLS is available, use it.
102 static THREAD_LOCAL bool _lookup_shared_first = false;
103 #endif
104 
105 // Static arena for symbols that are not deallocated
106 Arena* SymbolTable::_arena = nullptr;
107 
108 static bool _rehashed = false;
109 static uint64_t _alt_hash_seed = 0;
110 
111 static inline void log_trace_symboltable_helper(Symbol* sym, const char* msg) {
112 #ifndef PRODUCT
113   ResourceMark rm;
114   log_trace(symboltable)("%s [%s]", msg, sym->as_quoted_ascii());
115 #endif // PRODUCT
116 }
117 
118 // Pick hashing algorithm.
119 static unsigned int hash_symbol(const char* s, int len, bool useAlt) {
120   return useAlt ?
121   AltHashing::halfsiphash_32(_alt_hash_seed, (const uint8_t*)s, len) :
122   java_lang_String::hash_code((const jbyte*)s, len);
123 }
124 
125 #if INCLUDE_CDS
126 static unsigned int hash_shared_symbol(const char* s, int len) {
127   return java_lang_String::hash_code((const jbyte*)s, len);
128 }
129 #endif
130 
131 class SymbolTableConfig : public AllStatic {
132 
133 public:
134   typedef Symbol Value;  // value of the Node in the hashtable
135 
136   static uintx get_hash(Value const& value, bool* is_dead) {
137     *is_dead = (value.refcount() == 0);
138     if (*is_dead) {
139       return 0;
140     } else {
141       return hash_symbol((const char*)value.bytes(), value.utf8_length(), _alt_hash);
142     }
143   }
144   // We use default allocation/deallocation but counted
145   static void* allocate_node(void* context, size_t size, Value const& value) {
146     SymbolTable::item_added();
147     return allocate_node_impl(size, value);
148   }
149   static void free_node(void* context, void* memory, Value & value) {
150     // We get here because #1 some threads lost a race to insert a newly created Symbol
151     // or #2 we're cleaning up unused symbol.
152     // If #1, then the symbol can be either permanent,
153     // or regular newly created one (refcount==1)
154     // If #2, then the symbol is dead (refcount==0)
155     assert(value.is_permanent() || (value.refcount() == 1) || (value.refcount() == 0),
156            "refcount %d", value.refcount());
157 #if INCLUDE_CDS
158     if (CDSConfig::is_dumping_static_archive()) {
159       // We have allocated with MetaspaceShared::symbol_space_alloc(). No deallocation is needed.
160       // Unreferenced Symbols will not be copied into the archive.
161       return;
162     }
163 #endif
164     if (value.refcount() == 1) {
165       value.decrement_refcount();
166       assert(value.refcount() == 0, "expected dead symbol");
167     }
168     if (value.refcount() != PERM_REFCOUNT) {
169       FreeHeap(memory);
170     } else {
171       MutexLocker ml(SymbolArena_lock, Mutex::_no_safepoint_check_flag); // Protect arena
172       // Deleting permanent symbol should not occur very often (insert race condition),
173       // so log it.
174       log_trace_symboltable_helper(&value, "Freeing permanent symbol");
175       size_t alloc_size = _local_table->get_node_size() + value.byte_size() + value.effective_length();
176       if (!SymbolTable::arena()->Afree(memory, alloc_size)) {
177         log_trace_symboltable_helper(&value, "Leaked permanent symbol");
178       }
179     }
180     SymbolTable::item_removed();
181   }
182 
183 private:
184   static void* allocate_node_impl(size_t size, Value const& value) {
185     size_t alloc_size = size + value.byte_size() + value.effective_length();
186 #if INCLUDE_CDS
187     if (CDSConfig::is_dumping_static_archive()) {
188       MutexLocker ml(DumpRegion_lock, Mutex::_no_safepoint_check_flag);
189       // To get deterministic output from -Xshare:dump, we ensure that Symbols are allocated in
190       // increasing addresses. When the symbols are copied into the archive, we preserve their
191       // relative address order (sorted, see ArchiveBuilder::gather_klasses_and_symbols).
192       //
193       // We cannot use arena because arena chunks are allocated by the OS. As a result, for example,
194       // the archived symbol of "java/lang/Object" may sometimes be lower than "java/lang/String", and
195       // sometimes be higher. This would cause non-deterministic contents in the archive.
196       DEBUG_ONLY(static void* last = 0);
197       void* p = (void*)MetaspaceShared::symbol_space_alloc(alloc_size);
198       assert(p > last, "must increase monotonically");
199       DEBUG_ONLY(last = p);
200       return p;
201     }
202 #endif
203     if (value.refcount() != PERM_REFCOUNT) {
204       return AllocateHeap(alloc_size, mtSymbol);
205     } else {
206       // Allocate to global arena
207       MutexLocker ml(SymbolArena_lock, Mutex::_no_safepoint_check_flag); // Protect arena
208       return SymbolTable::arena()->Amalloc(alloc_size);
209     }
210   }
211 };
212 
213 void SymbolTable::create_table ()  {
214   size_t start_size_log_2 = ceil_log2(SymbolTableSize);
215   _current_size = ((size_t)1) << start_size_log_2;
216   log_trace(symboltable)("Start size: " SIZE_FORMAT " (" SIZE_FORMAT ")",
217                          _current_size, start_size_log_2);
218   _local_table = new SymbolTableHash(start_size_log_2, END_SIZE, REHASH_LEN, true);
219 
220   // Initialize the arena for global symbols, size passed in depends on CDS.
221   if (symbol_alloc_arena_size == 0) {
222     _arena = new (mtSymbol) Arena(mtSymbol);
223   } else {
224     _arena = new (mtSymbol) Arena(mtSymbol, Arena::Tag::tag_other, symbol_alloc_arena_size);
225   }
226 }
227 
228 void SymbolTable::reset_has_items_to_clean() { Atomic::store(&_has_items_to_clean, false); }
229 void SymbolTable::mark_has_items_to_clean()  { Atomic::store(&_has_items_to_clean, true); }
230 bool SymbolTable::has_items_to_clean()       { return Atomic::load(&_has_items_to_clean); }
231 
232 void SymbolTable::item_added() {
233   Atomic::inc(&_items_count);
234 }
235 
236 void SymbolTable::item_removed() {
237   Atomic::inc(&(_symbols_removed));
238   Atomic::dec(&_items_count);
239 }
240 
241 double SymbolTable::get_load_factor() {
242   return (double)_items_count/(double)_current_size;
243 }
244 
245 size_t SymbolTable::table_size() {
246   return ((size_t)1) << _local_table->get_size_log2(Thread::current());
247 }
248 
249 void SymbolTable::trigger_cleanup() {
250   MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
251   _has_work = true;
252   Service_lock->notify_all();
253 }
254 
255 class SymbolsDo : StackObj {
256   SymbolClosure *_cl;
257 public:
258   SymbolsDo(SymbolClosure *cl) : _cl(cl) {}
259   bool operator()(Symbol* value) {
260     assert(value != nullptr, "expected valid value");
261     _cl->do_symbol(&value);
262     return true;
263   };
264 };
265 
266 class SharedSymbolIterator {
267   SymbolClosure* _symbol_closure;
268 public:
269   SharedSymbolIterator(SymbolClosure* f) : _symbol_closure(f) {}
270   void do_value(Symbol* symbol) {
271     _symbol_closure->do_symbol(&symbol);
272   }
273 };
274 
275 // Call function for all symbols in the symbol table.
276 void SymbolTable::symbols_do(SymbolClosure *cl) {
277   assert(SafepointSynchronize::is_at_safepoint(), "Must be at safepoint");
278   // all symbols from shared table
279   SharedSymbolIterator iter(cl);
280   _shared_table.iterate(&iter);
281   _dynamic_shared_table.iterate(&iter);
282 
283   // all symbols from the dynamic table
284   SymbolsDo sd(cl);
285   _local_table->do_safepoint_scan(sd);
286 }
287 
288 // Call function for all symbols in shared table. Used by -XX:+PrintSharedArchiveAndExit
289 void SymbolTable::shared_symbols_do(SymbolClosure *cl) {
290   SharedSymbolIterator iter(cl);
291   _shared_table.iterate(&iter);
292   _dynamic_shared_table.iterate(&iter);
293 }
294 
295 Symbol* SymbolTable::lookup_dynamic(const char* name,
296                                     int len, unsigned int hash) {
297   Symbol* sym = do_lookup(name, len, hash);
298   assert((sym == nullptr) || sym->refcount() != 0, "refcount must not be zero");
299   return sym;
300 }
301 
302 #if INCLUDE_CDS
303 Symbol* SymbolTable::lookup_shared(const char* name,
304                                    int len, unsigned int hash) {
305   Symbol* sym = nullptr;
306   if (!_shared_table.empty()) {
307     if (_alt_hash) {
308       // hash_code parameter may use alternate hashing algorithm but the shared table
309       // always uses the same original hash code.
310       hash = hash_shared_symbol(name, len);
311     }
312     sym = _shared_table.lookup(name, hash, len);
313     if (sym == nullptr && DynamicArchive::is_mapped()) {
314       sym = _dynamic_shared_table.lookup(name, hash, len);
315     }
316   }
317   return sym;
318 }
319 #endif
320 
321 Symbol* SymbolTable::lookup_common(const char* name,
322                             int len, unsigned int hash) {
323   Symbol* sym;
324   if (_lookup_shared_first) {
325     sym = lookup_shared(name, len, hash);
326     if (sym == nullptr) {
327       _lookup_shared_first = false;
328       sym = lookup_dynamic(name, len, hash);
329     }
330   } else {
331     sym = lookup_dynamic(name, len, hash);
332     if (sym == nullptr) {
333       sym = lookup_shared(name, len, hash);
334       if (sym != nullptr) {
335         _lookup_shared_first = true;
336       }
337     }
338   }
339   return sym;
340 }
341 
342 Symbol* SymbolTable::new_symbol(const char* name, int len) {
343   assert(len <= Symbol::max_length(), "sanity");
344   unsigned int hash = hash_symbol(name, len, _alt_hash);
345   Symbol* sym = lookup_common(name, len, hash);
346   if (sym == nullptr) {
347     sym = do_add_if_needed(name, len, hash, /* is_permanent */ false);
348   }
349   assert(sym->refcount() != 0, "lookup should have incremented the count");
350   assert(sym->equals(name, len), "symbol must be properly initialized");
351   return sym;
352 }
353 
354 Symbol* SymbolTable::new_symbol(const Symbol* sym, int begin, int end) {
355   assert(begin <= end && end <= sym->utf8_length(), "just checking");
356   assert(sym->refcount() != 0, "require a valid symbol");
357   const char* name = (const char*)sym->base() + begin;
358   int len = end - begin;
359   assert(len <= Symbol::max_length(), "sanity");
360   unsigned int hash = hash_symbol(name, len, _alt_hash);
361   Symbol* found = lookup_common(name, len, hash);
362   if (found == nullptr) {
363     found = do_add_if_needed(name, len, hash, /* is_permanent */ false);
364   }
365   return found;
366 }
367 
368 class SymbolTableLookup : StackObj {
369 private:
370   uintx _hash;
371   int _len;
372   const char* _str;
373 public:
374   SymbolTableLookup(const char* key, int len, uintx hash)
375   : _hash(hash), _len(len), _str(key) {}
376   uintx get_hash() const {
377     return _hash;
378   }
379   // Note: When equals() returns "true", the symbol's refcount is incremented. This is
380   // needed to ensure that the symbol is kept alive before equals() returns to the caller,
381   // so that another thread cannot clean the symbol up concurrently. The caller is
382   // responsible for decrementing the refcount, when the symbol is no longer needed.
383   bool equals(Symbol* value) {
384     assert(value != nullptr, "expected valid value");
385     Symbol *sym = value;
386     if (sym->equals(_str, _len)) {
387       if (sym->try_increment_refcount()) {
388         // something is referencing this symbol now.
389         return true;
390       } else {
391         assert(sym->refcount() == 0, "expected dead symbol");
392         return false;
393       }
394     } else {
395       return false;
396     }
397   }
398   bool is_dead(Symbol* value) {
399     return value->refcount() == 0;
400   }
401 };
402 
403 class SymbolTableGet : public StackObj {
404   Symbol* _return;
405 public:
406   SymbolTableGet() : _return(nullptr) {}
407   void operator()(Symbol* value) {
408     assert(value != nullptr, "expected valid value");
409     _return = value;
410   }
411   Symbol* get_res_sym() const {
412     return _return;
413   }
414 };
415 
416 Symbol* SymbolTable::do_lookup(const char* name, int len, uintx hash) {
417   Thread* thread = Thread::current();
418   SymbolTableLookup lookup(name, len, hash);
419   SymbolTableGet stg;
420   bool rehash_warning = false;
421   _local_table->get(thread, lookup, stg, &rehash_warning);
422   update_needs_rehash(rehash_warning);
423   Symbol* sym = stg.get_res_sym();
424   assert((sym == nullptr) || sym->refcount() != 0, "found dead symbol");
425   return sym;
426 }
427 
428 Symbol* SymbolTable::lookup_only(const char* name, int len, unsigned int& hash) {
429   hash = hash_symbol(name, len, _alt_hash);
430   return lookup_common(name, len, hash);
431 }
432 
433 // Suggestion: Push unicode-based lookup all the way into the hashing
434 // and probing logic, so there is no need for convert_to_utf8 until
435 // an actual new Symbol* is created.
436 Symbol* SymbolTable::new_symbol(const jchar* name, int utf16_length) {
437   int utf8_length = UNICODE::utf8_length((jchar*) name, utf16_length);
438   char stack_buf[ON_STACK_BUFFER_LENGTH];
439   if (utf8_length < (int) sizeof(stack_buf)) {
440     char* chars = stack_buf;
441     UNICODE::convert_to_utf8(name, utf16_length, chars);
442     return new_symbol(chars, utf8_length);
443   } else {
444     ResourceMark rm;
445     char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);
446     UNICODE::convert_to_utf8(name, utf16_length, chars);
447     return new_symbol(chars, utf8_length);
448   }
449 }
450 
451 Symbol* SymbolTable::lookup_only_unicode(const jchar* name, int utf16_length,
452                                          unsigned int& hash) {
453   int utf8_length = UNICODE::utf8_length((jchar*) name, utf16_length);
454   char stack_buf[ON_STACK_BUFFER_LENGTH];
455   if (utf8_length < (int) sizeof(stack_buf)) {
456     char* chars = stack_buf;
457     UNICODE::convert_to_utf8(name, utf16_length, chars);
458     return lookup_only(chars, utf8_length, hash);
459   } else {
460     ResourceMark rm;
461     char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);
462     UNICODE::convert_to_utf8(name, utf16_length, chars);
463     return lookup_only(chars, utf8_length, hash);
464   }
465 }
466 
467 void SymbolTable::new_symbols(ClassLoaderData* loader_data, const constantPoolHandle& cp,
468                               int names_count, const char** names, int* lengths,
469                               int* cp_indices, unsigned int* hashValues) {
470   // Note that is_permanent will be false for non-strong hidden classes.
471   // even if their loader is the boot loader because they will have a different cld.
472   bool is_permanent = loader_data->is_the_null_class_loader_data();
473   for (int i = 0; i < names_count; i++) {
474     const char *name = names[i];
475     int len = lengths[i];
476     unsigned int hash = hashValues[i];
477     assert(lookup_shared(name, len, hash) == nullptr, "must have checked already");
478     Symbol* sym = do_add_if_needed(name, len, hash, is_permanent);
479     assert(sym->refcount() != 0, "lookup should have incremented the count");
480     cp->symbol_at_put(cp_indices[i], sym);
481   }
482 }
483 
484 Symbol* SymbolTable::do_add_if_needed(const char* name, int len, uintx hash, bool is_permanent) {
485   SymbolTableLookup lookup(name, len, hash);
486   SymbolTableGet stg;
487   bool clean_hint = false;
488   bool rehash_warning = false;
489   Thread* current = Thread::current();
490   Symbol* sym;
491 
492   ResourceMark rm(current);
493   const int alloc_size = Symbol::byte_size(len);
494   u1* u1_buf = NEW_RESOURCE_ARRAY_IN_THREAD(current, u1, alloc_size);
495   Symbol* tmp = ::new ((void*)u1_buf) Symbol((const u1*)name, len,
496                                              (is_permanent || CDSConfig::is_dumping_static_archive()) ? PERM_REFCOUNT : 1);
497 
498   do {
499     if (_local_table->insert(current, lookup, *tmp, &rehash_warning, &clean_hint)) {
500       if (_local_table->get(current, lookup, stg, &rehash_warning)) {
501         sym = stg.get_res_sym();
502         // The get adds one to ref count, but we inserted with our ref already included.
503         // Therefore decrement with one.
504         if (sym->refcount() != PERM_REFCOUNT) {
505           sym->decrement_refcount();
506         }
507         break;
508       }
509     }
510 
511     // In case another thread did a concurrent add, return value already in the table.
512     // This could fail if the symbol got deleted concurrently, so loop back until success.
513     if (_local_table->get(current, lookup, stg, &rehash_warning)) {
514       // The lookup added a refcount, which is ours.
515       sym = stg.get_res_sym();
516       break;
517     }
518   } while(true);
519 
520   update_needs_rehash(rehash_warning);
521 
522   if (clean_hint) {
523     mark_has_items_to_clean();
524     check_concurrent_work();
525   }
526 
527   assert((sym == nullptr) || sym->refcount() != 0, "found dead symbol");
528   return sym;
529 }
530 
531 Symbol* SymbolTable::new_permanent_symbol(const char* name) {
532   unsigned int hash = 0;
533   int len = (int)strlen(name);
534   Symbol* sym = SymbolTable::lookup_only(name, len, hash);
535   if (sym == nullptr) {
536     sym = do_add_if_needed(name, len, hash, /* is_permanent */ true);
537   }
538   if (!sym->is_permanent()) {
539     sym->make_permanent();
540     log_trace_symboltable_helper(sym, "Asked for a permanent symbol, but got a regular one");
541   }
542   return sym;
543 }
544 
545 struct SizeFunc : StackObj {
546   size_t operator()(Symbol* value) {
547     assert(value != nullptr, "expected valid value");
548     return (value)->size() * HeapWordSize;
549   };
550 };
551 
552 TableStatistics SymbolTable::get_table_statistics() {
553   static TableStatistics ts;
554   SizeFunc sz;
555   ts = _local_table->statistics_get(Thread::current(), sz, ts);
556   return ts;
557 }
558 
559 void SymbolTable::print_table_statistics(outputStream* st) {
560   SizeFunc sz;
561   _local_table->statistics_to(Thread::current(), sz, st, "SymbolTable");
562 
563   if (!_shared_table.empty()) {
564     _shared_table.print_table_statistics(st, "Shared Symbol Table");
565   }
566 
567   if (!_dynamic_shared_table.empty()) {
568     _dynamic_shared_table.print_table_statistics(st, "Dynamic Shared Symbol Table");
569   }
570 }
571 
572 // Verification
573 class VerifySymbols : StackObj {
574 public:
575   bool operator()(Symbol* value) {
576     guarantee(value != nullptr, "expected valid value");
577     Symbol* sym = value;
578     guarantee(sym->equals((const char*)sym->bytes(), sym->utf8_length()),
579               "symbol must be internally consistent");
580     return true;
581   };
582 };
583 
584 void SymbolTable::verify() {
585   Thread* thr = Thread::current();
586   VerifySymbols vs;
587   if (!_local_table->try_scan(thr, vs)) {
588     log_info(symboltable)("verify unavailable at this moment");
589   }
590 }
591 
592 static void print_symbol(outputStream* st, Symbol* sym) {
593   const char* utf8_string = (const char*)sym->bytes();
594   int utf8_length = sym->utf8_length();
595   st->print("%d %d: ", utf8_length, sym->refcount());
596   HashtableTextDump::put_utf8(st, utf8_string, utf8_length);
597   st->cr();
598 }
599 
600 // Dumping
601 class DumpSymbol : StackObj {
602   Thread* _thr;
603   outputStream* _st;
604 public:
605   DumpSymbol(Thread* thr, outputStream* st) : _thr(thr), _st(st) {}
606   bool operator()(Symbol* value) {
607     assert(value != nullptr, "expected valid value");
608     print_symbol(_st, value);
609     return true;
610   };
611 };
612 
613 class DumpSharedSymbol : StackObj {
614   outputStream* _st;
615 public:
616   DumpSharedSymbol(outputStream* st) : _st(st) {}
617   void do_value(Symbol* value) {
618     assert(value != nullptr, "value should point to a symbol");
619     print_symbol(_st, value);
620   };
621 };
622 
623 void SymbolTable::dump(outputStream* st, bool verbose) {
624   if (!verbose) {
625     print_table_statistics(st);
626   } else {
627     Thread* thr = Thread::current();
628     ResourceMark rm(thr);
629     st->print_cr("VERSION: 1.1");
630     DumpSymbol ds(thr, st);
631     if (!_local_table->try_scan(thr, ds)) {
632       log_info(symboltable)("dump unavailable at this moment");
633     }
634     if (!_shared_table.empty()) {
635       st->print_cr("#----------------");
636       st->print_cr("# Shared symbols:");
637       st->print_cr("#----------------");
638       DumpSharedSymbol dss(st);
639       _shared_table.iterate(&dss);
640     }
641     if (!_dynamic_shared_table.empty()) {
642       st->print_cr("#------------------------");
643       st->print_cr("# Dynamic shared symbols:");
644       st->print_cr("#------------------------");
645       DumpSharedSymbol dss(st);
646       _dynamic_shared_table.iterate(&dss);
647     }
648   }
649 }
650 
651 #if INCLUDE_CDS
652 void SymbolTable::copy_shared_symbol_table(GrowableArray<Symbol*>* symbols,
653                                            CompactHashtableWriter* writer) {
654   ArchiveBuilder* builder = ArchiveBuilder::current();
655   int len = symbols->length();
656   for (int i = 0; i < len; i++) {
657     Symbol* sym = ArchiveBuilder::get_buffered_symbol(symbols->at(i));
658     unsigned int fixed_hash = hash_shared_symbol((const char*)sym->bytes(), sym->utf8_length());
659     assert(fixed_hash == hash_symbol((const char*)sym->bytes(), sym->utf8_length(), false),
660            "must not rehash during dumping");
661     sym->set_permanent();
662     writer->add(fixed_hash, builder->buffer_to_offset_u4((address)sym));
663   }
664 }
665 
666 size_t SymbolTable::estimate_size_for_archive() {
667   if (_items_count > (size_t)max_jint) {
668     fatal("Too many symbols to be archived: %zu", _items_count);
669   }
670   return CompactHashtableWriter::estimate_size(int(_items_count));
671 }
672 
673 void SymbolTable::write_to_archive(GrowableArray<Symbol*>* symbols) {
674   CompactHashtableWriter writer(int(_items_count), ArchiveBuilder::symbol_stats());
675   copy_shared_symbol_table(symbols, &writer);
676   if (CDSConfig::is_dumping_static_archive()) {
677     _shared_table.reset();
678     writer.dump(&_shared_table, "symbol");
679   } else {
680     assert(CDSConfig::is_dumping_dynamic_archive(), "must be");
681     _dynamic_shared_table.reset();
682     writer.dump(&_dynamic_shared_table, "symbol");
683   }
684 }
685 
686 void SymbolTable::serialize_shared_table_header(SerializeClosure* soc,
687                                                 bool is_static_archive) {
688   OffsetCompactHashtable<const char*, Symbol*, symbol_equals_compact_hashtable_entry> * table;
689   if (is_static_archive) {
690     table = &_shared_table;
691   } else {
692     table = &_dynamic_shared_table;
693   }
694   table->serialize_header(soc);
695   if (soc->writing()) {
696     // Sanity. Make sure we don't use the shared table at dump time
697     table->reset();
698   }
699 }
700 #endif //INCLUDE_CDS
701 
702 // Concurrent work
703 void SymbolTable::grow(JavaThread* jt) {
704   SymbolTableHash::GrowTask gt(_local_table);
705   if (!gt.prepare(jt)) {
706     return;
707   }
708   log_trace(symboltable)("Started to grow");
709   {
710     TraceTime timer("Grow", TRACETIME_LOG(Debug, symboltable, perf));
711     while (gt.do_task(jt)) {
712       gt.pause(jt);
713       {
714         ThreadBlockInVM tbivm(jt);
715       }
716       gt.cont(jt);
717     }
718   }
719   gt.done(jt);
720   _current_size = table_size();
721   log_debug(symboltable)("Grown to size:" SIZE_FORMAT, _current_size);
722 }
723 
724 struct SymbolTableDoDelete : StackObj {
725   size_t _deleted;
726   SymbolTableDoDelete() : _deleted(0) {}
727   void operator()(Symbol* value) {
728     assert(value != nullptr, "expected valid value");
729     Symbol *sym = value;
730     assert(sym->refcount() == 0, "refcount");
731     _deleted++;
732   }
733 };
734 
735 struct SymbolTableDeleteCheck : StackObj {
736   size_t _processed;
737   SymbolTableDeleteCheck() : _processed(0) {}
738   bool operator()(Symbol* value) {
739     assert(value != nullptr, "expected valid value");
740     _processed++;
741     Symbol *sym = value;
742     return (sym->refcount() == 0);
743   }
744 };
745 
746 void SymbolTable::clean_dead_entries(JavaThread* jt) {
747   SymbolTableHash::BulkDeleteTask bdt(_local_table);
748   if (!bdt.prepare(jt)) {
749     return;
750   }
751 
752   SymbolTableDeleteCheck stdc;
753   SymbolTableDoDelete stdd;
754   NativeHeapTrimmer::SuspendMark sm("symboltable");
755   {
756     TraceTime timer("Clean", TRACETIME_LOG(Debug, symboltable, perf));
757     while (bdt.do_task(jt, stdc, stdd)) {
758       bdt.pause(jt);
759       {
760         ThreadBlockInVM tbivm(jt);
761       }
762       bdt.cont(jt);
763     }
764     reset_has_items_to_clean();
765     bdt.done(jt);
766   }
767 
768   Atomic::add(&_symbols_counted, stdc._processed);
769 
770   log_debug(symboltable)("Cleaned " SIZE_FORMAT " of " SIZE_FORMAT,
771                          stdd._deleted, stdc._processed);
772 }
773 
774 void SymbolTable::check_concurrent_work() {
775   if (_has_work) {
776     return;
777   }
778   // We should clean/resize if we have
779   // more items than preferred load factor or
780   // more dead items than water mark.
781   if (has_items_to_clean() || (get_load_factor() > PREF_AVG_LIST_LEN)) {
782     log_debug(symboltable)("Concurrent work triggered, load factor: %f, items to clean: %s",
783                            get_load_factor(), has_items_to_clean() ? "true" : "false");
784     trigger_cleanup();
785   }
786 }
787 
788 void SymbolTable::do_concurrent_work(JavaThread* jt) {
789   double load_factor = get_load_factor();
790   log_debug(symboltable, perf)("Concurrent work, live factor: %g", load_factor);
791   // We prefer growing, since that also removes dead items
792   if (load_factor > PREF_AVG_LIST_LEN && !_local_table->is_max_size_reached()) {
793     grow(jt);
794   } else {
795     clean_dead_entries(jt);
796   }
797   _has_work = false;
798 }
799 
800 // Rehash
801 bool SymbolTable::do_rehash() {
802   if (!_local_table->is_safepoint_safe()) {
803     return false;
804   }
805 
806   // We use current size
807   size_t new_size = _local_table->get_size_log2(Thread::current());
808   SymbolTableHash* new_table = new SymbolTableHash(new_size, END_SIZE, REHASH_LEN, true);
809   // Use alt hash from now on
810   _alt_hash = true;
811   if (!_local_table->try_move_nodes_to(Thread::current(), new_table)) {
812     _alt_hash = false;
813     delete new_table;
814     return false;
815   }
816 
817   // free old table
818   delete _local_table;
819   _local_table = new_table;
820 
821   return true;
822 }
823 
824 bool SymbolTable::should_grow() {
825   return get_load_factor() > PREF_AVG_LIST_LEN && !_local_table->is_max_size_reached();
826 }
827 
828 bool SymbolTable::rehash_table_expects_safepoint_rehashing() {
829   // No rehashing required
830   if (!needs_rehashing()) {
831     return false;
832   }
833 
834   // Grow instead of rehash
835   if (should_grow()) {
836     return false;
837   }
838 
839   // Already rehashed
840   if (_rehashed) {
841     return false;
842   }
843 
844   // Resizing in progress
845   if (!_local_table->is_safepoint_safe()) {
846     return false;
847   }
848 
849   return true;
850 }
851 
852 void SymbolTable::rehash_table() {
853   log_debug(symboltable)("Table imbalanced, rehashing called.");
854 
855   // Grow instead of rehash.
856   if (should_grow()) {
857     log_debug(symboltable)("Choosing growing over rehashing.");
858     trigger_cleanup();
859     _needs_rehashing = false;
860     return;
861   }
862 
863   // Already rehashed.
864   if (_rehashed) {
865     log_warning(symboltable)("Rehashing already done, still long lists.");
866     trigger_cleanup();
867     _needs_rehashing = false;
868     return;
869   }
870 
871   _alt_hash_seed = AltHashing::compute_seed();
872 
873   if (do_rehash()) {
874     _rehashed = true;
875   } else {
876     log_info(symboltable)("Resizes in progress rehashing skipped.");
877   }
878 
879   _needs_rehashing = false;
880 }
881 
882 //---------------------------------------------------------------------------
883 // Non-product code
884 
885 #ifndef PRODUCT
886 
887 class HistogramIterator : StackObj {
888 public:
889   static const size_t results_length = 100;
890   size_t counts[results_length];
891   size_t sizes[results_length];
892   size_t total_size;
893   size_t total_count;
894   size_t total_length;
895   size_t max_length;
896   size_t out_of_range_count;
897   size_t out_of_range_size;
898   HistogramIterator() : total_size(0), total_count(0), total_length(0),
899                         max_length(0), out_of_range_count(0), out_of_range_size(0) {
900     // initialize results to zero
901     for (size_t i = 0; i < results_length; i++) {
902       counts[i] = 0;
903       sizes[i] = 0;
904     }
905   }
906   bool operator()(Symbol* value) {
907     assert(value != nullptr, "expected valid value");
908     Symbol* sym = value;
909     size_t size = sym->size();
910     size_t len = sym->utf8_length();
911     if (len < results_length) {
912       counts[len]++;
913       sizes[len] += size;
914     } else {
915       out_of_range_count++;
916       out_of_range_size += size;
917     }
918     total_count++;
919     total_size += size;
920     total_length += len;
921     max_length = MAX2(max_length, len);
922 
923     return true;
924   };
925 };
926 
927 void SymbolTable::print_histogram() {
928   HistogramIterator hi;
929   _local_table->do_scan(Thread::current(), hi);
930   tty->print_cr("Symbol Table Histogram:");
931   tty->print_cr("  Total number of symbols  " SIZE_FORMAT_W(7), hi.total_count);
932   tty->print_cr("  Total size in memory     " SIZE_FORMAT_W(7) "K", (hi.total_size * wordSize) / K);
933   tty->print_cr("  Total counted            " SIZE_FORMAT_W(7), _symbols_counted);
934   tty->print_cr("  Total removed            " SIZE_FORMAT_W(7), _symbols_removed);
935   if (_symbols_counted > 0) {
936     tty->print_cr("  Percent removed          %3.2f",
937           ((double)_symbols_removed / (double)_symbols_counted) * 100);
938   }
939   tty->print_cr("  Reference counts         " SIZE_FORMAT_W(7), Symbol::_total_count);
940   tty->print_cr("  Symbol arena used        " SIZE_FORMAT_W(7) "K", arena()->used() / K);
941   tty->print_cr("  Symbol arena size        " SIZE_FORMAT_W(7) "K", arena()->size_in_bytes() / K);
942   tty->print_cr("  Total symbol length      " SIZE_FORMAT_W(7), hi.total_length);
943   tty->print_cr("  Maximum symbol length    " SIZE_FORMAT_W(7), hi.max_length);
944   tty->print_cr("  Average symbol length    %7.2f", ((double)hi.total_length / (double)hi.total_count));
945   tty->print_cr("  Symbol length histogram:");
946   tty->print_cr("    %6s %10s %10s", "Length", "#Symbols", "Size");
947   for (size_t i = 0; i < hi.results_length; i++) {
948     if (hi.counts[i] > 0) {
949       tty->print_cr("    " SIZE_FORMAT_W(6) " " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) "K",
950                     i, hi.counts[i], (hi.sizes[i] * wordSize) / K);
951     }
952   }
953   tty->print_cr("  >=" SIZE_FORMAT_W(6) " " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) "K\n",
954                 hi.results_length, hi.out_of_range_count, (hi.out_of_range_size*wordSize) / K);
955 }
956 #endif // PRODUCT
957 
958 // Utility for dumping symbols
959 SymboltableDCmd::SymboltableDCmd(outputStream* output, bool heap) :
960                                  DCmdWithParser(output, heap),
961   _verbose("-verbose", "Dump the content of each symbol in the table",
962            "BOOLEAN", false, "false") {
963   _dcmdparser.add_dcmd_option(&_verbose);
964 }
965 
966 void SymboltableDCmd::execute(DCmdSource source, TRAPS) {
967   VM_DumpHashtable dumper(output(), VM_DumpHashtable::DumpSymbols,
968                          _verbose.value());
969   VMThread::execute(&dumper);
970 }