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 
  26 #include "precompiled.hpp"
  27 #include "classfile/altHashing.hpp"
  28 #include "classfile/classLoaderData.hpp"
  29 #include "gc/shared/collectedHeap.hpp"
  30 #include "logging/log.hpp"
  31 #include "logging/logStream.hpp"
  32 #include "memory/allocation.inline.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "oops/symbol.hpp"
  35 #include "runtime/atomic.hpp"
  36 #include "runtime/os.hpp"
  37 #include "utilities/utf8.hpp"
  38 
  39 uint32_t Symbol::pack_length_and_refcount(int length, int refcount) {
  40   STATIC_ASSERT(max_symbol_length == ((1 << 16) - 1));
  41   STATIC_ASSERT(PERM_REFCOUNT == ((1 << 16) - 1));
  42   assert(length >= 0, "negative length");
  43   assert(length <= max_symbol_length, "too long symbol");
  44   assert(refcount >= 0, "negative refcount");
  45   assert(refcount <= PERM_REFCOUNT, "invalid refcount");
  46   uint32_t hi = length;
  47   uint32_t lo = refcount;
  48   return (hi << 16) | lo;
  49 }
  50 
  51 Symbol::Symbol(const u1* name, int length, int refcount) {
  52   _length_and_refcount =  pack_length_and_refcount(length, refcount);
  53   _identity_hash = (short)os::random();
  54   for (int i = 0; i < length; i++) {
  55     byte_at_put(i, name[i]);
  56   }
  57 }
  58 
  59 void* Symbol::operator new(size_t sz, int len, TRAPS) throw() {
  60   int alloc_size = size(len)*wordSize;
  61   address res = (address) AllocateHeap(alloc_size, mtSymbol);
  62   return res;
  63 }
  64 
  65 void* Symbol::operator new(size_t sz, int len, Arena* arena, TRAPS) throw() {
  66   int alloc_size = size(len)*wordSize;
  67   address res = (address)arena->Amalloc_4(alloc_size);
  68   return res;
  69 }
  70 
  71 void Symbol::operator delete(void *p) {
  72   assert(((Symbol*)p)->refcount() == 0, "should not call this");
  73   FreeHeap(p);
  74 }
  75 
  76 // ------------------------------------------------------------------
  77 // Symbol::starts_with
  78 //
  79 // Tests if the symbol starts with the specified prefix of the given
  80 // length.
  81 bool Symbol::starts_with(const char* prefix, int len) const {
  82   if (len > utf8_length()) return false;
  83   while (len-- > 0) {
  84     if (prefix[len] != char_at(len))
  85       return false;
  86   }
  87   assert(len == -1, "we should be at the beginning");
  88   return true;
  89 }
  90 
  91 
  92 // ------------------------------------------------------------------
  93 // Symbol::index_of
  94 //
  95 // Finds if the given string is a substring of this symbol's utf8 bytes.
  96 // Return -1 on failure.  Otherwise return the first index where str occurs.
  97 int Symbol::index_of_at(int i, const char* str, int len) const {
  98   assert(i >= 0 && i <= utf8_length(), "oob");
  99   if (len <= 0)  return 0;
 100   char first_char = str[0];
 101   address bytes = (address) ((Symbol*)this)->base();
 102   address limit = bytes + utf8_length() - len;  // inclusive limit
 103   address scan = bytes + i;
 104   if (scan > limit)
 105     return -1;
 106   for (; scan <= limit; scan++) {
 107     scan = (address) memchr(scan, first_char, (limit + 1 - scan));
 108     if (scan == NULL)
 109       return -1;  // not found
 110     assert(scan >= bytes+i && scan <= limit, "scan oob");
 111     if (memcmp(scan, str, len) == 0)
 112       return (int)(scan - bytes);
 113   }
 114   return -1;
 115 }
 116 
 117 
 118 char* Symbol::as_C_string(char* buf, int size) const {
 119   if (size > 0) {
 120     int len = MIN2(size - 1, utf8_length());
 121     for (int i = 0; i < len; i++) {
 122       buf[i] = char_at(i);
 123     }
 124     buf[len] = '\0';
 125   }
 126   return buf;
 127 }
 128 
 129 char* Symbol::as_C_string() const {
 130   int len = utf8_length();
 131   char* str = NEW_RESOURCE_ARRAY(char, len + 1);
 132   return as_C_string(str, len + 1);
 133 }
 134 
 135 void Symbol::print_utf8_on(outputStream* st) const {
 136   st->print("%s", as_C_string());
 137 }
 138 
 139 void Symbol::print_symbol_on(outputStream* st) const {
 140   char *s;
 141   st = st ? st : tty;
 142   {
 143     // ResourceMark may not affect st->print(). If st is a string
 144     // stream it could resize, using the same resource arena.
 145     ResourceMark rm;
 146     s = as_quoted_ascii();
 147     s = os::strdup(s);
 148   }
 149   if (s == NULL) {
 150     st->print("(null)");
 151   } else {
 152     st->print("%s", s);
 153     os::free(s);
 154   }
 155 }
 156 
 157 char* Symbol::as_quoted_ascii() const {
 158   const char *ptr = (const char *)&_body[0];
 159   int quoted_length = UTF8::quoted_ascii_length(ptr, utf8_length());
 160   char* result = NEW_RESOURCE_ARRAY(char, quoted_length + 1);
 161   UTF8::as_quoted_ascii(ptr, utf8_length(), result, quoted_length + 1);
 162   return result;
 163 }
 164 
 165 jchar* Symbol::as_unicode(int& length) const {
 166   Symbol* this_ptr = (Symbol*)this;
 167   length = UTF8::unicode_length((char*)this_ptr->bytes(), utf8_length());
 168   jchar* result = NEW_RESOURCE_ARRAY(jchar, length);
 169   if (length > 0) {
 170     UTF8::convert_to_unicode((char*)this_ptr->bytes(), result, length);
 171   }
 172   return result;
 173 }
 174 
 175 const char* Symbol::as_klass_external_name(char* buf, int size) const {
 176   if (size > 0) {
 177     char* str    = as_C_string(buf, size);
 178     int   length = (int)strlen(str);
 179     // Turn all '/'s into '.'s (also for array klasses)
 180     for (int index = 0; index < length; index++) {
 181       if (str[index] == '/') {
 182         str[index] = '.';
 183       }
 184     }
 185     return str;
 186   } else {
 187     return buf;
 188   }
 189 }
 190 
 191 const char* Symbol::as_klass_external_name() const {
 192   char* str    = as_C_string();
 193   int   length = (int)strlen(str);
 194   // Turn all '/'s into '.'s (also for array klasses)
 195   for (int index = 0; index < length; index++) {
 196     if (str[index] == '/') {
 197       str[index] = '.';
 198     }
 199   }
 200   return str;
 201 }
 202 
 203 // Increment refcount while checking for zero.  If the Symbol's refcount becomes zero
 204 // a thread could be concurrently removing the Symbol.  This is used during SymbolTable
 205 // lookup to avoid reviving a dead Symbol.
 206 bool Symbol::try_increment_refcount() {
 207   uint32_t found = _length_and_refcount;
 208   while (true) {
 209     uint32_t old_value = found;
 210     int refc = extract_refcount(old_value);
 211     if (refc == PERM_REFCOUNT) {
 212       return true;  // sticky max or created permanent
 213     } else if (refc == 0) {
 214       return false; // dead, can't revive.
 215     } else {
 216       found = Atomic::cmpxchg(old_value + 1, &_length_and_refcount, old_value);
 217       if (found == old_value) {
 218         return true; // successfully updated.
 219       }
 220       // refcount changed, try again.
 221     }
 222   }
 223 }
 224 
 225 // The increment_refcount() is called when not doing lookup. It is assumed that you
 226 // have a symbol with a non-zero refcount and it can't become zero while referenced by
 227 // this caller.
 228 void Symbol::increment_refcount() {
 229   if (!try_increment_refcount()) {
 230 #ifdef ASSERT
 231     print();
 232     fatal("refcount has gone to zero");
 233 #endif
 234   }
 235 #ifndef PRODUCT
 236   if (refcount() != PERM_REFCOUNT) { // not a permanent symbol
 237     NOT_PRODUCT(Atomic::inc(&_total_count);)
 238   }
 239 #endif
 240 }
 241 
 242 // Decrement refcount potentially while racing increment, so we need
 243 // to check the value after attempting to decrement so that if another
 244 // thread increments to PERM_REFCOUNT the value is not decremented.
 245 void Symbol::decrement_refcount() {
 246   uint32_t found = _length_and_refcount;
 247   while (true) {
 248     uint32_t old_value = found;
 249     int refc = extract_refcount(old_value);
 250     if (refc == PERM_REFCOUNT) {
 251       return;  // refcount is permanent, permanent is sticky
 252     } else if (refc == 0) {
 253 #ifdef ASSERT
 254       print();
 255       fatal("refcount underflow");
 256 #endif
 257       return;
 258     } else {
 259       found = Atomic::cmpxchg(old_value - 1, &_length_and_refcount, old_value);
 260       if (found == old_value) {
 261         return;  // successfully updated.
 262       }
 263       // refcount changed, try again.
 264     }
 265   }
 266 }
 267 
 268 void Symbol::make_permanent() {
 269   uint32_t found = _length_and_refcount;
 270   while (true) {
 271     uint32_t old_value = found;
 272     int refc = extract_refcount(old_value);
 273     if (refc == PERM_REFCOUNT) {
 274       return;  // refcount is permanent, permanent is sticky
 275     } else if (refc == 0) {
 276 #ifdef ASSERT
 277       print();
 278       fatal("refcount underflow");
 279 #endif
 280       return;
 281     } else {
 282       int len = extract_length(old_value);
 283       found = Atomic::cmpxchg(pack_length_and_refcount(len, PERM_REFCOUNT), &_length_and_refcount, old_value);
 284       if (found == old_value) {
 285         return;  // successfully updated.
 286       }
 287       // refcount changed, try again.
 288     }
 289   }
 290 }
 291 
 292 void Symbol::metaspace_pointers_do(MetaspaceClosure* it) {
 293   if (log_is_enabled(Trace, cds)) {
 294     LogStream trace_stream(Log(cds)::trace());
 295     trace_stream.print("Iter(Symbol): %p ", this);
 296     print_value_on(&trace_stream);
 297     trace_stream.cr();
 298   }
 299 }
 300 
 301 void Symbol::print_on(outputStream* st) const {
 302   st->print("Symbol: '");
 303   print_symbol_on(st);
 304   st->print("'");
 305   st->print(" count %d", refcount());
 306 }
 307 
 308 // The print_value functions are present in all builds, to support the
 309 // disassembler and error reporting.
 310 void Symbol::print_value_on(outputStream* st) const {
 311   st->print("'");
 312   for (int i = 0; i < utf8_length(); i++) {
 313     st->print("%c", char_at(i));
 314   }
 315   st->print("'");
 316 }
 317 
 318 bool Symbol::is_valid(Symbol* s) {
 319   if (!is_aligned(s, sizeof(MetaWord))) return false;
 320   if ((size_t)s < os::min_page_size()) return false;
 321 
 322   if (!os::is_readable_range(s, s + 1)) return false;
 323 
 324   // Symbols are not allocated in Java heap.
 325   if (Universe::heap()->is_in_reserved(s)) return false;
 326 
 327   int len = s->utf8_length();
 328   if (len < 0) return false;
 329 
 330   jbyte* bytes = (jbyte*) s->bytes();
 331   return os::is_readable_range(bytes, bytes + len);
 332 }
 333 
 334 // SymbolTable prints this in its statistics
 335 NOT_PRODUCT(size_t Symbol::_total_count = 0;)