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