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