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