src/share/vm/utilities/ostream.cpp

Thu, 05 Sep 2013 11:04:39 -0700

author
kvn
date
Thu, 05 Sep 2013 11:04:39 -0700
changeset 6462
e2722a66aba7
parent 6461
bdd155477289
child 6472
2b8e28fdf503
permissions
-rw-r--r--

Merge

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

mercurial