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