src/share/vm/utilities/ostream.cpp

Fri, 10 Jun 2011 15:08:36 -0700

author
minqi
date
Fri, 10 Jun 2011 15:08:36 -0700
changeset 2964
2a241e764894
parent 2702
8010c8c623ac
child 3156
f08d439fab8c
permissions
-rw-r--r--

6941923: RFE: Handling large log files produced by long running Java Applications
Summary: supply optinal flags to realize gc log rotation
Reviewed-by: ysr, jwilhelm

     1 /*
     2  * Copyright (c) 1997, 2011, 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  */
    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
    43 extern "C" void jio_print(const char* s); // Declarationtion of jvm method
    45 outputStream::outputStream(int width) {
    46   _width       = width;
    47   _position    = 0;
    48   _newlines    = 0;
    49   _precount    = 0;
    50   _indentation = 0;
    51 }
    53 outputStream::outputStream(int width, bool has_time_stamps) {
    54   _width       = width;
    55   _position    = 0;
    56   _newlines    = 0;
    57   _precount    = 0;
    58   _indentation = 0;
    59   if (has_time_stamps)  _stamp.update();
    60 }
    62 void outputStream::update_position(const char* s, size_t len) {
    63   for (size_t i = 0; i < len; i++) {
    64     char ch = s[i];
    65     if (ch == '\n') {
    66       _newlines += 1;
    67       _precount += _position + 1;
    68       _position = 0;
    69     } else if (ch == '\t') {
    70       int tw = 8 - (_position & 7);
    71       _position += tw;
    72       _precount -= tw-1;  // invariant:  _precount + _position == total count
    73     } else {
    74       _position += 1;
    75     }
    76   }
    77 }
    79 // Execute a vsprintf, using the given buffer if necessary.
    80 // Return a pointer to the formatted string.
    81 const char* outputStream::do_vsnprintf(char* buffer, size_t buflen,
    82                                        const char* format, va_list ap,
    83                                        bool add_cr,
    84                                        size_t& result_len) {
    85   const char* result;
    86   if (add_cr)  buflen--;
    87   if (!strchr(format, '%')) {
    88     // constant format string
    89     result = format;
    90     result_len = strlen(result);
    91     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
    92   } else if (format[0] == '%' && format[1] == 's' && format[2] == '\0') {
    93     // trivial copy-through format string
    94     result = va_arg(ap, const char*);
    95     result_len = strlen(result);
    96     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
    97   } else if (vsnprintf(buffer, buflen, format, ap) >= 0) {
    98     result = buffer;
    99     result_len = strlen(result);
   100   } else {
   101     DEBUG_ONLY(warning("increase O_BUFLEN in ostream.hpp -- output truncated");)
   102     result = buffer;
   103     result_len = buflen - 1;
   104     buffer[result_len] = 0;
   105   }
   106   if (add_cr) {
   107     if (result != buffer) {
   108       strncpy(buffer, result, buflen);
   109       result = buffer;
   110     }
   111     buffer[result_len++] = '\n';
   112     buffer[result_len] = 0;
   113   }
   114   return result;
   115 }
   117 void outputStream::print(const char* format, ...) {
   118   char buffer[O_BUFLEN];
   119   va_list ap;
   120   va_start(ap, format);
   121   size_t len;
   122   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, false, len);
   123   write(str, len);
   124   va_end(ap);
   125 }
   127 void outputStream::print_cr(const char* format, ...) {
   128   char buffer[O_BUFLEN];
   129   va_list ap;
   130   va_start(ap, format);
   131   size_t len;
   132   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, true, len);
   133   write(str, len);
   134   va_end(ap);
   135 }
   137 void outputStream::vprint(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, false, len);
   141   write(str, len);
   142 }
   144 void outputStream::vprint_cr(const char* format, va_list argptr) {
   145   char buffer[O_BUFLEN];
   146   size_t len;
   147   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, true, len);
   148   write(str, len);
   149 }
   151 void outputStream::fill_to(int col) {
   152   int need_fill = col - position();
   153   sp(need_fill);
   154 }
   156 void outputStream::move_to(int col, int slop, int min_space) {
   157   if (position() >= col + slop)
   158     cr();
   159   int need_fill = col - position();
   160   if (need_fill < min_space)
   161     need_fill = min_space;
   162   sp(need_fill);
   163 }
   165 void outputStream::put(char ch) {
   166   assert(ch != 0, "please fix call site");
   167   char buf[] = { ch, '\0' };
   168   write(buf, 1);
   169 }
   171 #define SP_USE_TABS false
   173 void outputStream::sp(int count) {
   174   if (count < 0)  return;
   175   if (SP_USE_TABS && count >= 8) {
   176     int target = position() + count;
   177     while (count >= 8) {
   178       this->write("\t", 1);
   179       count -= 8;
   180     }
   181     count = target - position();
   182   }
   183   while (count > 0) {
   184     int nw = (count > 8) ? 8 : count;
   185     this->write("        ", nw);
   186     count -= nw;
   187   }
   188 }
   190 void outputStream::cr() {
   191   this->write("\n", 1);
   192 }
   194 void outputStream::stamp() {
   195   if (! _stamp.is_updated()) {
   196     _stamp.update(); // start at 0 on first call to stamp()
   197   }
   199   // outputStream::stamp() may get called by ostream_abort(), use snprintf
   200   // to avoid allocating large stack buffer in print().
   201   char buf[40];
   202   jio_snprintf(buf, sizeof(buf), "%.3f", _stamp.seconds());
   203   print_raw(buf);
   204 }
   206 void outputStream::stamp(bool guard,
   207                          const char* prefix,
   208                          const char* suffix) {
   209   if (!guard) {
   210     return;
   211   }
   212   print_raw(prefix);
   213   stamp();
   214   print_raw(suffix);
   215 }
   217 void outputStream::date_stamp(bool guard,
   218                               const char* prefix,
   219                               const char* suffix) {
   220   if (!guard) {
   221     return;
   222   }
   223   print_raw(prefix);
   224   static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz";
   225   static const int buffer_length = 32;
   226   char buffer[buffer_length];
   227   const char* iso8601_result = os::iso8601_time(buffer, buffer_length);
   228   if (iso8601_result != NULL) {
   229     print_raw(buffer);
   230   } else {
   231     print_raw(error_time);
   232   }
   233   print_raw(suffix);
   234   return;
   235 }
   237 void outputStream::indent() {
   238   while (_position < _indentation) sp();
   239 }
   241 void outputStream::print_jlong(jlong value) {
   242   // N.B. Same as INT64_FORMAT
   243   print(os::jlong_format_specifier(), value);
   244 }
   246 void outputStream::print_julong(julong value) {
   247   // N.B. Same as UINT64_FORMAT
   248   print(os::julong_format_specifier(), value);
   249 }
   251 stringStream::stringStream(size_t initial_size) : outputStream() {
   252   buffer_length = initial_size;
   253   buffer        = NEW_RESOURCE_ARRAY(char, buffer_length);
   254   buffer_pos    = 0;
   255   buffer_fixed  = false;
   256 }
   258 // useful for output to fixed chunks of memory, such as performance counters
   259 stringStream::stringStream(char* fixed_buffer, size_t fixed_buffer_size) : outputStream() {
   260   buffer_length = fixed_buffer_size;
   261   buffer        = fixed_buffer;
   262   buffer_pos    = 0;
   263   buffer_fixed  = true;
   264 }
   266 void stringStream::write(const char* s, size_t len) {
   267   size_t write_len = len;               // number of non-null bytes to write
   268   size_t end = buffer_pos + len + 1;    // position after write and final '\0'
   269   if (end > buffer_length) {
   270     if (buffer_fixed) {
   271       // if buffer cannot resize, silently truncate
   272       end = buffer_length;
   273       write_len = end - buffer_pos - 1; // leave room for the final '\0'
   274     } else {
   275       // For small overruns, double the buffer.  For larger ones,
   276       // increase to the requested size.
   277       if (end < buffer_length * 2) {
   278         end = buffer_length * 2;
   279       }
   280       char* oldbuf = buffer;
   281       buffer = NEW_RESOURCE_ARRAY(char, end);
   282       strncpy(buffer, oldbuf, buffer_pos);
   283       buffer_length = end;
   284     }
   285   }
   286   // invariant: buffer is always null-terminated
   287   guarantee(buffer_pos + write_len + 1 <= buffer_length, "stringStream oob");
   288   buffer[buffer_pos + write_len] = 0;
   289   strncpy(buffer + buffer_pos, s, write_len);
   290   buffer_pos += write_len;
   292   // Note that the following does not depend on write_len.
   293   // This means that position and count get updated
   294   // even when overflow occurs.
   295   update_position(s, len);
   296 }
   298 char* stringStream::as_string() {
   299   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
   300   strncpy(copy, buffer, buffer_pos);
   301   copy[buffer_pos] = 0;  // terminating null
   302   return copy;
   303 }
   305 stringStream::~stringStream() {}
   307 xmlStream*   xtty;
   308 outputStream* tty;
   309 outputStream* gclog_or_tty;
   310 extern Mutex* tty_lock;
   312 fileStream::fileStream(const char* file_name) {
   313   _file = fopen(file_name, "w");
   314   _need_close = true;
   315 }
   317 fileStream::fileStream(const char* file_name, const char* opentype) {
   318   _file = fopen(file_name, opentype);
   319   _need_close = true;
   320 }
   322 void fileStream::write(const char* s, size_t len) {
   323   if (_file != NULL)  {
   324     // Make an unused local variable to avoid warning from gcc 4.x compiler.
   325     size_t count = fwrite(s, 1, len, _file);
   326   }
   327   update_position(s, len);
   328 }
   330 long fileStream::fileSize() {
   331   long size = -1;
   332   if (_file != NULL) {
   333     long pos  = ::ftell(_file);
   334     if (::fseek(_file, 0, SEEK_END) == 0) {
   335       size = ::ftell(_file);
   336     }
   337     ::fseek(_file, pos, SEEK_SET);
   338   }
   339   return size;
   340 }
   342 char* fileStream::readln(char *data, int count ) {
   343   char * ret = ::fgets(data, count, _file);
   344   //Get rid of annoying \n char
   345   data[::strlen(data)-1] = '\0';
   346   return ret;
   347 }
   349 fileStream::~fileStream() {
   350   if (_file != NULL) {
   351     if (_need_close) fclose(_file);
   352     _file      = NULL;
   353   }
   354 }
   356 void fileStream::flush() {
   357   fflush(_file);
   358 }
   360 fdStream::fdStream(const char* file_name) {
   361   _fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
   362   _need_close = true;
   363 }
   365 fdStream::~fdStream() {
   366   if (_fd != -1) {
   367     if (_need_close) close(_fd);
   368     _fd = -1;
   369   }
   370 }
   372 void fdStream::write(const char* s, size_t len) {
   373   if (_fd != -1) {
   374     // Make an unused local variable to avoid warning from gcc 4.x compiler.
   375     size_t count = ::write(_fd, s, (int)len);
   376   }
   377   update_position(s, len);
   378 }
   380 rotatingFileStream::~rotatingFileStream() {
   381   if (_file != NULL) {
   382     if (_need_close) fclose(_file);
   383     _file      = NULL;
   384     FREE_C_HEAP_ARRAY(char, _file_name);
   385     _file_name = NULL;
   386   }
   387 }
   389 rotatingFileStream::rotatingFileStream(const char* file_name) {
   390   _cur_file_num = 0;
   391   _bytes_writen = 0L;
   392   _file_name = NEW_C_HEAP_ARRAY(char, strlen(file_name)+10);
   393   jio_snprintf(_file_name, strlen(file_name)+10, "%s.%d", file_name, _cur_file_num);
   394   _file = fopen(_file_name, "w");
   395   _need_close = true;
   396 }
   398 rotatingFileStream::rotatingFileStream(const char* file_name, const char* opentype) {
   399   _cur_file_num = 0;
   400   _bytes_writen = 0L;
   401   _file_name = NEW_C_HEAP_ARRAY(char, strlen(file_name)+10);
   402   jio_snprintf(_file_name, strlen(file_name)+10, "%s.%d", file_name, _cur_file_num);
   403   _file = fopen(_file_name, opentype);
   404   _need_close = true;
   405 }
   407 void rotatingFileStream::write(const char* s, size_t len) {
   408   if (_file != NULL)  {
   409     // Make an unused local variable to avoid warning from gcc 4.x compiler.
   410     size_t count = fwrite(s, 1, len, _file);
   411     Atomic::add((jlong)count, &_bytes_writen);
   412   }
   413   update_position(s, len);
   414 }
   416 // rotate_log must be called from VMThread at safepoint. In case need change parameters
   417 // for gc log rotation from thread other than VMThread, a sub type of VM_Operation
   418 // should be created and be submitted to VMThread's operation queue. DO NOT call this
   419 // function directly. Currently, it is safe to rotate log at safepoint through VMThread.
   420 // That is, no mutator threads and concurrent GC threads run parallel with VMThread to
   421 // write to gc log file at safepoint. If in future, changes made for mutator threads or
   422 // concurrent GC threads to run parallel with VMThread at safepoint, write and rotate_log
   423 // must be synchronized.
   424 void rotatingFileStream::rotate_log() {
   425   if (_bytes_writen < (jlong)GCLogFileSize) return;
   426 #ifdef ASSERT
   427   Thread *thread = Thread::current();
   428   assert(thread == NULL ||
   429          (thread->is_VM_thread() && SafepointSynchronize::is_at_safepoint()),
   430          "Must be VMThread at safepoint");
   431 #endif
   432   if (NumberOfGCLogFiles == 1) {
   433     // rotate in same file
   434     rewind();
   435     _bytes_writen = 0L;
   436     return;
   437   }
   439   // rotate file in names file.0, file.1, file.2, ..., file.<MaxGCLogFileNumbers-1>
   440   // close current file, rotate to next file
   441   if (_file != NULL) {
   442     _cur_file_num ++;
   443     if (_cur_file_num >= NumberOfGCLogFiles) _cur_file_num = 0;
   444     jio_snprintf(_file_name, strlen(Arguments::gc_log_filename()) + 10, "%s.%d",
   445              Arguments::gc_log_filename(), _cur_file_num);
   446     fclose(_file);
   447     _file = NULL;
   448   }
   449   _file = fopen(_file_name, "w");
   450   if (_file != NULL) {
   451     _bytes_writen = 0L;
   452     _need_close = true;
   453   } else {
   454     tty->print_cr("failed to open rotation log file %s due to %s\n",
   455                   _file_name, strerror(errno));
   456     _need_close = false;
   457   }
   458 }
   460 defaultStream* defaultStream::instance = NULL;
   461 int defaultStream::_output_fd = 1;
   462 int defaultStream::_error_fd  = 2;
   463 FILE* defaultStream::_output_stream = stdout;
   464 FILE* defaultStream::_error_stream  = stderr;
   466 #define LOG_MAJOR_VERSION 160
   467 #define LOG_MINOR_VERSION 1
   469 void defaultStream::init() {
   470   _inited = true;
   471   if (LogVMOutput || LogCompilation) {
   472     init_log();
   473   }
   474 }
   476 bool defaultStream::has_log_file() {
   477   // lazily create log file (at startup, LogVMOutput is false even
   478   // if +LogVMOutput is used, because the flags haven't been parsed yet)
   479   // For safer printing during fatal error handling, do not init logfile
   480   // if a VM error has been reported.
   481   if (!_inited && !is_error_reported())  init();
   482   return _log_file != NULL;
   483 }
   485 static const char* make_log_name(const char* log_name, const char* force_directory) {
   486   const char* basename = log_name;
   487   char file_sep = os::file_separator()[0];
   488   const char* cp;
   489   for (cp = log_name; *cp != '\0'; cp++) {
   490     if (*cp == '/' || *cp == file_sep) {
   491       basename = cp+1;
   492     }
   493   }
   494   const char* nametail = log_name;
   496   // Compute buffer length
   497   size_t buffer_length;
   498   if (force_directory != NULL) {
   499     buffer_length = strlen(force_directory) + strlen(os::file_separator()) +
   500                     strlen(basename) + 1;
   501   } else {
   502     buffer_length = strlen(log_name) + 1;
   503   }
   505   const char* star = strchr(basename, '*');
   506   int star_pos = (star == NULL) ? -1 : (star - nametail);
   507   int skip = 1;
   508   if (star == NULL) {
   509     // Try %p
   510     star = strstr(basename, "%p");
   511     if (star != NULL) {
   512       skip = 2;
   513     }
   514   }
   515   star_pos = (star == NULL) ? -1 : (star - nametail);
   517   char pid[32];
   518   if (star_pos >= 0) {
   519     jio_snprintf(pid, sizeof(pid), "%u", os::current_process_id());
   520     buffer_length += strlen(pid);
   521   }
   523   // Create big enough buffer.
   524   char *buf = NEW_C_HEAP_ARRAY(char, buffer_length);
   526   strcpy(buf, "");
   527   if (force_directory != NULL) {
   528     strcat(buf, force_directory);
   529     strcat(buf, os::file_separator());
   530     nametail = basename;       // completely skip directory prefix
   531   }
   533   if (star_pos >= 0) {
   534     // convert foo*bar.log or foo%pbar.log to foo123bar.log
   535     int buf_pos = (int) strlen(buf);
   536     strncpy(&buf[buf_pos], nametail, star_pos);
   537     strcpy(&buf[buf_pos + star_pos], pid);
   538     nametail += star_pos + skip;  // skip prefix and pid format
   539   }
   541   strcat(buf, nametail);      // append rest of name, or all of name
   542   return buf;
   543 }
   545 void defaultStream::init_log() {
   546   // %%% Need a MutexLocker?
   547   const char* log_name = LogFile != NULL ? LogFile : "hotspot.log";
   548   const char* try_name = make_log_name(log_name, NULL);
   549   fileStream* file = new(ResourceObj::C_HEAP) fileStream(try_name);
   550   if (!file->is_open()) {
   551     // Try again to open the file.
   552     char warnbuf[O_BUFLEN*2];
   553     jio_snprintf(warnbuf, sizeof(warnbuf),
   554                  "Warning:  Cannot open log file: %s\n", try_name);
   555     // Note:  This feature is for maintainer use only.  No need for L10N.
   556     jio_print(warnbuf);
   557     FREE_C_HEAP_ARRAY(char, try_name);
   558     try_name = make_log_name("hs_pid%p.log", os::get_temp_directory());
   559     jio_snprintf(warnbuf, sizeof(warnbuf),
   560                  "Warning:  Forcing option -XX:LogFile=%s\n", try_name);
   561     jio_print(warnbuf);
   562     delete file;
   563     file = new(ResourceObj::C_HEAP) fileStream(try_name);
   564     FREE_C_HEAP_ARRAY(char, try_name);
   565   }
   566   if (file->is_open()) {
   567     _log_file = file;
   568     xmlStream* xs = new(ResourceObj::C_HEAP) xmlStream(file);
   569     _outer_xmlStream = xs;
   570     if (this == tty)  xtty = xs;
   571     // Write XML header.
   572     xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
   573     // (For now, don't bother to issue a DTD for this private format.)
   574     jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
   575     // %%% Should be: jlong time_ms = os::start_time_milliseconds(), if
   576     // we ever get round to introduce that method on the os class
   577     xs->head("hotspot_log version='%d %d'"
   578              " process='%d' time_ms='"INT64_FORMAT"'",
   579              LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
   580              os::current_process_id(), time_ms);
   581     // Write VM version header immediately.
   582     xs->head("vm_version");
   583     xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr();
   584     xs->tail("name");
   585     xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr();
   586     xs->tail("release");
   587     xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr();
   588     xs->tail("info");
   589     xs->tail("vm_version");
   590     // Record information about the command-line invocation.
   591     xs->head("vm_arguments");  // Cf. Arguments::print_on()
   592     if (Arguments::num_jvm_flags() > 0) {
   593       xs->head("flags");
   594       Arguments::print_jvm_flags_on(xs->text());
   595       xs->tail("flags");
   596     }
   597     if (Arguments::num_jvm_args() > 0) {
   598       xs->head("args");
   599       Arguments::print_jvm_args_on(xs->text());
   600       xs->tail("args");
   601     }
   602     if (Arguments::java_command() != NULL) {
   603       xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command());
   604       xs->tail("command");
   605     }
   606     if (Arguments::sun_java_launcher() != NULL) {
   607       xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher());
   608       xs->tail("launcher");
   609     }
   610     if (Arguments::system_properties() !=  NULL) {
   611       xs->head("properties");
   612       // Print it as a java-style property list.
   613       // System properties don't generally contain newlines, so don't bother with unparsing.
   614       for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
   615         xs->text()->print_cr("%s=%s", p->key(), p->value());
   616       }
   617       xs->tail("properties");
   618     }
   619     xs->tail("vm_arguments");
   620     // tty output per se is grouped under the <tty>...</tty> element.
   621     xs->head("tty");
   622     // All further non-markup text gets copied to the tty:
   623     xs->_text = this;  // requires friend declaration!
   624   } else {
   625     delete(file);
   626     // and leave xtty as NULL
   627     LogVMOutput = false;
   628     DisplayVMOutput = true;
   629     LogCompilation = false;
   630   }
   631 }
   633 // finish_log() is called during normal VM shutdown. finish_log_on_error() is
   634 // called by ostream_abort() after a fatal error.
   635 //
   636 void defaultStream::finish_log() {
   637   xmlStream* xs = _outer_xmlStream;
   638   xs->done("tty");
   640   // Other log forks are appended here, at the End of Time:
   641   CompileLog::finish_log(xs->out());  // write compile logging, if any, now
   643   xs->done("hotspot_log");
   644   xs->flush();
   646   fileStream* file = _log_file;
   647   _log_file = NULL;
   649   delete _outer_xmlStream;
   650   _outer_xmlStream = NULL;
   652   file->flush();
   653   delete file;
   654 }
   656 void defaultStream::finish_log_on_error(char *buf, int buflen) {
   657   xmlStream* xs = _outer_xmlStream;
   659   if (xs && xs->out()) {
   661     xs->done_raw("tty");
   663     // Other log forks are appended here, at the End of Time:
   664     CompileLog::finish_log_on_error(xs->out(), buf, buflen);  // write compile logging, if any, now
   666     xs->done_raw("hotspot_log");
   667     xs->flush();
   669     fileStream* file = _log_file;
   670     _log_file = NULL;
   671     _outer_xmlStream = NULL;
   673     if (file) {
   674       file->flush();
   676       // Can't delete or close the file because delete and fclose aren't
   677       // async-safe. We are about to die, so leave it to the kernel.
   678       // delete file;
   679     }
   680   }
   681 }
   683 intx defaultStream::hold(intx writer_id) {
   684   bool has_log = has_log_file();  // check before locking
   685   if (// impossible, but who knows?
   686       writer_id == NO_WRITER ||
   688       // bootstrap problem
   689       tty_lock == NULL ||
   691       // can't grab a lock or call Thread::current() if TLS isn't initialized
   692       ThreadLocalStorage::thread() == NULL ||
   694       // developer hook
   695       !SerializeVMOutput ||
   697       // VM already unhealthy
   698       is_error_reported() ||
   700       // safepoint == global lock (for VM only)
   701       (SafepointSynchronize::is_synchronizing() &&
   702        Thread::current()->is_VM_thread())
   703       ) {
   704     // do not attempt to lock unless we know the thread and the VM is healthy
   705     return NO_WRITER;
   706   }
   707   if (_writer == writer_id) {
   708     // already held, no need to re-grab the lock
   709     return NO_WRITER;
   710   }
   711   tty_lock->lock_without_safepoint_check();
   712   // got the lock
   713   if (writer_id != _last_writer) {
   714     if (has_log) {
   715       _log_file->bol();
   716       // output a hint where this output is coming from:
   717       _log_file->print_cr("<writer thread='"INTX_FORMAT"'/>", writer_id);
   718     }
   719     _last_writer = writer_id;
   720   }
   721   _writer = writer_id;
   722   return writer_id;
   723 }
   725 void defaultStream::release(intx holder) {
   726   if (holder == NO_WRITER) {
   727     // nothing to release:  either a recursive lock, or we scribbled (too bad)
   728     return;
   729   }
   730   if (_writer != holder) {
   731     return;  // already unlocked, perhaps via break_tty_lock_for_safepoint
   732   }
   733   _writer = NO_WRITER;
   734   tty_lock->unlock();
   735 }
   738 // Yuck:  jio_print does not accept char*/len.
   739 static void call_jio_print(const char* s, size_t len) {
   740   char buffer[O_BUFLEN+100];
   741   if (len > sizeof(buffer)-1) {
   742     warning("increase O_BUFLEN in ostream.cpp -- output truncated");
   743     len = sizeof(buffer)-1;
   744   }
   745   strncpy(buffer, s, len);
   746   buffer[len] = '\0';
   747   jio_print(buffer);
   748 }
   751 void defaultStream::write(const char* s, size_t len) {
   752   intx thread_id = os::current_thread_id();
   753   intx holder = hold(thread_id);
   755   if (DisplayVMOutput &&
   756       (_outer_xmlStream == NULL || !_outer_xmlStream->inside_attrs())) {
   757     // print to output stream. It can be redirected by a vfprintf hook
   758     if (s[len] == '\0') {
   759       jio_print(s);
   760     } else {
   761       call_jio_print(s, len);
   762     }
   763   }
   765   // print to log file
   766   if (has_log_file()) {
   767     int nl0 = _newlines;
   768     xmlTextStream::write(s, len);
   769     // flush the log file too, if there were any newlines
   770     if (nl0 != _newlines){
   771       flush();
   772     }
   773   } else {
   774     update_position(s, len);
   775   }
   777   release(holder);
   778 }
   780 intx ttyLocker::hold_tty() {
   781   if (defaultStream::instance == NULL)  return defaultStream::NO_WRITER;
   782   intx thread_id = os::current_thread_id();
   783   return defaultStream::instance->hold(thread_id);
   784 }
   786 void ttyLocker::release_tty(intx holder) {
   787   if (holder == defaultStream::NO_WRITER)  return;
   788   defaultStream::instance->release(holder);
   789 }
   791 bool ttyLocker::release_tty_if_locked() {
   792   intx thread_id = os::current_thread_id();
   793   if (defaultStream::instance->writer() == thread_id) {
   794     // release the lock and return true so callers know if was
   795     // previously held.
   796     release_tty(thread_id);
   797     return true;
   798   }
   799   return false;
   800 }
   802 void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
   803   if (defaultStream::instance != NULL &&
   804       defaultStream::instance->writer() == holder) {
   805     if (xtty != NULL) {
   806       xtty->print_cr("<!-- safepoint while printing -->");
   807     }
   808     defaultStream::instance->release(holder);
   809   }
   810   // (else there was no lock to break)
   811 }
   813 void ostream_init() {
   814   if (defaultStream::instance == NULL) {
   815     defaultStream::instance = new(ResourceObj::C_HEAP) defaultStream();
   816     tty = defaultStream::instance;
   818     // We want to ensure that time stamps in GC logs consider time 0
   819     // the time when the JVM is initialized, not the first time we ask
   820     // for a time stamp. So, here, we explicitly update the time stamp
   821     // of tty.
   822     tty->time_stamp().update_to(1);
   823   }
   824 }
   826 void ostream_init_log() {
   827   // For -Xloggc:<file> option - called in runtime/thread.cpp
   828   // Note : this must be called AFTER ostream_init()
   830   gclog_or_tty = tty; // default to tty
   831   if (Arguments::gc_log_filename() != NULL) {
   832     fileStream * gclog  = UseGCLogFileRotation ?
   833                           new(ResourceObj::C_HEAP)
   834                              rotatingFileStream(Arguments::gc_log_filename()) :
   835                           new(ResourceObj::C_HEAP)
   836                              fileStream(Arguments::gc_log_filename());
   837     if (gclog->is_open()) {
   838       // now we update the time stamp of the GC log to be synced up
   839       // with tty.
   840       gclog->time_stamp().update_to(tty->time_stamp().ticks());
   841     }
   842     gclog_or_tty = gclog;
   843   }
   845   // If we haven't lazily initialized the logfile yet, do it now,
   846   // to avoid the possibility of lazy initialization during a VM
   847   // crash, which can affect the stability of the fatal error handler.
   848   defaultStream::instance->has_log_file();
   849 }
   851 // ostream_exit() is called during normal VM exit to finish log files, flush
   852 // output and free resource.
   853 void ostream_exit() {
   854   static bool ostream_exit_called = false;
   855   if (ostream_exit_called)  return;
   856   ostream_exit_called = true;
   857   if (gclog_or_tty != tty) {
   858       delete gclog_or_tty;
   859   }
   860   {
   861       // we temporaly disable PrintMallocFree here
   862       // as otherwise it'll lead to using of almost deleted
   863       // tty or defaultStream::instance in logging facility
   864       // of HeapFree(), see 6391258
   865       DEBUG_ONLY(FlagSetting fs(PrintMallocFree, false);)
   866       if (tty != defaultStream::instance) {
   867           delete tty;
   868       }
   869       if (defaultStream::instance != NULL) {
   870           delete defaultStream::instance;
   871       }
   872   }
   873   tty = NULL;
   874   xtty = NULL;
   875   gclog_or_tty = NULL;
   876   defaultStream::instance = NULL;
   877 }
   879 // ostream_abort() is called by os::abort() when VM is about to die.
   880 void ostream_abort() {
   881   // Here we can't delete gclog_or_tty and tty, just flush their output
   882   if (gclog_or_tty) gclog_or_tty->flush();
   883   if (tty) tty->flush();
   885   if (defaultStream::instance != NULL) {
   886     static char buf[4096];
   887     defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
   888   }
   889 }
   891 staticBufferStream::staticBufferStream(char* buffer, size_t buflen,
   892                                        outputStream *outer_stream) {
   893   _buffer = buffer;
   894   _buflen = buflen;
   895   _outer_stream = outer_stream;
   896   // compile task prints time stamp relative to VM start
   897   _stamp.update_to(1);
   898 }
   900 void staticBufferStream::write(const char* c, size_t len) {
   901   _outer_stream->print_raw(c, (int)len);
   902 }
   904 void staticBufferStream::flush() {
   905   _outer_stream->flush();
   906 }
   908 void staticBufferStream::print(const char* format, ...) {
   909   va_list ap;
   910   va_start(ap, format);
   911   size_t len;
   912   const char* str = do_vsnprintf(_buffer, _buflen, format, ap, false, len);
   913   write(str, len);
   914   va_end(ap);
   915 }
   917 void staticBufferStream::print_cr(const char* format, ...) {
   918   va_list ap;
   919   va_start(ap, format);
   920   size_t len;
   921   const char* str = do_vsnprintf(_buffer, _buflen, format, ap, true, len);
   922   write(str, len);
   923   va_end(ap);
   924 }
   926 void staticBufferStream::vprint(const char *format, va_list argptr) {
   927   size_t len;
   928   const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, false, len);
   929   write(str, len);
   930 }
   932 void staticBufferStream::vprint_cr(const char* format, va_list argptr) {
   933   size_t len;
   934   const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, true, len);
   935   write(str, len);
   936 }
   938 bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
   939   buffer_length = initial_size;
   940   buffer        = NEW_C_HEAP_ARRAY(char, buffer_length);
   941   buffer_pos    = 0;
   942   buffer_fixed  = false;
   943   buffer_max    = bufmax;
   944 }
   946 bufferedStream::bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax) : outputStream() {
   947   buffer_length = fixed_buffer_size;
   948   buffer        = fixed_buffer;
   949   buffer_pos    = 0;
   950   buffer_fixed  = true;
   951   buffer_max    = bufmax;
   952 }
   954 void bufferedStream::write(const char* s, size_t len) {
   956   if(buffer_pos + len > buffer_max) {
   957     flush();
   958   }
   960   size_t end = buffer_pos + len;
   961   if (end >= buffer_length) {
   962     if (buffer_fixed) {
   963       // if buffer cannot resize, silently truncate
   964       len = buffer_length - buffer_pos - 1;
   965     } else {
   966       // For small overruns, double the buffer.  For larger ones,
   967       // increase to the requested size.
   968       if (end < buffer_length * 2) {
   969         end = buffer_length * 2;
   970       }
   971       buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end);
   972       buffer_length = end;
   973     }
   974   }
   975   memcpy(buffer + buffer_pos, s, len);
   976   buffer_pos += len;
   977   update_position(s, len);
   978 }
   980 char* bufferedStream::as_string() {
   981   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
   982   strncpy(copy, buffer, buffer_pos);
   983   copy[buffer_pos] = 0;  // terminating null
   984   return copy;
   985 }
   987 bufferedStream::~bufferedStream() {
   988   if (!buffer_fixed) {
   989     FREE_C_HEAP_ARRAY(char, buffer);
   990   }
   991 }
   993 #ifndef PRODUCT
   995 #if defined(SOLARIS) || defined(LINUX)
   996 #include <sys/types.h>
   997 #include <sys/socket.h>
   998 #include <netinet/in.h>
   999 #include <arpa/inet.h>
  1000 #endif
  1002 // Network access
  1003 networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
  1005   _socket = -1;
  1007   int result = os::socket(AF_INET, SOCK_STREAM, 0);
  1008   if (result <= 0) {
  1009     assert(false, "Socket could not be created!");
  1010   } else {
  1011     _socket = result;
  1015 int networkStream::read(char *buf, size_t len) {
  1016   return os::recv(_socket, buf, (int)len, 0);
  1019 void networkStream::flush() {
  1020   if (size() != 0) {
  1021     int result = os::raw_send(_socket, (char *)base(), (int)size(), 0);
  1022     assert(result != -1, "connection error");
  1023     assert(result == (int)size(), "didn't send enough data");
  1025   reset();
  1028 networkStream::~networkStream() {
  1029   close();
  1032 void networkStream::close() {
  1033   if (_socket != -1) {
  1034     flush();
  1035     os::socket_close(_socket);
  1036     _socket = -1;
  1040 bool networkStream::connect(const char *ip, short port) {
  1042   struct sockaddr_in server;
  1043   server.sin_family = AF_INET;
  1044   server.sin_port = htons(port);
  1046   server.sin_addr.s_addr = inet_addr(ip);
  1047   if (server.sin_addr.s_addr == (uint32_t)-1) {
  1048     struct hostent* host = os::get_host_by_name((char*)ip);
  1049     if (host != NULL) {
  1050       memcpy(&server.sin_addr, host->h_addr_list[0], host->h_length);
  1051     } else {
  1052       return false;
  1057   int result = os::connect(_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_in));
  1058   return (result >= 0);
  1061 #endif

mercurial