src/share/vm/classfile/symbolTable.cpp

changeset 0
f90c822e73f8
child 6876
710a3c8b516e
equal deleted inserted replaced
-1:000000000000 0:f90c822e73f8
1 /*
2 * Copyright (c) 1997, 2014, 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 #if INCLUDE_ALL_GCS
39 #include "gc_implementation/g1/g1StringDedup.hpp"
40 #endif
41
42 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
43
44 // --------------------------------------------------------------------------
45
46 // the number of buckets a thread claims
47 const int ClaimChunkSize = 32;
48
49 SymbolTable* SymbolTable::_the_table = NULL;
50 // Static arena for symbols that are not deallocated
51 Arena* SymbolTable::_arena = NULL;
52 bool SymbolTable::_needs_rehashing = false;
53
54 Symbol* SymbolTable::allocate_symbol(const u1* name, int len, bool c_heap, TRAPS) {
55 assert (len <= Symbol::max_length(), "should be checked by caller");
56
57 Symbol* sym;
58
59 if (DumpSharedSpaces) {
60 // Allocate all symbols to CLD shared metaspace
61 sym = new (len, ClassLoaderData::the_null_class_loader_data(), THREAD) Symbol(name, len, -1);
62 } else if (c_heap) {
63 // refcount starts as 1
64 sym = new (len, THREAD) Symbol(name, len, 1);
65 assert(sym != NULL, "new should call vm_exit_out_of_memory if C_HEAP is exhausted");
66 } else {
67 // Allocate to global arena
68 sym = new (len, arena(), THREAD) Symbol(name, len, -1);
69 }
70 return sym;
71 }
72
73 void SymbolTable::initialize_symbols(int arena_alloc_size) {
74 // Initialize the arena for global symbols, size passed in depends on CDS.
75 if (arena_alloc_size == 0) {
76 _arena = new (mtSymbol) Arena();
77 } else {
78 _arena = new (mtSymbol) Arena(arena_alloc_size);
79 }
80 }
81
82 // Call function for all symbols in the symbol table.
83 void SymbolTable::symbols_do(SymbolClosure *cl) {
84 const int n = the_table()->table_size();
85 for (int i = 0; i < n; i++) {
86 for (HashtableEntry<Symbol*, mtSymbol>* p = the_table()->bucket(i);
87 p != NULL;
88 p = p->next()) {
89 cl->do_symbol(p->literal_addr());
90 }
91 }
92 }
93
94 int SymbolTable::_symbols_removed = 0;
95 int SymbolTable::_symbols_counted = 0;
96 volatile int SymbolTable::_parallel_claimed_idx = 0;
97
98 void SymbolTable::buckets_unlink(int start_idx, int end_idx, int* processed, int* removed, size_t* memory_total) {
99 for (int i = start_idx; i < end_idx; ++i) {
100 HashtableEntry<Symbol*, mtSymbol>** p = the_table()->bucket_addr(i);
101 HashtableEntry<Symbol*, mtSymbol>* entry = the_table()->bucket(i);
102 while (entry != NULL) {
103 // Shared entries are normally at the end of the bucket and if we run into
104 // a shared entry, then there is nothing more to remove. However, if we
105 // have rehashed the table, then the shared entries are no longer at the
106 // end of the bucket.
107 if (entry->is_shared() && !use_alternate_hashcode()) {
108 break;
109 }
110 Symbol* s = entry->literal();
111 (*memory_total) += s->size();
112 (*processed)++;
113 assert(s != NULL, "just checking");
114 // If reference count is zero, remove.
115 if (s->refcount() == 0) {
116 assert(!entry->is_shared(), "shared entries should be kept live");
117 delete s;
118 (*removed)++;
119 *p = entry->next();
120 the_table()->free_entry(entry);
121 } else {
122 p = entry->next_addr();
123 }
124 // get next entry
125 entry = (HashtableEntry<Symbol*, mtSymbol>*)HashtableEntry<Symbol*, mtSymbol>::make_ptr(*p);
126 }
127 }
128 }
129
130 // Remove unreferenced symbols from the symbol table
131 // This is done late during GC.
132 void SymbolTable::unlink(int* processed, int* removed) {
133 size_t memory_total = 0;
134 buckets_unlink(0, the_table()->table_size(), processed, removed, &memory_total);
135 _symbols_removed += *removed;
136 _symbols_counted += *processed;
137 // Exclude printing for normal PrintGCDetails because people parse
138 // this output.
139 if (PrintGCDetails && Verbose && WizardMode) {
140 gclog_or_tty->print(" [Symbols=%d size=" SIZE_FORMAT "K] ", *processed,
141 (memory_total*HeapWordSize)/1024);
142 }
143 }
144
145 void SymbolTable::possibly_parallel_unlink(int* processed, int* removed) {
146 const int limit = the_table()->table_size();
147
148 size_t memory_total = 0;
149
150 for (;;) {
151 // Grab next set of buckets to scan
152 int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
153 if (start_idx >= limit) {
154 // End of table
155 break;
156 }
157
158 int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
159 buckets_unlink(start_idx, end_idx, processed, removed, &memory_total);
160 }
161 Atomic::add(*processed, &_symbols_counted);
162 Atomic::add(*removed, &_symbols_removed);
163 // Exclude printing for normal PrintGCDetails because people parse
164 // this output.
165 if (PrintGCDetails && Verbose && WizardMode) {
166 gclog_or_tty->print(" [Symbols: scanned=%d removed=%d size=" SIZE_FORMAT "K] ", *processed, *removed,
167 (memory_total*HeapWordSize)/1024);
168 }
169 }
170
171 // Create a new table and using alternate hash code, populate the new table
172 // with the existing strings. Set flag to use the alternate hash code afterwards.
173 void SymbolTable::rehash_table() {
174 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
175 // This should never happen with -Xshare:dump but it might in testing mode.
176 if (DumpSharedSpaces) return;
177 // Create a new symbol table
178 SymbolTable* new_table = new SymbolTable();
179
180 the_table()->move_to(new_table);
181
182 // Delete the table and buckets (entries are reused in new table).
183 delete _the_table;
184 // Don't check if we need rehashing until the table gets unbalanced again.
185 // Then rehash with a new global seed.
186 _needs_rehashing = false;
187 _the_table = new_table;
188 }
189
190 // Lookup a symbol in a bucket.
191
192 Symbol* SymbolTable::lookup(int index, const char* name,
193 int len, unsigned int hash) {
194 int count = 0;
195 for (HashtableEntry<Symbol*, mtSymbol>* e = bucket(index); e != NULL; e = e->next()) {
196 count++; // count all entries in this bucket, not just ones with same hash
197 if (e->hash() == hash) {
198 Symbol* sym = e->literal();
199 if (sym->equals(name, len)) {
200 // something is referencing this symbol now.
201 sym->increment_refcount();
202 return sym;
203 }
204 }
205 }
206 // If the bucket size is too deep check if this hash code is insufficient.
207 if (count >= BasicHashtable<mtSymbol>::rehash_count && !needs_rehashing()) {
208 _needs_rehashing = check_rehash_table(count);
209 }
210 return NULL;
211 }
212
213 // Pick hashing algorithm.
214 unsigned int SymbolTable::hash_symbol(const char* s, int len) {
215 return use_alternate_hashcode() ?
216 AltHashing::murmur3_32(seed(), (const jbyte*)s, len) :
217 java_lang_String::hash_code(s, len);
218 }
219
220
221 // We take care not to be blocking while holding the
222 // SymbolTable_lock. Otherwise, the system might deadlock, since the
223 // symboltable is used during compilation (VM_thread) The lock free
224 // synchronization is simplified by the fact that we do not delete
225 // entries in the symbol table during normal execution (only during
226 // safepoints).
227
228 Symbol* SymbolTable::lookup(const char* name, int len, TRAPS) {
229 unsigned int hashValue = hash_symbol(name, len);
230 int index = the_table()->hash_to_index(hashValue);
231
232 Symbol* s = the_table()->lookup(index, name, len, hashValue);
233
234 // Found
235 if (s != NULL) return s;
236
237 // Grab SymbolTable_lock first.
238 MutexLocker ml(SymbolTable_lock, THREAD);
239
240 // Otherwise, add to symbol to table
241 return the_table()->basic_add(index, (u1*)name, len, hashValue, true, CHECK_NULL);
242 }
243
244 Symbol* SymbolTable::lookup(const Symbol* sym, int begin, int end, TRAPS) {
245 char* buffer;
246 int index, len;
247 unsigned int hashValue;
248 char* name;
249 {
250 debug_only(No_Safepoint_Verifier nsv;)
251
252 name = (char*)sym->base() + begin;
253 len = end - begin;
254 hashValue = hash_symbol(name, len);
255 index = the_table()->hash_to_index(hashValue);
256 Symbol* s = the_table()->lookup(index, name, len, hashValue);
257
258 // Found
259 if (s != NULL) return s;
260 }
261
262 // Otherwise, add to symbol to table. Copy to a C string first.
263 char stack_buf[128];
264 ResourceMark rm(THREAD);
265 if (len <= 128) {
266 buffer = stack_buf;
267 } else {
268 buffer = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, len);
269 }
270 for (int i=0; i<len; i++) {
271 buffer[i] = name[i];
272 }
273 // Make sure there is no safepoint in the code above since name can't move.
274 // We can't include the code in No_Safepoint_Verifier because of the
275 // ResourceMark.
276
277 // Grab SymbolTable_lock first.
278 MutexLocker ml(SymbolTable_lock, THREAD);
279
280 return the_table()->basic_add(index, (u1*)buffer, len, hashValue, true, CHECK_NULL);
281 }
282
283 Symbol* SymbolTable::lookup_only(const char* name, int len,
284 unsigned int& hash) {
285 hash = hash_symbol(name, len);
286 int index = the_table()->hash_to_index(hash);
287
288 Symbol* s = the_table()->lookup(index, name, len, hash);
289 return s;
290 }
291
292 // Look up the address of the literal in the SymbolTable for this Symbol*
293 // Do not create any new symbols
294 // Do not increment the reference count to keep this alive
295 Symbol** SymbolTable::lookup_symbol_addr(Symbol* sym){
296 unsigned int hash = hash_symbol((char*)sym->bytes(), sym->utf8_length());
297 int index = the_table()->hash_to_index(hash);
298
299 for (HashtableEntry<Symbol*, mtSymbol>* e = the_table()->bucket(index); e != NULL; e = e->next()) {
300 if (e->hash() == hash) {
301 Symbol* literal_sym = e->literal();
302 if (sym == literal_sym) {
303 return e->literal_addr();
304 }
305 }
306 }
307 return NULL;
308 }
309
310 // Suggestion: Push unicode-based lookup all the way into the hashing
311 // and probing logic, so there is no need for convert_to_utf8 until
312 // an actual new Symbol* is created.
313 Symbol* SymbolTable::lookup_unicode(const jchar* name, int utf16_length, TRAPS) {
314 int utf8_length = UNICODE::utf8_length((jchar*) name, utf16_length);
315 char stack_buf[128];
316 if (utf8_length < (int) sizeof(stack_buf)) {
317 char* chars = stack_buf;
318 UNICODE::convert_to_utf8(name, utf16_length, chars);
319 return lookup(chars, utf8_length, THREAD);
320 } else {
321 ResourceMark rm(THREAD);
322 char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);;
323 UNICODE::convert_to_utf8(name, utf16_length, chars);
324 return lookup(chars, utf8_length, THREAD);
325 }
326 }
327
328 Symbol* SymbolTable::lookup_only_unicode(const jchar* name, int utf16_length,
329 unsigned int& hash) {
330 int utf8_length = UNICODE::utf8_length((jchar*) name, utf16_length);
331 char stack_buf[128];
332 if (utf8_length < (int) sizeof(stack_buf)) {
333 char* chars = stack_buf;
334 UNICODE::convert_to_utf8(name, utf16_length, chars);
335 return lookup_only(chars, utf8_length, hash);
336 } else {
337 ResourceMark rm;
338 char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);;
339 UNICODE::convert_to_utf8(name, utf16_length, chars);
340 return lookup_only(chars, utf8_length, hash);
341 }
342 }
343
344 void SymbolTable::add(ClassLoaderData* loader_data, constantPoolHandle cp,
345 int names_count,
346 const char** names, int* lengths, int* cp_indices,
347 unsigned int* hashValues, TRAPS) {
348 // Grab SymbolTable_lock first.
349 MutexLocker ml(SymbolTable_lock, THREAD);
350
351 SymbolTable* table = the_table();
352 bool added = table->basic_add(loader_data, cp, names_count, names, lengths,
353 cp_indices, hashValues, CHECK);
354 if (!added) {
355 // do it the hard way
356 for (int i=0; i<names_count; i++) {
357 int index = table->hash_to_index(hashValues[i]);
358 bool c_heap = !loader_data->is_the_null_class_loader_data();
359 Symbol* sym = table->basic_add(index, (u1*)names[i], lengths[i], hashValues[i], c_heap, CHECK);
360 cp->symbol_at_put(cp_indices[i], sym);
361 }
362 }
363 }
364
365 Symbol* SymbolTable::new_permanent_symbol(const char* name, TRAPS) {
366 unsigned int hash;
367 Symbol* result = SymbolTable::lookup_only((char*)name, (int)strlen(name), hash);
368 if (result != NULL) {
369 return result;
370 }
371 // Grab SymbolTable_lock first.
372 MutexLocker ml(SymbolTable_lock, THREAD);
373
374 SymbolTable* table = the_table();
375 int index = table->hash_to_index(hash);
376 return table->basic_add(index, (u1*)name, (int)strlen(name), hash, false, THREAD);
377 }
378
379 Symbol* SymbolTable::basic_add(int index_arg, u1 *name, int len,
380 unsigned int hashValue_arg, bool c_heap, TRAPS) {
381 assert(!Universe::heap()->is_in_reserved(name),
382 "proposed name of symbol must be stable");
383
384 // Don't allow symbols to be created which cannot fit in a Symbol*.
385 if (len > Symbol::max_length()) {
386 THROW_MSG_0(vmSymbols::java_lang_InternalError(),
387 "name is too long to represent");
388 }
389
390 // Cannot hit a safepoint in this function because the "this" pointer can move.
391 No_Safepoint_Verifier nsv;
392
393 // Check if the symbol table has been rehashed, if so, need to recalculate
394 // the hash value and index.
395 unsigned int hashValue;
396 int index;
397 if (use_alternate_hashcode()) {
398 hashValue = hash_symbol((const char*)name, len);
399 index = hash_to_index(hashValue);
400 } else {
401 hashValue = hashValue_arg;
402 index = index_arg;
403 }
404
405 // Since look-up was done lock-free, we need to check if another
406 // thread beat us in the race to insert the symbol.
407 Symbol* test = lookup(index, (char*)name, len, hashValue);
408 if (test != NULL) {
409 // A race occurred and another thread introduced the symbol.
410 assert(test->refcount() != 0, "lookup should have incremented the count");
411 return test;
412 }
413
414 // Create a new symbol.
415 Symbol* sym = allocate_symbol(name, len, c_heap, CHECK_NULL);
416 assert(sym->equals((char*)name, len), "symbol must be properly initialized");
417
418 HashtableEntry<Symbol*, mtSymbol>* entry = new_entry(hashValue, sym);
419 add_entry(index, entry);
420 return sym;
421 }
422
423 // This version of basic_add adds symbols in batch from the constant pool
424 // parsing.
425 bool SymbolTable::basic_add(ClassLoaderData* loader_data, constantPoolHandle cp,
426 int names_count,
427 const char** names, int* lengths,
428 int* cp_indices, unsigned int* hashValues,
429 TRAPS) {
430
431 // Check symbol names are not too long. If any are too long, don't add any.
432 for (int i = 0; i< names_count; i++) {
433 if (lengths[i] > Symbol::max_length()) {
434 THROW_MSG_0(vmSymbols::java_lang_InternalError(),
435 "name is too long to represent");
436 }
437 }
438
439 // Cannot hit a safepoint in this function because the "this" pointer can move.
440 No_Safepoint_Verifier nsv;
441
442 for (int i=0; i<names_count; i++) {
443 // Check if the symbol table has been rehashed, if so, need to recalculate
444 // the hash value.
445 unsigned int hashValue;
446 if (use_alternate_hashcode()) {
447 hashValue = hash_symbol(names[i], lengths[i]);
448 } else {
449 hashValue = hashValues[i];
450 }
451 // Since look-up was done lock-free, we need to check if another
452 // thread beat us in the race to insert the symbol.
453 int index = hash_to_index(hashValue);
454 Symbol* test = lookup(index, names[i], lengths[i], hashValue);
455 if (test != NULL) {
456 // A race occurred and another thread introduced the symbol, this one
457 // will be dropped and collected. Use test instead.
458 cp->symbol_at_put(cp_indices[i], test);
459 assert(test->refcount() != 0, "lookup should have incremented the count");
460 } else {
461 // Create a new symbol. The null class loader is never unloaded so these
462 // are allocated specially in a permanent arena.
463 bool c_heap = !loader_data->is_the_null_class_loader_data();
464 Symbol* sym = allocate_symbol((const u1*)names[i], lengths[i], c_heap, CHECK_(false));
465 assert(sym->equals(names[i], lengths[i]), "symbol must be properly initialized"); // why wouldn't it be???
466 HashtableEntry<Symbol*, mtSymbol>* entry = new_entry(hashValue, sym);
467 add_entry(index, entry);
468 cp->symbol_at_put(cp_indices[i], sym);
469 }
470 }
471 return true;
472 }
473
474
475 void SymbolTable::verify() {
476 for (int i = 0; i < the_table()->table_size(); ++i) {
477 HashtableEntry<Symbol*, mtSymbol>* p = the_table()->bucket(i);
478 for ( ; p != NULL; p = p->next()) {
479 Symbol* s = (Symbol*)(p->literal());
480 guarantee(s != NULL, "symbol is NULL");
481 unsigned int h = hash_symbol((char*)s->bytes(), s->utf8_length());
482 guarantee(p->hash() == h, "broken hash in symbol table entry");
483 guarantee(the_table()->hash_to_index(h) == i,
484 "wrong index in symbol table");
485 }
486 }
487 }
488
489 void SymbolTable::dump(outputStream* st) {
490 the_table()->dump_table(st, "SymbolTable");
491 }
492
493
494 //---------------------------------------------------------------------------
495 // Non-product code
496
497 #ifndef PRODUCT
498
499 void SymbolTable::print_histogram() {
500 MutexLocker ml(SymbolTable_lock);
501 const int results_length = 100;
502 int results[results_length];
503 int i,j;
504
505 // initialize results to zero
506 for (j = 0; j < results_length; j++) {
507 results[j] = 0;
508 }
509
510 int total = 0;
511 int max_symbols = 0;
512 int out_of_range = 0;
513 int memory_total = 0;
514 int count = 0;
515 for (i = 0; i < the_table()->table_size(); i++) {
516 HashtableEntry<Symbol*, mtSymbol>* p = the_table()->bucket(i);
517 for ( ; p != NULL; p = p->next()) {
518 memory_total += p->literal()->size();
519 count++;
520 int counter = p->literal()->utf8_length();
521 total += counter;
522 if (counter < results_length) {
523 results[counter]++;
524 } else {
525 out_of_range++;
526 }
527 max_symbols = MAX2(max_symbols, counter);
528 }
529 }
530 tty->print_cr("Symbol Table:");
531 tty->print_cr("Total number of symbols %5d", count);
532 tty->print_cr("Total size in memory %5dK",
533 (memory_total*HeapWordSize)/1024);
534 tty->print_cr("Total counted %5d", _symbols_counted);
535 tty->print_cr("Total removed %5d", _symbols_removed);
536 if (_symbols_counted > 0) {
537 tty->print_cr("Percent removed %3.2f",
538 ((float)_symbols_removed/(float)_symbols_counted)* 100);
539 }
540 tty->print_cr("Reference counts %5d", Symbol::_total_count);
541 tty->print_cr("Symbol arena size %5d used %5d",
542 arena()->size_in_bytes(), arena()->used());
543 tty->print_cr("Histogram of symbol length:");
544 tty->print_cr("%8s %5d", "Total ", total);
545 tty->print_cr("%8s %5d", "Maximum", max_symbols);
546 tty->print_cr("%8s %3.2f", "Average",
547 ((float) total / (float) the_table()->table_size()));
548 tty->print_cr("%s", "Histogram:");
549 tty->print_cr(" %s %29s", "Length", "Number chains that length");
550 for (i = 0; i < results_length; i++) {
551 if (results[i] > 0) {
552 tty->print_cr("%6d %10d", i, results[i]);
553 }
554 }
555 if (Verbose) {
556 int line_length = 70;
557 tty->print_cr("%s %30s", " Length", "Number chains that length");
558 for (i = 0; i < results_length; i++) {
559 if (results[i] > 0) {
560 tty->print("%4d", i);
561 for (j = 0; (j < results[i]) && (j < line_length); j++) {
562 tty->print("%1s", "*");
563 }
564 if (j == line_length) {
565 tty->print("%1s", "+");
566 }
567 tty->cr();
568 }
569 }
570 }
571 tty->print_cr(" %s %d: %d\n", "Number chains longer than",
572 results_length, out_of_range);
573 }
574
575 void SymbolTable::print() {
576 for (int i = 0; i < the_table()->table_size(); ++i) {
577 HashtableEntry<Symbol*, mtSymbol>** p = the_table()->bucket_addr(i);
578 HashtableEntry<Symbol*, mtSymbol>* entry = the_table()->bucket(i);
579 if (entry != NULL) {
580 while (entry != NULL) {
581 tty->print(PTR_FORMAT " ", entry->literal());
582 entry->literal()->print();
583 tty->print(" %d", entry->literal()->refcount());
584 p = entry->next_addr();
585 entry = (HashtableEntry<Symbol*, mtSymbol>*)HashtableEntry<Symbol*, mtSymbol>::make_ptr(*p);
586 }
587 tty->cr();
588 }
589 }
590 }
591 #endif // PRODUCT
592
593 // --------------------------------------------------------------------------
594
595 #ifdef ASSERT
596 class StableMemoryChecker : public StackObj {
597 enum { _bufsize = wordSize*4 };
598
599 address _region;
600 jint _size;
601 u1 _save_buf[_bufsize];
602
603 int sample(u1* save_buf) {
604 if (_size <= _bufsize) {
605 memcpy(save_buf, _region, _size);
606 return _size;
607 } else {
608 // copy head and tail
609 memcpy(&save_buf[0], _region, _bufsize/2);
610 memcpy(&save_buf[_bufsize/2], _region + _size - _bufsize/2, _bufsize/2);
611 return (_bufsize/2)*2;
612 }
613 }
614
615 public:
616 StableMemoryChecker(const void* region, jint size) {
617 _region = (address) region;
618 _size = size;
619 sample(_save_buf);
620 }
621
622 bool verify() {
623 u1 check_buf[sizeof(_save_buf)];
624 int check_size = sample(check_buf);
625 return (0 == memcmp(_save_buf, check_buf, check_size));
626 }
627
628 void set_region(const void* region) { _region = (address) region; }
629 };
630 #endif
631
632
633 // --------------------------------------------------------------------------
634 StringTable* StringTable::_the_table = NULL;
635
636 bool StringTable::_needs_rehashing = false;
637
638 volatile int StringTable::_parallel_claimed_idx = 0;
639
640 // Pick hashing algorithm
641 unsigned int StringTable::hash_string(const jchar* s, int len) {
642 return use_alternate_hashcode() ? AltHashing::murmur3_32(seed(), s, len) :
643 java_lang_String::hash_code(s, len);
644 }
645
646 oop StringTable::lookup(int index, jchar* name,
647 int len, unsigned int hash) {
648 int count = 0;
649 for (HashtableEntry<oop, mtSymbol>* l = bucket(index); l != NULL; l = l->next()) {
650 count++;
651 if (l->hash() == hash) {
652 if (java_lang_String::equals(l->literal(), name, len)) {
653 return l->literal();
654 }
655 }
656 }
657 // If the bucket size is too deep check if this hash code is insufficient.
658 if (count >= BasicHashtable<mtSymbol>::rehash_count && !needs_rehashing()) {
659 _needs_rehashing = check_rehash_table(count);
660 }
661 return NULL;
662 }
663
664
665 oop StringTable::basic_add(int index_arg, Handle string, jchar* name,
666 int len, unsigned int hashValue_arg, TRAPS) {
667
668 assert(java_lang_String::equals(string(), name, len),
669 "string must be properly initialized");
670 // Cannot hit a safepoint in this function because the "this" pointer can move.
671 No_Safepoint_Verifier nsv;
672
673 // Check if the symbol table has been rehashed, if so, need to recalculate
674 // the hash value and index before second lookup.
675 unsigned int hashValue;
676 int index;
677 if (use_alternate_hashcode()) {
678 hashValue = hash_string(name, len);
679 index = hash_to_index(hashValue);
680 } else {
681 hashValue = hashValue_arg;
682 index = index_arg;
683 }
684
685 // Since look-up was done lock-free, we need to check if another
686 // thread beat us in the race to insert the symbol.
687
688 oop test = lookup(index, name, len, hashValue); // calls lookup(u1*, int)
689 if (test != NULL) {
690 // Entry already added
691 return test;
692 }
693
694 HashtableEntry<oop, mtSymbol>* entry = new_entry(hashValue, string());
695 add_entry(index, entry);
696 return string();
697 }
698
699
700 oop StringTable::lookup(Symbol* symbol) {
701 ResourceMark rm;
702 int length;
703 jchar* chars = symbol->as_unicode(length);
704 return lookup(chars, length);
705 }
706
707
708 oop StringTable::lookup(jchar* name, int len) {
709 unsigned int hash = hash_string(name, len);
710 int index = the_table()->hash_to_index(hash);
711 return the_table()->lookup(index, name, len, hash);
712 }
713
714
715 oop StringTable::intern(Handle string_or_null, jchar* name,
716 int len, TRAPS) {
717 unsigned int hashValue = hash_string(name, len);
718 int index = the_table()->hash_to_index(hashValue);
719 oop found_string = the_table()->lookup(index, name, len, hashValue);
720
721 // Found
722 if (found_string != NULL) return found_string;
723
724 debug_only(StableMemoryChecker smc(name, len * sizeof(name[0])));
725 assert(!Universe::heap()->is_in_reserved(name),
726 "proposed name of symbol must be stable");
727
728 Handle string;
729 // try to reuse the string if possible
730 if (!string_or_null.is_null()) {
731 string = string_or_null;
732 } else {
733 string = java_lang_String::create_from_unicode(name, len, CHECK_NULL);
734 }
735
736 #if INCLUDE_ALL_GCS
737 if (G1StringDedup::is_enabled()) {
738 // Deduplicate the string before it is interned. Note that we should never
739 // deduplicate a string after it has been interned. Doing so will counteract
740 // compiler optimizations done on e.g. interned string literals.
741 G1StringDedup::deduplicate(string());
742 }
743 #endif
744
745 // Grab the StringTable_lock before getting the_table() because it could
746 // change at safepoint.
747 MutexLocker ml(StringTable_lock, THREAD);
748
749 // Otherwise, add to symbol to table
750 return the_table()->basic_add(index, string, name, len,
751 hashValue, CHECK_NULL);
752 }
753
754 oop StringTable::intern(Symbol* symbol, TRAPS) {
755 if (symbol == NULL) return NULL;
756 ResourceMark rm(THREAD);
757 int length;
758 jchar* chars = symbol->as_unicode(length);
759 Handle string;
760 oop result = intern(string, chars, length, CHECK_NULL);
761 return result;
762 }
763
764
765 oop StringTable::intern(oop string, TRAPS)
766 {
767 if (string == NULL) return NULL;
768 ResourceMark rm(THREAD);
769 int length;
770 Handle h_string (THREAD, string);
771 jchar* chars = java_lang_String::as_unicode_string(string, length, CHECK_NULL);
772 oop result = intern(h_string, chars, length, CHECK_NULL);
773 return result;
774 }
775
776
777 oop StringTable::intern(const char* utf8_string, TRAPS) {
778 if (utf8_string == NULL) return NULL;
779 ResourceMark rm(THREAD);
780 int length = UTF8::unicode_length(utf8_string);
781 jchar* chars = NEW_RESOURCE_ARRAY(jchar, length);
782 UTF8::convert_to_unicode(utf8_string, chars, length);
783 Handle string;
784 oop result = intern(string, chars, length, CHECK_NULL);
785 return result;
786 }
787
788 void StringTable::unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int* processed, int* removed) {
789 buckets_unlink_or_oops_do(is_alive, f, 0, the_table()->table_size(), processed, removed);
790 }
791
792 void StringTable::possibly_parallel_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int* processed, int* removed) {
793 // Readers of the table are unlocked, so we should only be removing
794 // entries at a safepoint.
795 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
796 const int limit = the_table()->table_size();
797
798 for (;;) {
799 // Grab next set of buckets to scan
800 int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
801 if (start_idx >= limit) {
802 // End of table
803 break;
804 }
805
806 int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
807 buckets_unlink_or_oops_do(is_alive, f, start_idx, end_idx, processed, removed);
808 }
809 }
810
811 void StringTable::buckets_oops_do(OopClosure* f, int start_idx, int end_idx) {
812 const int limit = the_table()->table_size();
813
814 assert(0 <= start_idx && start_idx <= limit,
815 err_msg("start_idx (" INT32_FORMAT ") is out of bounds", start_idx));
816 assert(0 <= end_idx && end_idx <= limit,
817 err_msg("end_idx (" INT32_FORMAT ") is out of bounds", end_idx));
818 assert(start_idx <= end_idx,
819 err_msg("Index ordering: start_idx=" INT32_FORMAT", end_idx=" INT32_FORMAT,
820 start_idx, end_idx));
821
822 for (int i = start_idx; i < end_idx; i += 1) {
823 HashtableEntry<oop, mtSymbol>* entry = the_table()->bucket(i);
824 while (entry != NULL) {
825 assert(!entry->is_shared(), "CDS not used for the StringTable");
826
827 f->do_oop((oop*)entry->literal_addr());
828
829 entry = entry->next();
830 }
831 }
832 }
833
834 void StringTable::buckets_unlink_or_oops_do(BoolObjectClosure* is_alive, OopClosure* f, int start_idx, int end_idx, int* processed, int* removed) {
835 const int limit = the_table()->table_size();
836
837 assert(0 <= start_idx && start_idx <= limit,
838 err_msg("start_idx (" INT32_FORMAT ") is out of bounds", start_idx));
839 assert(0 <= end_idx && end_idx <= limit,
840 err_msg("end_idx (" INT32_FORMAT ") is out of bounds", end_idx));
841 assert(start_idx <= end_idx,
842 err_msg("Index ordering: start_idx=" INT32_FORMAT", end_idx=" INT32_FORMAT,
843 start_idx, end_idx));
844
845 for (int i = start_idx; i < end_idx; ++i) {
846 HashtableEntry<oop, mtSymbol>** p = the_table()->bucket_addr(i);
847 HashtableEntry<oop, mtSymbol>* entry = the_table()->bucket(i);
848 while (entry != NULL) {
849 assert(!entry->is_shared(), "CDS not used for the StringTable");
850
851 if (is_alive->do_object_b(entry->literal())) {
852 if (f != NULL) {
853 f->do_oop((oop*)entry->literal_addr());
854 }
855 p = entry->next_addr();
856 } else {
857 *p = entry->next();
858 the_table()->free_entry(entry);
859 (*removed)++;
860 }
861 (*processed)++;
862 entry = *p;
863 }
864 }
865 }
866
867 void StringTable::oops_do(OopClosure* f) {
868 buckets_oops_do(f, 0, the_table()->table_size());
869 }
870
871 void StringTable::possibly_parallel_oops_do(OopClosure* f) {
872 const int limit = the_table()->table_size();
873
874 for (;;) {
875 // Grab next set of buckets to scan
876 int start_idx = Atomic::add(ClaimChunkSize, &_parallel_claimed_idx) - ClaimChunkSize;
877 if (start_idx >= limit) {
878 // End of table
879 break;
880 }
881
882 int end_idx = MIN2(limit, start_idx + ClaimChunkSize);
883 buckets_oops_do(f, start_idx, end_idx);
884 }
885 }
886
887 // This verification is part of Universe::verify() and needs to be quick.
888 // See StringTable::verify_and_compare() below for exhaustive verification.
889 void StringTable::verify() {
890 for (int i = 0; i < the_table()->table_size(); ++i) {
891 HashtableEntry<oop, mtSymbol>* p = the_table()->bucket(i);
892 for ( ; p != NULL; p = p->next()) {
893 oop s = p->literal();
894 guarantee(s != NULL, "interned string is NULL");
895 unsigned int h = java_lang_String::hash_string(s);
896 guarantee(p->hash() == h, "broken hash in string table entry");
897 guarantee(the_table()->hash_to_index(h) == i,
898 "wrong index in string table");
899 }
900 }
901 }
902
903 void StringTable::dump(outputStream* st) {
904 the_table()->dump_table(st, "StringTable");
905 }
906
907 StringTable::VerifyRetTypes StringTable::compare_entries(
908 int bkt1, int e_cnt1,
909 HashtableEntry<oop, mtSymbol>* e_ptr1,
910 int bkt2, int e_cnt2,
911 HashtableEntry<oop, mtSymbol>* e_ptr2) {
912 // These entries are sanity checked by verify_and_compare_entries()
913 // before this function is called.
914 oop str1 = e_ptr1->literal();
915 oop str2 = e_ptr2->literal();
916
917 if (str1 == str2) {
918 tty->print_cr("ERROR: identical oop values (0x" PTR_FORMAT ") "
919 "in entry @ bucket[%d][%d] and entry @ bucket[%d][%d]",
920 (void *)str1, bkt1, e_cnt1, bkt2, e_cnt2);
921 return _verify_fail_continue;
922 }
923
924 if (java_lang_String::equals(str1, str2)) {
925 tty->print_cr("ERROR: identical String values in entry @ "
926 "bucket[%d][%d] and entry @ bucket[%d][%d]",
927 bkt1, e_cnt1, bkt2, e_cnt2);
928 return _verify_fail_continue;
929 }
930
931 return _verify_pass;
932 }
933
934 StringTable::VerifyRetTypes StringTable::verify_entry(int bkt, int e_cnt,
935 HashtableEntry<oop, mtSymbol>* e_ptr,
936 StringTable::VerifyMesgModes mesg_mode) {
937
938 VerifyRetTypes ret = _verify_pass; // be optimistic
939
940 oop str = e_ptr->literal();
941 if (str == NULL) {
942 if (mesg_mode == _verify_with_mesgs) {
943 tty->print_cr("ERROR: NULL oop value in entry @ bucket[%d][%d]", bkt,
944 e_cnt);
945 }
946 // NULL oop means no more verifications are possible
947 return _verify_fail_done;
948 }
949
950 if (str->klass() != SystemDictionary::String_klass()) {
951 if (mesg_mode == _verify_with_mesgs) {
952 tty->print_cr("ERROR: oop is not a String in entry @ bucket[%d][%d]",
953 bkt, e_cnt);
954 }
955 // not a String means no more verifications are possible
956 return _verify_fail_done;
957 }
958
959 unsigned int h = java_lang_String::hash_string(str);
960 if (e_ptr->hash() != h) {
961 if (mesg_mode == _verify_with_mesgs) {
962 tty->print_cr("ERROR: broken hash value in entry @ bucket[%d][%d], "
963 "bkt_hash=%d, str_hash=%d", bkt, e_cnt, e_ptr->hash(), h);
964 }
965 ret = _verify_fail_continue;
966 }
967
968 if (the_table()->hash_to_index(h) != bkt) {
969 if (mesg_mode == _verify_with_mesgs) {
970 tty->print_cr("ERROR: wrong index value for entry @ bucket[%d][%d], "
971 "str_hash=%d, hash_to_index=%d", bkt, e_cnt, h,
972 the_table()->hash_to_index(h));
973 }
974 ret = _verify_fail_continue;
975 }
976
977 return ret;
978 }
979
980 // See StringTable::verify() above for the quick verification that is
981 // part of Universe::verify(). This verification is exhaustive and
982 // reports on every issue that is found. StringTable::verify() only
983 // reports on the first issue that is found.
984 //
985 // StringTable::verify_entry() checks:
986 // - oop value != NULL (same as verify())
987 // - oop value is a String
988 // - hash(String) == hash in entry (same as verify())
989 // - index for hash == index of entry (same as verify())
990 //
991 // StringTable::compare_entries() checks:
992 // - oops are unique across all entries
993 // - String values are unique across all entries
994 //
995 int StringTable::verify_and_compare_entries() {
996 assert(StringTable_lock->is_locked(), "sanity check");
997
998 int fail_cnt = 0;
999
1000 // first, verify all the entries individually:
1001 for (int bkt = 0; bkt < the_table()->table_size(); bkt++) {
1002 HashtableEntry<oop, mtSymbol>* e_ptr = the_table()->bucket(bkt);
1003 for (int e_cnt = 0; e_ptr != NULL; e_ptr = e_ptr->next(), e_cnt++) {
1004 VerifyRetTypes ret = verify_entry(bkt, e_cnt, e_ptr, _verify_with_mesgs);
1005 if (ret != _verify_pass) {
1006 fail_cnt++;
1007 }
1008 }
1009 }
1010
1011 // Optimization: if the above check did not find any failures, then
1012 // the comparison loop below does not need to call verify_entry()
1013 // before calling compare_entries(). If there were failures, then we
1014 // have to call verify_entry() to see if the entry can be passed to
1015 // compare_entries() safely. When we call verify_entry() in the loop
1016 // below, we do so quietly to void duplicate messages and we don't
1017 // increment fail_cnt because the failures have already been counted.
1018 bool need_entry_verify = (fail_cnt != 0);
1019
1020 // second, verify all entries relative to each other:
1021 for (int bkt1 = 0; bkt1 < the_table()->table_size(); bkt1++) {
1022 HashtableEntry<oop, mtSymbol>* e_ptr1 = the_table()->bucket(bkt1);
1023 for (int e_cnt1 = 0; e_ptr1 != NULL; e_ptr1 = e_ptr1->next(), e_cnt1++) {
1024 if (need_entry_verify) {
1025 VerifyRetTypes ret = verify_entry(bkt1, e_cnt1, e_ptr1,
1026 _verify_quietly);
1027 if (ret == _verify_fail_done) {
1028 // cannot use the current entry to compare against other entries
1029 continue;
1030 }
1031 }
1032
1033 for (int bkt2 = bkt1; bkt2 < the_table()->table_size(); bkt2++) {
1034 HashtableEntry<oop, mtSymbol>* e_ptr2 = the_table()->bucket(bkt2);
1035 int e_cnt2;
1036 for (e_cnt2 = 0; e_ptr2 != NULL; e_ptr2 = e_ptr2->next(), e_cnt2++) {
1037 if (bkt1 == bkt2 && e_cnt2 <= e_cnt1) {
1038 // skip the entries up to and including the one that
1039 // we're comparing against
1040 continue;
1041 }
1042
1043 if (need_entry_verify) {
1044 VerifyRetTypes ret = verify_entry(bkt2, e_cnt2, e_ptr2,
1045 _verify_quietly);
1046 if (ret == _verify_fail_done) {
1047 // cannot compare against this entry
1048 continue;
1049 }
1050 }
1051
1052 // compare two entries, report and count any failures:
1053 if (compare_entries(bkt1, e_cnt1, e_ptr1, bkt2, e_cnt2, e_ptr2)
1054 != _verify_pass) {
1055 fail_cnt++;
1056 }
1057 }
1058 }
1059 }
1060 }
1061 return fail_cnt;
1062 }
1063
1064 // Create a new table and using alternate hash code, populate the new table
1065 // with the existing strings. Set flag to use the alternate hash code afterwards.
1066 void StringTable::rehash_table() {
1067 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1068 // This should never happen with -Xshare:dump but it might in testing mode.
1069 if (DumpSharedSpaces) return;
1070 StringTable* new_table = new StringTable();
1071
1072 // Rehash the table
1073 the_table()->move_to(new_table);
1074
1075 // Delete the table and buckets (entries are reused in new table).
1076 delete _the_table;
1077 // Don't check if we need rehashing until the table gets unbalanced again.
1078 // Then rehash with a new global seed.
1079 _needs_rehashing = false;
1080 _the_table = new_table;
1081 }

mercurial