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