1 /*
  2  * Copyright (c) 1997, 2024, 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 #ifndef SHARE_OOPS_SYMBOL_HPP
 26 #define SHARE_OOPS_SYMBOL_HPP
 27 
 28 #include "memory/allocation.hpp"
 29 #include "utilities/exceptions.hpp"
 30 #include "utilities/macros.hpp"
 31 #include "utilities/vmEnums.hpp"
 32 
 33 // A Symbol is a canonicalized string.
 34 // All Symbols reside in global SymbolTable and are reference counted.
 35 
 36 // Reference counting
 37 //
 38 // All Symbols are allocated and added to the SymbolTable.
 39 // When a class is unloaded, the reference counts of the Symbol pointers in
 40 // the ConstantPool and in InstanceKlass (see release_C_heap_structures) are
 41 // decremented.  When the reference count for a Symbol goes to 0, the garbage
 42 // collector can free the Symbol and remove it from the SymbolTable.
 43 //
 44 // 0) Symbols need to be reference counted when a pointer to the Symbol is
 45 // saved in persistent storage.  This does not include the pointer
 46 // in the SymbolTable bucket (the _literal field in HashtableEntry)
 47 // that points to the Symbol.  All other stores of a Symbol*
 48 // to a field of a persistent variable (e.g., the _name field in
 49 // fieldDescriptor or symbol in a constant pool) is reference counted.
 50 //
 51 // 1) The lookup of a "name" in the SymbolTable either creates a Symbol F for
 52 // "name" and returns a pointer to F or finds a pre-existing Symbol F for
 53 // "name" and returns a pointer to it. In both cases the reference count for F
 54 // is incremented under the assumption that a pointer to F will be created from
 55 // the return value. Thus the increment of the reference count is on the lookup
 56 // and not on the assignment to the new Symbol*.  That is
 57 //    Symbol* G = lookup()
 58 //                ^ increment on lookup()
 59 // and not
 60 //    Symbol* G = lookup()
 61 //              ^ increment on assignment
 62 // The reference count must be decremented manually when the copy of the
 63 // pointer G is destroyed.
 64 //
 65 // 2) For a local Symbol* A that is a copy of an existing Symbol* B, the
 66 // reference counting is elided when the scope of B is greater than the scope
 67 // of A.  For example, in the code fragment
 68 // below "klass" is passed as a parameter to the method.  Symbol* "kn"
 69 // is a copy of the name in "klass".
 70 //
 71 //   Symbol*  kn = klass->name();
 72 //   unsigned int d_hash = dictionary()->compute_hash(kn, class_loader);
 73 //
 74 // The scope of "klass" is greater than the scope of "kn" so the reference
 75 // counting for "kn" is elided.
 76 //
 77 // Symbol* copied from ConstantPool entries are good candidates for reference
 78 // counting elision.  The ConstantPool entries for a class C exist until C is
 79 // unloaded.  If a Symbol* is copied out of the ConstantPool into Symbol* X,
 80 // the Symbol* in the ConstantPool will in general out live X so the reference
 81 // counting on X can be elided.
 82 //
 83 // For cases where the scope of A is not greater than the scope of B,
 84 // the reference counting is explicitly done.  See ciSymbol,
 85 // ResolutionErrorEntry and ClassVerifier for examples.
 86 //
 87 // 3) When a Symbol K is created for temporary use, generally for substrings of
 88 // an existing symbol or to create a new symbol, assign it to a
 89 // TempNewSymbol. The SymbolTable methods new_symbol(), lookup()
 90 // and probe() all potentially return a pointer to a new Symbol.
 91 // The allocation (or lookup) of K increments the reference count for K
 92 // and the destructor decrements the reference count.
 93 //
 94 // This cannot be inherited from ResourceObj because it cannot have a vtable.
 95 // Since sometimes this is allocated from Metadata, pick a base allocation
 96 // type without virtual functions.
 97 class ClassLoaderData;
 98 
 99 // Set _refcount to PERM_REFCOUNT to prevent the Symbol from being freed.
100 #ifndef PERM_REFCOUNT
101 #define PERM_REFCOUNT 0xffff
102 #endif
103 
104 class Symbol : public MetaspaceObj {
105   friend class VMStructs;
106   friend class SymbolTable;
107   friend class vmSymbols;
108   friend class JVMCIVMStructs;
109 
110  private:
111 
112   // This is an int because it needs atomic operation on the refcount.  Mask hash
113   // in high half word. length is the number of UTF8 characters in the symbol
114   volatile uint32_t _hash_and_refcount;
115   u2 _length;
116   u1 _body[2];
117 
118   static Symbol* _vm_symbols[];
119 
120   enum {
121     max_symbol_length = 0xffff
122   };
123 
124   static int byte_size(int length) {
125     // minimum number of bytes needed to hold these bits (no non-heap version)
126     return (int)(sizeof(Symbol) + (length > 2 ? length - 2 : 0));
127   }
128   static int size(int length) {
129     // minimum number of natural words needed to hold these bits (no non-heap version)
130     return (int)heap_word_size(byte_size(length));
131   }
132 
133   // Constructor is private for use only by SymbolTable.
134   Symbol(const u1* name, int length, int refcount);
135 
136   static short extract_hash(uint32_t value)   { return (short)(value >> 16); }
137   static int extract_refcount(uint32_t value) { return value & 0xffff; }
138   static uint32_t pack_hash_and_refcount(short hash, int refcount);
139 
140   int length() const   { return _length; }
141 
142  public:
143   Symbol(const Symbol& s1);
144 
145   // Low-level access (used with care, since not GC-safe)
146   const u1* base() const { return &_body[0]; }
147 
148   int size()      const     { return size(utf8_length()); }
149   int byte_size() const     { return byte_size(utf8_length()); };
150 
151   // Symbols should be stored in the read-only region of CDS archive.
152   static bool is_read_only_by_default() { return true; }
153 
154   // Returns the largest size symbol we can safely hold.
155   static int max_length() { return max_symbol_length; }
156   unsigned identity_hash() const {
157     unsigned addr_bits = (unsigned)((uintptr_t)this >> LogBytesPerWord);
158     return ((unsigned)extract_hash(_hash_and_refcount) & 0xffff) |
159            ((addr_bits ^ (length() << 8) ^ (( _body[0] << 8) | _body[1])) << 16);
160   }
161   static unsigned identity_hash(const Symbol* symbol_or_null) {
162     return symbol_or_null == nullptr ? 0 : symbol_or_null->identity_hash();
163   }
164 
165   // Reference counting.  See comments above this class for when to use.
166   int refcount() const { return extract_refcount(_hash_and_refcount); }
167   bool try_increment_refcount();
168   void increment_refcount();
169   void decrement_refcount();
170   bool is_permanent() const {
171     return (refcount() == PERM_REFCOUNT);
172   }
173   void update_identity_hash() NOT_CDS_RETURN;
174   void set_permanent() NOT_CDS_RETURN;
175   void make_permanent();
176 
177   static void maybe_increment_refcount(Symbol* s) {
178     if (s != nullptr) {
179       s->increment_refcount();
180     }
181   }
182   static void maybe_decrement_refcount(Symbol* s) {
183     if (s != nullptr) {
184       s->decrement_refcount();
185     }
186   }
187   // Function char_at() returns the Symbol's selected u1 byte as a char type.
188   //
189   // Note that all multi-byte chars have the sign bit set on all their bytes.
190   // No single byte chars have their sign bit set.
191   char char_at(int index) const {
192     assert(index >=0 && index < length(), "symbol index overflow");
193     return (char)base()[index];
194   }
195 
196   const u1* bytes() const { return base(); }
197 
198   int utf8_length() const { return length(); }
199 
200   // Compares the symbol with a string.
201   bool equals(const char* str, int len) const {
202     int l = utf8_length();
203     if (l != len) return false;
204     return contains_utf8_at(0, str, len);
205   }
206   bool equals(const char* str) const { return equals(str, (int) strlen(str)); }
207   bool is_star_match(const char* pattern) const;
208 
209   // Tests if the symbol starts with the given prefix.
210   bool starts_with(const char* prefix, int len) const {
211     return contains_utf8_at(0, prefix, len);
212   }
213   bool starts_with(const char* prefix) const {
214     return starts_with(prefix, (int) strlen(prefix));
215   }
216   bool starts_with(char prefix_char) const {
217     return contains_byte_at(0, prefix_char);
218   }
219   // Tests if the symbol ends with the given suffix.
220   bool ends_with(const char* suffix, int len) const {
221     return contains_utf8_at(utf8_length() - len, suffix, len);
222   }
223   bool ends_with(const char* suffix) const {
224     return ends_with(suffix, (int) strlen(suffix));
225   }
226   bool ends_with(char suffix_char) const {
227     return contains_byte_at(utf8_length() - 1, suffix_char);
228   }
229 
230   // Tests if the symbol contains the given utf8 substring
231   // at the given byte position.
232   bool contains_utf8_at(int position, const char* substring, int len) const {
233     assert(len >= 0 && substring != nullptr, "substring must be valid");
234     if (position < 0)  return false;  // can happen with ends_with
235     if (position + len > utf8_length()) return false;
236     return (memcmp((char*)base() + position, substring, len) == 0);
237   }
238 
239   // Tests if the symbol contains the given byte at the given position.
240   bool contains_byte_at(int position, char code_byte) const {
241     if (position < 0)  return false;  // can happen with ends_with
242     if (position >= utf8_length()) return false;
243     return code_byte == char_at(position);
244   }
245 
246   // Test if the symbol has the give substring at or after the i-th char.
247   int index_of_at(int i, const char* substr, int substr_len) const;
248 
249   // Three-way compare for sorting; returns -1/0/1 if receiver is </==/> than arg
250   // note that the ordering is not alfabetical
251   inline int fast_compare(const Symbol* other) const;
252 
253   // Perform a memcmp against the other block of bytes, up to the end
254   // of the shorter of the two.  If lengths differ but the bytes are
255   // the same, the shorter one compares lower.
256   int cmp(const Symbol* other) const {
257     return cmp((char*)other->base(), other->utf8_length());
258   }
259   int cmp(const char* str, int len) const {
260     int mylen = utf8_length();
261     int cmp = memcmp((char*)base(), str, mylen < len ? mylen : len);
262     // mylen - len cannot overflow because symbol length >= 0
263     return cmp != 0 ? cmp : mylen - len;
264   }
265 
266   // Returns receiver converted to null-terminated UTF-8 string; string is
267   // allocated in resource area, or in the char buffer provided by caller.
268   char* as_C_string() const;
269   char* as_C_string(char* buf, int size) const;
270 
271   // Returns an escaped form of a Java string.
272   char* as_quoted_ascii() const;
273 
274   // Returns a null terminated utf8 string in a resource array
275   char* as_utf8() const { return as_C_string(); }
276 
277   jchar* as_unicode(int& length) const;
278 
279   // Treating this symbol as a class name, returns the Java name for the class.
280   // String is allocated in resource area if buffer is not provided.
281   // See Klass::external_name()
282   const char* as_klass_external_name() const;
283   const char* as_klass_external_name(char* buf, int size) const;
284 
285   // Treating the symbol as a signature, print the return
286   // type to the outputStream. Prints external names as 'double' or
287   // 'java.lang.Object[][]'.
288   void print_as_signature_external_return_type(outputStream *os);
289   // Treating the symbol as a signature, print the parameter types
290   // separated by ', ' to the outputStream.  Prints external names as
291   //  'double' or 'java.lang.Object[][]'.
292   void print_as_signature_external_parameters(outputStream *os);
293   void print_as_field_external_type(outputStream *os);
294 
295   void metaspace_pointers_do(MetaspaceClosure* it);
296   MetaspaceObj::Type type() const { return SymbolType; }
297 
298   // Printing
299   void print_symbol_on(outputStream* st = nullptr) const;
300   void print_utf8_on(outputStream* st) const;
301   void print_on(outputStream* st) const;         // First level print
302   void print_value_on(outputStream* st) const;   // Second level print.
303 
304   // printing on default output stream
305   void print() const;
306   void print_value() const;
307 
308   static bool is_valid(Symbol* s);
309 
310   static bool is_valid_id(vmSymbolID vm_symbol_id) PRODUCT_RETURN_(return true;);
311 
312   static Symbol* vm_symbol_at(vmSymbolID vm_symbol_id) {
313     assert(is_valid_id(vm_symbol_id), "must be");
314     return _vm_symbols[static_cast<int>(vm_symbol_id)];
315   }
316 
317   static unsigned int compute_hash(const Symbol* const& name) {
318     return (unsigned int) name->identity_hash();
319   }
320 
321 #ifndef PRODUCT
322   // Empty constructor to create a dummy symbol object on stack
323   // only for getting its vtable pointer.
324   Symbol() { }
325 
326   static size_t _total_count;
327 #endif
328 };
329 
330 // Note: this comparison is used for vtable sorting only; it doesn't matter
331 // what order it defines, as long as it is a total, time-invariant order
332 // Since Symbol*s are in C_HEAP, their relative order in memory never changes,
333 // so use address comparison for speed
334 int Symbol::fast_compare(const Symbol* other) const {
335  return (((uintptr_t)this < (uintptr_t)other) ? -1
336    : ((uintptr_t)this == (uintptr_t) other) ? 0 : 1);
337 }
338 #endif // SHARE_OOPS_SYMBOL_HPP