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 // ------------------------------------------------------------------
 91 // Symbol::index_of
 92 //
 93 // Test if we have the give substring at or after the i-th char of this
 94 // symbol's utf8 bytes.
 95 // Return -1 on failure.  Otherwise return the first index where substr occurs.
 96 int Symbol::index_of_at(int i, const char* substr, int substr_len) const {
 97   assert(i >= 0 && i <= utf8_length(), "oob");
 98   if (substr_len <= 0)  return 0;
 99   char first_char = substr[0];
100   address bytes = (address) ((Symbol*)this)->base();
101   address limit = bytes + utf8_length() - substr_len;  // inclusive limit
102   address scan = bytes + i;
103   if (scan > limit)
104     return -1;
105   for (; scan <= limit; scan++) {
106     scan = (address) memchr(scan, first_char, (limit + 1 - scan));
107     if (scan == nullptr)
108       return -1;  // not found
109     assert(scan >= bytes+i && scan <= limit, "scan oob");
110     if (substr_len <= 2
111         ? (char) scan[substr_len-1] == substr[substr_len-1]
112         : memcmp(scan+1, substr+1, substr_len-1) == 0) {
113       return (int)(scan - bytes);
114     }
115   }
116   return -1;
117 }
118 
119 bool Symbol::is_star_match(const char* pattern) const {
120   if (strchr(pattern, '*') == nullptr) {
121     return equals(pattern);
122   } else {
123     ResourceMark rm;
124     char* buf = as_C_string();
125     return StringUtils::is_star_match(pattern, buf);
126   }
127 }
128 
129 char* Symbol::as_C_string(char* buf, int size) const {
130   if (size > 0) {
131     int len = MIN2(size - 1, utf8_length());
132     for (int i = 0; i < len; i++) {
133       buf[i] = char_at(i);
134     }
135     buf[len] = '\0';
136   }
137   return buf;
138 }
139 
140 char* Symbol::as_C_string() const {
141   int len = utf8_length();
142   char* str = NEW_RESOURCE_ARRAY(char, len + 1);
143   return as_C_string(str, len + 1);
144 }
145 
146 void Symbol::print_utf8_on(outputStream* st) const {
147   st->print("%s", as_C_string());
148 }
149 
150 void Symbol::print_symbol_on(outputStream* st) const {
151   char *s;
152   st = st ? st : tty;
153   {
154     // ResourceMark may not affect st->print(). If st is a string
155     // stream it could resize, using the same resource arena.
156     ResourceMark rm;
157     s = as_quoted_ascii();
158     s = os::strdup(s);
159   }
160   if (s == nullptr) {
161     st->print("(null)");
162   } else {
163     st->print("%s", s);
164     os::free(s);
165   }
166 }
167 
168 char* Symbol::as_quoted_ascii() const {
169   const char *ptr = (const char *)&_body[0];
170   int quoted_length = UTF8::quoted_ascii_length(ptr, utf8_length());
171   char* result = NEW_RESOURCE_ARRAY(char, quoted_length + 1);
172   UTF8::as_quoted_ascii(ptr, utf8_length(), result, quoted_length + 1);
173   return result;
174 }
175 
176 jchar* Symbol::as_unicode(int& length) const {
177   Symbol* this_ptr = (Symbol*)this;
178   length = UTF8::unicode_length((char*)this_ptr->bytes(), utf8_length());
179   jchar* result = NEW_RESOURCE_ARRAY(jchar, length);
180   if (length > 0) {
181     UTF8::convert_to_unicode((char*)this_ptr->bytes(), result, length);
182   }
183   return result;
184 }
185 
186 const char* Symbol::as_klass_external_name(char* buf, int size) const {
187   if (size > 0) {
188     char* str    = as_C_string(buf, size);
189     int   length = (int)strlen(str);
190     // Turn all '/'s into '.'s (also for array klasses)
191     for (int index = 0; index < length; index++) {
192       if (str[index] == JVM_SIGNATURE_SLASH) {
193         str[index] = JVM_SIGNATURE_DOT;
194       }
195     }
196     return str;
197   } else {
198     return buf;
199   }
200 }
201 
202 const char* Symbol::as_klass_external_name() const {
203   char* str    = as_C_string();
204   int   length = (int)strlen(str);
205   // Turn all '/'s into '.'s (also for array klasses)
206   for (int index = 0; index < length; index++) {
207     if (str[index] == JVM_SIGNATURE_SLASH) {
208       str[index] = JVM_SIGNATURE_DOT;
209     }
210   }
211   return str;
212 }
213 
214 static void print_class(outputStream *os, const SignatureStream& ss) {
215   int sb = ss.raw_symbol_begin(), se = ss.raw_symbol_end();
216   for (int i = sb; i < se; ++i) {
217     char ch = ss.raw_char_at(i);
218     if (ch == JVM_SIGNATURE_SLASH) {
219       os->put(JVM_SIGNATURE_DOT);
220     } else {
221       os->put(ch);
222     }
223   }
224 }
225 
226 static void print_array(outputStream *os, SignatureStream& ss) {
227   int dimensions = ss.skip_array_prefix();
228   assert(dimensions > 0, "");
229   if (ss.is_reference()) {
230     print_class(os, ss);
231   } else {
232     os->print("%s", type2name(ss.type()));
233   }
234   for (int i = 0; i < dimensions; ++i) {
235     os->print("[]");
236   }
237 }
238 
239 void Symbol::print_as_signature_external_return_type(outputStream *os) {
240   for (SignatureStream ss(this); !ss.is_done(); ss.next()) {
241     if (ss.at_return_type()) {
242       if (ss.is_array()) {
243         print_array(os, ss);
244       } else if (ss.is_reference()) {
245         print_class(os, ss);
246       } else {
247         os->print("%s", type2name(ss.type()));
248       }
249     }
250   }
251 }
252 
253 void Symbol::print_as_signature_external_parameters(outputStream *os) {
254   bool first = true;
255   for (SignatureStream ss(this); !ss.is_done(); ss.next()) {
256     if (ss.at_return_type()) break;
257     if (!first) { os->print(", "); }
258     if (ss.is_array()) {
259       print_array(os, ss);
260     } else if (ss.is_reference()) {
261       print_class(os, ss);
262     } else {
263       os->print("%s", type2name(ss.type()));
264     }
265     first = false;
266   }
267 }
268 
269 void Symbol::print_as_field_external_type(outputStream *os) {
270   SignatureStream ss(this, false);
271   assert(!ss.is_done(), "must have at least one element in field ref");
272   assert(!ss.at_return_type(), "field ref cannot be a return type");
273   assert(!Signature::is_method(this), "field ref cannot be a method");
274 
275   if (ss.is_array()) {
276     print_array(os, ss);
277   } else if (ss.is_reference()) {
278     print_class(os, ss);
279   } else {
280     os->print("%s", type2name(ss.type()));
281   }
282 #ifdef ASSERT
283   ss.next();
284   assert(ss.is_done(), "must have at most one element in field ref");
285 #endif
286 }
287 
288 // Increment refcount while checking for zero.  If the Symbol's refcount becomes zero
289 // a thread could be concurrently removing the Symbol.  This is used during SymbolTable
290 // lookup to avoid reviving a dead Symbol.
291 bool Symbol::try_increment_refcount() {
292   uint32_t found = _hash_and_refcount;
293   while (true) {
294     uint32_t old_value = found;
295     int refc = extract_refcount(old_value);
296     if (refc == PERM_REFCOUNT) {
297       return true;  // sticky max or created permanent
298     } else if (refc == 0) {
299       return false; // dead, can't revive.
300     } else {
301       found = Atomic::cmpxchg(&_hash_and_refcount, old_value, old_value + 1);
302       if (found == old_value) {
303         return true; // successfully updated.
304       }
305       // refcount changed, try again.
306     }
307   }
308 }
309 
310 // The increment_refcount() is called when not doing lookup. It is assumed that you
311 // have a symbol with a non-zero refcount and it can't become zero while referenced by
312 // this caller.
313 void Symbol::increment_refcount() {
314   if (!try_increment_refcount()) {
315     print();
316     fatal("refcount has gone to zero");
317   }
318 #ifndef PRODUCT
319   if (refcount() != PERM_REFCOUNT) { // not a permanent symbol
320     NOT_PRODUCT(Atomic::inc(&_total_count);)
321   }
322 #endif
323 }
324 
325 // Decrement refcount potentially while racing increment, so we need
326 // to check the value after attempting to decrement so that if another
327 // thread increments to PERM_REFCOUNT the value is not decremented.
328 void Symbol::decrement_refcount() {
329   uint32_t found = _hash_and_refcount;
330   while (true) {
331     uint32_t old_value = found;
332     int refc = extract_refcount(old_value);
333     if (refc == PERM_REFCOUNT) {
334       return;  // refcount is permanent, permanent is sticky
335     } else if (refc == 0) {
336       print();
337       fatal("refcount underflow");
338       return;
339     } else {
340       found = Atomic::cmpxchg(&_hash_and_refcount, old_value, old_value - 1);
341       if (found == old_value) {
342         return;  // successfully updated.
343       }
344       // refcount changed, try again.
345     }
346   }
347 }
348 
349 void Symbol::make_permanent() {
350   uint32_t found = _hash_and_refcount;
351   while (true) {
352     uint32_t old_value = found;
353     int refc = extract_refcount(old_value);
354     if (refc == PERM_REFCOUNT) {
355       return;  // refcount is permanent, permanent is sticky
356     } else if (refc == 0) {
357       print();
358       fatal("refcount underflow");
359       return;
360     } else {
361       short hash = extract_hash(old_value);
362       found = Atomic::cmpxchg(&_hash_and_refcount, old_value, pack_hash_and_refcount(hash, PERM_REFCOUNT));
363       if (found == old_value) {
364         return;  // successfully updated.
365       }
366       // refcount changed, try again.
367     }
368   }
369 }
370 
371 void Symbol::metaspace_pointers_do(MetaspaceClosure* it) {
372   if (log_is_enabled(Trace, cds)) {
373     LogStream trace_stream(Log(cds)::trace());
374     trace_stream.print("Iter(Symbol): %p ", this);
375     print_value_on(&trace_stream);
376     trace_stream.cr();
377   }
378 }
379 
380 void Symbol::print_on(outputStream* st) const {
381   st->print("Symbol: '");
382   print_symbol_on(st);
383   st->print("'");
384   st->print(" count %d", refcount());
385 }
386 
387 void Symbol::print() const { print_on(tty); }
388 
389 // The print_value functions are present in all builds, to support the
390 // disassembler and error reporting.
391 void Symbol::print_value_on(outputStream* st) const {
392   st->print_raw("'", 1);
393   st->print_raw((const char*)base(), utf8_length());
394   st->print_raw("'", 1);
395 }
396 
397 void Symbol::print_value() const { print_value_on(tty); }
398 
399 bool Symbol::is_valid(Symbol* s) {
400   if (!is_aligned(s, sizeof(MetaWord))) return false;
401   if ((size_t)s < os::min_page_size()) return false;
402 
403   if (!os::is_readable_range(s, s + 1)) return false;
404 
405   // Symbols are not allocated in Java heap.
406   if (Universe::heap()->is_in(s)) return false;
407 
408   int len = s->utf8_length();
409   if (len < 0) return false;
410 
411   jbyte* bytes = (jbyte*) s->bytes();
412   return os::is_readable_range(bytes, bytes + len);
413 }
414 
415 // SymbolTable prints this in its statistics
416 NOT_PRODUCT(size_t Symbol::_total_count = 0;)
417 
418 #ifndef PRODUCT
419 bool Symbol::is_valid_id(vmSymbolID vm_symbol_id) {
420   return vmSymbols::is_valid_id(vm_symbol_id);
421 }
422 #endif