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