1 /*
   2  * Copyright (c) 1997, 2024, 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 "cds/classListWriter.hpp"
  27 #include "compiler/compileLog.hpp"
  28 #include "jvm.h"
  29 #include "memory/allocation.inline.hpp"
  30 #include "oops/oop.inline.hpp"
  31 #include "runtime/arguments.hpp"
  32 #include "runtime/mutexLocker.hpp"
  33 #include "runtime/orderAccess.hpp"
  34 #include "runtime/os.inline.hpp"
  35 #include "runtime/safepoint.hpp"
  36 #include "runtime/vm_version.hpp"
  37 #include "utilities/defaultStream.hpp"
  38 #include "utilities/macros.hpp"
  39 #include "utilities/ostream.hpp"
  40 #include "utilities/vmError.hpp"
  41 #include "utilities/xmlstream.hpp"
  42 
  43 // Declarations of jvm methods
  44 extern "C" void jio_print(const char* s, size_t len);
  45 extern "C" int jio_printf(const char *fmt, ...);
  46 
  47 outputStream::outputStream() {
  48   _position    = 0;
  49   _precount    = 0;
  50   _indentation = 0;
  51   _scratch     = nullptr;
  52   _scratch_len = 0;
  53 }
  54 
  55 outputStream::outputStream(bool has_time_stamps) {
  56   _position    = 0;
  57   _precount    = 0;
  58   _indentation = 0;
  59   _scratch     = nullptr;
  60   _scratch_len = 0;
  61   if (has_time_stamps)  _stamp.update();
  62 }
  63 
  64 bool outputStream::update_position(const char* s, size_t len) {
  65   bool saw_newline = false;
  66   for (size_t i = 0; i < len; i++) {
  67     char ch = s[i];
  68     if (ch == '\n') {
  69       saw_newline = true;
  70       _precount += _position + 1;
  71       _position = 0;
  72     } else if (ch == '\t') {
  73       int tw = 8 - (_position & 7);
  74       _position += tw;
  75       _precount -= tw-1;  // invariant:  _precount + _position == total count
  76     } else {
  77       _position += 1;
  78     }
  79   }
  80   return saw_newline;
  81 }
  82 
  83 // Execute a vsprintf, using the given buffer if necessary.
  84 // Return a pointer to the formatted string.
  85 const char* outputStream::do_vsnprintf(char* buffer, size_t buflen,
  86                                        const char* format, va_list ap,
  87                                        bool add_cr,
  88                                        size_t& result_len) {
  89   assert(buflen >= 2, "buffer too small");
  90 
  91   const char* result;
  92   if (add_cr)  buflen--;
  93   if (!strchr(format, '%')) {
  94     // constant format string
  95     result = format;
  96     result_len = strlen(result);
  97     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
  98   } else if (format[0] == '%' && format[1] == 's' && format[2] == '\0') {
  99     // trivial copy-through format string
 100     result = va_arg(ap, const char*);
 101     result_len = strlen(result);
 102     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
 103   } else {
 104     int required_len = os::vsnprintf(buffer, buflen, format, ap);
 105     assert(required_len >= 0, "vsnprintf encoding error");
 106     result = buffer;
 107     if ((size_t)required_len < buflen) {
 108       result_len = required_len;
 109     } else {
 110       DEBUG_ONLY(warning("outputStream::do_vsnprintf output truncated -- buffer length is %d bytes but %d bytes are needed.",
 111                          add_cr ? (int)buflen + 1 : (int)buflen, add_cr ? required_len + 2 : required_len + 1);)
 112       result_len = buflen - 1;
 113     }
 114   }
 115   if (add_cr) {
 116     if (result != buffer) {
 117       memcpy(buffer, result, result_len);
 118       result = buffer;
 119     }
 120     buffer[result_len++] = '\n';
 121     buffer[result_len] = 0;
 122   }
 123   return result;
 124 }
 125 
 126 void outputStream::do_vsnprintf_and_write_with_automatic_buffer(const char* format, va_list ap, bool add_cr) {
 127   char buffer[O_BUFLEN];
 128   size_t len;
 129   const char* str = do_vsnprintf(buffer, sizeof(buffer), format, ap, add_cr, len);
 130   write(str, len);
 131 }
 132 
 133 void outputStream::do_vsnprintf_and_write_with_scratch_buffer(const char* format, va_list ap, bool add_cr) {
 134   size_t len;
 135   const char* str = do_vsnprintf(_scratch, _scratch_len, format, ap, add_cr, len);
 136   write(str, len);
 137 }
 138 
 139 void outputStream::do_vsnprintf_and_write(const char* format, va_list ap, bool add_cr) {
 140   if (_scratch) {
 141     do_vsnprintf_and_write_with_scratch_buffer(format, ap, add_cr);
 142   } else {
 143     do_vsnprintf_and_write_with_automatic_buffer(format, ap, add_cr);
 144   }
 145 }
 146 
 147 void outputStream::print(const char* format, ...) {
 148   va_list ap;
 149   va_start(ap, format);
 150   do_vsnprintf_and_write(format, ap, false);
 151   va_end(ap);
 152 }
 153 
 154 void outputStream::print_cr(const char* format, ...) {
 155   va_list ap;
 156   va_start(ap, format);
 157   do_vsnprintf_and_write(format, ap, true);
 158   va_end(ap);
 159 }
 160 
 161 void outputStream::vprint(const char *format, va_list argptr) {
 162   do_vsnprintf_and_write(format, argptr, false);
 163 }
 164 
 165 void outputStream::vprint_cr(const char* format, va_list argptr) {
 166   do_vsnprintf_and_write(format, argptr, true);
 167 }
 168 
 169 void outputStream::fill_to(int col) {
 170   int need_fill = col - position();
 171   sp(need_fill);
 172 }
 173 
 174 void outputStream::move_to(int col, int slop, int min_space) {
 175   if (position() >= col + slop)
 176     cr();
 177   int need_fill = col - position();
 178   if (need_fill < min_space)
 179     need_fill = min_space;
 180   sp(need_fill);
 181 }
 182 
 183 void outputStream::put(char ch) {
 184   assert(ch != 0, "please fix call site");
 185   char buf[] = { ch, '\0' };
 186   write(buf, 1);
 187 }
 188 
 189 void outputStream::sp(int count) {
 190   if (count < 0)  return;
 191 
 192   while (count > 0) {
 193     int nw = (count > 8) ? 8 : count;
 194     this->write("        ", nw);
 195     count -= nw;
 196   }
 197 }
 198 
 199 void outputStream::cr() {
 200   this->write("\n", 1);
 201 }
 202 
 203 void outputStream::cr_indent() {
 204   cr(); indent();
 205 }
 206 
 207 void outputStream::stamp() {
 208   if (! _stamp.is_updated()) {
 209     _stamp.update(); // start at 0 on first call to stamp()
 210   }
 211 
 212   // outputStream::stamp() may get called by ostream_abort(), use snprintf
 213   // to avoid allocating large stack buffer in print().
 214   char buf[40];
 215   jio_snprintf(buf, sizeof(buf), "%.3f", _stamp.seconds());
 216   print_raw(buf);
 217 }
 218 
 219 void outputStream::stamp(bool guard,
 220                          const char* prefix,
 221                          const char* suffix) {
 222   if (!guard) {
 223     return;
 224   }
 225   print_raw(prefix);
 226   stamp();
 227   print_raw(suffix);
 228 }
 229 
 230 void outputStream::date_stamp(bool guard,
 231                               const char* prefix,
 232                               const char* suffix) {
 233   if (!guard) {
 234     return;
 235   }
 236   print_raw(prefix);
 237   static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz";
 238   static const int buffer_length = 32;
 239   char buffer[buffer_length];
 240   const char* iso8601_result = os::iso8601_time(buffer, buffer_length);
 241   if (iso8601_result != nullptr) {
 242     print_raw(buffer);
 243   } else {
 244     print_raw(error_time);
 245   }
 246   print_raw(suffix);
 247   return;
 248 }
 249 
 250 outputStream& outputStream::indent() {
 251   sp(_indentation - _position);
 252   return *this;
 253 }
 254 
 255 void outputStream::print_jlong(jlong value) {
 256   print(JLONG_FORMAT, value);
 257 }
 258 
 259 void outputStream::print_julong(julong value) {
 260   print(JULONG_FORMAT, value);
 261 }
 262 
 263 /**
 264  * This prints out hex data in a 'windbg' or 'xxd' form, where each line is:
 265  *   <hex-address>: 8 * <hex-halfword> <ascii translation (optional)>
 266  * example:
 267  * 0000000: 7f44 4f46 0102 0102 0000 0000 0000 0000  .DOF............
 268  * 0000010: 0000 0000 0000 0040 0000 0020 0000 0005  .......@... ....
 269  * 0000020: 0000 0000 0000 0040 0000 0000 0000 015d  .......@.......]
 270  * ...
 271  *
 272  * indent is applied to each line.  Ends with a CR.
 273  */
 274 void outputStream::print_data(void* data, size_t len, bool with_ascii, bool rel_addr) {
 275   size_t limit = (len + 16) / 16 * 16;
 276   for (size_t i = 0; i < limit; ++i) {
 277     if (i % 16 == 0) {
 278       if (rel_addr) {
 279         indent().print("%07" PRIxPTR ":", i);
 280       } else {
 281         indent().print(PTR_FORMAT ":", p2i((unsigned char*)data + i));
 282       }
 283     }
 284     if (i % 2 == 0) {
 285       print(" ");
 286     }
 287     if (i < len) {
 288       print("%02x", ((unsigned char*)data)[i]);
 289     } else {
 290       print("  ");
 291     }
 292     if ((i + 1) % 16 == 0) {
 293       if (with_ascii) {
 294         print("  ");
 295         for (size_t j = 0; j < 16; ++j) {
 296           size_t idx = i + j - 15;
 297           if (idx < len) {
 298             char c = ((char*)data)[idx];
 299             print("%c", c >= 32 && c <= 126 ? c : '.');
 300           }
 301         }
 302       }
 303       cr();
 304     }
 305   }
 306 }
 307 
 308 stringStream::stringStream(size_t initial_capacity) :
 309   outputStream(),
 310   _buffer(_small_buffer),
 311   _written(0),
 312   _capacity(sizeof(_small_buffer)),
 313   _is_fixed(false)
 314 {
 315   if (initial_capacity > _capacity) {
 316     grow(initial_capacity);
 317   }
 318   zero_terminate();
 319 }
 320 
 321 // useful for output to fixed chunks of memory, such as performance counters
 322 stringStream::stringStream(char* fixed_buffer, size_t fixed_buffer_size) :
 323   outputStream(),
 324   _buffer(fixed_buffer),
 325   _written(0),
 326   _capacity(fixed_buffer_size),
 327   _is_fixed(true)
 328 {
 329   zero_terminate();
 330 }
 331 
 332 // Grow backing buffer to desired capacity. Don't call for fixed buffers
 333 void stringStream::grow(size_t new_capacity) {
 334   assert(!_is_fixed, "Don't call for caller provided buffers");
 335   assert(new_capacity > _capacity, "Sanity");
 336   assert(new_capacity > sizeof(_small_buffer), "Sanity");
 337   if (_buffer == _small_buffer) {
 338     _buffer = NEW_C_HEAP_ARRAY(char, new_capacity, mtInternal);
 339     _capacity = new_capacity;
 340     if (_written > 0) {
 341       ::memcpy(_buffer, _small_buffer, _written);
 342     }
 343     zero_terminate();
 344   } else {
 345     _buffer = REALLOC_C_HEAP_ARRAY(char, _buffer, new_capacity, mtInternal);
 346     _capacity = new_capacity;
 347   }
 348 }
 349 
 350 void stringStream::write(const char* s, size_t len) {
 351   assert(_is_frozen == false, "Modification forbidden");
 352   assert(_capacity >= _written + 1, "Sanity");
 353   if (len == 0) {
 354     return;
 355   }
 356   const size_t reasonable_max_len = 1 * G;
 357   if (len >= reasonable_max_len) {
 358     assert(false, "bad length? (" SIZE_FORMAT ")", len);
 359     return;
 360   }
 361   size_t write_len = 0;
 362   if (_is_fixed) {
 363     write_len = MIN2(len, _capacity - _written - 1);
 364   } else {
 365     write_len = len;
 366     size_t needed = _written + len + 1;
 367     if (needed > _capacity) {
 368       grow(MAX2(needed, _capacity * 2));
 369     }
 370   }
 371   assert(_written + write_len + 1 <= _capacity, "stringStream oob");
 372   if (write_len > 0) {
 373     ::memcpy(_buffer + _written, s, write_len);
 374     _written += write_len;
 375     zero_terminate();
 376   }
 377 
 378   // Note that the following does not depend on write_len.
 379   // This means that position and count get updated
 380   // even when overflow occurs.
 381   update_position(s, len);
 382 }
 383 
 384 void stringStream::zero_terminate() {
 385   assert(_buffer != nullptr &&
 386          _written < _capacity, "sanity");
 387   _buffer[_written] = '\0';
 388 }
 389 
 390 void stringStream::reset() {
 391   assert(_is_frozen == false, "Modification forbidden");
 392   _written = 0; _precount = 0; _position = 0;
 393   zero_terminate();
 394 }
 395 
 396 char* stringStream::as_string(bool c_heap) const {
 397   char* copy = c_heap ?
 398     NEW_C_HEAP_ARRAY(char, _written + 1, mtInternal) : NEW_RESOURCE_ARRAY(char, _written + 1);
 399   ::memcpy(copy, _buffer, _written);
 400   copy[_written] = '\0';  // terminating null
 401   if (c_heap) {
 402     // Need to ensure our content is written to memory before we return
 403     // the pointer to it.
 404     OrderAccess::storestore();
 405   }
 406   return copy;
 407 }
 408 
 409 stringStream::~stringStream() {
 410   if (!_is_fixed && _buffer != _small_buffer) {
 411     FREE_C_HEAP_ARRAY(char, _buffer);
 412   }
 413 }
 414 
 415 // tty needs to be always accessible since there are code paths that may write to it
 416 // outside of the VM lifespan.
 417 // Examples for pre-VM-init accesses: Early NMT init, Early UL init
 418 // Examples for post-VM-exit accesses: many, e.g. NMT C-heap bounds checker, signal handling, AGCT, ...
 419 // During lifetime tty is served by an instance of defaultStream. That instance's deletion cannot
 420 // be (easily) postponed or omitted since it has ties to the JVM infrastructure.
 421 // The policy followed here is a compromise reached during review of JDK-8292351:
 422 // - pre-init: we silently swallow all output. We won't see anything, but at least won't crash
 423 // - post-exit: we write to a simple fdStream, but somewhat mimic the behavior of the real defaultStream
 424 static nullStream tty_preinit_stream;
 425 outputStream* tty = &tty_preinit_stream;
 426 
 427 xmlStream*   xtty;
 428 
 429 #define EXTRACHARLEN   32
 430 #define CURRENTAPPX    ".current"
 431 // convert YYYY-MM-DD HH:MM:SS to YYYY-MM-DD_HH-MM-SS
 432 static char* get_datetime_string(char *buf, size_t len) {
 433   os::local_time_string(buf, len);
 434   int i = (int)strlen(buf);
 435   while (--i >= 0) {
 436     if (buf[i] == ' ') buf[i] = '_';
 437     else if (buf[i] == ':') buf[i] = '-';
 438   }
 439   return buf;
 440 }
 441 
 442 static const char* make_log_name_internal(const char* log_name, const char* force_directory,
 443                                                 int pid, const char* tms) {
 444   const char* basename = log_name;
 445   char file_sep = os::file_separator()[0];
 446   const char* cp;
 447   char  pid_text[32];
 448 
 449   for (cp = log_name; *cp != '\0'; cp++) {
 450     if (*cp == '/' || *cp == file_sep) {
 451       basename = cp + 1;
 452     }
 453   }
 454   const char* nametail = log_name;
 455   // Compute buffer length
 456   size_t buffer_length;
 457   if (force_directory != nullptr) {
 458     buffer_length = strlen(force_directory) + strlen(os::file_separator()) +
 459                     strlen(basename) + 1;
 460   } else {
 461     buffer_length = strlen(log_name) + 1;
 462   }
 463 
 464   const char* pts = strstr(basename, "%p");
 465   int pid_pos = (pts == nullptr) ? -1 : (pts - nametail);
 466 
 467   if (pid_pos >= 0) {
 468     jio_snprintf(pid_text, sizeof(pid_text), "pid%u", pid);
 469     buffer_length += strlen(pid_text);
 470   }
 471 
 472   pts = strstr(basename, "%t");
 473   int tms_pos = (pts == nullptr) ? -1 : (pts - nametail);
 474   if (tms_pos >= 0) {
 475     buffer_length += strlen(tms);
 476   }
 477 
 478   // File name is too long.
 479   if (buffer_length > JVM_MAXPATHLEN) {
 480     return nullptr;
 481   }
 482 
 483   // Create big enough buffer.
 484   char *buf = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
 485 
 486   strcpy(buf, "");
 487   if (force_directory != nullptr) {
 488     strcat(buf, force_directory);
 489     strcat(buf, os::file_separator());
 490     nametail = basename;       // completely skip directory prefix
 491   }
 492 
 493   // who is first, %p or %t?
 494   int first = -1, second = -1;
 495   const char *p1st = nullptr;
 496   const char *p2nd = nullptr;
 497 
 498   if (pid_pos >= 0 && tms_pos >= 0) {
 499     // contains both %p and %t
 500     if (pid_pos < tms_pos) {
 501       // case foo%pbar%tmonkey.log
 502       first  = pid_pos;
 503       p1st   = pid_text;
 504       second = tms_pos;
 505       p2nd   = tms;
 506     } else {
 507       // case foo%tbar%pmonkey.log
 508       first  = tms_pos;
 509       p1st   = tms;
 510       second = pid_pos;
 511       p2nd   = pid_text;
 512     }
 513   } else if (pid_pos >= 0) {
 514     // contains %p only
 515     first  = pid_pos;
 516     p1st   = pid_text;
 517   } else if (tms_pos >= 0) {
 518     // contains %t only
 519     first  = tms_pos;
 520     p1st   = tms;
 521   }
 522 
 523   int buf_pos = (int)strlen(buf);
 524   const char* tail = nametail;
 525 
 526   if (first >= 0) {
 527     tail = nametail + first + 2;
 528     strncpy(&buf[buf_pos], nametail, first);
 529     strcpy(&buf[buf_pos + first], p1st);
 530     buf_pos = (int)strlen(buf);
 531     if (second >= 0) {
 532       strncpy(&buf[buf_pos], tail, second - first - 2);
 533       strcpy(&buf[buf_pos + second - first - 2], p2nd);
 534       tail = nametail + second + 2;
 535     }
 536   }
 537   strcat(buf, tail);      // append rest of name, or all of name
 538   return buf;
 539 }
 540 
 541 // log_name comes from -XX:LogFile=log_name or
 542 // -XX:DumpLoadedClassList=<file_name>
 543 // in log_name, %p => pid1234 and
 544 //              %t => YYYY-MM-DD_HH-MM-SS
 545 const char* make_log_name(const char* log_name, const char* force_directory) {
 546   char timestr[32];
 547   get_datetime_string(timestr, sizeof(timestr));
 548   return make_log_name_internal(log_name, force_directory, os::current_process_id(),
 549                                 timestr);
 550 }
 551 
 552 fileStream::fileStream(const char* file_name) {
 553   _file = os::fopen(file_name, "w");
 554   if (_file != nullptr) {
 555     _need_close = true;
 556   } else {
 557     warning("Cannot open file %s due to %s\n", file_name, os::strerror(errno));
 558     _need_close = false;
 559   }
 560 }
 561 
 562 fileStream::fileStream(const char* file_name, const char* opentype) {
 563   _file = os::fopen(file_name, opentype);
 564   if (_file != nullptr) {
 565     _need_close = true;
 566   } else {
 567     warning("Cannot open file %s due to %s\n", file_name, os::strerror(errno));
 568     _need_close = false;
 569   }
 570 }
 571 
 572 void fileStream::write(const char* s, size_t len) {
 573   if (_file != nullptr)  {
 574     // Make an unused local variable to avoid warning from gcc compiler.
 575     size_t count = fwrite(s, 1, len, _file);
 576     update_position(s, len);
 577   }
 578 }
 579 
 580 long fileStream::fileSize() {
 581   long size = -1;
 582   if (_file != nullptr) {
 583     long pos = ::ftell(_file);
 584     if (pos < 0) return pos;
 585     if (::fseek(_file, 0, SEEK_END) == 0) {
 586       size = ::ftell(_file);
 587     }
 588     ::fseek(_file, pos, SEEK_SET);
 589   }
 590   return size;
 591 }
 592 
 593 fileStream::~fileStream() {
 594   if (_file != nullptr) {
 595     close();
 596     _file = nullptr;
 597   }
 598 }
 599 
 600 void fileStream::flush() {
 601   if (_file != nullptr) {
 602     fflush(_file);
 603   }
 604 }
 605 
 606 fdStream fdStream::_stdout_stream(1);
 607 fdStream fdStream::_stderr_stream(2);
 608 
 609 void fdStream::write(const char* s, size_t len) {
 610   if (_fd != -1) {
 611     // Make an unused local variable to avoid warning from gcc compiler.
 612     ssize_t count = ::write(_fd, s, (int)len);
 613     update_position(s, len);
 614   }
 615 }
 616 
 617 defaultStream* defaultStream::instance = nullptr;
 618 int defaultStream::_output_fd = 1;
 619 int defaultStream::_error_fd  = 2;
 620 FILE* defaultStream::_output_stream = stdout;
 621 FILE* defaultStream::_error_stream  = stderr;
 622 
 623 #define LOG_MAJOR_VERSION 160
 624 #define LOG_MINOR_VERSION 1
 625 
 626 void defaultStream::init() {
 627   _inited = true;
 628   if (LogVMOutput || LogCompilation) {
 629     init_log();
 630   }
 631 }
 632 
 633 bool defaultStream::has_log_file() {
 634   // lazily create log file (at startup, LogVMOutput is false even
 635   // if +LogVMOutput is used, because the flags haven't been parsed yet)
 636   // For safer printing during fatal error handling, do not init logfile
 637   // if a VM error has been reported.
 638   if (!_inited && !VMError::is_error_reported())  init();
 639   return _log_file != nullptr;
 640 }
 641 
 642 fileStream* defaultStream::open_file(const char* log_name) {
 643   const char* try_name = make_log_name(log_name, nullptr);
 644   if (try_name == nullptr) {
 645     warning("Cannot open file %s: file name is too long.\n", log_name);
 646     return nullptr;
 647   }
 648 
 649   fileStream* file = new (mtInternal) fileStream(try_name);
 650   FREE_C_HEAP_ARRAY(char, try_name);
 651   if (file->is_open()) {
 652     return file;
 653   }
 654 
 655   if (RecordTraining) {
 656     vm_exit_during_initialization("cannot create log file for RecordTraining mode: %s", try_name);
 657   }
 658 
 659   // Try again to open the file in the temp directory.
 660   delete file;
 661   // Note: This feature is for maintainer use only.  No need for L10N.
 662   jio_printf("Warning:  Cannot open log file: %s\n", log_name);
 663   try_name = make_log_name(log_name, os::get_temp_directory());
 664   if (try_name == nullptr) {
 665     warning("Cannot open file %s: file name is too long for directory %s.\n", log_name, os::get_temp_directory());
 666     return nullptr;
 667   }
 668 
 669   jio_printf("Warning:  Forcing option -XX:LogFile=%s\n", try_name);
 670 
 671   file = new (mtInternal) fileStream(try_name);
 672   FREE_C_HEAP_ARRAY(char, try_name);
 673   if (file->is_open()) {
 674     return file;
 675   }
 676 
 677   delete file;
 678   return nullptr;
 679 }
 680 
 681 void defaultStream::init_log() {
 682   // %%% Need a MutexLocker?
 683   const char* log_name = LogFile != nullptr ? LogFile : "hotspot_%p.log";
 684   fileStream* file = open_file(log_name);
 685 
 686   if (file != nullptr) {
 687     _log_file = file;
 688     _outer_xmlStream = new(mtInternal) xmlStream(file);
 689     start_log();
 690   } else {
 691     // and leave xtty as null
 692     LogVMOutput = false;
 693     DisplayVMOutput = true;
 694     LogCompilation = false;
 695   }
 696 }
 697 
 698 void defaultStream::start_log() {
 699   xmlStream*xs = _outer_xmlStream;
 700     if (this == tty)  xtty = xs;
 701     // Write XML header.
 702     xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
 703     // (For now, don't bother to issue a DTD for this private format.)
 704 
 705     // Calculate the start time of the log as ms since the epoch: this is
 706     // the current time in ms minus the uptime in ms.
 707     jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
 708     xs->head("hotspot_log version='%d %d'"
 709              " process='%d' time_ms='" INT64_FORMAT "'",
 710              LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
 711              os::current_process_id(), (int64_t)time_ms);
 712     // Write VM version header immediately.
 713     xs->head("vm_version");
 714     xs->head("name");  // FIXME: should be an elem attr, not head/tail pair
 715     xs->log_only()->print_cr("%s", VM_Version::vm_name());
 716     xs->tail("name");
 717     xs->head("release");
 718     xs->log_only()->print_cr("%s", VM_Version::vm_release());
 719     xs->tail("release");
 720     xs->head("info");
 721     xs->log_only()->print_cr("%s", VM_Version::internal_vm_info_string());
 722     xs->tail("info");
 723     xs->tail("vm_version");
 724     // Record information about the command-line invocation.
 725     xs->head("vm_arguments");  // Cf. Arguments::print_on()
 726     if (Arguments::num_jvm_flags() > 0) {
 727       xs->head("flags");
 728       Arguments::print_jvm_flags_on(xs->log_only());
 729       xs->tail("flags");
 730     }
 731     if (Arguments::num_jvm_args() > 0) {
 732       xs->head("args");
 733       Arguments::print_jvm_args_on(xs->log_only());
 734       xs->tail("args");
 735     }
 736     if (Arguments::java_command() != nullptr) {
 737       xs->head("command"); xs->log_only()->print_cr("%s", Arguments::java_command());
 738       xs->tail("command");
 739     }
 740     if (Arguments::sun_java_launcher() != nullptr) {
 741       xs->head("launcher"); xs->log_only()->print_cr("%s", Arguments::sun_java_launcher());
 742       xs->tail("launcher");
 743     }
 744     if (Arguments::system_properties() !=  nullptr) {
 745       xs->head("properties");
 746       // Print it as a java-style property list.
 747       // System properties don't generally contain newlines, so don't bother with unparsing.
 748       outputStream *text = xs->log_only();
 749       for (SystemProperty* p = Arguments::system_properties(); p != nullptr; p = p->next()) {
 750         assert(p->key() != nullptr, "p->key() is null");
 751         if (p->readable()) {
 752           // Print in two stages to avoid problems with long
 753           // keys/values.
 754           text->print_raw(p->key());
 755           text->put('=');
 756           assert(p->value() != nullptr, "p->value() is null");
 757           text->print_raw_cr(p->value());
 758         }
 759       }
 760       xs->tail("properties");
 761     }
 762     xs->tail("vm_arguments");
 763     // tty output per se is grouped under the <tty>...</tty> element.
 764     xs->head("tty");
 765     // All further non-markup text gets copied to the tty:
 766     xs->_text = this;  // requires friend declaration!
 767     // (And xtty->log_only() remains as a back door to the non-tty log file.)
 768 }
 769 
 770 // finish_log() is called during normal VM shutdown. finish_log_on_error() is
 771 // called by ostream_abort() after a fatal error.
 772 //
 773 void defaultStream::finish_log() {
 774   xmlStream* xs = _outer_xmlStream;
 775   xs->done("tty");
 776 
 777   // Other log forks are appended here, at the End of Time:
 778   CompileLog::finish_log(xs->out());  // write compile logging, if any, now
 779 
 780   xs->done("hotspot_log");
 781   xs->flush();
 782 
 783   fileStream* file = _log_file;
 784   _log_file = nullptr;
 785 
 786   delete _outer_xmlStream;
 787   _outer_xmlStream = nullptr;
 788 
 789   file->flush();
 790   delete file;
 791 }
 792 
 793 void defaultStream::finish_log_on_error(char *buf, int buflen) {
 794   xmlStream* xs = _outer_xmlStream;
 795 
 796   if (xs && xs->out()) {
 797 
 798     xs->done_raw("tty");
 799 
 800     // Other log forks are appended here, at the End of Time:
 801     CompileLog::finish_log_on_error(xs->out(), buf, buflen);  // write compile logging, if any, now
 802 
 803     xs->done_raw("hotspot_log");
 804     xs->flush();
 805 
 806     fileStream* file = _log_file;
 807     _log_file = nullptr;
 808     _outer_xmlStream = nullptr;
 809 
 810     if (file) {
 811       file->flush();
 812 
 813       // Can't delete or close the file because delete and fclose aren't
 814       // async-safe. We are about to die, so leave it to the kernel.
 815       // delete file;
 816     }
 817   }
 818 }
 819 
 820 intx defaultStream::hold(intx writer_id) {
 821   bool has_log = has_log_file();  // check before locking
 822   if (// impossible, but who knows?
 823       writer_id == NO_WRITER ||
 824 
 825       // bootstrap problem
 826       tty_lock == nullptr ||
 827 
 828       // can't grab a lock if current Thread isn't set
 829       Thread::current_or_null() == nullptr ||
 830 
 831       // developer hook
 832       !SerializeVMOutput ||
 833 
 834       // VM already unhealthy
 835       VMError::is_error_reported() ||
 836 
 837       // safepoint == global lock (for VM only)
 838       (SafepointSynchronize::is_synchronizing() &&
 839        Thread::current()->is_VM_thread())
 840       ) {
 841     // do not attempt to lock unless we know the thread and the VM is healthy
 842     return NO_WRITER;
 843   }
 844   if (_writer == writer_id) {
 845     // already held, no need to re-grab the lock
 846     return NO_WRITER;
 847   }
 848   tty_lock->lock_without_safepoint_check();
 849   // got the lock
 850   if (writer_id != _last_writer) {
 851     if (has_log) {
 852       _log_file->bol();
 853       // output a hint where this output is coming from:
 854       _log_file->print_cr("<writer thread='" UINTX_FORMAT "'/>", writer_id);
 855     }
 856     _last_writer = writer_id;
 857   }
 858   _writer = writer_id;
 859   return writer_id;
 860 }
 861 
 862 void defaultStream::release(intx holder) {
 863   if (holder == NO_WRITER) {
 864     // nothing to release:  either a recursive lock, or we scribbled (too bad)
 865     return;
 866   }
 867   if (_writer != holder) {
 868     return;  // already unlocked, perhaps via break_tty_lock_for_safepoint
 869   }
 870   _writer = NO_WRITER;
 871   tty_lock->unlock();
 872 }
 873 
 874 void defaultStream::write(const char* s, size_t len) {
 875   intx thread_id = os::current_thread_id();
 876   intx holder = hold(thread_id);
 877 
 878   if (DisplayVMOutput &&
 879       (_outer_xmlStream == nullptr || !_outer_xmlStream->inside_attrs())) {
 880     // print to output stream. It can be redirected by a vfprintf hook
 881     jio_print(s, len);
 882   }
 883 
 884   // print to log file
 885   if (has_log_file() && _outer_xmlStream != nullptr) {
 886      _outer_xmlStream->write_text(s, len);
 887     bool nl = update_position(s, len);
 888     // flush the log file too, if there were any newlines
 889     if (nl) {
 890       flush();
 891     }
 892   } else {
 893     update_position(s, len);
 894   }
 895 
 896   release(holder);
 897 }
 898 
 899 intx ttyLocker::hold_tty() {
 900   if (defaultStream::instance == nullptr)  return defaultStream::NO_WRITER;
 901   intx thread_id = os::current_thread_id();
 902   return defaultStream::instance->hold(thread_id);
 903 }
 904 
 905 void ttyLocker::release_tty(intx holder) {
 906   if (holder == defaultStream::NO_WRITER)  return;
 907   defaultStream::instance->release(holder);
 908 }
 909 
 910 bool ttyLocker::release_tty_if_locked() {
 911   intx thread_id = os::current_thread_id();
 912   if (defaultStream::instance->writer() == thread_id) {
 913     // release the lock and return true so callers know if was
 914     // previously held.
 915     release_tty(thread_id);
 916     return true;
 917   }
 918   return false;
 919 }
 920 
 921 void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
 922   if (defaultStream::instance != nullptr &&
 923       defaultStream::instance->writer() == holder) {
 924     if (xtty != nullptr) {
 925       xtty->print_cr("<!-- safepoint while printing -->");
 926     }
 927     defaultStream::instance->release(holder);
 928   }
 929   // (else there was no lock to break)
 930 }
 931 
 932 void ostream_init() {
 933   if (defaultStream::instance == nullptr) {
 934     defaultStream::instance = new(mtInternal) defaultStream();
 935     tty = defaultStream::instance;
 936 
 937     // We want to ensure that time stamps in GC logs consider time 0
 938     // the time when the JVM is initialized, not the first time we ask
 939     // for a time stamp. So, here, we explicitly update the time stamp
 940     // of tty.
 941     tty->time_stamp().update_to(1);
 942   }
 943 }
 944 
 945 void ostream_init_log() {
 946   // Note : this must be called AFTER ostream_init()
 947 
 948   ClassListWriter::init();
 949 
 950   // If we haven't lazily initialized the logfile yet, do it now,
 951   // to avoid the possibility of lazy initialization during a VM
 952   // crash, which can affect the stability of the fatal error handler.
 953   defaultStream::instance->has_log_file();
 954 }
 955 
 956 // ostream_exit() is called during normal VM exit to finish log files, flush
 957 // output and free resource.
 958 void ostream_exit() {
 959   static bool ostream_exit_called = false;
 960   if (ostream_exit_called)  return;
 961   ostream_exit_called = true;
 962   ClassListWriter::delete_classlist();
 963   // Make sure tty works after VM exit by assigning an always-on functioning fdStream.
 964   outputStream* tmp = tty;
 965   tty = DisplayVMOutputToStderr ? fdStream::stdout_stream() : fdStream::stderr_stream();
 966   if (tmp != &tty_preinit_stream && tmp != defaultStream::instance) {
 967     delete tmp;
 968   }
 969   delete defaultStream::instance;
 970   xtty = nullptr;
 971   defaultStream::instance = nullptr;
 972 }
 973 
 974 // ostream_abort() is called by os::abort() when VM is about to die.
 975 void ostream_abort() {
 976   // Here we can't delete tty, just flush its output
 977   if (tty) tty->flush();
 978 
 979   if (defaultStream::instance != nullptr) {
 980     static char buf[4096];
 981     defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
 982   }
 983 }
 984 
 985 bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
 986   buffer_length = initial_size;
 987   buffer        = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
 988   buffer_pos    = 0;
 989   buffer_max    = bufmax;
 990   truncated     = false;
 991 }
 992 
 993 void bufferedStream::write(const char* s, size_t len) {
 994 
 995   if (truncated) {
 996     return;
 997   }
 998 
 999   if(buffer_pos + len > buffer_max) {
1000     flush(); // Note: may be a noop.
1001   }
1002 
1003   size_t end = buffer_pos + len;
1004   if (end >= buffer_length) {
1005     // For small overruns, double the buffer.  For larger ones,
1006     // increase to the requested size.
1007     if (end < buffer_length * 2) {
1008       end = buffer_length * 2;
1009     }
1010     // Impose a cap beyond which the buffer cannot grow - a size which
1011     // in all probability indicates a real error, e.g. faulty printing
1012     // code looping, while not affecting cases of just-very-large-but-its-normal
1013     // output.
1014     const size_t reasonable_cap = MAX2(100 * M, buffer_max * 2);
1015     if (end > reasonable_cap) {
1016       // In debug VM, assert right away.
1017       assert(false, "Exceeded max buffer size for this string.");
1018       // Release VM: silently truncate. We do this since these kind of errors
1019       // are both difficult to predict with testing (depending on logging content)
1020       // and usually not serious enough to kill a production VM for it.
1021       end = reasonable_cap;
1022       size_t remaining = end - buffer_pos;
1023       if (len >= remaining) {
1024         len = remaining - 1;
1025         truncated = true;
1026       }
1027     }
1028     if (buffer_length < end) {
1029       buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end, mtInternal);
1030       buffer_length = end;
1031     }
1032   }
1033   if (len > 0) {
1034     memcpy(buffer + buffer_pos, s, len);
1035     buffer_pos += len;
1036     update_position(s, len);
1037   }
1038 }
1039 
1040 char* bufferedStream::as_string() {
1041   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
1042   strncpy(copy, buffer, buffer_pos);
1043   copy[buffer_pos] = 0;  // terminating null
1044   return copy;
1045 }
1046 
1047 bufferedStream::~bufferedStream() {
1048   FREE_C_HEAP_ARRAY(char, buffer);
1049 }
1050 
1051 #ifndef PRODUCT
1052 
1053 #if defined(LINUX) || defined(AIX) || defined(_ALLBSD_SOURCE)
1054 #include <sys/types.h>
1055 #include <sys/socket.h>
1056 #include <netinet/in.h>
1057 #include <netdb.h>
1058 #include <arpa/inet.h>
1059 #elif defined(_WINDOWS)
1060 #include <Ws2tcpip.h>
1061 #endif
1062 
1063 // Network access
1064 networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
1065 
1066   _socket = -1;
1067 
1068   int result = ::socket(AF_INET, SOCK_STREAM, 0);
1069   if (result <= 0) {
1070     assert(false, "Socket could not be created!");
1071   } else {
1072     _socket = result;
1073   }
1074 }
1075 
1076 ssize_t networkStream::read(char *buf, size_t len) {
1077   return os::recv(_socket, buf, len, 0);
1078 }
1079 
1080 void networkStream::flush() {
1081   if (size() != 0) {
1082     ssize_t result = os::raw_send(_socket, (char *)base(), size(), 0);
1083     assert(result != -1, "connection error");
1084     assert(result >= 0 && (size_t)result == size(), "didn't send enough data");
1085   }
1086   reset();
1087 }
1088 
1089 networkStream::~networkStream() {
1090   close();
1091 }
1092 
1093 void networkStream::close() {
1094   if (_socket != -1) {
1095     flush();
1096     os::socket_close(_socket);
1097     _socket = -1;
1098   }
1099 }
1100 
1101 // host could be IP address, or a host name
1102 bool networkStream::connect(const char *host, short port) {
1103 
1104   char s_port[6]; // 5 digits max plus terminator
1105   int ret = os::snprintf(s_port, sizeof(s_port), "%hu", (unsigned short) port);
1106   assert(ret > 0, "snprintf failed: %d", ret);
1107 
1108   struct addrinfo* addr_info = nullptr;
1109   struct addrinfo hints;
1110 
1111   memset(&hints, 0, sizeof(hints));
1112   hints.ai_family = AF_INET;       // Allow IPv4 only
1113   hints.ai_socktype = SOCK_STREAM; // TCP only
1114 
1115   // getaddrinfo can resolve both an IP address and a host name
1116   ret = getaddrinfo(host, s_port, &hints, &addr_info);
1117   if (ret != 0) {
1118     warning("networkStream::connect getaddrinfo for host %s and port %s failed: %s",
1119             host, s_port, gai_strerror(ret));
1120     return false;
1121   }
1122 
1123   ssize_t conn = os::connect(_socket, addr_info->ai_addr, (socklen_t)addr_info->ai_addrlen);
1124   freeaddrinfo(addr_info);
1125   return (conn >= 0);
1126 }
1127 
1128 #endif