1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "compiler/compileLog.hpp"
  27 #include "gc/shared/gcId.hpp"
  28 #include "gc/shared/gcId.hpp"
  29 #include "oops/oop.inline.hpp"
  30 #include "runtime/arguments.hpp"
  31 #include "runtime/os.hpp"
  32 #include "runtime/vm_version.hpp"
  33 #include "utilities/defaultStream.hpp"
  34 #include "utilities/macros.hpp"
  35 #include "utilities/ostream.hpp"
  36 #include "utilities/top.hpp"
  37 #include "utilities/xmlstream.hpp"
  38 
  39 extern "C" void jio_print(const char* s); // Declarationtion of jvm method
  40 
  41 outputStream::outputStream(int width) {
  42   _width       = width;
  43   _position    = 0;
  44   _newlines    = 0;
  45   _precount    = 0;
  46   _indentation = 0;
  47 }
  48 
  49 outputStream::outputStream(int width, bool has_time_stamps) {
  50   _width       = width;
  51   _position    = 0;
  52   _newlines    = 0;
  53   _precount    = 0;
  54   _indentation = 0;
  55   if (has_time_stamps)  _stamp.update();
  56 }
  57 
  58 void outputStream::update_position(const char* s, size_t len) {
  59   for (size_t i = 0; i < len; i++) {
  60     char ch = s[i];
  61     if (ch == '\n') {
  62       _newlines += 1;
  63       _precount += _position + 1;
  64       _position = 0;
  65     } else if (ch == '\t') {
  66       int tw = 8 - (_position & 7);
  67       _position += tw;
  68       _precount -= tw-1;  // invariant:  _precount + _position == total count
  69     } else {
  70       _position += 1;
  71     }
  72   }
  73 }
  74 
  75 // Execute a vsprintf, using the given buffer if necessary.
  76 // Return a pointer to the formatted string.
  77 const char* outputStream::do_vsnprintf(char* buffer, size_t buflen,
  78                                        const char* format, va_list ap,
  79                                        bool add_cr,
  80                                        size_t& result_len) {
  81   assert(buflen >= 2, "buffer too small");
  82 
  83   const char* result;
  84   if (add_cr)  buflen--;
  85   if (!strchr(format, '%')) {
  86     // constant format string
  87     result = format;
  88     result_len = strlen(result);
  89     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
  90   } else if (format[0] == '%' && format[1] == 's' && format[2] == '\0') {
  91     // trivial copy-through format string
  92     result = va_arg(ap, const char*);
  93     result_len = strlen(result);
  94     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
  95   } else {
  96     // Handle truncation:
  97     // posix: upon truncation, vsnprintf returns number of bytes which
  98     //   would have been written (excluding terminating zero) had the buffer
  99     //   been large enough
 100     // windows: upon truncation, vsnprintf returns -1
 101     const int written = vsnprintf(buffer, buflen, format, ap);
 102     result = buffer;
 103     if (written < (int) buflen && written >= 0) {
 104       result_len = written;
 105     } else {
 106       DEBUG_ONLY(warning("increase O_BUFLEN in ostream.hpp -- output truncated");)
 107       result_len = buflen - 1;
 108       buffer[result_len] = 0;
 109     }
 110   }
 111   if (add_cr) {
 112     if (result != buffer) {
 113       memcpy(buffer, result, result_len);
 114       result = buffer;
 115     }
 116     buffer[result_len++] = '\n';
 117     buffer[result_len] = 0;
 118   }
 119   return result;
 120 }
 121 
 122 void outputStream::print(const char* format, ...) {
 123   char buffer[O_BUFLEN];
 124   va_list ap;
 125   va_start(ap, format);
 126   size_t len;
 127   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, false, len);
 128   write(str, len);
 129   va_end(ap);
 130 }
 131 
 132 void outputStream::print_cr(const char* format, ...) {
 133   char buffer[O_BUFLEN];
 134   va_list ap;
 135   va_start(ap, format);
 136   size_t len;
 137   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, true, len);
 138   write(str, len);
 139   va_end(ap);
 140 }
 141 
 142 void outputStream::vprint(const char *format, va_list argptr) {
 143   char buffer[O_BUFLEN];
 144   size_t len;
 145   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, false, len);
 146   write(str, len);
 147 }
 148 
 149 void outputStream::vprint_cr(const char* format, va_list argptr) {
 150   char buffer[O_BUFLEN];
 151   size_t len;
 152   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, true, len);
 153   write(str, len);
 154 }
 155 
 156 void outputStream::fill_to(int col) {
 157   int need_fill = col - position();
 158   sp(need_fill);
 159 }
 160 
 161 void outputStream::move_to(int col, int slop, int min_space) {
 162   if (position() >= col + slop)
 163     cr();
 164   int need_fill = col - position();
 165   if (need_fill < min_space)
 166     need_fill = min_space;
 167   sp(need_fill);
 168 }
 169 
 170 void outputStream::put(char ch) {
 171   assert(ch != 0, "please fix call site");
 172   char buf[] = { ch, '\0' };
 173   write(buf, 1);
 174 }
 175 
 176 #define SP_USE_TABS false
 177 
 178 void outputStream::sp(int count) {
 179   if (count < 0)  return;
 180   if (SP_USE_TABS && count >= 8) {
 181     int target = position() + count;
 182     while (count >= 8) {
 183       this->write("\t", 1);
 184       count -= 8;
 185     }
 186     count = target - position();
 187   }
 188   while (count > 0) {
 189     int nw = (count > 8) ? 8 : count;
 190     this->write("        ", nw);
 191     count -= nw;
 192   }
 193 }
 194 
 195 void outputStream::cr() {
 196   this->write("\n", 1);
 197 }
 198 
 199 void outputStream::stamp() {
 200   if (! _stamp.is_updated()) {
 201     _stamp.update(); // start at 0 on first call to stamp()
 202   }
 203 
 204   // outputStream::stamp() may get called by ostream_abort(), use snprintf
 205   // to avoid allocating large stack buffer in print().
 206   char buf[40];
 207   jio_snprintf(buf, sizeof(buf), "%.3f", _stamp.seconds());
 208   print_raw(buf);
 209 }
 210 
 211 void outputStream::stamp(bool guard,
 212                          const char* prefix,
 213                          const char* suffix) {
 214   if (!guard) {
 215     return;
 216   }
 217   print_raw(prefix);
 218   stamp();
 219   print_raw(suffix);
 220 }
 221 
 222 void outputStream::date_stamp(bool guard,
 223                               const char* prefix,
 224                               const char* suffix) {
 225   if (!guard) {
 226     return;
 227   }
 228   print_raw(prefix);
 229   static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz";
 230   static const int buffer_length = 32;
 231   char buffer[buffer_length];
 232   const char* iso8601_result = os::iso8601_time(buffer, buffer_length);
 233   if (iso8601_result != NULL) {
 234     print_raw(buffer);
 235   } else {
 236     print_raw(error_time);
 237   }
 238   print_raw(suffix);
 239   return;
 240 }
 241 
 242 void outputStream::gclog_stamp() {
 243   date_stamp(PrintGCDateStamps);
 244   stamp(PrintGCTimeStamps);
 245   if (PrintGCID) {
 246     print("#%u: ", GCId::current());
 247   }
 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");
 337       buffer = NEW_RESOURCE_ARRAY(char, end);
 338       if (buffer_pos > 0) {
 339         memcpy(buffer, oldbuf, buffer_pos);
 340       }
 341       buffer_length = end;
 342     }
 343   }
 344   // invariant: buffer is always null-terminated
 345   guarantee(buffer_pos + write_len + 1 <= buffer_length, "stringStream oob");
 346   if (write_len > 0) {
 347     buffer[buffer_pos + write_len] = 0;
 348     memcpy(buffer + buffer_pos, s, write_len);
 349     buffer_pos += write_len;
 350   }
 351 
 352   // Note that the following does not depend on write_len.
 353   // This means that position and count get updated
 354   // even when overflow occurs.
 355   update_position(s, len);
 356 }
 357 
 358 char* stringStream::as_string() {
 359   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos + 1);
 360   strncpy(copy, buffer, buffer_pos);
 361   copy[buffer_pos] = 0;  // terminating null
 362   return copy;
 363 }
 364 
 365 stringStream::~stringStream() {}
 366 
 367 xmlStream*   xtty;
 368 outputStream* tty;
 369 outputStream* gclog_or_tty;
 370 CDS_ONLY(fileStream* classlist_file;) // Only dump the classes that can be stored into the CDS archive
 371 extern Mutex* tty_lock;
 372 
 373 #define EXTRACHARLEN   32
 374 #define CURRENTAPPX    ".current"
 375 // convert YYYY-MM-DD HH:MM:SS to YYYY-MM-DD_HH-MM-SS
 376 char* get_datetime_string(char *buf, size_t len) {
 377   os::local_time_string(buf, len);
 378   int i = (int)strlen(buf);
 379   while (i-- >= 0) {
 380     if (buf[i] == ' ') buf[i] = '_';
 381     else if (buf[i] == ':') buf[i] = '-';
 382   }
 383   return buf;
 384 }
 385 
 386 static const char* make_log_name_internal(const char* log_name, const char* force_directory,
 387                                                 int pid, const char* tms) {
 388   const char* basename = log_name;
 389   char file_sep = os::file_separator()[0];
 390   const char* cp;
 391   char  pid_text[32];
 392 
 393   for (cp = log_name; *cp != '\0'; cp++) {
 394     if (*cp == '/' || *cp == file_sep) {
 395       basename = cp + 1;
 396     }
 397   }
 398   const char* nametail = log_name;
 399   // Compute buffer length
 400   size_t buffer_length;
 401   if (force_directory != NULL) {
 402     buffer_length = strlen(force_directory) + strlen(os::file_separator()) +
 403                     strlen(basename) + 1;
 404   } else {
 405     buffer_length = strlen(log_name) + 1;
 406   }
 407 
 408   const char* pts = strstr(basename, "%p");
 409   int pid_pos = (pts == NULL) ? -1 : (pts - nametail);
 410 
 411   if (pid_pos >= 0) {
 412     jio_snprintf(pid_text, sizeof(pid_text), "pid%u", pid);
 413     buffer_length += strlen(pid_text);
 414   }
 415 
 416   pts = strstr(basename, "%t");
 417   int tms_pos = (pts == NULL) ? -1 : (pts - nametail);
 418   if (tms_pos >= 0) {
 419     buffer_length += strlen(tms);
 420   }
 421 
 422   // File name is too long.
 423   if (buffer_length > JVM_MAXPATHLEN) {
 424     return NULL;
 425   }
 426 
 427   // Create big enough buffer.
 428   char *buf = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
 429 
 430   strcpy(buf, "");
 431   if (force_directory != NULL) {
 432     strcat(buf, force_directory);
 433     strcat(buf, os::file_separator());
 434     nametail = basename;       // completely skip directory prefix
 435   }
 436 
 437   // who is first, %p or %t?
 438   int first = -1, second = -1;
 439   const char *p1st = NULL;
 440   const char *p2nd = NULL;
 441 
 442   if (pid_pos >= 0 && tms_pos >= 0) {
 443     // contains both %p and %t
 444     if (pid_pos < tms_pos) {
 445       // case foo%pbar%tmonkey.log
 446       first  = pid_pos;
 447       p1st   = pid_text;
 448       second = tms_pos;
 449       p2nd   = tms;
 450     } else {
 451       // case foo%tbar%pmonkey.log
 452       first  = tms_pos;
 453       p1st   = tms;
 454       second = pid_pos;
 455       p2nd   = pid_text;
 456     }
 457   } else if (pid_pos >= 0) {
 458     // contains %p only
 459     first  = pid_pos;
 460     p1st   = pid_text;
 461   } else if (tms_pos >= 0) {
 462     // contains %t only
 463     first  = tms_pos;
 464     p1st   = tms;
 465   }
 466 
 467   int buf_pos = (int)strlen(buf);
 468   const char* tail = nametail;
 469 
 470   if (first >= 0) {
 471     tail = nametail + first + 2;
 472     strncpy(&buf[buf_pos], nametail, first);
 473     strcpy(&buf[buf_pos + first], p1st);
 474     buf_pos = (int)strlen(buf);
 475     if (second >= 0) {
 476       strncpy(&buf[buf_pos], tail, second - first - 2);
 477       strcpy(&buf[buf_pos + second - first - 2], p2nd);
 478       tail = nametail + second + 2;
 479     }
 480   }
 481   strcat(buf, tail);      // append rest of name, or all of name
 482   return buf;
 483 }
 484 
 485 // log_name comes from -XX:LogFile=log_name, -Xloggc:log_name or
 486 // -XX:DumpLoadedClassList=<file_name>
 487 // in log_name, %p => pid1234 and
 488 //              %t => YYYY-MM-DD_HH-MM-SS
 489 static const char* make_log_name(const char* log_name, const char* force_directory) {
 490   char timestr[32];
 491   get_datetime_string(timestr, sizeof(timestr));
 492   return make_log_name_internal(log_name, force_directory, os::current_process_id(),
 493                                 timestr);
 494 }
 495 
 496 #ifndef PRODUCT
 497 void test_loggc_filename() {
 498   int pid;
 499   char  tms[32];
 500   char  i_result[JVM_MAXPATHLEN];
 501   const char* o_result;
 502   get_datetime_string(tms, sizeof(tms));
 503   pid = os::current_process_id();
 504 
 505   // test.log
 506   jio_snprintf(i_result, JVM_MAXPATHLEN, "test.log", tms);
 507   o_result = make_log_name_internal("test.log", NULL, pid, tms);
 508   assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test.log\", NULL)");
 509   FREE_C_HEAP_ARRAY(char, o_result);
 510 
 511   // test-%t-%p.log
 512   jio_snprintf(i_result, JVM_MAXPATHLEN, "test-%s-pid%u.log", tms, pid);
 513   o_result = make_log_name_internal("test-%t-%p.log", NULL, pid, tms);
 514   assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test-%%t-%%p.log\", NULL)");
 515   FREE_C_HEAP_ARRAY(char, o_result);
 516 
 517   // test-%t%p.log
 518   jio_snprintf(i_result, JVM_MAXPATHLEN, "test-%spid%u.log", tms, pid);
 519   o_result = make_log_name_internal("test-%t%p.log", NULL, pid, tms);
 520   assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test-%%t%%p.log\", NULL)");
 521   FREE_C_HEAP_ARRAY(char, o_result);
 522 
 523   // %p%t.log
 524   jio_snprintf(i_result, JVM_MAXPATHLEN, "pid%u%s.log", pid, tms);
 525   o_result = make_log_name_internal("%p%t.log", NULL, pid, tms);
 526   assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%p%%t.log\", NULL)");
 527   FREE_C_HEAP_ARRAY(char, o_result);
 528 
 529   // %p-test.log
 530   jio_snprintf(i_result, JVM_MAXPATHLEN, "pid%u-test.log", pid);
 531   o_result = make_log_name_internal("%p-test.log", NULL, pid, tms);
 532   assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%p-test.log\", NULL)");
 533   FREE_C_HEAP_ARRAY(char, o_result);
 534 
 535   // %t.log
 536   jio_snprintf(i_result, JVM_MAXPATHLEN, "%s.log", tms);
 537   o_result = make_log_name_internal("%t.log", NULL, pid, tms);
 538   assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%t.log\", NULL)");
 539   FREE_C_HEAP_ARRAY(char, o_result);
 540 
 541   {
 542     // longest filename
 543     char longest_name[JVM_MAXPATHLEN];
 544     memset(longest_name, 'a', sizeof(longest_name));
 545     longest_name[JVM_MAXPATHLEN - 1] = '\0';
 546     o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms);
 547     assert(strcmp(longest_name, o_result) == 0, "longest name does not match. expected '%s' but got '%s'", longest_name, o_result);
 548     FREE_C_HEAP_ARRAY(char, o_result);
 549   }
 550 
 551   {
 552     // too long file name
 553     char too_long_name[JVM_MAXPATHLEN + 100];
 554     int too_long_length = sizeof(too_long_name);
 555     memset(too_long_name, 'a', too_long_length);
 556     too_long_name[too_long_length - 1] = '\0';
 557     o_result = make_log_name_internal((const char*)&too_long_name, NULL, pid, tms);
 558     assert(o_result == NULL, "Too long file name should return NULL, but got '%s'", o_result);
 559   }
 560 
 561   {
 562     // too long with timestamp
 563     char longest_name[JVM_MAXPATHLEN];
 564     memset(longest_name, 'a', JVM_MAXPATHLEN);
 565     longest_name[JVM_MAXPATHLEN - 3] = '%';
 566     longest_name[JVM_MAXPATHLEN - 2] = 't';
 567     longest_name[JVM_MAXPATHLEN - 1] = '\0';
 568     o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms);
 569     assert(o_result == NULL, "Too long file name after timestamp expansion should return NULL, but got '%s'", o_result);
 570   }
 571 
 572   {
 573     // too long with pid
 574     char longest_name[JVM_MAXPATHLEN];
 575     memset(longest_name, 'a', JVM_MAXPATHLEN);
 576     longest_name[JVM_MAXPATHLEN - 3] = '%';
 577     longest_name[JVM_MAXPATHLEN - 2] = 'p';
 578     longest_name[JVM_MAXPATHLEN - 1] = '\0';
 579     o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms);
 580     assert(o_result == NULL, "Too long file name after pid expansion should return NULL, but got '%s'", o_result);
 581   }
 582 }
 583 #endif // PRODUCT
 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, 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, 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 // dump vm version, os version, platform info, build id,
 664 // memory usage and command line flags into header
 665 void gcLogFileStream::dump_loggc_header() {
 666   if (is_open()) {
 667     print_cr("%s", Abstract_VM_Version::internal_vm_info_string());
 668     os::print_memory_info(this);
 669     print("CommandLine flags: ");
 670     CommandLineFlags::printSetFlags(this);
 671   }
 672 }
 673 
 674 gcLogFileStream::~gcLogFileStream() {
 675   if (_file != NULL) {
 676     if (_need_close) fclose(_file);
 677     _file = NULL;
 678   }
 679   if (_file_name != NULL) {
 680     FREE_C_HEAP_ARRAY(char, _file_name);
 681     _file_name = NULL;
 682   }
 683 }
 684 
 685 gcLogFileStream::gcLogFileStream(const char* file_name) {
 686   _cur_file_num = 0;
 687   _bytes_written = 0L;
 688   _file_name = make_log_name(file_name, NULL);
 689 
 690   if (_file_name == NULL) {
 691     warning("Cannot open file %s: file name is too long.\n", file_name);
 692     _need_close = false;
 693     UseGCLogFileRotation = false;
 694     return;
 695   }
 696 
 697   // gc log file rotation
 698   if (UseGCLogFileRotation && NumberOfGCLogFiles > 1) {
 699     char tempbuf[JVM_MAXPATHLEN];
 700     jio_snprintf(tempbuf, sizeof(tempbuf), "%s.%d" CURRENTAPPX, _file_name, _cur_file_num);
 701     _file = fopen(tempbuf, "w");
 702   } else {
 703     _file = fopen(_file_name, "w");
 704   }
 705   if (_file != NULL) {
 706     _need_close = true;
 707     dump_loggc_header();
 708   } else {
 709     warning("Cannot open file %s due to %s\n", _file_name, strerror(errno));
 710     _need_close = false;
 711   }
 712 }
 713 
 714 void gcLogFileStream::write(const char* s, size_t len) {
 715   if (_file != NULL) {
 716     size_t count = fwrite(s, 1, len, _file);
 717     _bytes_written += count;
 718   }
 719   update_position(s, len);
 720 }
 721 
 722 // rotate_log must be called from VMThread at safepoint. In case need change parameters
 723 // for gc log rotation from thread other than VMThread, a sub type of VM_Operation
 724 // should be created and be submitted to VMThread's operation queue. DO NOT call this
 725 // function directly. Currently, it is safe to rotate log at safepoint through VMThread.
 726 // That is, no mutator threads and concurrent GC threads run parallel with VMThread to
 727 // write to gc log file at safepoint. If in future, changes made for mutator threads or
 728 // concurrent GC threads to run parallel with VMThread at safepoint, write and rotate_log
 729 // must be synchronized.
 730 void gcLogFileStream::rotate_log(bool force, outputStream* out) {
 731   char time_msg[O_BUFLEN];
 732   char time_str[EXTRACHARLEN];
 733   char current_file_name[JVM_MAXPATHLEN];
 734   char renamed_file_name[JVM_MAXPATHLEN];
 735 
 736   if (!should_rotate(force)) {
 737     return;
 738   }
 739 
 740 #ifdef ASSERT
 741   Thread *thread = Thread::current();
 742   assert(thread == NULL ||
 743          (thread->is_VM_thread() && SafepointSynchronize::is_at_safepoint()),
 744          "Must be VMThread at safepoint");
 745 #endif
 746   if (NumberOfGCLogFiles == 1) {
 747     // rotate in same file
 748     rewind();
 749     _bytes_written = 0L;
 750     jio_snprintf(time_msg, sizeof(time_msg), "File  %s rotated at %s\n",
 751                  _file_name, os::local_time_string((char *)time_str, sizeof(time_str)));
 752     write(time_msg, strlen(time_msg));
 753 
 754     if (out != NULL) {
 755       out->print("%s", time_msg);
 756     }
 757 
 758     dump_loggc_header();
 759     return;
 760   }
 761 
 762 #if defined(_WINDOWS)
 763 #ifndef F_OK
 764 #define F_OK 0
 765 #endif
 766 #endif // _WINDOWS
 767 
 768   // rotate file in names extended_filename.0, extended_filename.1, ...,
 769   // extended_filename.<NumberOfGCLogFiles - 1>. Current rotation file name will
 770   // have a form of extended_filename.<i>.current where i is the current rotation
 771   // file number. After it reaches max file size, the file will be saved and renamed
 772   // with .current removed from its tail.
 773   if (_file != NULL) {
 774     jio_snprintf(renamed_file_name, JVM_MAXPATHLEN, "%s.%d",
 775                  _file_name, _cur_file_num);
 776     int result = jio_snprintf(current_file_name, JVM_MAXPATHLEN,
 777                               "%s.%d" CURRENTAPPX, _file_name, _cur_file_num);
 778     if (result >= JVM_MAXPATHLEN) {
 779       warning("Cannot create new log file name: %s: file name is too long.\n", current_file_name);
 780       return;
 781     }
 782 
 783     const char* msg = force ? "GC log rotation request has been received."
 784                             : "GC log file has reached the maximum size.";
 785     jio_snprintf(time_msg, sizeof(time_msg), "%s %s Saved as %s\n",
 786                      os::local_time_string((char *)time_str, sizeof(time_str)),
 787                                                          msg, renamed_file_name);
 788     write(time_msg, strlen(time_msg));
 789 
 790     if (out != NULL) {
 791       out->print("%s", time_msg);
 792     }
 793 
 794     fclose(_file);
 795     _file = NULL;
 796 
 797     bool can_rename = true;
 798     if (access(current_file_name, F_OK) != 0) {
 799       // current file does not exist?
 800       warning("No source file exists, cannot rename\n");
 801       can_rename = false;
 802     }
 803     if (can_rename) {
 804       if (access(renamed_file_name, F_OK) == 0) {
 805         if (remove(renamed_file_name) != 0) {
 806           warning("Could not delete existing file %s\n", renamed_file_name);
 807           can_rename = false;
 808         }
 809       } else {
 810         // file does not exist, ok to rename
 811       }
 812     }
 813     if (can_rename && rename(current_file_name, renamed_file_name) != 0) {
 814       warning("Could not rename %s to %s\n", _file_name, renamed_file_name);
 815     }
 816   }
 817 
 818   _cur_file_num++;
 819   if (_cur_file_num > NumberOfGCLogFiles - 1) _cur_file_num = 0;
 820   int result = jio_snprintf(current_file_name,  JVM_MAXPATHLEN, "%s.%d" CURRENTAPPX,
 821                _file_name, _cur_file_num);
 822   if (result >= JVM_MAXPATHLEN) {
 823     warning("Cannot create new log file name: %s: file name is too long.\n", current_file_name);
 824     return;
 825   }
 826 
 827   _file = fopen(current_file_name, "w");
 828 
 829   if (_file != NULL) {
 830     _bytes_written = 0L;
 831     _need_close = true;
 832     // reuse current_file_name for time_msg
 833     jio_snprintf(current_file_name, JVM_MAXPATHLEN,
 834                  "%s.%d", _file_name, _cur_file_num);
 835     jio_snprintf(time_msg, sizeof(time_msg), "%s GC log file created %s\n",
 836                  os::local_time_string((char *)time_str, sizeof(time_str)), current_file_name);
 837     write(time_msg, strlen(time_msg));
 838 
 839     if (out != NULL) {
 840       out->print("%s", time_msg);
 841     }
 842 
 843     dump_loggc_header();
 844     // remove the existing file
 845     if (access(current_file_name, F_OK) == 0) {
 846       if (remove(current_file_name) != 0) {
 847         warning("Could not delete existing file %s\n", current_file_name);
 848       }
 849     }
 850   } else {
 851     warning("failed to open rotation log file %s due to %s\n"
 852             "Turned off GC log file rotation\n",
 853                   _file_name, strerror(errno));
 854     _need_close = false;
 855     FLAG_SET_DEFAULT(UseGCLogFileRotation, false);
 856   }
 857 }
 858 
 859 defaultStream* defaultStream::instance = NULL;
 860 int defaultStream::_output_fd = 1;
 861 int defaultStream::_error_fd  = 2;
 862 FILE* defaultStream::_output_stream = stdout;
 863 FILE* defaultStream::_error_stream  = stderr;
 864 
 865 #define LOG_MAJOR_VERSION 160
 866 #define LOG_MINOR_VERSION 1
 867 
 868 void defaultStream::init() {
 869   _inited = true;
 870   if (LogVMOutput || LogCompilation) {
 871     init_log();
 872   }
 873 }
 874 
 875 bool defaultStream::has_log_file() {
 876   // lazily create log file (at startup, LogVMOutput is false even
 877   // if +LogVMOutput is used, because the flags haven't been parsed yet)
 878   // For safer printing during fatal error handling, do not init logfile
 879   // if a VM error has been reported.
 880   if (!_inited && !is_error_reported())  init();
 881   return _log_file != NULL;
 882 }
 883 
 884 fileStream* defaultStream::open_file(const char* log_name) {
 885   const char* try_name = make_log_name(log_name, NULL);
 886   if (try_name == NULL) {
 887     warning("Cannot open file %s: file name is too long.\n", log_name);
 888     return NULL;
 889   }
 890 
 891   fileStream* file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name);
 892   FREE_C_HEAP_ARRAY(char, try_name);
 893   if (file->is_open()) {
 894     return file;
 895   }
 896 
 897   // Try again to open the file in the temp directory.
 898   delete file;
 899   char warnbuf[O_BUFLEN*2];
 900   jio_snprintf(warnbuf, sizeof(warnbuf), "Warning:  Cannot open log file: %s\n", log_name);
 901   // Note:  This feature is for maintainer use only.  No need for L10N.
 902   jio_print(warnbuf);
 903   try_name = make_log_name(log_name, os::get_temp_directory());
 904   if (try_name == NULL) {
 905     warning("Cannot open file %s: file name is too long for directory %s.\n", log_name, os::get_temp_directory());
 906     return NULL;
 907   }
 908 
 909   jio_snprintf(warnbuf, sizeof(warnbuf),
 910                "Warning:  Forcing option -XX:LogFile=%s\n", try_name);
 911   jio_print(warnbuf);
 912 
 913   file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name);
 914   FREE_C_HEAP_ARRAY(char, try_name);
 915   if (file->is_open()) {
 916     return file;
 917   }
 918 
 919   delete file;
 920   return NULL;
 921 }
 922 
 923 void defaultStream::init_log() {
 924   // %%% Need a MutexLocker?
 925   const char* log_name = LogFile != NULL ? LogFile : "hotspot_%p.log";
 926   fileStream* file = open_file(log_name);
 927 
 928   if (file != NULL) {
 929     _log_file = file;
 930     _outer_xmlStream = new(ResourceObj::C_HEAP, mtInternal) xmlStream(file);
 931     start_log();
 932   } else {
 933     // and leave xtty as NULL
 934     LogVMOutput = false;
 935     DisplayVMOutput = true;
 936     LogCompilation = false;
 937   }
 938 }
 939 
 940 void defaultStream::start_log() {
 941   xmlStream*xs = _outer_xmlStream;
 942     if (this == tty)  xtty = xs;
 943     // Write XML header.
 944     xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
 945     // (For now, don't bother to issue a DTD for this private format.)
 946     jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
 947     // %%% Should be: jlong time_ms = os::start_time_milliseconds(), if
 948     // we ever get round to introduce that method on the os class
 949     xs->head("hotspot_log version='%d %d'"
 950              " process='%d' time_ms='" INT64_FORMAT "'",
 951              LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
 952              os::current_process_id(), (int64_t)time_ms);
 953     // Write VM version header immediately.
 954     xs->head("vm_version");
 955     xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr();
 956     xs->tail("name");
 957     xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr();
 958     xs->tail("release");
 959     xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr();
 960     xs->tail("info");
 961     xs->tail("vm_version");
 962     // Record information about the command-line invocation.
 963     xs->head("vm_arguments");  // Cf. Arguments::print_on()
 964     if (Arguments::num_jvm_flags() > 0) {
 965       xs->head("flags");
 966       Arguments::print_jvm_flags_on(xs->text());
 967       xs->tail("flags");
 968     }
 969     if (Arguments::num_jvm_args() > 0) {
 970       xs->head("args");
 971       Arguments::print_jvm_args_on(xs->text());
 972       xs->tail("args");
 973     }
 974     if (Arguments::java_command() != NULL) {
 975       xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command());
 976       xs->tail("command");
 977     }
 978     if (Arguments::sun_java_launcher() != NULL) {
 979       xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher());
 980       xs->tail("launcher");
 981     }
 982     if (Arguments::system_properties() !=  NULL) {
 983       xs->head("properties");
 984       // Print it as a java-style property list.
 985       // System properties don't generally contain newlines, so don't bother with unparsing.
 986       outputStream *text = xs->text();
 987       for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
 988         // Print in two stages to avoid problems with long
 989         // keys/values.
 990         text->print_raw(p->key());
 991         text->put('=');
 992         text->print_raw_cr(p->value());
 993       }
 994       xs->tail("properties");
 995     }
 996     xs->tail("vm_arguments");
 997     // tty output per se is grouped under the <tty>...</tty> element.
 998     xs->head("tty");
 999     // All further non-markup text gets copied to the tty:
