src/share/vm/utilities/ostream.cpp

Wed, 15 Apr 2020 15:19:07 +0200

author
shade
date
Wed, 15 Apr 2020 15:19:07 +0200
changeset 9906
0df63a32f7bb
parent 9904
4698900b8221
child 9920
3a3803a0c789
permissions
-rw-r--r--

8242788: Non-PCH build is broken after JDK-8191393
Reviewed-by: aph

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

mercurial