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   // Try again to open the file in the temp directory.
 688   delete file;
 689   // Note: This feature is for maintainer use only.  No need for L10N.
 690   jio_printf("Warning:  Cannot open log file: %s\n", log_name);
 691   try_name = make_log_name(log_name, os::get_temp_directory());
 692   if (try_name == nullptr) {
 693     warning("Cannot open file %s: file name is too long for directory %s.\n", log_name, os::get_temp_directory());
 694     return nullptr;
 695   }
 696 
 697   jio_printf("Warning:  Forcing option -XX:LogFile=%s\n", try_name);
 698 
 699   file = new (mtInternal) fileStream(try_name);
 700   FREE_C_HEAP_ARRAY(char, try_name);
 701   if (file->is_open()) {
 702     return file;
 703   }
 704 
 705   delete file;
 706   return nullptr;
 707 }
 708 
 709 void defaultStream::init_log() {
 710   // %%% Need a MutexLocker?
 711   const char* log_name = LogFile != nullptr ? LogFile : "hotspot_%p.log";
 712   fileStream* file = open_file(log_name);
 713 
 714   if (file != nullptr) {
 715     _log_file = file;
 716     _outer_xmlStream = new(mtInternal) xmlStream(file);
 717     start_log();
 718   } else {
 719     // and leave xtty as null
 720     LogVMOutput = false;
 721     DisplayVMOutput = true;
 722     LogCompilation = false;
 723   }
 724 }
 725 
 726 void defaultStream::start_log() {
 727   xmlStream*xs = _outer_xmlStream;
 728     if (this == tty)  xtty = xs;
 729     // Write XML header.
 730     xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
 731     // (For now, don't bother to issue a DTD for this private format.)
 732 
 733     // Calculate the start time of the log as ms since the epoch: this is
 734     // the current time in ms minus the uptime in ms.
 735     jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
 736     xs->head("hotspot_log version='%d %d'"
 737              " process='%d' time_ms='" INT64_FORMAT "'",
 738              LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
 739              os::current_process_id(), (int64_t)time_ms);
 740     // Write VM version header immediately.
 741     xs->head("vm_version");
 742     xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr();
 743     xs->tail("name");
 744     xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr();
 745     xs->tail("release");
 746     xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr();
 747     xs->tail("info");
 748     xs->tail("vm_version");
 749     // Record information about the command-line invocation.
 750     xs->head("vm_arguments");  // Cf. Arguments::print_on()
 751     if (Arguments::num_jvm_flags() > 0) {
 752       xs->head("flags");
 753       Arguments::print_jvm_flags_on(xs->text());
 754       xs->tail("flags");
 755     }
 756     if (Arguments::num_jvm_args() > 0) {
 757       xs->head("args");
 758       Arguments::print_jvm_args_on(xs->text());
 759       xs->tail("args");
 760     }
 761     if (Arguments::java_command() != nullptr) {
 762       xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command());
 763       xs->tail("command");
 764     }
 765     if (Arguments::sun_java_launcher() != nullptr) {
 766       xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher());
 767       xs->tail("launcher");
 768     }
 769     if (Arguments::system_properties() !=  nullptr) {
 770       xs->head("properties");
 771       // Print it as a java-style property list.
 772       // System properties don't generally contain newlines, so don't bother with unparsing.
 773       outputStream *text = xs->text();
 774       for (SystemProperty* p = Arguments::system_properties(); p != nullptr; p = p->next()) {
 775         assert(p->key() != nullptr, "p->key() is null");
 776         if (p->readable()) {
 777           // Print in two stages to avoid problems with long
 778           // keys/values.
 779           text->print_raw(p->key());
 780           text->put('=');
 781           assert(p->value() != nullptr, "p->value() is null");
 782           text->print_raw_cr(p->value());
 783         }
 784       }
 785       xs->tail("properties");
 786     }
 787     xs->tail("vm_arguments");
 788     // tty output per se is grouped under the <tty>...</tty> element.
 789     xs->head("tty");
 790     // All further non-markup text gets copied to the tty:
 791     xs->_text = this;  // requires friend declaration!
 792 }
 793 
 794 // finish_log() is called during normal VM shutdown. finish_log_on_error() is
 795 // called by ostream_abort() after a fatal error.
 796 //
 797 void defaultStream::finish_log() {
 798   xmlStream* xs = _outer_xmlStream;
 799   xs->done("tty");
 800 
 801   // Other log forks are appended here, at the End of Time:
 802   CompileLog::finish_log(xs->out());  // write compile logging, if any, now
 803 
 804   xs->done("hotspot_log");
 805   xs->flush();
 806 
 807   fileStream* file = _log_file;
 808   _log_file = nullptr;
 809 
 810   delete _outer_xmlStream;
 811   _outer_xmlStream = nullptr;
 812 
 813   file->flush();
 814   delete file;
 815 }
 816 
 817 void defaultStream::finish_log_on_error(char *buf, int buflen) {
 818   xmlStream* xs = _outer_xmlStream;
 819 
 820   if (xs && xs->out()) {
 821 
 822     xs->done_raw("tty");
 823 
 824     // Other log forks are appended here, at the End of Time:
 825     CompileLog::finish_log_on_error(xs->out(), buf, buflen);  // write compile logging, if any, now
 826 
 827     xs->done_raw("hotspot_log");
 828     xs->flush();
 829 
 830     fileStream* file = _log_file;
 831     _log_file = nullptr;
 832     _outer_xmlStream = nullptr;
 833 
 834     if (file) {
 835       file->flush();
 836 
 837       // Can't delete or close the file because delete and fclose aren't
 838       // async-safe. We are about to die, so leave it to the kernel.
 839       // delete file;
 840     }
 841   }
 842 }
 843 
 844 intx defaultStream::hold(intx writer_id) {
 845   bool has_log = has_log_file();  // check before locking
 846   if (// impossible, but who knows?
 847       writer_id == NO_WRITER ||
 848 
 849       // bootstrap problem
 850       tty_lock == nullptr ||
 851 
 852       // can't grab a lock if current Thread isn't set
 853       Thread::current_or_null() == nullptr ||
 854 
 855       // developer hook
 856       !SerializeVMOutput ||
 857 
 858       // VM already unhealthy
 859       VMError::is_error_reported() ||
 860 
 861       // safepoint == global lock (for VM only)
 862       (SafepointSynchronize::is_synchronizing() &&
 863        Thread::current()->is_VM_thread())
 864       ) {
 865     // do not attempt to lock unless we know the thread and the VM is healthy
 866     return NO_WRITER;
 867   }
 868   if (_writer == writer_id) {
 869     // already held, no need to re-grab the lock
 870     return NO_WRITER;
 871   }
 872   tty_lock->lock_without_safepoint_check();
 873   // got the lock
 874   if (writer_id != _last_writer) {
 875     if (has_log) {
 876       _log_file->bol();
 877       // output a hint where this output is coming from:
 878       _log_file->print_cr("<writer thread='" UINTX_FORMAT "'/>", writer_id);
 879     }
 880     _last_writer = writer_id;
 881   }
 882   _writer = writer_id;
 883   return writer_id;
 884 }
 885 
 886 void defaultStream::release(intx holder) {
 887   if (holder == NO_WRITER) {
 888     // nothing to release:  either a recursive lock, or we scribbled (too bad)
 889     return;
 890   }
 891   if (_writer != holder) {
 892     return;  // already unlocked, perhaps via break_tty_lock_for_safepoint
 893   }
 894   _writer = NO_WRITER;
 895   tty_lock->unlock();
 896 }
 897 
 898 void defaultStream::write(const char* s, size_t len) {
 899   intx thread_id = os::current_thread_id();
 900   intx holder = hold(thread_id);
 901 
 902   if (DisplayVMOutput &&
 903       (_outer_xmlStream == nullptr || !_outer_xmlStream->inside_attrs())) {
 904     // print to output stream. It can be redirected by a vfprintf hook
 905     jio_print(s, len);
 906   }
 907 
 908   // print to log file
 909   if (has_log_file() && _outer_xmlStream != nullptr) {
 910      _outer_xmlStream->write_text(s, len);
 911     bool nl = update_position(s, len);
 912     // flush the log file too, if there were any newlines
 913     if (nl) {
 914       flush();
 915     }
 916   } else {
 917     update_position(s, len);
 918   }
 919 
 920   release(holder);
 921 }
 922 
 923 intx ttyLocker::hold_tty() {
 924   if (defaultStream::instance == nullptr)  return defaultStream::NO_WRITER;
 925   intx thread_id = os::current_thread_id();
 926   return defaultStream::instance->hold(thread_id);
 927 }
 928 
 929 void ttyLocker::release_tty(intx holder) {
 930   if (holder == defaultStream::NO_WRITER)  return;
 931   defaultStream::instance->release(holder);
 932 }
 933 
 934 bool ttyLocker::release_tty_if_locked() {
 935   intx thread_id = os::current_thread_id();
 936   if (defaultStream::instance->writer() == thread_id) {
 937     // release the lock and return true so callers know if was
 938     // previously held.
 939     release_tty(thread_id);
 940     return true;
 941   }
 942   return false;
 943 }
 944 
 945 void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
 946   if (defaultStream::instance != nullptr &&
 947       defaultStream::instance->writer() == holder) {
 948     if (xtty != nullptr) {
 949       xtty->print_cr("<!-- safepoint while printing -->");
 950     }
 951     defaultStream::instance->release(holder);
 952   }
 953   // (else there was no lock to break)
 954 }
 955 
 956 void ostream_init() {
 957   if (defaultStream::instance == nullptr) {
 958     defaultStream::instance = new(mtInternal) defaultStream();
 959     tty = defaultStream::instance;
 960 
 961     // We want to ensure that time stamps in GC logs consider time 0
 962     // the time when the JVM is initialized, not the first time we ask
 963     // for a time stamp. So, here, we explicitly update the time stamp
 964     // of tty.
 965     tty->time_stamp().update_to(1);
 966   }
 967 }
 968 
 969 void ostream_init_log() {
 970   // Note : this must be called AFTER ostream_init()
 971 
 972   ClassListWriter::init();
 973 
 974   // If we haven't lazily initialized the logfile yet, do it now,
 975   // to avoid the possibility of lazy initialization during a VM
 976   // crash, which can affect the stability of the fatal error handler.
 977   defaultStream::instance->has_log_file();
 978 }
 979 
 980 // ostream_exit() is called during normal VM exit to finish log files, flush
 981 // output and free resource.
 982 void ostream_exit() {
 983   static bool ostream_exit_called = false;
 984   if (ostream_exit_called)  return;
 985   ostream_exit_called = true;
 986   ClassListWriter::delete_classlist();
 987   // Make sure tty works after VM exit by assigning an always-on functioning fdStream.
 988   outputStream* tmp = tty;
 989   tty = DisplayVMOutputToStderr ? fdStream::stderr_stream() : fdStream::stdout_stream();
 990   if (tmp != &tty_preinit_stream && tmp != defaultStream::instance) {
 991     delete tmp;
 992   }
 993   delete defaultStream::instance;
 994   xtty = nullptr;
 995   defaultStream::instance = nullptr;
 996 }
 997 
 998 // ostream_abort() is called by os::abort() when VM is about to die.
 999 void ostream_abort() {
1000   // Here we can't delete tty, just flush its output
1001   if (tty) tty->flush();
1002 
1003   if (defaultStream::instance != nullptr) {
1004     static char buf[4096];
1005     defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
1006   }
1007 }
1008 
1009 bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
1010   buffer_length = initial_size;
1011   buffer        = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
1012   buffer_pos    = 0;
1013   buffer_max    = bufmax;
1014   truncated     = false;
1015 }
1016 
1017 void bufferedStream::write(const char* s, size_t len) {
1018 
1019   if (truncated) {
1020     return;
1021   }
1022 
1023   if(buffer_pos + len > buffer_max) {
1024     flush(); // Note: may be a noop.
1025   }
1026 
1027   size_t end = buffer_pos + len;
1028   if (end >= buffer_length) {
1029     // For small overruns, double the buffer.  For larger ones,
1030     // increase to the requested size.
1031     if (end < buffer_length * 2) {
1032       end = buffer_length * 2;
1033     }
1034     // Impose a cap beyond which the buffer cannot grow - a size which
1035     // in all probability indicates a real error, e.g. faulty printing
1036     // code looping, while not affecting cases of just-very-large-but-its-normal
1037     // output.
1038     const size_t reasonable_cap = MAX2(100 * M, buffer_max * 2);
1039     if (end > reasonable_cap) {
1040       // In debug VM, assert right away.
1041       assert(false, "Exceeded max buffer size for this string (\"%.200s...\").", buffer);
1042       // Release VM: silently truncate. We do this since these kind of errors
1043       // are both difficult to predict with testing (depending on logging content)
1044       // and usually not serious enough to kill a production VM for it.
1045       end = reasonable_cap;
1046       size_t remaining = end - buffer_pos;
1047       if (len >= remaining) {
1048         len = remaining - 1;
1049         truncated = true;
1050       }
1051     }
1052     if (buffer_length < end) {
1053       buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end, mtInternal);
1054       buffer_length = end;
1055     }
1056   }
1057   if (len > 0) {
1058     memcpy(buffer + buffer_pos, s, len);
1059     buffer_pos += len;
1060     update_position(s, len);
1061   }
1062 }
1063 
1064 char* bufferedStream::as_string() {
1065   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
1066   strncpy(copy, buffer, buffer_pos);
1067   copy[buffer_pos] = 0;  // terminating null
1068   return copy;
1069 }
1070 
1071 bufferedStream::~bufferedStream() {
1072   FREE_C_HEAP_ARRAY(char, buffer);
1073 }
1074 
1075 #ifndef PRODUCT
1076 
1077 #if defined(LINUX) || defined(AIX) || defined(_ALLBSD_SOURCE)
1078 #include <sys/types.h>
1079 #include <sys/socket.h>
1080 #include <netinet/in.h>
1081 #include <netdb.h>
1082 #include <arpa/inet.h>
1083 #elif defined(_WINDOWS)
1084 #include <Ws2tcpip.h>
1085 #endif
1086 
1087 // Network access
1088 networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
1089 
1090   _socket = -1;
1091 
1092   int result = ::socket(AF_INET, SOCK_STREAM, 0);
1093   if (result <= 0) {
1094     assert(false, "Socket could not be created!");
1095   } else {
1096     _socket = result;
1097   }
1098 }
1099 
1100 ssize_t networkStream::read(char *buf, size_t len) {
1101   return os::recv(_socket, buf, len, 0);
1102 }
1103 
1104 void networkStream::flush() {
1105   if (size() != 0) {
1106     ssize_t result = os::raw_send(_socket, (char *)base(), size(), 0);
1107     assert(result != -1, "connection error");
1108     assert(result >= 0 && (size_t)result == size(), "didn't send enough data");
1109   }
1110   reset();
1111 }
1112 
1113 networkStream::~networkStream() {
1114   close();
1115 }
1116 
1117 void networkStream::close() {
1118   if (_socket != -1) {
1119     flush();
1120     os::socket_close(_socket);
1121     _socket = -1;
1122   }
1123 }
1124 
1125 // host could be IP address, or a host name
1126 bool networkStream::connect(const char *host, short port) {
1127 
1128   char s_port[6]; // 5 digits max plus terminator
1129   int ret = os::snprintf(s_port, sizeof(s_port), "%hu", (unsigned short) port);
1130   assert(ret > 0, "snprintf failed: %d", ret);
1131 
1132   struct addrinfo* addr_info = nullptr;
1133   struct addrinfo hints;
1134 
1135   memset(&hints, 0, sizeof(hints));
1136   hints.ai_family = AF_INET;       // Allow IPv4 only
1137   hints.ai_socktype = SOCK_STREAM; // TCP only
1138 
1139   // getaddrinfo can resolve both an IP address and a host name
1140   ret = getaddrinfo(host, s_port, &hints, &addr_info);
1141   if (ret != 0) {
1142     warning("networkStream::connect getaddrinfo for host %s and port %s failed: %s",
1143             host, s_port, gai_strerror(ret));
1144     return false;
1145   }
1146 
1147   ssize_t conn = os::connect(_socket, addr_info->ai_addr, (socklen_t)addr_info->ai_addrlen);
1148   freeaddrinfo(addr_info);
1149   return (conn >= 0);
1150 }
1151 
1152 #endif