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