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