1000     xs->_text = this;  // requires friend declaration!
1001 }
1002 
1003 // finish_log() is called during normal VM shutdown. finish_log_on_error() is
1004 // called by ostream_abort() after a fatal error.
1005 //
1006 void defaultStream::finish_log() {
1007   xmlStream* xs = _outer_xmlStream;
1008   xs->done("tty");
1009 
1010   // Other log forks are appended here, at the End of Time:
1011   CompileLog::finish_log(xs->out());  // write compile logging, if any, now
1012 
1013   xs->done("hotspot_log");
1014   xs->flush();
1015 
1016   fileStream* file = _log_file;
1017   _log_file = NULL;
1018 
1019   delete _outer_xmlStream;
1020   _outer_xmlStream = NULL;
1021 
1022   file->flush();
1023   delete file;
1024 }
1025 
1026 void defaultStream::finish_log_on_error(char *buf, int buflen) {
1027   xmlStream* xs = _outer_xmlStream;
1028 
1029   if (xs && xs->out()) {
1030 
1031     xs->done_raw("tty");
1032 
1033     // Other log forks are appended here, at the End of Time:
1034     CompileLog::finish_log_on_error(xs->out(), buf, buflen);  // write compile logging, if any, now
1035 
1036     xs->done_raw("hotspot_log");
1037     xs->flush();
1038 
1039     fileStream* file = _log_file;
1040     _log_file = NULL;
1041     _outer_xmlStream = NULL;
1042 
1043     if (file) {
1044       file->flush();
1045 
1046       // Can't delete or close the file because delete and fclose aren't
1047       // async-safe. We are about to die, so leave it to the kernel.
1048       // delete file;
1049     }
1050   }
1051 }
1052 
1053 intx defaultStream::hold(intx writer_id) {
1054   bool has_log = has_log_file();  // check before locking
1055   if (// impossible, but who knows?
1056       writer_id == NO_WRITER ||
1057 
1058       // bootstrap problem
1059       tty_lock == NULL ||
1060 
1061       // can't grab a lock if current Thread isn't set
1062       Thread::current() == NULL ||
1063 
1064       // developer hook
1065       !SerializeVMOutput ||
1066 
1067       // VM already unhealthy
1068       is_error_reported() ||
1069 
1070       // safepoint == global lock (for VM only)
1071       (SafepointSynchronize::is_synchronizing() &&
1072        Thread::current()->is_VM_thread())
1073       ) {
1074     // do not attempt to lock unless we know the thread and the VM is healthy
1075     return NO_WRITER;
1076   }
1077   if (_writer == writer_id) {
1078     // already held, no need to re-grab the lock
1079     return NO_WRITER;
1080   }
1081   tty_lock->lock_without_safepoint_check();
1082   // got the lock
1083   if (writer_id != _last_writer) {
1084     if (has_log) {
1085       _log_file->bol();
1086       // output a hint where this output is coming from:
1087       _log_file->print_cr("<writer thread='" UINTX_FORMAT "'/>", writer_id);
1088     }
1089     _last_writer = writer_id;
1090   }
1091   _writer = writer_id;
1092   return writer_id;
1093 }
1094 
1095 void defaultStream::release(intx holder) {
1096   if (holder == NO_WRITER) {
1097     // nothing to release:  either a recursive lock, or we scribbled (too bad)
1098     return;
1099   }
1100   if (_writer != holder) {
1101     return;  // already unlocked, perhaps via break_tty_lock_for_safepoint
1102   }
1103   _writer = NO_WRITER;
1104   tty_lock->unlock();
1105 }
1106 
1107 
1108 // Yuck:  jio_print does not accept char*/len.
1109 static void call_jio_print(const char* s, size_t len) {
1110   char buffer[O_BUFLEN+100];
1111   if (len > sizeof(buffer)-1) {
1112     warning("increase O_BUFLEN in ostream.cpp -- output truncated");
1113     len = sizeof(buffer)-1;
1114   }
1115   strncpy(buffer, s, len);
1116   buffer[len] = '\0';
1117   jio_print(buffer);
1118 }
1119 
1120 
1121 void defaultStream::write(const char* s, size_t len) {
1122   intx thread_id = os::current_thread_id();
1123   intx holder = hold(thread_id);
1124 
1125   if (DisplayVMOutput &&
1126       (_outer_xmlStream == NULL || !_outer_xmlStream->inside_attrs())) {
1127     // print to output stream. It can be redirected by a vfprintf hook
1128     if (s[len] == '\0') {
1129       jio_print(s);
1130     } else {
1131       call_jio_print(s, len);
1132     }
1133   }
1134 
1135   // print to log file
1136   if (has_log_file()) {
1137     int nl0 = _newlines;
1138     xmlTextStream::write(s, len);
1139     // flush the log file too, if there were any newlines
1140     if (nl0 != _newlines){
1141       flush();
1142     }
1143   } else {
1144     update_position(s, len);
1145   }
1146 
1147   release(holder);
1148 }
1149 
1150 intx ttyLocker::hold_tty() {
1151   if (defaultStream::instance == NULL)  return defaultStream::NO_WRITER;
1152   intx thread_id = os::current_thread_id();
1153   return defaultStream::instance->hold(thread_id);
1154 }
1155 
1156 void ttyLocker::release_tty(intx holder) {
1157   if (holder == defaultStream::NO_WRITER)  return;
1158   defaultStream::instance->release(holder);
1159 }
1160 
1161 bool ttyLocker::release_tty_if_locked() {
1162   intx thread_id = os::current_thread_id();
1163   if (defaultStream::instance->writer() == thread_id) {
1164     // release the lock and return true so callers know if was
1165     // previously held.
1166     release_tty(thread_id);
1167     return true;
1168   }
1169   return false;
1170 }
1171 
1172 void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
1173   if (defaultStream::instance != NULL &&
1174       defaultStream::instance->writer() == holder) {
1175     if (xtty != NULL) {
1176       xtty->print_cr("<!-- safepoint while printing -->");
1177     }
1178     defaultStream::instance->release(holder);
1179   }
1180   // (else there was no lock to break)
1181 }
1182 
1183 void ostream_init() {
1184   if (defaultStream::instance == NULL) {
1185     defaultStream::instance = new(ResourceObj::C_HEAP, mtInternal) defaultStream();
1186     tty = defaultStream::instance;
1187 
1188     // We want to ensure that time stamps in GC logs consider time 0
1189     // the time when the JVM is initialized, not the first time we ask
1190     // for a time stamp. So, here, we explicitly update the time stamp
1191     // of tty.
1192     tty->time_stamp().update_to(1);
1193   }
1194 }
1195 
1196 void ostream_init_log() {
1197   // For -Xloggc:<file> option - called in runtime/thread.cpp
1198   // Note : this must be called AFTER ostream_init()
1199 
1200   gclog_or_tty = tty; // default to tty
1201   if (Arguments::gc_log_filename() != NULL) {
1202     fileStream * gclog  = new(ResourceObj::C_HEAP, mtInternal)
1203                              gcLogFileStream(Arguments::gc_log_filename());
1204     if (gclog->is_open()) {
1205       // now we update the time stamp of the GC log to be synced up
1206       // with tty.
1207       gclog->time_stamp().update_to(tty->time_stamp().ticks());
1208     }
1209     gclog_or_tty = gclog;
1210   }
1211 
1212 #if INCLUDE_CDS
1213   // For -XX:DumpLoadedClassList=<file> option
1214   if (DumpLoadedClassList != NULL) {
1215     const char* list_name = make_log_name(DumpLoadedClassList, NULL);
1216     classlist_file = new(ResourceObj::C_HEAP, mtInternal)
1217                          fileStream(list_name);
1218     FREE_C_HEAP_ARRAY(char, list_name);
1219   }
1220 #endif
1221 
1222   // If we haven't lazily initialized the logfile yet, do it now,
1223   // to avoid the possibility of lazy initialization during a VM
1224   // crash, which can affect the stability of the fatal error handler.
1225   defaultStream::instance->has_log_file();
1226 }
1227 
1228 // ostream_exit() is called during normal VM exit to finish log files, flush
1229 // output and free resource.
1230 void ostream_exit() {
1231   static bool ostream_exit_called = false;
1232   if (ostream_exit_called)  return;
1233   ostream_exit_called = true;
1234 #if INCLUDE_CDS
1235   if (classlist_file != NULL) {
1236     delete classlist_file;
1237   }
1238 #endif
1239   if (gclog_or_tty != tty) {
1240       delete gclog_or_tty;
1241   }
1242   {
1243       // we temporaly disable PrintMallocFree here
1244       // as otherwise it'll lead to using of almost deleted
1245       // tty or defaultStream::instance in logging facility
1246       // of HeapFree(), see 6391258
1247       DEBUG_ONLY(FlagSetting fs(PrintMallocFree, false);)
1248       if (tty != defaultStream::instance) {
1249           delete tty;
1250       }
1251       if (defaultStream::instance != NULL) {
1252           delete defaultStream::instance;
1253       }
1254   }
1255   tty = NULL;
1256   xtty = NULL;
1257   gclog_or_tty = NULL;
1258   defaultStream::instance = NULL;
1259 }
1260 
1261 // ostream_abort() is called by os::abort() when VM is about to die.
1262 void ostream_abort() {
1263   // Here we can't delete gclog_or_tty and tty, just flush their output
1264   if (gclog_or_tty) gclog_or_tty->flush();
1265   if (tty) tty->flush();
1266 
1267   if (defaultStream::instance != NULL) {
1268     static char buf[4096];
1269     defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
1270   }
1271 }
1272 
1273 staticBufferStream::staticBufferStream(char* buffer, size_t buflen,
1274                                        outputStream *outer_stream) {
1275   _buffer = buffer;
1276   _buflen = buflen;
1277   _outer_stream = outer_stream;
1278   // compile task prints time stamp relative to VM start
1279   _stamp.update_to(1);
1280 }
1281 
1282 void staticBufferStream::write(const char* c, size_t len) {
1283   _outer_stream->print_raw(c, (int)len);
1284 }
1285 
1286 void staticBufferStream::flush() {
1287   _outer_stream->flush();
1288 }
1289 
1290 void staticBufferStream::print(const char* format, ...) {
1291   va_list ap;
1292   va_start(ap, format);
1293   size_t len;
1294   const char* str = do_vsnprintf(_buffer, _buflen, format, ap, false, len);
1295   write(str, len);
1296   va_end(ap);
1297 }
1298 
1299 void staticBufferStream::print_cr(const char* format, ...) {
1300   va_list ap;
1301   va_start(ap, format);
1302   size_t len;
1303   const char* str = do_vsnprintf(_buffer, _buflen, format, ap, true, len);
1304   write(str, len);
1305   va_end(ap);
1306 }
1307 
1308 void staticBufferStream::vprint(const char *format, va_list argptr) {
1309   size_t len;
1310   const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, false, len);
1311   write(str, len);
1312 }
1313 
1314 void staticBufferStream::vprint_cr(const char* format, va_list argptr) {
1315   size_t len;
1316   const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, true, len);
1317   write(str, len);
1318 }
1319 
1320 bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
1321   buffer_length = initial_size;
1322   buffer        = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
1323   buffer_pos    = 0;
1324   buffer_fixed  = false;
1325   buffer_max    = bufmax;
1326 }
1327 
1328 bufferedStream::bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax) : outputStream() {
1329   buffer_length = fixed_buffer_size;
1330   buffer        = fixed_buffer;
1331   buffer_pos    = 0;
1332   buffer_fixed  = true;
1333   buffer_max    = bufmax;
1334 }
1335 
1336 void bufferedStream::write(const char* s, size_t len) {
1337 
1338   if(buffer_pos + len > buffer_max) {
1339     flush();
1340   }
1341 
1342   size_t end = buffer_pos + len;
1343   if (end >= buffer_length) {
1344     if (buffer_fixed) {
1345       // if buffer cannot resize, silently truncate
1346       len = buffer_length - buffer_pos - 1;
1347     } else {
1348       // For small overruns, double the buffer.  For larger ones,
1349       // increase to the requested size.
1350       if (end < buffer_length * 2) {
1351         end = buffer_length * 2;
1352       }
1353       buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end, mtInternal);
1354       buffer_length = end;
1355     }
1356   }
1357   memcpy(buffer + buffer_pos, s, len);
1358   buffer_pos += len;
1359   update_position(s, len);
1360 }
1361 
1362 char* bufferedStream::as_string() {
1363   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
1364   strncpy(copy, buffer, buffer_pos);
1365   copy[buffer_pos] = 0;  // terminating null
1366   return copy;
1367 }
1368 
1369 bufferedStream::~bufferedStream() {
1370   if (!buffer_fixed) {
1371     FREE_C_HEAP_ARRAY(char, buffer);
1372   }
1373 }
1374 
1375 #ifndef PRODUCT
1376 
1377 #if defined(SOLARIS) || defined(LINUX) || defined(AIX) || defined(_ALLBSD_SOURCE)
1378 #include <sys/types.h>
1379 #include <sys/socket.h>
1380 #include <netinet/in.h>
1381 #include <arpa/inet.h>
1382 #endif
1383 
1384 // Network access
1385 networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
1386 
1387   _socket = -1;
1388 
1389   int result = os::socket(AF_INET, SOCK_STREAM, 0);
1390   if (result <= 0) {
1391     assert(false, "Socket could not be created!");
1392   } else {
1393     _socket = result;
1394   }
1395 }
1396 
1397 int networkStream::read(char *buf, size_t len) {
1398   return os::recv(_socket, buf, (int)len, 0);
1399 }
1400 
1401 void networkStream::flush() {
1402   if (size() != 0) {
1403     int result = os::raw_send(_socket, (char *)base(), size(), 0);
1404     assert(result != -1, "connection error");
1405     assert(result == (int)size(), "didn't send enough data");
1406   }
1407   reset();
1408 }
1409 
1410 networkStream::~networkStream() {
1411   close();
1412 }
1413 
1414 void networkStream::close() {
1415   if (_socket != -1) {
1416     flush();
1417     os::socket_close(_socket);
1418     _socket = -1;
1419   }
1420 }
1421 
1422 bool networkStream::connect(const char *ip, short port) {
1423 
1424   struct sockaddr_in server;
1425   server.sin_family = AF_INET;
1426   server.sin_port = htons(port);
1427 
1428   server.sin_addr.s_addr = inet_addr(ip);
1429   if (server.sin_addr.s_addr == (uint32_t)-1) {
1430     struct hostent* host = os::get_host_by_name((char*)ip);
1431     if (host != NULL) {
1432       memcpy(&server.sin_addr, host->h_addr_list[0], host->h_length);
1433     } else {
1434       return false;
1435     }
1436   }
1437 
1438 
1439   int result = os::connect(_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_in));
1440   return (result >= 0);
1441 }
1442 
1443 #endif
1444 
1445 void logStream::write(const char* s, size_t len) {
1446   if (len > 0 && s[len - 1] == '\n') {
1447     _current_line.write(s, len - 1);
1448     _log_func(_current_line.as_string());
1449     _current_line.reset();
1450   } else {
1451     _current_line.write(s, len);
1452   }
1453   update_position(s, len);
1454 }