1 /*
   2  * Copyright (c) 1997, 2016, 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_VM_OOPS_SYMBOL_HPP
  26 #define SHARE_VM_OOPS_SYMBOL_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "utilities/exceptions.hpp"
  30 #include "utilities/macros.hpp"
  31 #include "utilities/utf8.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 filed in
  49 // fieldDescriptor or _ptr in a CPSlot) 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 assignmnet
  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 GC'ed.
 100 #ifndef PERM_REFCOUNT
 101 #define PERM_REFCOUNT -1
 102 #endif
 103 
 104 class Symbol : public MetaspaceObj {
 105   friend class VMStructs;
 106   friend class SymbolTable;
 107   friend class MoveSymbols;
 108 
 109  private:
 110   ATOMIC_SHORT_PAIR(
 111     volatile short _refcount,  // needs atomic operation
 112     unsigned short _length     // number of UTF8 characters in the symbol (does not need atomic op)
 113   );
 114   short _identity_hash;
 115   jbyte _body[2];
 116 
 117   enum {
 118     // max_symbol_length is constrained by type of _length
 119     max_symbol_length = (1 << 16) -1
 120   };
 121 
 122   static int size(int length) {
 123     // minimum number of natural words needed to hold these bits (no non-heap version)
 124     return (int)heap_word_size(sizeof(Symbol) + (length > 2 ? length - 2 : 0));
 125   }
 126 
 127   void byte_at_put(int index, int value) {
 128     assert(index >=0 && index < _length, "symbol index overflow");
 129     _body[index] = value;
 130   }
 131 
 132   Symbol(const u1* name, int length, int refcount);
 133   void* operator new(size_t size, int len, TRAPS) throw();
 134   void* operator new(size_t size, int len, Arena* arena, TRAPS) throw();
 135   void* operator new(size_t size, int len, ClassLoaderData* loader_data, TRAPS) throw();
 136 
 137   void  operator delete(void* p);
 138 
 139  public:
 140   // Low-level access (used with care, since not GC-safe)
 141   const jbyte* base() const { return &_body[0]; }
 142 
 143   int size()                { return size(utf8_length()); }
 144 
 145   // Returns the largest size symbol we can safely hold.
 146   static int max_length() { return max_symbol_length; }
 147   unsigned identity_hash() const {
 148     unsigned addr_bits = (unsigned)((uintptr_t)this >> (LogMinObjAlignmentInBytes + 3));
 149     return ((unsigned)_identity_hash & 0xffff) |
 150            ((addr_bits ^ (_length << 8) ^ (( _body[0] << 8) | _body[1])) << 16);
 151   }
 152 
 153   // For symbol table alternate hashing
 154   unsigned int new_hash(juint seed);
 155 
 156   // Reference counting.  See comments above this class for when to use.
 157   int refcount() const      { return _refcount; }
 158   void increment_refcount();
 159   void decrement_refcount();
 160   // Set _refcount non zero to avoid being reclaimed by GC.
 161   void set_permanent() {
 162     assert(LogTouchedMethods, "Should not be called with LogTouchedMethods off");
 163     if (_refcount != PERM_REFCOUNT) {
 164       _refcount = PERM_REFCOUNT;
 165     }
 166   }
 167 
 168   int byte_at(int index) const {
 169     assert(index >=0 && index < _length, "symbol index overflow");
 170     return base()[index];
 171   }
 172 
 173   const jbyte* bytes() const { return base(); }
 174 
 175   int utf8_length() const { return _length; }
 176 
 177   // Compares the symbol with a string.
 178   bool equals(const char* str, int len) const;
 179   bool equals(const char* str) const { return equals(str, (int) strlen(str)); }
 180 
 181   // Tests if the symbol starts with the given prefix.
 182   bool starts_with(const char* prefix, int len) const;
 183   bool starts_with(const char* prefix) const {
 184     return starts_with(prefix, (int) strlen(prefix));
 185   }
 186 
 187   // Tests if the symbol ends with the given suffix.
 188   bool ends_with(const char* suffix, int len) const;
 189   bool ends_with(const char* suffix) const {
 190     return ends_with(suffix, (int) strlen(suffix));
 191   }
 192 
 193   // Returns index of the given substring in the symbol, starting
 194   // at index 'i'.
 195   // If the symbol doesn't contain the given substring, return -1.
 196   int index_of_at(int i, const char* str, int len) const;
 197   int index_of_at(int i, const char* str) const {
 198     return index_of_at(i, str, (int) strlen(str));
 199   }
 200 
 201   // Three-way compare for sorting; returns -1/0/1 if receiver is </==/> than arg
 202   // note that the ordering is not alfabetical
 203   inline int fast_compare(const Symbol* other) const;
 204 
 205   // Returns receiver converted to null-terminated UTF-8 string; string is
 206   // allocated in resource area, or in the char buffer provided by caller.
 207   char* as_C_string() const;
 208   char* as_C_string(char* buf, int size) const;
 209   // Use buf if needed buffer length is <= size.
 210   char* as_C_string_flexible_buffer(Thread* t, char* buf, int size) const;
 211 
 212   // Returns an escaped form of a Java string.
 213   char* as_quoted_ascii() const;
 214 
 215   // Returns a null terminated utf8 string in a resource array
 216   char* as_utf8() const { return as_C_string(); }
 217   char* as_utf8_flexible_buffer(Thread* t, char* buf, int size) const {
 218     return as_C_string_flexible_buffer(t, buf, size);
 219   }
 220 
 221   jchar* as_unicode(int& length) const;
 222 
 223   // Treating this symbol as a class name, returns the Java name for the class.
 224   // String is allocated in resource area if buffer is not provided.
 225   // See Klass::external_name()
 226   const char* as_klass_external_name() const;
 227   const char* as_klass_external_name(char* buf, int size) const;
 228 
 229   // Printing
 230   void print_symbol_on(outputStream* st = NULL) const;
 231   void print_utf8_on(outputStream* st) const;
 232   void print_on(outputStream* st) const;         // First level print
 233   void print_value_on(outputStream* st) const;   // Second level print.
 234 
 235   // printing on default output stream
 236   void print()         { print_on(tty);       }
 237   void print_value()   { print_value_on(tty); }
 238 
 239 #ifndef PRODUCT
 240   // Empty constructor to create a dummy symbol object on stack
 241   // only for getting its vtable pointer.
 242   Symbol() { }
 243 
 244   static int _total_count;
 245 #endif
 246 };
 247 
 248 // Note: this comparison is used for vtable sorting only; it doesn't matter
 249 // what order it defines, as long as it is a total, time-invariant order
 250 // Since Symbol*s are in C_HEAP, their relative order in memory never changes,
 251 // so use address comparison for speed
 252 int Symbol::fast_compare(const Symbol* other) const {
 253  return (((uintptr_t)this < (uintptr_t)other) ? -1
 254    : ((uintptr_t)this == (uintptr_t) other) ? 0 : 1);
 255 }
 256 #endif // SHARE_VM_OOPS_SYMBOL_HPP