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