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