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 bool Symbol::is_Q_signature() const {
  92   return utf8_length() > 2 && char_at(0) == 'Q' && char_at(utf8_length() - 1) == ';';
  93 }
  94 
  95 Symbol* Symbol::fundamental_name(TRAPS) {
  96   if ((char_at(0) == 'Q' || char_at(0) == 'L') && char_at(utf8_length() - 1) == ';') {
  97     return SymbolTable::lookup(this, 1, utf8_length() - 1, CHECK_NULL);
  98   } else {
  99     // reference count is incremented to be consistent with the behavior with
 100     // the SymbolTable::lookup() call above
 101     this->increment_refcount();
 102     return this;
 103   }
 104 }
 105 
 106 bool Symbol::is_same_fundamental_type(Symbol* s) const {
 107   if (this == s) return true;
 108   if (utf8_length() < 3) return false;
 109   int offset1, offset2, len;
 110   if (char_at(utf8_length() - 1) == ';') {
 111     if (char_at(0) != 'Q' && char_at(0) != 'L') return false;
 112     offset1 = 1;
 113     len = utf8_length() - 2;
 114   } else {
 115     offset1 = 0;
 116     len = utf8_length();
 117   }
 118   if (s->char_at(s->utf8_length() - 1) == ';') {
 119     if (s->char_at(0) != 'Q' && s->char_at(0) != 'L') return false;
 120     offset2 = 1;
 121   } else {
 122     offset2 = 0;
 123   }
 124   if ((offset2 + len) > s->utf8_length()) return false;
 125   if ((utf8_length() - offset1 * 2) != (s->utf8_length() - offset2 * 2))
 126     return false;
 127   int l = len;
 128   while (l-- > 0) {
 129     if (char_at(offset1 + l) != s->char_at(offset2 + l))
 130       return false;
 131   }
 132   return true;
 133 }
 134 
 135 // ------------------------------------------------------------------
 136 // Symbol::index_of
 137 //
 138 // Finds if the given string is a substring of this symbol's utf8 bytes.
 139 // Return -1 on failure.  Otherwise return the first index where str occurs.
 140 int Symbol::index_of_at(int i, const char* str, int len) const {
 141   assert(i >= 0 && i <= utf8_length(), "oob");
 142   if (len <= 0)  return 0;
 143   char first_char = str[0];
 144   address bytes = (address) ((Symbol*)this)->base();
 145   address limit = bytes + utf8_length() - len;  // inclusive limit
 146   address scan = bytes + i;
 147   if (scan > limit)
 148     return -1;
 149   for (; scan <= limit; scan++) {
 150     scan = (address) memchr(scan, first_char, (limit + 1 - scan));
 151     if (scan == NULL)
 152       return -1;  // not found
 153     assert(scan >= bytes+i && scan <= limit, "scan oob");
 154     if (memcmp(scan, str, len) == 0)
 155       return (int)(scan - bytes);
 156   }
 157   return -1;
 158 }
 159 
 160 
 161 char* Symbol::as_C_string(char* buf, int size) const {
 162   if (size > 0) {
 163     int len = MIN2(size - 1, utf8_length());
 164     for (int i = 0; i < len; i++) {
 165       buf[i] = char_at(i);
 166     }
 167     buf[len] = '\0';
 168   }
 169   return buf;
 170 }
 171 
 172 char* Symbol::as_C_string() const {
 173   int len = utf8_length();
 174   char* str = NEW_RESOURCE_ARRAY(char, len + 1);
 175   return as_C_string(str, len + 1);
 176 }
 177 
 178 void Symbol::print_utf8_on(outputStream* st) const {
 179   st->print("%s", as_C_string());
 180 }
 181 
 182 void Symbol::print_symbol_on(outputStream* st) const {
 183   char *s;
 184   st = st ? st : tty;
 185   {
 186     // ResourceMark may not affect st->print(). If st is a string
 187     // stream it could resize, using the same resource arena.
 188     ResourceMark rm;
 189     s = as_quoted_ascii();
 190     s = os::strdup(s);
 191   }
 192   if (s == NULL) {
 193     st->print("(null)");
 194   } else {
 195     st->print("%s", s);
 196     os::free(s);
 197   }
 198 }
 199 
 200 char* Symbol::as_quoted_ascii() const {
 201   const char *ptr = (const char *)&_body[0];
 202   int quoted_length = UTF8::quoted_ascii_length(ptr, utf8_length());
 203   char* result = NEW_RESOURCE_ARRAY(char, quoted_length + 1);
 204   UTF8::as_quoted_ascii(ptr, utf8_length(), result, quoted_length + 1);
 205   return result;
 206 }
 207 
 208 jchar* Symbol::as_unicode(int& length) const {
 209   Symbol* this_ptr = (Symbol*)this;
 210   length = UTF8::unicode_length((char*)this_ptr->bytes(), utf8_length());
 211   jchar* result = NEW_RESOURCE_ARRAY(jchar, length);
 212   if (length > 0) {
 213     UTF8::convert_to_unicode((char*)this_ptr->bytes(), result, length);
 214   }
 215   return result;
 216 }
 217 
 218 const char* Symbol::as_klass_external_name(char* buf, int size) const {
 219   if (size > 0) {
 220     char* str    = as_C_string(buf, size);
 221     int   length = (int)strlen(str);
 222     // Turn all '/'s into '.'s (also for array klasses)
 223     for (int index = 0; index < length; index++) {
 224       if (str[index] == '/') {
 225         str[index] = '.';
 226       }
 227     }
 228     return str;
 229   } else {
 230     return buf;
 231   }
 232 }
 233 
 234 const char* Symbol::as_klass_external_name() const {
 235   char* str    = as_C_string();
 236   int   length = (int)strlen(str);
 237   // Turn all '/'s into '.'s (also for array klasses)
 238   for (int index = 0; index < length; index++) {
 239     if (str[index] == '/') {
 240       str[index] = '.';
 241     }
 242   }
 243   return str;
 244 }
 245 
 246 static void print_class(outputStream *os, char *class_str, int len) {
 247   for (int i = 0; i < len; ++i) {
 248     if (class_str[i] == '/') {
 249       os->put('.');
 250     } else {
 251       os->put(class_str[i]);
 252     }
 253   }
 254 }
 255 
 256 static void print_array(outputStream *os, char *array_str, int len) {
 257   int dimensions = 0;
 258   for (int i = 0; i < len; ++i) {
 259     if (array_str[i] == '[') {
 260       dimensions++;
 261     } else if (array_str[i] == 'L' || array_str[i] == 'Q') {
 262       // Expected format: L<type name>;. Skip 'L' and ';' delimiting the type name.
 263       print_class(os, array_str+i+1, len-i-2);
 264       break;
 265     } else {
 266       os->print("%s", type2name(char2type(array_str[i])));
 267     }
 268   }
 269   for (int i = 0; i < dimensions; ++i) {
 270     os->print("[]");
 271   }
 272 }
 273 
 274 void Symbol::print_as_signature_external_return_type(outputStream *os) {
 275   for (SignatureStream ss(this); !ss.is_done(); ss.next()) {
 276     if (ss.at_return_type()) {
 277       if (ss.is_array()) {
 278         print_array(os, (char*)ss.raw_bytes(), (int)ss.raw_length());
 279       } else if (ss.is_object()) {
 280         // Expected format: L<type name>;. Skip 'L' and ';' delimiting the class name.
 281         print_class(os, (char*)ss.raw_bytes()+1, (int)ss.raw_length()-2);
 282       } else {
 283         os->print("%s", type2name(ss.type()));
 284       }
 285     }
 286   }
 287 }
 288 
 289 void Symbol::print_as_signature_external_parameters(outputStream *os) {
 290   bool first = true;
 291   for (SignatureStream ss(this); !ss.is_done(); ss.next()) {
 292     if (ss.at_return_type()) break;
 293     if (!first) { os->print(", "); }
 294     if (ss.is_array()) {
 295       print_array(os, (char*)ss.raw_bytes(), (int)ss.raw_length());
 296     } else if (ss.is_object()) {
 297       // Skip 'L' and ';'.
 298       print_class(os, (char*)ss.raw_bytes()+1, (int)ss.raw_length()-2);
 299     } else {
 300       os->print("%s", type2name(ss.type()));
 301     }
 302     first = false;
 303   }
 304 }
 305 
 306 // Increment refcount while checking for zero.  If the Symbol's refcount becomes zero
 307 // a thread could be concurrently removing the Symbol.  This is used during SymbolTable
 308 // lookup to avoid reviving a dead Symbol.
 309 bool Symbol::try_increment_refcount() {
 310   uint32_t found = _length_and_refcount;
 311   while (true) {
 312     uint32_t old_value = found;
 313     int refc = extract_refcount(old_value);
 314     if (refc == PERM_REFCOUNT) {
 315       return true;  // sticky max or created permanent
 316     } else if (refc == 0) {
 317       return false; // dead, can't revive.
 318     } else {
 319       found = Atomic::cmpxchg(old_value + 1, &_length_and_refcount, old_value);
 320       if (found == old_value) {
 321         return true; // successfully updated.
 322       }
 323       // refcount changed, try again.
 324     }
 325   }
 326 }
 327 
 328 // The increment_refcount() is called when not doing lookup. It is assumed that you
 329 // have a symbol with a non-zero refcount and it can't become zero while referenced by
 330 // this caller.
 331 void Symbol::increment_refcount() {
 332   if (!try_increment_refcount()) {
 333 #ifdef ASSERT
 334     print();
 335     fatal("refcount has gone to zero");
 336 #endif
 337   }
 338 #ifndef PRODUCT
 339   if (refcount() != PERM_REFCOUNT) { // not a permanent symbol
 340     NOT_PRODUCT(Atomic::inc(&_total_count);)
 341   }
 342 #endif
 343 }
 344 
 345 // Decrement refcount potentially while racing increment, so we need
 346 // to check the value after attempting to decrement so that if another
 347 // thread increments to PERM_REFCOUNT the value is not decremented.
 348 void Symbol::decrement_refcount() {
 349   uint32_t found = _length_and_refcount;
 350   while (true) {
 351     uint32_t old_value = found;
 352     int refc = extract_refcount(old_value);
 353     if (refc == PERM_REFCOUNT) {
 354       return;  // refcount is permanent, permanent is sticky
 355     } else if (refc == 0) {
 356 #ifdef ASSERT
 357       print();
 358       fatal("refcount underflow");
 359 #endif
 360       return;
 361     } else {
 362       found = Atomic::cmpxchg(old_value - 1, &_length_and_refcount, old_value);
 363       if (found == old_value) {
 364         return;  // successfully updated.
 365       }
 366       // refcount changed, try again.
 367     }
 368   }
 369 }
 370 
 371 void Symbol::make_permanent() {
 372   uint32_t found = _length_and_refcount;
 373   while (true) {
 374     uint32_t old_value = found;
 375     int refc = extract_refcount(old_value);
 376     if (refc == PERM_REFCOUNT) {
 377       return;  // refcount is permanent, permanent is sticky
 378     } else if (refc == 0) {
 379 #ifdef ASSERT
 380       print();
 381       fatal("refcount underflow");
 382 #endif
 383       return;
 384     } else {
 385       int len = extract_length(old_value);
 386       found = Atomic::cmpxchg(pack_length_and_refcount(len, PERM_REFCOUNT), &_length_and_refcount, old_value);
 387       if (found == old_value) {
 388         return;  // successfully updated.
 389       }
 390       // refcount changed, try again.
 391     }
 392   }
 393 }
 394 
 395 void Symbol::metaspace_pointers_do(MetaspaceClosure* it) {
 396   if (log_is_enabled(Trace, cds)) {
 397     LogStream trace_stream(Log(cds)::trace());
 398     trace_stream.print("Iter(Symbol): %p ", this);
 399     print_value_on(&trace_stream);
 400     trace_stream.cr();
 401   }
 402 }
 403 
 404 void Symbol::print_on(outputStream* st) const {
 405   st->print("Symbol: '");
 406   print_symbol_on(st);
 407   st->print("'");
 408   st->print(" count %d", refcount());
 409 }
 410 
 411 // The print_value functions are present in all builds, to support the
 412 // disassembler and error reporting.
 413 void Symbol::print_value_on(outputStream* st) const {
 414   st->print("'");
 415   for (int i = 0; i < utf8_length(); i++) {
 416     st->print("%c", char_at(i));
 417   }
 418   st->print("'");
 419 }
 420 
 421 bool Symbol::is_valid(Symbol* s) {
 422   if (!is_aligned(s, sizeof(MetaWord))) return false;
 423   if ((size_t)s < os::min_page_size()) return false;
 424 
 425   if (!os::is_readable_range(s, s + 1)) return false;
 426 
 427   // Symbols are not allocated in Java heap.
 428   if (Universe::heap()->is_in_reserved(s)) return false;
 429 
 430   int len = s->utf8_length();
 431   if (len < 0) return false;
 432 
 433   jbyte* bytes = (jbyte*) s->bytes();
 434   return os::is_readable_range(bytes, bytes + len);
 435 }
 436 
 437 void Symbol::print_Qvalue_on(outputStream* st) const {
 438   if (this == NULL) {
 439     st->print("NULL");
 440   } else {
 441     st->print("'Q");
 442     for (int i = 0; i < utf8_length(); i++) {
 443       st->print("%c", char_at(i));
 444     }
 445     st->print(";'");
 446   }
 447 }
 448 
 449 // SymbolTable prints this in its statistics
 450 NOT_PRODUCT(size_t Symbol::_total_count = 0;)