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