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