1 /*
  2  * Copyright (c) 1997, 2022, 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 
 26 #include "precompiled.hpp"
 27 #include "cds/metaspaceShared.hpp"
 28 #include "classfile/altHashing.hpp"
 29 #include "classfile/classLoaderData.hpp"
 30 #include "classfile/vmSymbols.hpp"
 31 #include "gc/shared/collectedHeap.hpp"
 32 #include "logging/log.hpp"
 33 #include "logging/logStream.hpp"
 34 #include "memory/allocation.inline.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "memory/universe.hpp"
 37 #include "oops/symbol.hpp"
 38 #include "runtime/atomic.hpp"
 39 #include "runtime/mutexLocker.hpp"
 40 #include "runtime/os.hpp"
 41 #include "runtime/signature.hpp"
 42 #include "utilities/utf8.hpp"
 43 
 44 Symbol* Symbol::_vm_symbols[vmSymbols::number_of_symbols()];
 45 
 46 uint32_t Symbol::pack_hash_and_refcount(short hash, int refcount) {
 47   STATIC_ASSERT(PERM_REFCOUNT == ((1 << 16) - 1));
 48   assert(refcount >= 0, "negative refcount");
 49   assert(refcount <= PERM_REFCOUNT, "invalid refcount");
 50   uint32_t hi = hash;
 51   uint32_t lo = refcount;
 52   return (hi << 16) | lo;
 53 }
 54 
 55 Symbol::Symbol(const u1* name, int length, int refcount) {
 56   _hash_and_refcount =  pack_hash_and_refcount((short)os::random(), refcount);
 57   _length = length;
 58   // _body[0..1] are allocated in the header just by coincidence in the current
 59   // implementation of Symbol. They are read by identity_hash(), so make sure they
 60   // are initialized.
 61   // No other code should assume that _body[0..1] are always allocated. E.g., do
 62   // not unconditionally read base()[0] as that will be invalid for an empty Symbol.
 63   _body[0] = _body[1] = 0;
 64   memcpy(_body, name, length);
 65 }
 66 
 67 void* Symbol::operator new(size_t sz, int len) throw() {
 68 #if INCLUDE_CDS
 69  if (DumpSharedSpaces) {
 70    MutexLocker ml(DumpRegion_lock, Mutex::_no_safepoint_check_flag);
 71    // To get deterministic output from -Xshare:dump, we ensure that Symbols are allocated in
 72    // increasing addresses. When the symbols are copied into the archive, we preserve their
 73    // relative address order (sorted, see ArchiveBuilder::gather_klasses_and_symbols).
 74    //
 75    // We cannot use arena because arena chunks are allocated by the OS. As a result, for example,
 76    // the archived symbol of "java/lang/Object" may sometimes be lower than "java/lang/String", and
 77    // sometimes be higher. This would cause non-deterministic contents in the archive.
 78    DEBUG_ONLY(static void* last = 0);
 79    void* p = (void*)MetaspaceShared::symbol_space_alloc(size(len)*wordSize);
 80    assert(p > last, "must increase monotonically");
 81    DEBUG_ONLY(last = p);
 82    return p;
 83  }
 84 #endif
 85   int alloc_size = size(len)*wordSize;
 86   address res = (address) AllocateHeap(alloc_size, mtSymbol);
 87   return res;
 88 }
 89 
 90 void* Symbol::operator new(size_t sz, int len, Arena* arena) throw() {
 91   int alloc_size = size(len)*wordSize;
 92   address res = (address)arena->AmallocWords(alloc_size);
 93   return res;
 94 }
 95 
 96 void Symbol::operator delete(void *p) {
 97   assert(((Symbol*)p)->refcount() == 0, "should not call this");
 98   FreeHeap(p);
 99 }
100 
101 #if INCLUDE_CDS
102 void Symbol::update_identity_hash() {
103   // This is called at a safepoint during dumping of a static CDS archive. The caller should have
104   // called os::init_random() with a deterministic seed and then iterate all archived Symbols in
105   // a deterministic order.
106   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
107   _hash_and_refcount =  pack_hash_and_refcount((short)os::random(), PERM_REFCOUNT);
108 }
109 
110 void Symbol::set_permanent() {
111   // This is called at a safepoint during dumping of a dynamic CDS archive.
112   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
113   _hash_and_refcount =  pack_hash_and_refcount(extract_hash(_hash_and_refcount), PERM_REFCOUNT);
114 }
115 #endif
116 
117 bool Symbol::is_Q_signature() const {
118   int len = utf8_length();
119   return len > 2 && char_at(0) == JVM_SIGNATURE_PRIMITIVE_OBJECT && char_at(len - 1) == JVM_SIGNATURE_ENDCLASS;
120 }
121 
122 bool Symbol::is_Q_array_signature() const {
123   int l = utf8_length();
124   if (l < 2 || char_at(0) != JVM_SIGNATURE_ARRAY || char_at(l - 1) != JVM_SIGNATURE_ENDCLASS) {
125     return false;
126   }
127   for (int i = 1; i < (l - 2); i++) {
128     char c = char_at(i);
129     if (c == JVM_SIGNATURE_PRIMITIVE_OBJECT) {
130       return true;
131     }
132     if (c != JVM_SIGNATURE_ARRAY) {
133       return false;
134     }
135   }
136   return false;
137 }
138 
139 bool Symbol::is_Q_method_signature() const {
140   assert(SignatureVerifier::is_valid_method_signature(this), "must be");
141   int len = utf8_length();
142   if (len > 4 && char_at(0) == JVM_SIGNATURE_FUNC) {
143     for (int i=1; i<len-3; i++) { // Must end with ")Qx;", where x is at least one character or more.
144       if (char_at(i) == JVM_SIGNATURE_ENDFUNC && char_at(i+1) == JVM_SIGNATURE_PRIMITIVE_OBJECT) {
145         return true;
146       }
147     }
148   }
149   return false;
150 }
151 
152 Symbol* Symbol::fundamental_name(TRAPS) {
153   if ((char_at(0) == JVM_SIGNATURE_PRIMITIVE_OBJECT || char_at(0) == JVM_SIGNATURE_CLASS) && ends_with(JVM_SIGNATURE_ENDCLASS)) {
154     return SymbolTable::new_symbol(this, 1, utf8_length() - 1);
155   } else {
156     // reference count is incremented to be consistent with the behavior with
157     // the SymbolTable::new_symbol() call above
158     this->increment_refcount();
159     return this;
160   }
161 }
162 
163 bool Symbol::is_same_fundamental_type(Symbol* s) const {
164   if (this == s) return true;
165   if (utf8_length() < 3) return false;
166   int offset1, offset2, len;
167   if (ends_with(JVM_SIGNATURE_ENDCLASS)) {
168     if (char_at(0) != JVM_SIGNATURE_PRIMITIVE_OBJECT && char_at(0) != JVM_SIGNATURE_CLASS) return false;
169     offset1 = 1;
170     len = utf8_length() - 2;
171   } else {
172     offset1 = 0;
173     len = utf8_length();
174   }
175   if (ends_with(JVM_SIGNATURE_ENDCLASS)) {
176     if (s->char_at(0) != JVM_SIGNATURE_PRIMITIVE_OBJECT && s->char_at(0) != JVM_SIGNATURE_CLASS) return false;
177     offset2 = 1;
178   } else {
179     offset2 = 0;
180   }
181   if ((offset2 + len) > s->utf8_length()) return false;
182   if ((utf8_length() - offset1 * 2) != (s->utf8_length() - offset2 * 2))
183     return false;
184   int l = len;
185   while (l-- > 0) {
186     if (char_at(offset1 + l) != s->char_at(offset2 + l))
187       return false;
188   }
189   return true;
190 }
191 
192 // ------------------------------------------------------------------
193 // Symbol::index_of
194 //
195 // Test if we have the give substring at or after the i-th char of this
196 // symbol's utf8 bytes.
197 // Return -1 on failure.  Otherwise return the first index where substr occurs.
198 int Symbol::index_of_at(int i, const char* substr, int substr_len) const {
199   assert(i >= 0 && i <= utf8_length(), "oob");
200   if (substr_len <= 0)  return 0;
201   char first_char = substr[0];
202   address bytes = (address) ((Symbol*)this)->base();
203   address limit = bytes + utf8_length() - substr_len;  // inclusive limit
204   address scan = bytes + i;
205   if (scan > limit)
206     return -1;
207   for (; scan <= limit; scan++) {
208     scan = (address) memchr(scan, first_char, (limit + 1 - scan));
209     if (scan == NULL)
210       return -1;  // not found
211     assert(scan >= bytes+i && scan <= limit, "scan oob");
212     if (substr_len <= 2
213         ? (char) scan[substr_len-1] == substr[substr_len-1]
214         : memcmp(scan+1, substr+1, substr_len-1) == 0) {
215       return (int)(scan - bytes);
216     }
217   }
218   return -1;
219 }
220 
221 
222 char* Symbol::as_C_string(char* buf, int size) const {
223   if (size > 0) {
224     int len = MIN2(size - 1, utf8_length());
225     for (int i = 0; i < len; i++) {
226       buf[i] = char_at(i);
227     }
228     buf[len] = '\0';
229   }
230   return buf;
231 }
232 
233 char* Symbol::as_C_string() const {
234   int len = utf8_length();
235   char* str = NEW_RESOURCE_ARRAY(char, len + 1);
236   return as_C_string(str, len + 1);
237 }
238 
239 void Symbol::print_utf8_on(outputStream* st) const {
240   st->print("%s", as_C_string());
241 }
242 
243 void Symbol::print_symbol_on(outputStream* st) const {
244   char *s;
245   st = st ? st : tty;
246   {
247     // ResourceMark may not affect st->print(). If st is a string
248     // stream it could resize, using the same resource arena.
249     ResourceMark rm;
250     s = as_quoted_ascii();
251     s = os::strdup(s);
252   }
253   if (s == NULL) {
254     st->print("(null)");
255   } else {
256     st->print("%s", s);
257     os::free(s);
258   }
259 }
260 
261 char* Symbol::as_quoted_ascii() const {
262   const char *ptr = (const char *)&_body[0];
263   int quoted_length = UTF8::quoted_ascii_length(ptr, utf8_length());
264   char* result = NEW_RESOURCE_ARRAY(char, quoted_length + 1);
265   UTF8::as_quoted_ascii(ptr, utf8_length(), result, quoted_length + 1);
266   return result;
267 }
268 
269 jchar* Symbol::as_unicode(int& length) const {
270   Symbol* this_ptr = (Symbol*)this;
271   length = UTF8::unicode_length((char*)this_ptr->bytes(), utf8_length());
272   jchar* result = NEW_RESOURCE_ARRAY(jchar, length);
273   if (length > 0) {
274     UTF8::convert_to_unicode((char*)this_ptr->bytes(), result, length);
275   }
276   return result;
277 }
278 
279 const char* Symbol::as_klass_external_name(char* buf, int size) const {
280   if (size > 0) {
281     char* str    = as_C_string(buf, size);
282     int   length = (int)strlen(str);
283     // Turn all '/'s into '.'s (also for array klasses)
284     for (int index = 0; index < length; index++) {
285       if (str[index] == JVM_SIGNATURE_SLASH) {
286         str[index] = JVM_SIGNATURE_DOT;
287       }
288     }
289     return str;
290   } else {
291     return buf;
292   }
293 }
294 
295 const char* Symbol::as_klass_external_name() const {
296   char* str    = as_C_string();
297   int   length = (int)strlen(str);
298   // Turn all '/'s into '.'s (also for array klasses)
299   for (int index = 0; index < length; index++) {
300     if (str[index] == JVM_SIGNATURE_SLASH) {
301       str[index] = JVM_SIGNATURE_DOT;
302     }
303   }
304   return str;
305 }
306 
307 static void print_class(outputStream *os, const SignatureStream& ss) {
308   int sb = ss.raw_symbol_begin(), se = ss.raw_symbol_end();
309   for (int i = sb; i < se; ++i) {
310     int ch = ss.raw_char_at(i);
311     if (ch == JVM_SIGNATURE_SLASH) {
312       os->put(JVM_SIGNATURE_DOT);
313     } else {
314       os->put(ch);
315     }
316   }
317 }
318 
319 static void print_array(outputStream *os, SignatureStream& ss) {
320   int dimensions = ss.skip_array_prefix();
321   assert(dimensions > 0, "");
322   if (ss.is_reference()) {
323     print_class(os, ss);
324   } else {
325     os->print("%s", type2name(ss.type()));
326   }
327   for (int i = 0; i < dimensions; ++i) {
328     os->print("[]");
329   }
330 }
331 
332 void Symbol::print_as_signature_external_return_type(outputStream *os) {
333   for (SignatureStream ss(this); !ss.is_done(); ss.next()) {
334     if (ss.at_return_type()) {
335       if (ss.is_array()) {
336         print_array(os, ss);
337       } else if (ss.is_reference()) {
338         print_class(os, ss);
339       } else {
340         os->print("%s", type2name(ss.type()));
341       }
342     }
343   }
344 }
345 
346 void Symbol::print_as_signature_external_parameters(outputStream *os) {
347   bool first = true;
348   for (SignatureStream ss(this); !ss.is_done(); ss.next()) {
349     if (ss.at_return_type()) break;
350     if (!first) { os->print(", "); }
351     if (ss.is_array()) {
352       print_array(os, ss);
353     } else if (ss.is_reference()) {
354       print_class(os, ss);
355     } else {
356       os->print("%s", type2name(ss.type()));
357     }
358     first = false;
359   }
360 }
361 
362 // Increment refcount while checking for zero.  If the Symbol's refcount becomes zero
363 // a thread could be concurrently removing the Symbol.  This is used during SymbolTable
364 // lookup to avoid reviving a dead Symbol.
365 bool Symbol::try_increment_refcount() {
366   uint32_t found = _hash_and_refcount;
367   while (true) {
368     uint32_t old_value = found;
369     int refc = extract_refcount(old_value);
370     if (refc == PERM_REFCOUNT) {
371       return true;  // sticky max or created permanent
372     } else if (refc == 0) {
373       return false; // dead, can't revive.
374     } else {
375       found = Atomic::cmpxchg(&_hash_and_refcount, old_value, old_value + 1);
376       if (found == old_value) {
377         return true; // successfully updated.
378       }
379       // refcount changed, try again.
380     }
381   }
382 }
383 
384 // The increment_refcount() is called when not doing lookup. It is assumed that you
385 // have a symbol with a non-zero refcount and it can't become zero while referenced by
386 // this caller.
387 void Symbol::increment_refcount() {
388   if (!try_increment_refcount()) {
389 #ifdef ASSERT
390     print();
391     fatal("refcount has gone to zero");
392 #endif
393   }
394 #ifndef PRODUCT
395   if (refcount() != PERM_REFCOUNT) { // not a permanent symbol
396     NOT_PRODUCT(Atomic::inc(&_total_count);)
397   }
398 #endif
399 }
400 
401 // Decrement refcount potentially while racing increment, so we need
402 // to check the value after attempting to decrement so that if another
403 // thread increments to PERM_REFCOUNT the value is not decremented.
404 void Symbol::decrement_refcount() {
405   uint32_t found = _hash_and_refcount;
406   while (true) {
407     uint32_t old_value = found;
408     int refc = extract_refcount(old_value);
409     if (refc == PERM_REFCOUNT) {
410       return;  // refcount is permanent, permanent is sticky
411     } else if (refc == 0) {
412 #ifdef ASSERT
413       print();
414       fatal("refcount underflow");
415 #endif
416       return;
417     } else {
418       found = Atomic::cmpxchg(&_hash_and_refcount, old_value, old_value - 1);
419       if (found == old_value) {
420         return;  // successfully updated.
421       }
422       // refcount changed, try again.
423     }
424   }
425 }
426 
427 void Symbol::make_permanent() {
428   uint32_t found = _hash_and_refcount;
429   while (true) {
430     uint32_t old_value = found;
431     int refc = extract_refcount(old_value);
432     if (refc == PERM_REFCOUNT) {
433       return;  // refcount is permanent, permanent is sticky
434     } else if (refc == 0) {
435 #ifdef ASSERT
436       print();
437       fatal("refcount underflow");
438 #endif
439       return;
440     } else {
441       int hash = extract_hash(old_value);
442       found = Atomic::cmpxchg(&_hash_and_refcount, old_value, pack_hash_and_refcount(hash, PERM_REFCOUNT));
443       if (found == old_value) {
444         return;  // successfully updated.
445       }
446       // refcount changed, try again.
447     }
448   }
449 }
450 
451 void Symbol::metaspace_pointers_do(MetaspaceClosure* it) {
452   if (log_is_enabled(Trace, cds)) {
453     LogStream trace_stream(Log(cds)::trace());
454     trace_stream.print("Iter(Symbol): %p ", this);
455     print_value_on(&trace_stream);
456     trace_stream.cr();
457   }
458 }
459 
460 void Symbol::print_on(outputStream* st) const {
461   st->print("Symbol: '");
462   print_symbol_on(st);
463   st->print("'");
464   st->print(" count %d", refcount());
465 }
466 
467 void Symbol::print() const { print_on(tty); }
468 
469 // The print_value functions are present in all builds, to support the
470 // disassembler and error reporting.
471 void Symbol::print_value_on(outputStream* st) const {
472   st->print("'");
473   for (int i = 0; i < utf8_length(); i++) {
474     st->print("%c", char_at(i));
475   }
476   st->print("'");
477 }
478 
479 void Symbol::print_value() const { print_value_on(tty); }
480 
481 bool Symbol::is_valid(Symbol* s) {
482   if (!is_aligned(s, sizeof(MetaWord))) return false;
483   if ((size_t)s < os::min_page_size()) return false;
484 
485   if (!os::is_readable_range(s, s + 1)) return false;
486 
487   // Symbols are not allocated in Java heap.
488   if (Universe::heap()->is_in(s)) return false;
489 
490   int len = s->utf8_length();
491   if (len < 0) return false;
492 
493   jbyte* bytes = (jbyte*) s->bytes();
494   return os::is_readable_range(bytes, bytes + len);
495 }
496 
497 void Symbol::print_Qvalue_on(outputStream* st) const {
498   if (this == NULL) {
499     st->print("NULL");
500   } else {
501     st->print("'Q");
502     for (int i = 0; i < utf8_length(); i++) {
503       st->print("%c", char_at(i));
504     }
505     st->print(";'");
506   }
507 }
508 
509 // SymbolTable prints this in its statistics
510 NOT_PRODUCT(size_t Symbol::_total_count = 0;)
511 
512 #ifndef PRODUCT
513 bool Symbol::is_valid_id(vmSymbolID vm_symbol_id) {
514   return vmSymbols::is_valid_id(vm_symbol_id);
515 }
516 #endif