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