1 /*
   2  * Copyright (c) 1997, 2018, 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 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "classfile/compactHashtable.inline.hpp"
  28 #include "classfile/javaClasses.hpp"
  29 #include "logging/logMessage.hpp"
  30 #include "memory/metadataFactory.hpp"
  31 #include "memory/metaspaceShared.hpp"
  32 #include "runtime/vmThread.hpp"
  33 #include "utilities/numberSeq.hpp"
  34 #include <sys/stat.h>
  35 
  36 /////////////////////////////////////////////////////
  37 //
  38 // The compact hash table writer implementations
  39 //
  40 CompactHashtableWriter::CompactHashtableWriter(int num_buckets,
  41                                                CompactHashtableStats* stats) {
  42   assert(DumpSharedSpaces, "dump-time only");
  43   assert(num_buckets > 0, "no buckets");
  44   _num_buckets = num_buckets;
  45   _num_entries = 0;
  46   _buckets = NEW_C_HEAP_ARRAY(GrowableArray<Entry>*, _num_buckets, mtSymbol);
  47   for (int i=0; i<_num_buckets; i++) {
  48     _buckets[i] = new (ResourceObj::C_HEAP, mtSymbol) GrowableArray<Entry>(0, true, mtSymbol);
  49   }
  50 
  51   _stats = stats;
  52   _compact_buckets = NULL;
  53   _compact_entries = NULL;
  54   _num_empty_buckets = 0;
  55   _num_value_only_buckets = 0;
  56   _num_other_buckets = 0;
  57 }
  58 
  59 CompactHashtableWriter::~CompactHashtableWriter() {
  60   for (int index = 0; index < _num_buckets; index++) {
  61     GrowableArray<Entry>* bucket = _buckets[index];
  62     delete bucket;
  63   }
  64 
  65   FREE_C_HEAP_ARRAY(GrowableArray<Entry>*, _buckets);
  66 }
  67 
  68 // Add a symbol entry to the temporary hash table
  69 void CompactHashtableWriter::add(unsigned int hash, u4 value) {
  70   int index = hash % _num_buckets;
  71   _buckets[index]->append_if_missing(Entry(hash, value));
  72   _num_entries++;
  73 }
  74 
  75 void CompactHashtableWriter::allocate_table() {
  76   int entries_space = 0;
  77   for (int index = 0; index < _num_buckets; index++) {
  78     GrowableArray<Entry>* bucket = _buckets[index];
  79     int bucket_size = bucket->length();
  80     if (bucket_size == 1) {
  81       entries_space++;
  82     } else {
  83       entries_space += 2 * bucket_size;
  84     }
  85   }
  86 
  87   if (entries_space & ~BUCKET_OFFSET_MASK) {
  88     vm_exit_during_initialization("CompactHashtableWriter::allocate_table: Overflow! "
  89                                   "Too many entries.");
  90   }
  91 
  92   _compact_buckets = MetaspaceShared::new_ro_array<u4>(_num_buckets + 1);
  93   _compact_entries = MetaspaceShared::new_ro_array<u4>(entries_space);
  94 
  95   _stats->bucket_count    = _num_buckets;
  96   _stats->bucket_bytes    = _compact_buckets->size() * BytesPerWord;
  97   _stats->hashentry_count = _num_entries;
  98   _stats->hashentry_bytes = _compact_entries->size() * BytesPerWord;
  99 }
 100 
 101 // Write the compact table's buckets
 102 void CompactHashtableWriter::dump_table(NumberSeq* summary) {
 103   u4 offset = 0;
 104   for (int index = 0; index < _num_buckets; index++) {
 105     GrowableArray<Entry>* bucket = _buckets[index];
 106     int bucket_size = bucket->length();
 107     if (bucket_size == 1) {
 108       // bucket with one entry is compacted and only has the symbol offset
 109       _compact_buckets->at_put(index, BUCKET_INFO(offset, VALUE_ONLY_BUCKET_TYPE));
 110 
 111       Entry ent = bucket->at(0);
 112       _compact_entries->at_put(offset++, ent.value());
 113       _num_value_only_buckets++;
 114     } else {
 115       // regular bucket, each entry is a symbol (hash, offset) pair
 116       _compact_buckets->at_put(index, BUCKET_INFO(offset, REGULAR_BUCKET_TYPE));
 117 
 118       for (int i=0; i<bucket_size; i++) {
 119         Entry ent = bucket->at(i);
 120         _compact_entries->at_put(offset++, u4(ent.hash())); // write entry hash
 121         _compact_entries->at_put(offset++, ent.value());
 122       }
 123       if (bucket_size == 0) {
 124         _num_empty_buckets++;
 125       } else {
 126         _num_other_buckets++;
 127       }
 128     }
 129     summary->add(bucket_size);
 130   }
 131 
 132   // Mark the end of the buckets
 133   _compact_buckets->at_put(_num_buckets, BUCKET_INFO(offset, TABLEEND_BUCKET_TYPE));
 134   assert(offset == (u4)_compact_entries->length(), "sanity");
 135 }
 136 
 137 
 138 // Write the compact table
 139 void CompactHashtableWriter::dump(SimpleCompactHashtable *cht, const char* table_name) {
 140   NumberSeq summary;
 141   allocate_table();
 142   dump_table(&summary);
 143 
 144   int table_bytes = _stats->bucket_bytes + _stats->hashentry_bytes;
 145   address base_address = address(MetaspaceShared::shared_rs()->base());
 146   cht->init(base_address,  _num_entries, _num_buckets,
 147             _compact_buckets->data(), _compact_entries->data());
 148 
 149   LogMessage(cds, hashtables) msg;
 150   if (msg.is_info()) {
 151     double avg_cost = 0.0;
 152     if (_num_entries > 0) {
 153       avg_cost = double(table_bytes)/double(_num_entries);
 154     }
 155     msg.info("Shared %s table stats -------- base: " PTR_FORMAT,
 156                          table_name, (intptr_t)base_address);
 157     msg.info("Number of entries       : %9d", _num_entries);
 158     msg.info("Total bytes used        : %9d", table_bytes);
 159     msg.info("Average bytes per entry : %9.3f", avg_cost);
 160     msg.info("Average bucket size     : %9.3f", summary.avg());
 161     msg.info("Variance of bucket size : %9.3f", summary.variance());
 162     msg.info("Std. dev. of bucket size: %9.3f", summary.sd());
 163     msg.info("Empty buckets           : %9d", _num_empty_buckets);
 164     msg.info("Value_Only buckets      : %9d", _num_value_only_buckets);
 165     msg.info("Other buckets           : %9d", _num_other_buckets);
 166   }
 167 }
 168 
 169 /////////////////////////////////////////////////////////////
 170 //
 171 // Customization for dumping Symbol and String tables
 172 
 173 void CompactSymbolTableWriter::add(unsigned int hash, Symbol *symbol) {
 174   uintx deltax = MetaspaceShared::object_delta(symbol);
 175   // When the symbols are stored into the archive, we already check that
 176   // they won't be more than MAX_SHARED_DELTA from the base address, or
 177   // else the dumping would have been aborted.
 178   assert(deltax <= MAX_SHARED_DELTA, "must not be");
 179   u4 delta = u4(deltax);
 180 
 181   CompactHashtableWriter::add(hash, delta);
 182 }
 183 
 184 void CompactStringTableWriter::add(unsigned int hash, oop string) {
 185   CompactHashtableWriter::add(hash, oopDesc::encode_heap_oop(string));
 186 }
 187 
 188 void CompactSymbolTableWriter::dump(CompactHashtable<Symbol*, char> *cht) {
 189   CompactHashtableWriter::dump(cht, "symbol");
 190 }
 191 
 192 void CompactStringTableWriter::dump(CompactHashtable<oop, char> *cht) {
 193   CompactHashtableWriter::dump(cht, "string");
 194 }
 195 
 196 /////////////////////////////////////////////////////////////
 197 //
 198 // The CompactHashtable implementation
 199 //
 200 
 201 void SimpleCompactHashtable::serialize(SerializeClosure* soc) {
 202   soc->do_ptr((void**)&_base_address);
 203   soc->do_u4(&_entry_count);
 204   soc->do_u4(&_bucket_count);
 205   soc->do_ptr((void**)&_buckets);
 206   soc->do_ptr((void**)&_entries);
 207 }
 208 
 209 bool SimpleCompactHashtable::exists(u4 value) {
 210   assert(!DumpSharedSpaces, "run-time only");
 211 
 212   if (_entry_count == 0) {
 213     return false;
 214   }
 215 
 216   unsigned int hash = (unsigned int)value;
 217   int index = hash % _bucket_count;
 218   u4 bucket_info = _buckets[index];
 219   u4 bucket_offset = BUCKET_OFFSET(bucket_info);
 220   int bucket_type = BUCKET_TYPE(bucket_info);
 221   u4* entry = _entries + bucket_offset;
 222 
 223   if (bucket_type == VALUE_ONLY_BUCKET_TYPE) {
 224     return (entry[0] == value);
 225   } else {
 226     u4*entry_max = _entries + BUCKET_OFFSET(_buckets[index + 1]);
 227     while (entry <entry_max) {
 228       if (entry[1] == value) {
 229         return true;
 230       }
 231       entry += 2;
 232     }
 233     return false;
 234   }
 235 }
 236 
 237 template <class I>
 238 inline void SimpleCompactHashtable::iterate(const I& iterator) {
 239   for (u4 i = 0; i < _bucket_count; i++) {
 240     u4 bucket_info = _buckets[i];
 241     u4 bucket_offset = BUCKET_OFFSET(bucket_info);
 242     int bucket_type = BUCKET_TYPE(bucket_info);
 243     u4* entry = _entries + bucket_offset;
 244 
 245     if (bucket_type == VALUE_ONLY_BUCKET_TYPE) {
 246       iterator.do_value(_base_address, entry[0]);
 247     } else {
 248       u4*entry_max = _entries + BUCKET_OFFSET(_buckets[i + 1]);
 249       while (entry < entry_max) {
 250         iterator.do_value(_base_address, entry[1]);
 251         entry += 2;
 252       }
 253     }
 254   }
 255 }
 256 
 257 template <class T, class N> void CompactHashtable<T, N>::serialize(SerializeClosure* soc) {
 258   SimpleCompactHashtable::serialize(soc);
 259   soc->do_u4(&_type);
 260 }
 261 
 262 class CompactHashtable_SymbolIterator {
 263   SymbolClosure* const _closure;
 264 public:
 265   CompactHashtable_SymbolIterator(SymbolClosure *cl) : _closure(cl) {}
 266   inline void do_value(address base_address, u4 offset) const {
 267     Symbol* sym = (Symbol*)((void*)(base_address + offset));
 268     _closure->do_symbol(&sym);
 269   }
 270 };
 271 
 272 template <class T, class N> void CompactHashtable<T, N>::symbols_do(SymbolClosure *cl) {
 273   CompactHashtable_SymbolIterator iterator(cl);
 274   iterate(iterator);
 275 }
 276 
 277 class CompactHashtable_OopIterator {
 278   OopClosure* const _closure;
 279 public:
 280   CompactHashtable_OopIterator(OopClosure *cl) : _closure(cl) {}
 281   inline void do_value(address base_address, u4 offset) const {
 282     narrowOop o = (narrowOop)offset;
 283     _closure->do_oop(&o);
 284   }
 285 };
 286 
 287 template <class T, class N> void CompactHashtable<T, N>::oops_do(OopClosure* cl) {
 288   assert(_type == _string_table || _bucket_count == 0, "sanity");
 289   CompactHashtable_OopIterator iterator(cl);
 290   iterate(iterator);
 291 }
 292 
 293 // Explicitly instantiate these types
 294 template class CompactHashtable<Symbol*, char>;
 295 template class CompactHashtable<oop, char>;
 296 
 297 #ifndef O_BINARY       // if defined (Win32) use binary files.
 298 #define O_BINARY 0     // otherwise do nothing.
 299 #endif
 300 
 301 ////////////////////////////////////////////////////////
 302 //
 303 // HashtableTextDump
 304 //
 305 HashtableTextDump::HashtableTextDump(const char* filename) : _fd(-1) {
 306   struct stat st;
 307   if (os::stat(filename, &st) != 0) {
 308     quit("Unable to get hashtable dump file size", filename);
 309   }
 310   _size = st.st_size;
 311   _fd = open(filename, O_RDONLY | O_BINARY, 0);
 312   if (_fd < 0) {
 313     quit("Unable to open hashtable dump file", filename);
 314   }
 315   _base = os::map_memory(_fd, filename, 0, NULL, _size, true, false);
 316   if (_base == NULL) {
 317     quit("Unable to map hashtable dump file", filename);
 318   }
 319   _p = _base;
 320   _end = _base + st.st_size;
 321   _filename = filename;
 322   _prefix_type = Unknown;
 323   _line_no = 1;
 324 }
 325 
 326 HashtableTextDump::~HashtableTextDump() {
 327   os::unmap_memory((char*)_base, _size);
 328   if (_fd >= 0) {
 329     close(_fd);
 330   }
 331 }
 332 
 333 void HashtableTextDump::quit(const char* err, const char* msg) {
 334   vm_exit_during_initialization(err, msg);
 335 }
 336 
 337 void HashtableTextDump::corrupted(const char *p, const char* msg) {
 338   char info[100];
 339   jio_snprintf(info, sizeof(info),
 340                "%s. Corrupted at line %d (file pos %d)",
 341                msg, _line_no, (int)(p - _base));
 342   quit(info, _filename);
 343 }
 344 
 345 bool HashtableTextDump::skip_newline() {
 346   if (_p[0] == '\r' && _p[1] == '\n') {
 347     _p += 2;
 348   } else if (_p[0] == '\n') {
 349     _p += 1;
 350   } else {
 351     corrupted(_p, "Unexpected character");
 352   }
 353   _line_no++;
 354   return true;
 355 }
 356 
 357 int HashtableTextDump::skip(char must_be_char) {
 358   corrupted_if(remain() < 1, "Truncated");
 359   corrupted_if(*_p++ != must_be_char, "Unexpected character");
 360   return 0;
 361 }
 362 
 363 void HashtableTextDump::skip_past(char c) {
 364   for (;;) {
 365     corrupted_if(remain() < 1, "Truncated");
 366     if (*_p++ == c) {
 367       return;
 368     }
 369   }
 370 }
 371 
 372 void HashtableTextDump::check_version(const char* ver) {
 373   int len = (int)strlen(ver);
 374   corrupted_if(remain() < len, "Truncated");
 375   if (strncmp(_p, ver, len) != 0) {
 376     quit("wrong version of hashtable dump file", _filename);
 377   }
 378   _p += len;
 379   skip_newline();
 380 }
 381 
 382 void HashtableTextDump::scan_prefix_type() {
 383   _p++;
 384   if (strncmp(_p, "SECTION: String", 15) == 0) {
 385     _p += 15;
 386     _prefix_type = StringPrefix;
 387   } else if (strncmp(_p, "SECTION: Symbol", 15) == 0) {
 388     _p += 15;
 389     _prefix_type = SymbolPrefix;
 390   } else {
 391     _prefix_type = Unknown;
 392   }
 393   skip_newline();
 394 }
 395 
 396 int HashtableTextDump::scan_prefix(int* utf8_length) {
 397   if (*_p == '@') {
 398     scan_prefix_type();
 399   }
 400 
 401   switch (_prefix_type) {
 402   case SymbolPrefix:
 403     *utf8_length = scan_symbol_prefix(); break;
 404   case StringPrefix:
 405     *utf8_length = scan_string_prefix(); break;
 406   default:
 407     tty->print_cr("Shared input data type: Unknown.");
 408     corrupted(_p, "Unknown data type");
 409   }
 410 
 411   return _prefix_type;
 412 }
 413 
 414 int HashtableTextDump::scan_string_prefix() {
 415   // Expect /[0-9]+: /
 416   int utf8_length = 0;
 417   get_num(':', &utf8_length);
 418   if (*_p != ' ') {
 419     corrupted(_p, "Wrong prefix format for string");
 420   }
 421   _p++;
 422   return utf8_length;
 423 }
 424 
 425 int HashtableTextDump::scan_symbol_prefix() {
 426   // Expect /[0-9]+ (-|)[0-9]+: /
 427   int utf8_length = 0;
 428   get_num(' ', &utf8_length);
 429   if (*_p == '-') {
 430     _p++;
 431   }
 432   int ref_num;
 433   get_num(':', &ref_num);
 434   if (*_p != ' ') {
 435     corrupted(_p, "Wrong prefix format for symbol");
 436   }
 437   _p++;
 438   return utf8_length;
 439 }
 440 
 441 jchar HashtableTextDump::unescape(const char* from, const char* end, int count) {
 442   jchar value = 0;
 443 
 444   corrupted_if(from + count > end, "Truncated");
 445 
 446   for (int i=0; i<count; i++) {
 447     char c = *from++;
 448     switch (c) {
 449     case '0': case '1': case '2': case '3': case '4':
 450     case '5': case '6': case '7': case '8': case '9':
 451       value = (value << 4) + c - '0';
 452       break;
 453     case 'a': case 'b': case 'c':
 454     case 'd': case 'e': case 'f':
 455       value = (value << 4) + 10 + c - 'a';
 456       break;
 457     case 'A': case 'B': case 'C':
 458     case 'D': case 'E': case 'F':
 459       value = (value << 4) + 10 + c - 'A';
 460       break;
 461     default:
 462       ShouldNotReachHere();
 463     }
 464   }
 465   return value;
 466 }
 467 
 468 void HashtableTextDump::get_utf8(char* utf8_buffer, int utf8_length) {
 469   // cache in local vars
 470   const char* from = _p;
 471   const char* end = _end;
 472   char* to = utf8_buffer;
 473   int n = utf8_length;
 474 
 475   for (; n > 0 && from < end; n--) {
 476     if (*from != '\\') {
 477       *to++ = *from++;
 478     } else {
 479       corrupted_if(from + 2 > end, "Truncated");
 480       char c = from[1];
 481       from += 2;
 482       switch (c) {
 483       case 'x':
 484         {
 485           jchar value = unescape(from, end, 2);
 486           from += 2;
 487           assert(value <= 0xff, "sanity");
 488           *to++ = (char)(value & 0xff);
 489         }
 490         break;
 491       case 't':  *to++ = '\t'; break;
 492       case 'n':  *to++ = '\n'; break;
 493       case 'r':  *to++ = '\r'; break;
 494       case '\\': *to++ = '\\'; break;
 495       default:
 496         corrupted(_p, "Unsupported character");
 497       }
 498     }
 499   }
 500   corrupted_if(n > 0, "Truncated"); // expected more chars but file has ended
 501   _p = from;
 502   skip_newline();
 503 }
 504 
 505 // NOTE: the content is NOT the same as
 506 // UTF8::as_quoted_ascii(const char* utf8_str, int utf8_length, char* buf, int buflen).
 507 // We want to escape \r\n\t so that output [1] is more readable; [2] can be more easily
 508 // parsed by scripts; [3] quickly processed by HashtableTextDump::get_utf8()
 509 void HashtableTextDump::put_utf8(outputStream* st, const char* utf8_string, int utf8_length) {
 510   const char *c = utf8_string;
 511   const char *end = c + utf8_length;
 512   for (; c < end; c++) {
 513     switch (*c) {
 514     case '\t': st->print("\\t"); break;
 515     case '\r': st->print("\\r"); break;
 516     case '\n': st->print("\\n"); break;
 517     case '\\': st->print("\\\\"); break;
 518     default:
 519       if (isprint(*c)) {
 520         st->print("%c", *c);
 521       } else {
 522         st->print("\\x%02x", ((unsigned int)*c) & 0xff);
 523       }
 524     }
 525   }
 526 }