1 /*
   2  * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "cds/classListWriter.hpp"
  26 #include "compiler/compileLog.hpp"
  27 #include "jvm.h"
  28 #include "memory/allocation.inline.hpp"
  29 #include "oops/oop.inline.hpp"
  30 #include "runtime/arguments.hpp"
  31 #include "runtime/mutexLocker.hpp"
  32 #include "runtime/orderAccess.hpp"
  33 #include "runtime/os.inline.hpp"
  34 #include "runtime/safepoint.hpp"
  35 #include "runtime/vm_version.hpp"
  36 #include "utilities/defaultStream.hpp"
  37 #include "utilities/macros.hpp"
  38 #include "utilities/ostream.hpp"
  39 #include "utilities/vmError.hpp"
  40 #include "utilities/xmlstream.hpp"
  41 
  42 // Declarations of jvm methods
  43 extern "C" void jio_print(const char* s, size_t len);
  44 extern "C" int jio_printf(const char *fmt, ...);
  45 
  46 outputStream::outputStream(bool has_time_stamps) {
  47   _position    = 0;
  48   _precount    = 0;
  49   _indentation = 0;
  50   _autoindent  = false;
  51   _scratch     = nullptr;
  52   _scratch_len = 0;
  53   if (has_time_stamps)  _stamp.update();
  54 }
  55 
  56 bool outputStream::update_position(const char* s, size_t len) {
  57   bool saw_newline = false;
  58   for (size_t i = 0; i < len; i++) {
  59     char ch = s[i];
  60     if (ch == '\n') {
  61       saw_newline = true;
  62       _precount += _position + 1;
  63       _position = 0;
  64     } else if (ch == '\t') {
  65       int tw = 8 - (_position & 7);
  66       _position += tw;
  67       _precount -= tw-1;  // invariant:  _precount + _position == total count
  68     } else {
  69       _position += 1;
  70     }
  71   }
  72   return saw_newline;
  73 }
  74 
  75 // Execute a vsprintf, using the given buffer if necessary.
  76 // Return a pointer to the formatted string. Optimise for
  77 // strings without format specifiers, or only "%s". See
  78 // comments in the header file for more details.
  79 const char* outputStream::do_vsnprintf(char* buffer, size_t buflen,
  80                                        const char* format, va_list ap,
  81                                        bool add_cr,
  82                                        size_t& result_len) {
  83   assert(buflen >= 2, "buffer too small");
  84 
  85   const char* result;  // The string to return. May not be the buffer.
  86   size_t required_len = 0; // The length of buffer needed to avoid truncation
  87                            // (excluding space for the nul terminator).
  88 
  89   if (add_cr) { // Ensure space for CR even if truncation occurs.
  90     buflen--;
  91   }
  92 
  93   if (!strchr(format, '%')) {
  94     // constant format string
  95     result = format;
  96     result_len = strlen(result);
  97     if (add_cr && result_len >= buflen) { // truncate
  98       required_len = result_len + 1;
  99       result_len = buflen - 1;
 100     }
 101   } else if (strncmp(format, "%s", 3) == 0) { //(format[0] == '%' && format[1] == 's' && format[2] == '\0') {
 102     // trivial copy-through format string
 103     result = va_arg(ap, const char*);
 104     result_len = strlen(result);
 105     if (add_cr && result_len >= buflen) { // truncate
 106       required_len = result_len + 1;
 107       result_len = buflen - 1;
 108     }
 109   } else {
 110     int required_buffer_len = os::vsnprintf(buffer, buflen, format, ap);
 111     assert(required_buffer_len >= 0, "vsnprintf encoding error");
 112     result = buffer;
 113     required_len = required_buffer_len;
 114     if (required_len < buflen) {
 115       result_len = required_len;
 116     } else { // truncation
 117       result_len = buflen - 1;
 118     }
 119   }
 120   if (add_cr) {
 121     if (result != buffer) { // Need to copy to add CR
 122       memcpy(buffer, result, result_len);
 123       result = buffer;
 124     } else {
 125       required_len++;
 126     }
 127     buffer[result_len++] = '\n';
 128     buffer[result_len] = 0;
 129   }
 130 #ifdef ASSERT
 131   if (required_len > result_len) {
 132     warning("outputStream::do_vsnprintf output truncated -- buffer length is %zu"
 133             " bytes but %zu bytes are needed.",
 134             add_cr ? buflen + 1 : buflen, required_len + 1);
 135   }
 136 #endif
 137   return result;
 138 }
 139 
 140 void outputStream::do_vsnprintf_and_write_with_automatic_buffer(const char* format, va_list ap, bool add_cr) {
 141   char buffer[O_BUFLEN];
 142   size_t len;
 143   const char* str = do_vsnprintf(buffer, sizeof(buffer), format, ap, add_cr, len);
 144   write(str, len);
 145 }
 146 
 147 void outputStream::do_vsnprintf_and_write_with_scratch_buffer(const char* format, va_list ap, bool add_cr) {
 148   size_t len;
 149   const char* str = do_vsnprintf(_scratch, _scratch_len, format, ap, add_cr, len);
 150   write(str, len);
 151 }
 152 
 153 void outputStream::do_vsnprintf_and_write(const char* format, va_list ap, bool add_cr) {
 154   if (_autoindent && _position == 0) {
 155     indent();
 156   }
 157   if (_scratch) {
 158     do_vsnprintf_and_write_with_scratch_buffer(format, ap, add_cr);
 159   } else {
 160     do_vsnprintf_and_write_with_automatic_buffer(format, ap, add_cr);
 161   }
 162 }
 163 
 164 void outputStream::print(const char* format, ...) {
 165   va_list ap;
 166   va_start(ap, format);
 167   do_vsnprintf_and_write(format, ap, false);
 168   va_end(ap);
 169 }
 170 
 171 void outputStream::print_cr(const char* format, ...) {
 172   va_list ap;
 173   va_start(ap, format);
 174   do_vsnprintf_and_write(format, ap, true);
 175   va_end(ap);
 176 }
 177 
 178 void outputStream::vprint(const char *format, va_list argptr) {
 179   do_vsnprintf_and_write(format, argptr, false);
 180 }
 181 
 182 void outputStream::vprint_cr(const char* format, va_list argptr) {
 183   do_vsnprintf_and_write(format, argptr, true);
 184 }
 185 
 186 void outputStream::print_raw(const char* str, size_t len) {
 187   if (_autoindent && _position == 0) {
 188     indent();
 189   }
 190   write(str, len);
 191 }
 192 
 193 int outputStream::fill_to(int col) {
 194   const int need_fill = MAX2(col - position(), 0);
 195   sp(need_fill);
 196   return 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? (%zu)", 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   if (RecordTraining) {
 687     vm_exit_during_initialization("cannot create log file for RecordTraining mode: %s", try_name);
 688   }
 689 
 690   // Try again to open the file in the temp directory.
 691   delete file;
 692   // Note: This feature is for maintainer use only.  No need for L10N.
 693   jio_printf("Warning:  Cannot open log file: %s\n", log_name);
 694   try_name = make_log_name(log_name, os::get_temp_directory());
 695   if (try_name == nullptr) {
 696     warning("Cannot open file %s: file name is too long for directory %s.\n", log_name, os::get_temp_directory());
 697     return nullptr;
 698   }
 699 
 700   jio_printf("Warning:  Forcing option -XX:LogFile=%s\n", try_name);
 701 
 702   file = new (mtInternal) fileStream(try_name);
 703   FREE_C_HEAP_ARRAY(char, try_name);
 704   if (file->is_open()) {
 705     return file;
 706   }
 707 
 708   delete file;
 709   return nullptr;
 710 }
 711 
 712 void defaultStream::init_log() {
 713   // %%% Need a MutexLocker?
 714   const char* log_name = LogFile != nullptr ? LogFile : "hotspot_%p.log";
 715   fileStream* file = open_file(log_name);
 716 
 717   if (file != nullptr) {
 718     _log_file = file;
 719     _outer_xmlStream = new(mtInternal) xmlStream(file);
 720     start_log();
 721   } else {
 722     // and leave xtty as null
 723     LogVMOutput = false;
 724     DisplayVMOutput = true;
 725     LogCompilation = false;
 726   }
 727 }
 728 
 729 void defaultStream::start_log() {
 730   xmlStream*xs = _outer_xmlStream;
 731     if (this == tty)  xtty = xs;
 732     // Write XML header.
 733     xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
 734     // (For now, don't bother to issue a DTD for this private format.)
 735 
 736     // Calculate the start time of the log as ms since the epoch: this is
 737     // the current time in ms minus the uptime in ms.
 738     jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
 739     xs->head("hotspot_log version='%d %d'"
 740              " process='%d' time_ms='" INT64_FORMAT "'",
 741              LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
 742              os::current_process_id(), (int64_t)time_ms);
 743     // Write VM version header immediately.
 744     xs->head("vm_version");
 745     xs->head("name");  // FIXME: should be an elem attr, not head/tail pair
 746     xs->log_only()->print_cr("%s", VM_Version::vm_name());
 747     xs->tail("name");
 748     xs->head("release");
 749     xs->log_only()->print_cr("%s", VM_Version::vm_release());
 750     xs->tail("release");
 751     xs->head("info");
 752     xs->log_only()->print_cr("%s", VM_Version::internal_vm_info_string());
 753     xs->tail("info");
 754     xs->tail("vm_version");
 755     // Record information about the command-line invocation.
 756     xs->head("vm_arguments");  // Cf. Arguments::print_on()
 757     if (Arguments::num_jvm_flags() > 0) {
 758       xs->head("flags");
 759       Arguments::print_jvm_flags_on(xs->log_only());
 760       xs->tail("flags");
 761     }
 762     if (Arguments::num_jvm_args() > 0) {
 763       xs->head("args");
 764       Arguments::print_jvm_args_on(xs->log_only());
 765       xs->tail("args");
 766     }
 767     if (Arguments::java_command() != nullptr) {
 768       xs->head("command"); xs->log_only()->print_cr("%s", Arguments::java_command());
 769       xs->tail("command");
 770     }
 771     if (Arguments::sun_java_launcher() != nullptr) {
 772       xs->head("launcher"); xs->log_only()->print_cr("%s", Arguments::sun_java_launcher());
 773       xs->tail("launcher");
 774     }
 775     if (Arguments::system_properties() !=  nullptr) {
 776       xs->head("properties");
 777       // Print it as a java-style property list.
 778       // System properties don't generally contain newlines, so don't bother with unparsing.
 779       outputStream *text = xs->log_only();
 780       for (SystemProperty* p = Arguments::system_properties(); p != nullptr; p = p->next()) {
 781         assert(p->key() != nullptr, "p->key() is null");
 782         if (p->readable()) {
 783           // Print in two stages to avoid problems with long
 784           // keys/values.
 785           text->print_raw(p->key());
 786           text->put('=');
 787           assert(p->value() != nullptr, "p->value() is null");
 788           text->print_raw_cr(p->value());
 789         }
 790       }
 791       xs->tail("properties");
 792     }
 793     xs->tail("vm_arguments");
 794     // tty output per se is grouped under the <tty>...</tty> element.
 795     xs->head("tty");
 796     // All further non-markup text gets copied to the tty:
 797     xs->_text = this;  // requires friend declaration!
 798     // (And xtty->log_only() remains as a back door to the non-tty log file.)
 799 }
 800 
 801 // finish_log() is called during normal VM shutdown. finish_log_on_error() is
 802 // called by ostream_abort() after a fatal error.
 803 //
 804 void defaultStream::finish_log() {
 805   xmlStream* xs = _outer_xmlStream;
 806   xs->done("tty");
 807 
 808   // Other log forks are appended here, at the End of Time:
 809   CompileLog::finish_log(xs->out());  // write compile logging, if any, now
 810 
 811   xs->done("hotspot_log");
 812   xs->flush();
 813 
 814   fileStream* file = _log_file;
 815   _log_file = nullptr;
 816 
 817   delete _outer_xmlStream;
 818   _outer_xmlStream = nullptr;
 819 
 820   file->flush();
 821   delete file;
 822 }
 823 
 824 void defaultStream::finish_log_on_error(char *buf, int buflen) {
 825   xmlStream* xs = _outer_xmlStream;
 826 
 827   if (xs && xs->out()) {
 828 
 829     xs->done_raw("tty");
 830 
 831     // Other log forks are appended here, at the End of Time:
 832     CompileLog::finish_log_on_error(xs->out(), buf, buflen);  // write compile logging, if any, now
 833 
 834     xs->done_raw("hotspot_log");
 835     xs->flush();
 836 
 837     fileStream* file = _log_file;
 838     _log_file = nullptr;
 839     _outer_xmlStream = nullptr;
 840 
 841     if (file) {
 842       file->flush();
 843 
 844       // Can't delete or close the file because delete and fclose aren't
 845       // async-safe. We are about to die, so leave it to the kernel.
 846       // delete file;
 847     }
 848   }
 849 }
 850 
 851 intx defaultStream::hold(intx writer_id) {
 852   bool has_log = has_log_file();  // check before locking
 853   if (// impossible, but who knows?
 854       writer_id == NO_WRITER ||
 855 
 856       // bootstrap problem
 857       tty_lock == nullptr ||
 858 
 859       // can't grab a lock if current Thread isn't set
 860       Thread::current_or_null() == nullptr ||
 861 
 862       // developer hook
 863       !SerializeVMOutput ||
 864 
 865       // VM already unhealthy
 866       VMError::is_error_reported() ||
 867 
 868       // safepoint == global lock (for VM only)
 869       (SafepointSynchronize::is_synchronizing() &&
 870        Thread::current()->is_VM_thread())
 871       ) {
 872     // do not attempt to lock unless we know the thread and the VM is healthy
 873     return NO_WRITER;
 874   }
 875   if (_writer == writer_id) {
 876     // already held, no need to re-grab the lock
 877     return NO_WRITER;
 878   }
 879   tty_lock->lock_without_safepoint_check();
 880   // got the lock
 881   if (writer_id != _last_writer) {
 882     if (has_log) {
 883       _log_file->bol();
 884       // output a hint where this output is coming from:
 885       _log_file->print_cr("<writer thread='%zu'/>", writer_id);
 886     }
 887     _last_writer = writer_id;
 888   }
 889   _writer = writer_id;
 890   return writer_id;
 891 }
 892 
 893 void defaultStream::release(intx holder) {
 894   if (holder == NO_WRITER) {
 895     // nothing to release:  either a recursive lock, or we scribbled (too bad)
 896     return;
 897   }
 898   if (_writer != holder) {
 899     return;  // already unlocked, perhaps via break_tty_lock_for_safepoint
 900   }
 901   _writer = NO_WRITER;
 902   tty_lock->unlock();
 903 }
 904 
 905 void defaultStream::write(const char* s, size_t len) {
 906   intx thread_id = os::current_thread_id();
 907   intx holder = hold(thread_id);
 908 
 909   if (DisplayVMOutput &&
 910       (_outer_xmlStream == nullptr || !_outer_xmlStream->inside_attrs())) {
 911     // print to output stream. It can be redirected by a vfprintf hook
 912     jio_print(s, len);
 913   }
 914 
 915   // print to log file
 916   if (has_log_file() && _outer_xmlStream != nullptr) {
 917      _outer_xmlStream->write_text(s, len);
 918     bool nl = update_position(s, len);
 919     // flush the log file too, if there were any newlines
 920     if (nl) {
 921       flush();
 922     }
 923   } else {
 924     update_position(s, len);
 925   }
 926 
 927   release(holder);
 928 }
 929 
 930 intx ttyLocker::hold_tty() {
 931   if (defaultStream::instance == nullptr)  return defaultStream::NO_WRITER;
 932   intx thread_id = os::current_thread_id();
 933   return defaultStream::instance->hold(thread_id);
 934 }
 935 
 936 void ttyLocker::release_tty(intx holder) {
 937   if (holder == defaultStream::NO_WRITER)  return;
 938   defaultStream::instance->release(holder);
 939 }
 940 
 941 bool ttyLocker::release_tty_if_locked() {
 942   intx thread_id = os::current_thread_id();
 943   if (defaultStream::instance->writer() == thread_id) {
 944     // release the lock and return true so callers know if was
 945     // previously held.
 946     release_tty(thread_id);
 947     return true;
 948   }
 949   return false;
 950 }
 951 
 952 void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
 953   if (defaultStream::instance != nullptr &&
 954       defaultStream::instance->writer() == holder) {
 955     if (xtty != nullptr) {
 956       xtty->print_cr("<!-- safepoint while printing -->");
 957     }
 958     defaultStream::instance->release(holder);
 959   }
 960   // (else there was no lock to break)
 961 }
 962 
 963 void ostream_init() {
 964   if (defaultStream::instance == nullptr) {
 965     defaultStream::instance = new(mtInternal) defaultStream();
 966     tty = defaultStream::instance;
 967 
 968     // We want to ensure that time stamps in GC logs consider time 0
 969     // the time when the JVM is initialized, not the first time we ask
 970     // for a time stamp. So, here, we explicitly update the time stamp
 971     // of tty.
 972     tty->time_stamp().update_to(1);
 973   }
 974 }
 975 
 976 void ostream_init_log() {
 977   // Note : this must be called AFTER ostream_init()
 978 
 979   ClassListWriter::init();
 980 
 981   // If we haven't lazily initialized the logfile yet, do it now,
 982   // to avoid the possibility of lazy initialization during a VM
 983   // crash, which can affect the stability of the fatal error handler.
 984   defaultStream::instance->has_log_file();
 985 }
 986 
 987 // ostream_exit() is called during normal VM exit to finish log files, flush
 988 // output and free resource.
 989 void ostream_exit() {
 990   static bool ostream_exit_called = false;
 991   if (ostream_exit_called)  return;
 992   ostream_exit_called = true;
 993   ClassListWriter::delete_classlist();
 994   // Make sure tty works after VM exit by assigning an always-on functioning fdStream.
 995   outputStream* tmp = tty;
 996   tty = DisplayVMOutputToStderr ? fdStream::stderr_stream() : fdStream::stdout_stream();
 997   if (tmp != &tty_preinit_stream && tmp != defaultStream::instance) {
 998     delete tmp;
 999   }
1000   delete defaultStream::instance;
1001   xtty = nullptr;
1002   defaultStream::instance = nullptr;
1003 }
1004 
1005 // ostream_abort() is called by os::abort() when VM is about to die.
1006 void ostream_abort() {
1007   // Here we can't delete tty, just flush its output
1008   if (tty) tty->flush();
1009 
1010   if (defaultStream::instance != nullptr) {
1011     static char buf[4096];
1012     defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
1013   }
1014 }
1015 
1016 bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
1017   buffer_length = initial_size;
1018   buffer        = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
1019   buffer_pos    = 0;
1020   buffer_max    = bufmax;
1021   truncated     = false;
1022 }
1023 
1024 void bufferedStream::write(const char* s, size_t len) {
1025 
1026   if (truncated) {
1027     return;
1028   }
1029 
1030   if(buffer_pos + len > buffer_max) {
1031     flush(); // Note: may be a noop.
1032   }
1033 
1034   size_t end = buffer_pos + len;
1035   if (end >= buffer_length) {
1036     // For small overruns, double the buffer.  For larger ones,
1037     // increase to the requested size.
1038     if (end < buffer_length * 2) {
1039       end = buffer_length * 2;
1040     }
1041     // Impose a cap beyond which the buffer cannot grow - a size which
1042     // in all probability indicates a real error, e.g. faulty printing
1043     // code looping, while not affecting cases of just-very-large-but-its-normal
1044     // output.
1045     const size_t reasonable_cap = MAX2(100 * M, buffer_max * 2);
1046     if (end > reasonable_cap) {
1047       // In debug VM, assert right away.
1048       assert(false, "Exceeded max buffer size for this string (\"%.200s...\").", buffer);
1049       // Release VM: silently truncate. We do this since these kind of errors
1050       // are both difficult to predict with testing (depending on logging content)
1051       // and usually not serious enough to kill a production VM for it.
1052       end = reasonable_cap;
1053       size_t remaining = end - buffer_pos;
1054       if (len >= remaining) {
1055         len = remaining - 1;
1056         truncated = true;
1057       }
1058     }
1059     if (buffer_length < end) {
1060       buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end, mtInternal);
1061       buffer_length = end;
1062     }
1063   }
1064   if (len > 0) {
1065     memcpy(buffer + buffer_pos, s, len);
1066     buffer_pos += len;
1067     update_position(s, len);
1068   }
1069 }
1070 
1071 char* bufferedStream::as_string() {
1072   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
1073   strncpy(copy, buffer, buffer_pos);
1074   copy[buffer_pos] = 0;  // terminating null
1075   return copy;
1076 }
1077 
1078 bufferedStream::~bufferedStream() {
1079   FREE_C_HEAP_ARRAY(char, buffer);
1080 }
1081 
1082 #ifndef PRODUCT
1083 
1084 #if defined(LINUX) || defined(AIX) || defined(_ALLBSD_SOURCE)
1085 #include <sys/types.h>
1086 #include <sys/socket.h>
1087 #include <netinet/in.h>
1088 #include <netdb.h>
1089 #include <arpa/inet.h>
1090 #elif defined(_WINDOWS)
1091 #include <Ws2tcpip.h>
1092 #endif
1093 
1094 // Network access
1095 networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
1096 
1097   _socket = -1;
1098 
1099   int result = ::socket(AF_INET, SOCK_STREAM, 0);
1100   if (result <= 0) {
1101     assert(false, "Socket could not be created!");
1102   } else {
1103     _socket = result;
1104   }
1105 }
1106 
1107 ssize_t networkStream::read(char *buf, size_t len) {
1108   return os::recv(_socket, buf, len, 0);
1109 }
1110 
1111 void networkStream::flush() {
1112   if (size() != 0) {
1113     ssize_t result = os::raw_send(_socket, (char *)base(), size(), 0);
1114     assert(result != -1, "connection error");
1115     assert(result >= 0 && (size_t)result == size(), "didn't send enough data");
1116   }
1117   reset();
1118 }
1119 
1120 networkStream::~networkStream() {
1121   close();
1122 }
1123 
1124 void networkStream::close() {
1125   if (_socket != -1) {
1126     flush();
1127     os::socket_close(_socket);
1128     _socket = -1;
1129   }
1130 }
1131 
1132 // host could be IP address, or a host name
1133 bool networkStream::connect(const char *host, short port) {
1134 
1135   char s_port[6]; // 5 digits max plus terminator
1136   int ret = os::snprintf(s_port, sizeof(s_port), "%hu", (unsigned short) port);
1137   assert(ret > 0, "snprintf failed: %d", ret);
1138 
1139   struct addrinfo* addr_info = nullptr;
1140   struct addrinfo hints;
1141 
1142   memset(&hints, 0, sizeof(hints));
1143   hints.ai_family = AF_INET;       // Allow IPv4 only
1144   hints.ai_socktype = SOCK_STREAM; // TCP only
1145 
1146   // getaddrinfo can resolve both an IP address and a host name
1147   ret = getaddrinfo(host, s_port, &hints, &addr_info);
1148   if (ret != 0) {
1149     warning("networkStream::connect getaddrinfo for host %s and port %s failed: %s",
1150             host, s_port, gai_strerror(ret));
1151     return false;
1152   }
1153 
1154   ssize_t conn = os::connect(_socket, addr_info->ai_addr, (socklen_t)addr_info->ai_addrlen);
1155   freeaddrinfo(addr_info);
1156   return (conn >= 0);
1157 }
1158 
1159 #endif
--- EOF ---