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