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