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