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