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