1 /*
   2  * Copyright (c) 1997, 2014, 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 "utilities/utf8.hpp"
  29 #include "memory/allocation.hpp"
  30 #include "runtime/atomic.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 // Another example of TempNewSymbol usage is parsed_name used in
  94 // ClassFileParser::parseClassFile() where parsed_name is used in the cleanup
  95 // after a failed attempt to load a class.  Here parsed_name is a
  96 // TempNewSymbol (passed in as a parameter) so the reference count on its symbol
  97 // will be decremented when it goes out of scope.
  98 
  99 
 100 // This cannot be inherited from ResourceObj because it cannot have a vtable.
 101 // Since sometimes this is allocated from Metadata, pick a base allocation
 102 // type without virtual functions.
 103 class ClassLoaderData;
 104 
 105 // We separate the fields in SymbolBase from Symbol::_body so that
 106 // Symbol::size(int) can correctly calculate the space needed.
 107 class SymbolBase : public MetaspaceObj {
 108  public:
 109   ATOMIC_SHORT_PAIR(
 110     volatile short _refcount,  // needs atomic operation
 111     unsigned short _length     // number of UTF8 characters in the symbol (does not need atomic op)
 112   );
 113   int            _identity_hash;
 114 };
 115 
 116 class Symbol : private SymbolBase {
 117   friend class VMStructs;
 118   friend class SymbolTable;
 119   friend class MoveSymbols;
 120  private:
 121   jbyte _body[1];
 122 
 123   enum {
 124     // max_symbol_length is constrained by type of _length
 125     max_symbol_length = (1 << 16) -1
 126   };
 127 
 128   static int size(int length) {
 129     size_t sz = heap_word_size(sizeof(SymbolBase) + (length > 0 ? length : 0));
 130     return align_object_size(sz);
 131   }
 132 
 133   void byte_at_put(int index, int value) {
 134     assert(index >=0 && index < _length, "symbol index overflow");
 135     _body[index] = value;
 136   }
 137 
 138   Symbol(const u1* name, int length, int refcount);
 139   void* operator new(size_t size, int len, TRAPS) throw();
 140   void* operator new(size_t size, int len, Arena* arena, TRAPS) throw();
 141   void* operator new(size_t size, int len, ClassLoaderData* loader_data, TRAPS) throw();
 142 
 143   void  operator delete(void* p);
 144 
 145  public:
 146   // Low-level access (used with care, since not GC-safe)
 147   const jbyte* base() const { return &_body[0]; }
 148 
 149   int size()                { return size(utf8_length()); }
 150 
 151   // Returns the largest size symbol we can safely hold.
 152   static int max_length()   { return max_symbol_length; }
 153 
 154   int identity_hash()       { return _identity_hash; }
 155 
 156   // For symbol table alternate hashing
 157   unsigned int new_hash(juint seed);
 158 
 159   // Reference counting.  See comments above this class for when to use.
 160   int refcount() const      { return _refcount; }
 161   void increment_refcount();
 162   void decrement_refcount();
 163 
 164   int byte_at(int index) const {
 165     assert(index >=0 && index < _length, "symbol index overflow");
 166     return base()[index];
 167   }
 168 
 169   const jbyte* bytes() const { return base(); }
 170 
 171   int utf8_length() const { return _length; }
 172 
 173   // Compares the symbol with a string.
 174   bool equals(const char* str, int len) const;
 175   bool equals(const char* str) const { return equals(str, (int) strlen(str)); }
 176 
 177   // Tests if the symbol starts with the given prefix.
 178   bool starts_with(const char* prefix, int len) const;
 179   bool starts_with(const char* prefix) const {
 180     return starts_with(prefix, (int) strlen(prefix));
 181   }
 182 
 183   // Tests if the symbol starts with the given prefix.
 184   int index_of_at(int i, const char* str, int len) const;
 185   int index_of_at(int i, const char* str) const {
 186     return index_of_at(i, str, (int) strlen(str));
 187   }
 188 
 189   // Three-way compare for sorting; returns -1/0/1 if receiver is </==/> than arg
 190   // note that the ordering is not alfabetical
 191   inline int fast_compare(Symbol* other) const;
 192 
 193   // Returns receiver converted to null-terminated UTF-8 string; string is
 194   // allocated in resource area, or in the char buffer provided by caller.
 195   char* as_C_string() const;
 196   char* as_C_string(char* buf, int size) const;
 197   // Use buf if needed buffer length is <= size.
 198   char* as_C_string_flexible_buffer(Thread* t, char* buf, int size) const;
 199 
 200   // Returns an escaped form of a Java string.
 201   char* as_quoted_ascii() const;
 202 
 203   // Returns a null terminated utf8 string in a resource array
 204   char* as_utf8() const { return as_C_string(); }
 205   char* as_utf8_flexible_buffer(Thread* t, char* buf, int size) const {
 206     return as_C_string_flexible_buffer(t, buf, size);
 207   }
 208 
 209   jchar* as_unicode(int& length) const;
 210 
 211   // Treating this symbol as a class name, returns the Java name for the class.
 212   // String is allocated in resource area if buffer is not provided.
 213   // See Klass::external_name()
 214   const char* as_klass_external_name() const;
 215   const char* as_klass_external_name(char* buf, int size) const;
 216 
 217   // Printing
 218   void print_symbol_on(outputStream* st = NULL) const;
 219   void print_on(outputStream* st) const;         // First level print
 220   void print_value_on(outputStream* st) const;   // Second level print.
 221 
 222   // printing on default output stream
 223   void print()         { print_on(tty);       }
 224   void print_value()   { print_value_on(tty); }
 225 
 226   // Allows two distinct Symbol objects to be considered equal as long as
 227   // they contain the same string. However, no two Symbol objects stored in the same
 228   // SymbolTable would contain the same string. Therefore, if two distinct Symbol
 229   // objects contain the same string, they must belong to different SymbolTables.
 230   inline bool equals(const Symbol* other) const {
 231     if (this && other) {
 232       int len = this->utf8_length();
 233       if (len != other->utf8_length()) {
 234         return false;
 235       }
 236       if (this->_identity_hash != other->_identity_hash) {
 237         return false;
 238       }
 239       return (strncmp((const char*)(this->base()), (const char*)(other->base()), len) == 0);
 240     } else {
 241       return (this == other);
 242     }
 243   }
 244   inline bool not_equals(const Symbol* other) const {
 245     return !(this->equals(other));
 246   }
 247 
 248 #ifndef PRODUCT
 249   // Empty constructor to create a dummy symbol object on stack
 250   // only for getting its vtable pointer.
 251   Symbol() { }
 252 
 253   static int _total_count;
 254 #endif
 255 };
 256 
 257 // Note: this comparison is used for vtable sorting only; it doesn't matter
 258 // what order it defines, as long as it is a total, time-invariant order
 259 // Since Symbol*s are in C_HEAP, their relative order in memory never changes,
 260 // so use address comparison for speed
 261 int Symbol::fast_compare(Symbol* other) const {
 262  return (((uintptr_t)this < (uintptr_t)other) ? -1
 263    : ((uintptr_t)this == (uintptr_t) other) ? 0 : 1);
 264 }
 265 #endif // SHARE_VM_OOPS_SYMBOL_HPP