1 /*
   2  * Copyright (c) 1997, 2015, 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/shared/gcId.hpp"
  28 #include "gc/shared/gcId.hpp"
  29 #include "oops/oop.inline.hpp"
  30 #include "runtime/arguments.hpp"
  31 #include "runtime/os.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/top.hpp"
  37 #include "utilities/xmlstream.hpp"
  38 
  39 extern "C" void jio_print(const char* s); // Declarationtion of jvm method
  40 
  41 outputStream::outputStream(int width) {
  42   _width       = width;
  43   _position    = 0;
  44   _newlines    = 0;
  45   _precount    = 0;
  46   _indentation = 0;
  47 }
  48 
  49 outputStream::outputStream(int width, bool has_time_stamps) {
  50   _width       = width;
  51   _position    = 0;
  52   _newlines    = 0;
  53   _precount    = 0;
  54   _indentation = 0;
  55   if (has_time_stamps)  _stamp.update();
  56 }
  57 
  58 void outputStream::update_position(const char* s, size_t len) {
  59   for (size_t i = 0; i < len; i++) {
  60     char ch = s[i];
  61     if (ch == '\n') {
  62       _newlines += 1;
  63       _precount += _position + 1;
  64       _position = 0;
  65     } else if (ch == '\t') {
  66       int tw = 8 - (_position & 7);
  67       _position += tw;
  68       _precount -= tw-1;  // invariant:  _precount + _position == total count
  69     } else {
  70       _position += 1;
  71     }
  72   }
  73 }
  74 
  75 // Execute a vsprintf, using the given buffer if necessary.
  76 // Return a pointer to the formatted string.
  77 const char* outputStream::do_vsnprintf(char* buffer, size_t buflen,
  78                                        const char* format, va_list ap,
  79                                        bool add_cr,
  80                                        size_t& result_len) {
  81   assert(buflen >= 2, "buffer too small");
  82 
  83   const char* result;
  84   if (add_cr)  buflen--;
  85   if (!strchr(format, '%')) {
  86     // constant format string
  87     result = format;
  88     result_len = strlen(result);
  89     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
  90   } else if (format[0] == '%' && format[1] == 's' && format[2] == '\0') {
  91     // trivial copy-through format string
  92     result = va_arg(ap, const char*);
  93     result_len = strlen(result);
  94     if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
  95   } else {
  96     // Handle truncation:
  97     // posix: upon truncation, vsnprintf returns number of bytes which
  98     //   would have been written (excluding terminating zero) had the buffer
  99     //   been large enough
 100     // windows: upon truncation, vsnprintf returns -1
 101     const int written = vsnprintf(buffer, buflen, format, ap);
 102     result = buffer;
 103     if (written < (int) buflen && written >= 0) {
 104       result_len = written;
 105     } else {
 106       DEBUG_ONLY(warning("increase O_BUFLEN in ostream.hpp -- output truncated");)
 107       result_len = buflen - 1;
 108       buffer[result_len] = 0;
 109     }
 110   }
 111   if (add_cr) {
 112     if (result != buffer) {
 113       memcpy(buffer, result, result_len);
 114       result = buffer;
 115     }
 116     buffer[result_len++] = '\n';
 117     buffer[result_len] = 0;
 118   }
 119   return result;
 120 }
 121 
 122 void outputStream::print(const char* format, ...) {
 123   char buffer[O_BUFLEN];
 124   va_list ap;
 125   va_start(ap, format);
 126   size_t len;
 127   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, false, len);
 128   write(str, len);
 129   va_end(ap);
 130 }
 131 
 132 void outputStream::print_cr(const char* format, ...) {
 133   char buffer[O_BUFLEN];
 134   va_list ap;
 135   va_start(ap, format);
 136   size_t len;
 137   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, true, len);
 138   write(str, len);
 139   va_end(ap);
 140 }
 141 
 142 void outputStream::vprint(const char *format, va_list argptr) {
 143   char buffer[O_BUFLEN];
 144   size_t len;
 145   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, false, len);
 146   write(str, len);
 147 }
 148 
 149 void outputStream::vprint_cr(const char* format, va_list argptr) {
 150   char buffer[O_BUFLEN];
 151   size_t len;
 152   const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, true, len);
 153   write(str, len);
 154 }
 155 
 156 void outputStream::fill_to(int col) {
 157   int need_fill = col - position();
 158   sp(need_fill);
 159 }
 160 
 161 void outputStream::move_to(int col, int slop, int min_space) {
 162   if (position() >= col + slop)
 163     cr();
 164   int need_fill = col - position();
 165   if (need_fill < min_space)
 166     need_fill = min_space;
 167   sp(need_fill);
 168 }
 169 
 170 void outputStream::put(char ch) {
 171   assert(ch != 0, "please fix call site");
 172   char buf[] = { ch, '\0' };
 173   write(buf, 1);
 174 }
 175 
 176 #define SP_USE_TABS false
 177 
 178 void outputStream::sp(int count) {
 179   if (count < 0)  return;
 180   if (SP_USE_TABS && count >= 8) {
 181     int target = position() + count;
 182     while (count >= 8) {
 183       this->write("\t", 1);
 184       count -= 8;
 185     }
 186     count = target - position();
 187   }
 188   while (count > 0) {
 189     int nw = (count > 8) ? 8 : count;
 190     this->write("        ", nw);
 191     count -= nw;
 192   }
 193 }
 194 
 195 void outputStream::cr() {
 196   this->write("\n", 1);
 197 }
 198 
 199 void outputStream::stamp() {
 200   if (! _stamp.is_updated()) {
 201     _stamp.update(); // start at 0 on first call to stamp()
 202   }
 203 
 204   // outputStream::stamp() may get called by ostream_abort(), use snprintf
 205   // to avoid allocating large stack buffer in print().
 206   char buf[40];
 207   jio_snprintf(buf, sizeof(buf), "%.3f", _stamp.seconds());
 208   print_raw(buf);
 209 }
 210 
 211 void outputStream::stamp(bool guard,
 212                          const char* prefix,
 213                          const char* suffix) {
 214   if (!guard) {
 215     return;
 216   }
 217   print_raw(prefix);
 218   stamp();
 219   print_raw(suffix);
 220 }
 221 
 222 void outputStream::date_stamp(bool guard,
 223                               const char* prefix,
 224                               const char* suffix) {
 225   if (!guard) {
 226     return;
 227   }
 228   print_raw(prefix);
 229   static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz";
 230   static const int buffer_length = 32;
 231   char buffer[buffer_length];
 232   const char* iso8601_result = os::iso8601_time(buffer, buffer_length);
 233   if (iso8601_result != NULL) {
 234     print_raw(buffer);
 235   } else {
 236     print_raw(error_time);
 237   }
 238   print_raw(suffix);
 239   return;
 240 }
 241 








 242 outputStream& outputStream::indent() {
 243   while (_position < _indentation) sp();
 244   return *this;
 245 }
 246 
 247 void outputStream::print_jlong(jlong value) {
 248   print(JLONG_FORMAT, value);
 249 }
 250 
 251 void outputStream::print_julong(julong value) {
 252   print(JULONG_FORMAT, value);
 253 }
 254 
 255 /**
 256  * This prints out hex data in a 'windbg' or 'xxd' form, where each line is:
 257  *   <hex-address>: 8 * <hex-halfword> <ascii translation (optional)>
 258  * example:
 259  * 0000000: 7f44 4f46 0102 0102 0000 0000 0000 0000  .DOF............
 260  * 0000010: 0000 0000 0000 0040 0000 0020 0000 0005  .......@... ....
 261  * 0000020: 0000 0000 0000 0040 0000 0000 0000 015d  .......@.......]
 262  * ...
 263  *
 264  * indent is applied to each line.  Ends with a CR.
 265  */
 266 void outputStream::print_data(void* data, size_t len, bool with_ascii) {
 267   size_t limit = (len + 16) / 16 * 16;
 268   for (size_t i = 0; i < limit; ++i) {
 269     if (i % 16 == 0) {
 270       indent().print(INTPTR_FORMAT_W(07) ":", i);
 271     }
 272     if (i % 2 == 0) {
 273       print(" ");
 274     }
 275     if (i < len) {
 276       print("%02x", ((unsigned char*)data)[i]);
 277     } else {
 278       print("  ");
 279     }
 280     if ((i + 1) % 16 == 0) {
 281       if (with_ascii) {
 282         print("  ");
 283         for (size_t j = 0; j < 16; ++j) {
 284           size_t idx = i + j - 15;
 285           if (idx < len) {
 286             char c = ((char*)data)[idx];
 287             print("%c", c >= 32 && c <= 126 ? c : '.');
 288           }
 289         }
 290       }
 291       cr();
 292     }
 293   }
 294 }
 295 
 296 stringStream::stringStream(size_t initial_size) : outputStream() {
 297   buffer_length = initial_size;
 298   buffer        = NEW_RESOURCE_ARRAY(char, buffer_length);
 299   buffer_pos    = 0;
 300   buffer_fixed  = false;
 301   DEBUG_ONLY(rm = Thread::current()->current_resource_mark();)
 302 }
 303 
 304 // useful for output to fixed chunks of memory, such as performance counters
 305 stringStream::stringStream(char* fixed_buffer, size_t fixed_buffer_size) : outputStream() {
 306   buffer_length = fixed_buffer_size;
 307   buffer        = fixed_buffer;
 308   buffer_pos    = 0;
 309   buffer_fixed  = true;
 310 }
 311 
 312 void stringStream::write(const char* s, size_t len) {
 313   size_t write_len = len;               // number of non-null bytes to write
 314   size_t end = buffer_pos + len + 1;    // position after write and final '\0'
 315   if (end > buffer_length) {
 316     if (buffer_fixed) {
 317       // if buffer cannot resize, silently truncate
 318       end = buffer_length;
 319       write_len = end - buffer_pos - 1; // leave room for the final '\0'
 320     } else {
 321       // For small overruns, double the buffer.  For larger ones,
 322       // increase to the requested size.
 323       if (end < buffer_length * 2) {
 324         end = buffer_length * 2;
 325       }
 326       char* oldbuf = buffer;
 327       assert(rm == NULL || Thread::current()->current_resource_mark() == rm,
 328              "stringStream is re-allocated with a different ResourceMark");
 329       buffer = NEW_RESOURCE_ARRAY(char, end);
 330       if (buffer_pos > 0) {
 331         memcpy(buffer, oldbuf, buffer_pos);
 332       }
 333       buffer_length = end;
 334     }
 335   }
 336   // invariant: buffer is always null-terminated
 337   guarantee(buffer_pos + write_len + 1 <= buffer_length, "stringStream oob");
 338   if (write_len > 0) {
 339     buffer[buffer_pos + write_len] = 0;
 340     memcpy(buffer + buffer_pos, s, write_len);
 341     buffer_pos += write_len;
 342   }
 343 
 344   // Note that the following does not depend on write_len.
 345   // This means that position and count get updated
 346   // even when overflow occurs.
 347   update_position(s, len);
 348 }
 349 
 350 char* stringStream::as_string() {
 351   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos + 1);
 352   strncpy(copy, buffer, buffer_pos);
 353   copy[buffer_pos] = 0;  // terminating null
 354   return copy;
 355 }
 356 
 357 stringStream::~stringStream() {}
 358 
 359 xmlStream*   xtty;
 360 outputStream* tty;

 361 CDS_ONLY(fileStream* classlist_file;) // Only dump the classes that can be stored into the CDS archive
 362 extern Mutex* tty_lock;
 363 
 364 #define EXTRACHARLEN   32
 365 #define CURRENTAPPX    ".current"
 366 // convert YYYY-MM-DD HH:MM:SS to YYYY-MM-DD_HH-MM-SS
 367 char* get_datetime_string(char *buf, size_t len) {
 368   os::local_time_string(buf, len);
 369   int i = (int)strlen(buf);
 370   while (i-- >= 0) {
 371     if (buf[i] == ' ') buf[i] = '_';
 372     else if (buf[i] == ':') buf[i] = '-';
 373   }
 374   return buf;
 375 }
 376 
 377 static const char* make_log_name_internal(const char* log_name, const char* force_directory,
 378                                                 int pid, const char* tms) {
 379   const char* basename = log_name;
 380   char file_sep = os::file_separator()[0];
 381   const char* cp;
 382   char  pid_text[32];
 383 
 384   for (cp = log_name; *cp != '\0'; cp++) {
 385     if (*cp == '/' || *cp == file_sep) {
 386       basename = cp + 1;
 387     }
 388   }
 389   const char* nametail = log_name;
 390   // Compute buffer length
 391   size_t buffer_length;
 392   if (force_directory != NULL) {
 393     buffer_length = strlen(force_directory) + strlen(os::file_separator()) +
 394                     strlen(basename) + 1;
 395   } else {
 396     buffer_length = strlen(log_name) + 1;
 397   }
 398 
 399   const char* pts = strstr(basename, "%p");
 400   int pid_pos = (pts == NULL) ? -1 : (pts - nametail);
 401 
 402   if (pid_pos >= 0) {
 403     jio_snprintf(pid_text, sizeof(pid_text), "pid%u", pid);
 404     buffer_length += strlen(pid_text);
 405   }
 406 
 407   pts = strstr(basename, "%t");
 408   int tms_pos = (pts == NULL) ? -1 : (pts - nametail);
 409   if (tms_pos >= 0) {
 410     buffer_length += strlen(tms);
 411   }
 412 
 413   // File name is too long.
 414   if (buffer_length > JVM_MAXPATHLEN) {
 415     return NULL;
 416   }
 417 
 418   // Create big enough buffer.
 419   char *buf = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
 420 
 421   strcpy(buf, "");
 422   if (force_directory != NULL) {
 423     strcat(buf, force_directory);
 424     strcat(buf, os::file_separator());
 425     nametail = basename;       // completely skip directory prefix
 426   }
 427 
 428   // who is first, %p or %t?
 429   int first = -1, second = -1;
 430   const char *p1st = NULL;
 431   const char *p2nd = NULL;
 432 
 433   if (pid_pos >= 0 && tms_pos >= 0) {
 434     // contains both %p and %t
 435     if (pid_pos < tms_pos) {
 436       // case foo%pbar%tmonkey.log
 437       first  = pid_pos;
 438       p1st   = pid_text;
 439       second = tms_pos;
 440       p2nd   = tms;
 441     } else {
 442       // case foo%tbar%pmonkey.log
 443       first  = tms_pos;
 444       p1st   = tms;
 445       second = pid_pos;
 446       p2nd   = pid_text;
 447     }
 448   } else if (pid_pos >= 0) {
 449     // contains %p only
 450     first  = pid_pos;
 451     p1st   = pid_text;
 452   } else if (tms_pos >= 0) {
 453     // contains %t only
 454     first  = tms_pos;
 455     p1st   = tms;
 456   }
 457 
 458   int buf_pos = (int)strlen(buf);
 459   const char* tail = nametail;
 460 
 461   if (first >= 0) {
 462     tail = nametail + first + 2;
 463     strncpy(&buf[buf_pos], nametail, first);
 464     strcpy(&buf[buf_pos + first], p1st);
 465     buf_pos = (int)strlen(buf);
 466     if (second >= 0) {
 467       strncpy(&buf[buf_pos], tail, second - first - 2);
 468       strcpy(&buf[buf_pos + second - first - 2], p2nd);
 469       tail = nametail + second + 2;
 470     }
 471   }
 472   strcat(buf, tail);      // append rest of name, or all of name
 473   return buf;
 474 }
 475 
 476 // log_name comes from -XX:LogFile=log_name or
 477 // -XX:DumpLoadedClassList=<file_name>
 478 // in log_name, %p => pid1234 and
 479 //              %t => YYYY-MM-DD_HH-MM-SS
 480 static const char* make_log_name(const char* log_name, const char* force_directory) {
 481   char timestr[32];
 482   get_datetime_string(timestr, sizeof(timestr));
 483   return make_log_name_internal(log_name, force_directory, os::current_process_id(),
 484                                 timestr);
 485 }
 486 

























































































 487 fileStream::fileStream(const char* file_name) {
 488   _file = fopen(file_name, "w");
 489   if (_file != NULL) {
 490     _need_close = true;
 491   } else {
 492     warning("Cannot open file %s due to %s\n", file_name, strerror(errno));
 493     _need_close = false;
 494   }
 495 }
 496 
 497 fileStream::fileStream(const char* file_name, const char* opentype) {
 498   _file = fopen(file_name, opentype);
 499   if (_file != NULL) {
 500     _need_close = true;
 501   } else {
 502     warning("Cannot open file %s due to %s\n", file_name, strerror(errno));
 503     _need_close = false;
 504   }
 505 }
 506 
 507 void fileStream::write(const char* s, size_t len) {
 508   if (_file != NULL)  {
 509     // Make an unused local variable to avoid warning from gcc 4.x compiler.
 510     size_t count = fwrite(s, 1, len, _file);
 511   }
 512   update_position(s, len);
 513 }
 514 
 515 long fileStream::fileSize() {
 516   long size = -1;
 517   if (_file != NULL) {
 518     long pos  = ::ftell(_file);
 519     if (::fseek(_file, 0, SEEK_END) == 0) {
 520       size = ::ftell(_file);
 521     }
 522     ::fseek(_file, pos, SEEK_SET);
 523   }
 524   return size;
 525 }
 526 
 527 char* fileStream::readln(char *data, int count ) {
 528   char * ret = ::fgets(data, count, _file);
 529   //Get rid of annoying \n char
 530   data[::strlen(data)-1] = '\0';
 531   return ret;
 532 }
 533 
 534 fileStream::~fileStream() {
 535   if (_file != NULL) {
 536     if (_need_close) fclose(_file);
 537     _file      = NULL;
 538   }
 539 }
 540 
 541 void fileStream::flush() {
 542   fflush(_file);
 543 }
 544 
 545 fdStream::fdStream(const char* file_name) {
 546   _fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
 547   _need_close = true;
 548 }
 549 
 550 fdStream::~fdStream() {
 551   if (_fd != -1) {
 552     if (_need_close) close(_fd);
 553     _fd = -1;
 554   }
 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 && !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   char warnbuf[O_BUFLEN*2];
 606   jio_snprintf(warnbuf, sizeof(warnbuf), "Warning:  Cannot open log file: %s\n", log_name);
 607   // Note:  This feature is for maintainer use only.  No need for L10N.
 608   jio_print(warnbuf);
 609   try_name = make_log_name(log_name, os::get_temp_directory());
 610   if (try_name == NULL) {
 611     warning("Cannot open file %s: file name is too long for directory %s.\n", log_name, os::get_temp_directory());
 612     return NULL;
 613   }
 614 
 615   jio_snprintf(warnbuf, sizeof(warnbuf),
 616                "Warning:  Forcing option -XX:LogFile=%s\n", try_name);
 617   jio_print(warnbuf);
 618 
 619   file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name);
 620   FREE_C_HEAP_ARRAY(char, try_name);
 621   if (file->is_open()) {
 622     return file;
 623   }
 624 
 625   delete file;
 626   return NULL;
 627 }
 628 
 629 void defaultStream::init_log() {
 630   // %%% Need a MutexLocker?
 631   const char* log_name = LogFile != NULL ? LogFile : "hotspot_%p.log";
 632   fileStream* file = open_file(log_name);
 633 
 634   if (file != NULL) {
 635     _log_file = file;
 636     _outer_xmlStream = new(ResourceObj::C_HEAP, mtInternal) xmlStream(file);
 637     start_log();
 638   } else {
 639     // and leave xtty as NULL
 640     LogVMOutput = false;
 641     DisplayVMOutput = true;
 642     LogCompilation = false;
 643   }
 644 }
 645 
 646 void defaultStream::start_log() {
 647   xmlStream*xs = _outer_xmlStream;
 648     if (this == tty)  xtty = xs;
 649     // Write XML header.
 650     xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
 651     // (For now, don't bother to issue a DTD for this private format.)
 652     jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
 653     // %%% Should be: jlong time_ms = os::start_time_milliseconds(), if
 654     // we ever get round to introduce that method on the os class
 655     xs->head("hotspot_log version='%d %d'"
 656              " process='%d' time_ms='" INT64_FORMAT "'",
 657              LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
 658              os::current_process_id(), (int64_t)time_ms);
 659     // Write VM version header immediately.
 660     xs->head("vm_version");
 661     xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr();
 662     xs->tail("name");
 663     xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr();
 664     xs->tail("release");
 665     xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr();
 666     xs->tail("info");
 667     xs->tail("vm_version");
 668     // Record information about the command-line invocation.
 669     xs->head("vm_arguments");  // Cf. Arguments::print_on()
 670     if (Arguments::num_jvm_flags() > 0) {
 671       xs->head("flags");
 672       Arguments::print_jvm_flags_on(xs->text());
 673       xs->tail("flags");
 674     }
 675     if (Arguments::num_jvm_args() > 0) {
 676       xs->head("args");
 677       Arguments::print_jvm_args_on(xs->text());
 678       xs->tail("args");
 679     }
 680     if (Arguments::java_command() != NULL) {
 681       xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command());
 682       xs->tail("command");
 683     }
 684     if (Arguments::sun_java_launcher() != NULL) {
 685       xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher());
 686       xs->tail("launcher");
 687     }
 688     if (Arguments::system_properties() !=  NULL) {
 689       xs->head("properties");
 690       // Print it as a java-style property list.
 691       // System properties don't generally contain newlines, so don't bother with unparsing.
 692       outputStream *text = xs->text();
 693       for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
 694         // Print in two stages to avoid problems with long
 695         // keys/values.
 696         text->print_raw(p->key());
 697         text->put('=');
 698         text->print_raw_cr(p->value());
 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 or call Thread::current() if TLS isn't initialized
 768       ThreadLocalStorage::thread() == NULL ||
 769 
 770       // developer hook
 771       !SerializeVMOutput ||
 772 
 773       // VM already unhealthy
 774       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 
 814 // Yuck:  jio_print does not accept char*/len.
 815 static void call_jio_print(const char* s, size_t len) {
 816   char buffer[O_BUFLEN+100];
 817   if (len > sizeof(buffer)-1) {
 818     warning("increase O_BUFLEN in ostream.cpp -- output truncated");
 819     len = sizeof(buffer)-1;
 820   }
 821   strncpy(buffer, s, len);
 822   buffer[len] = '\0';
 823   jio_print(buffer);
 824 }
 825 
 826 
 827 void defaultStream::write(const char* s, size_t len) {
 828   intx thread_id = os::current_thread_id();
 829   intx holder = hold(thread_id);
 830 
 831   if (DisplayVMOutput &&
 832       (_outer_xmlStream == NULL || !_outer_xmlStream->inside_attrs())) {
 833     // print to output stream. It can be redirected by a vfprintf hook
 834     if (s[len] == '\0') {
 835       jio_print(s);
 836     } else {
 837       call_jio_print(s, len);
 838     }
 839   }
 840 
 841   // print to log file
 842   if (has_log_file()) {
 843     int nl0 = _newlines;
 844     xmlTextStream::write(s, len);
 845     // flush the log file too, if there were any newlines
 846     if (nl0 != _newlines){
 847       flush();
 848     }
 849   } else {
 850     update_position(s, len);
 851   }
 852 
 853   release(holder);
 854 }
 855 
 856 intx ttyLocker::hold_tty() {
 857   if (defaultStream::instance == NULL)  return defaultStream::NO_WRITER;
 858   intx thread_id = os::current_thread_id();
 859   return defaultStream::instance->hold(thread_id);
 860 }
 861 
 862 void ttyLocker::release_tty(intx holder) {
 863   if (holder == defaultStream::NO_WRITER)  return;
 864   defaultStream::instance->release(holder);
 865 }
 866 
 867 bool ttyLocker::release_tty_if_locked() {
 868   intx thread_id = os::current_thread_id();
 869   if (defaultStream::instance->writer() == thread_id) {
 870     // release the lock and return true so callers know if was
 871     // previously held.
 872     release_tty(thread_id);
 873     return true;
 874   }
 875   return false;
 876 }
 877 
 878 void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
 879   if (defaultStream::instance != NULL &&
 880       defaultStream::instance->writer() == holder) {
 881     if (xtty != NULL) {
 882       xtty->print_cr("<!-- safepoint while printing -->");
 883     }
 884     defaultStream::instance->release(holder);
 885   }
 886   // (else there was no lock to break)
 887 }
 888 
 889 void ostream_init() {
 890   if (defaultStream::instance == NULL) {
 891     defaultStream::instance = new(ResourceObj::C_HEAP, mtInternal) defaultStream();
 892     tty = defaultStream::instance;
 893 
 894     // We want to ensure that time stamps in GC logs consider time 0
 895     // the time when the JVM is initialized, not the first time we ask
 896     // for a time stamp. So, here, we explicitly update the time stamp
 897     // of tty.
 898     tty->time_stamp().update_to(1);
 899   }
 900 }
 901 
 902 void ostream_init_log() {

 903   // Note : this must be called AFTER ostream_init()
 904 












 905 #if INCLUDE_CDS
 906   // For -XX:DumpLoadedClassList=<file> option
 907   if (DumpLoadedClassList != NULL) {
 908     const char* list_name = make_log_name(DumpLoadedClassList, NULL);
 909     classlist_file = new(ResourceObj::C_HEAP, mtInternal)
 910                          fileStream(list_name);
 911     FREE_C_HEAP_ARRAY(char, list_name);
 912   }
 913 #endif
 914 
 915   // If we haven't lazily initialized the logfile yet, do it now,
 916   // to avoid the possibility of lazy initialization during a VM
 917   // crash, which can affect the stability of the fatal error handler.
 918   defaultStream::instance->has_log_file();
 919 }
 920 
 921 // ostream_exit() is called during normal VM exit to finish log files, flush
 922 // output and free resource.
 923 void ostream_exit() {
 924   static bool ostream_exit_called = false;
 925   if (ostream_exit_called)  return;
 926   ostream_exit_called = true;
 927 #if INCLUDE_CDS
 928   if (classlist_file != NULL) {
 929     delete classlist_file;
 930   }
 931 #endif



 932   {
 933       // we temporaly disable PrintMallocFree here
 934       // as otherwise it'll lead to using of almost deleted
 935       // tty or defaultStream::instance in logging facility
 936       // of HeapFree(), see 6391258
 937       DEBUG_ONLY(FlagSetting fs(PrintMallocFree, false);)
 938       if (tty != defaultStream::instance) {
 939           delete tty;
 940       }
 941       if (defaultStream::instance != NULL) {
 942           delete defaultStream::instance;
 943       }
 944   }
 945   tty = NULL;
 946   xtty = NULL;

 947   defaultStream::instance = NULL;
 948 }
 949 
 950 // ostream_abort() is called by os::abort() when VM is about to die.
 951 void ostream_abort() {
 952   // Here we can't delete tty, just flush its output

 953   if (tty) tty->flush();
 954 
 955   if (defaultStream::instance != NULL) {
 956     static char buf[4096];
 957     defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
 958   }
 959 }
 960 
 961 staticBufferStream::staticBufferStream(char* buffer, size_t buflen,
 962                                        outputStream *outer_stream) {
 963   _buffer = buffer;
 964   _buflen = buflen;
 965   _outer_stream = outer_stream;
 966   // compile task prints time stamp relative to VM start
 967   _stamp.update_to(1);
 968 }
 969 
 970 void staticBufferStream::write(const char* c, size_t len) {
 971   _outer_stream->print_raw(c, (int)len);
 972 }
 973 
 974 void staticBufferStream::flush() {
 975   _outer_stream->flush();
 976 }
 977 
 978 void staticBufferStream::print(const char* format, ...) {
 979   va_list ap;
 980   va_start(ap, format);
 981   size_t len;
 982   const char* str = do_vsnprintf(_buffer, _buflen, format, ap, false, len);
 983   write(str, len);
 984   va_end(ap);
 985 }
 986 
 987 void staticBufferStream::print_cr(const char* format, ...) {
 988   va_list ap;
 989   va_start(ap, format);
 990   size_t len;
 991   const char* str = do_vsnprintf(_buffer, _buflen, format, ap, true, len);
 992   write(str, len);
 993   va_end(ap);
 994 }
 995 
 996 void staticBufferStream::vprint(const char *format, va_list argptr) {
 997   size_t len;
 998   const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, false, len);
 999   write(str, len);
1000 }
1001 
1002 void staticBufferStream::vprint_cr(const char* format, va_list argptr) {
1003   size_t len;
1004   const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, true, len);
1005   write(str, len);
1006 }
1007 
1008 bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
1009   buffer_length = initial_size;
1010   buffer        = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
1011   buffer_pos    = 0;
1012   buffer_fixed  = false;
1013   buffer_max    = bufmax;
1014 }
1015 
1016 bufferedStream::bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax) : outputStream() {
1017   buffer_length = fixed_buffer_size;
1018   buffer        = fixed_buffer;
1019   buffer_pos    = 0;
1020   buffer_fixed  = true;
1021   buffer_max    = bufmax;
1022 }
1023 
1024 void bufferedStream::write(const char* s, size_t len) {
1025 
1026   if(buffer_pos + len > buffer_max) {
1027     flush();
1028   }
1029 
1030   size_t end = buffer_pos + len;
1031   if (end >= buffer_length) {
1032     if (buffer_fixed) {
1033       // if buffer cannot resize, silently truncate
1034       len = buffer_length - buffer_pos - 1;
1035     } else {
1036       // For small overruns, double the buffer.  For larger ones,
1037       // increase to the requested size.
1038       if (end < buffer_length * 2) {
1039         end = buffer_length * 2;
1040       }
1041       buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end, mtInternal);
1042       buffer_length = end;
1043     }
1044   }
1045   memcpy(buffer + buffer_pos, s, len);
1046   buffer_pos += len;
1047   update_position(s, len);
1048 }
1049 
1050 char* bufferedStream::as_string() {
1051   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
1052   strncpy(copy, buffer, buffer_pos);
1053   copy[buffer_pos] = 0;  // terminating null
1054   return copy;
1055 }
1056 
1057 bufferedStream::~bufferedStream() {
1058   if (!buffer_fixed) {
1059     FREE_C_HEAP_ARRAY(char, buffer);
1060   }
1061 }
1062 
1063 #ifndef PRODUCT
1064 
1065 #if defined(SOLARIS) || defined(LINUX) || defined(AIX) || defined(_ALLBSD_SOURCE)
1066 #include <sys/types.h>
1067 #include <sys/socket.h>
1068 #include <netinet/in.h>
1069 #include <arpa/inet.h>
1070 #endif
1071 
1072 // Network access
1073 networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
1074 
1075   _socket = -1;
1076 
1077   int result = os::socket(AF_INET, SOCK_STREAM, 0);
1078   if (result <= 0) {
1079     assert(false, "Socket could not be created!");
1080   } else {
1081     _socket = result;
1082   }
1083 }
1084 
1085 int networkStream::read(char *buf, size_t len) {
1086   return os::recv(_socket, buf, (int)len, 0);
1087 }
1088 
1089 void networkStream::flush() {
1090   if (size() != 0) {
1091     int result = os::raw_send(_socket, (char *)base(), size(), 0);
1092     assert(result != -1, "connection error");
1093     assert(result == (int)size(), "didn't send enough data");
1094   }
1095   reset();
1096 }
1097 
1098 networkStream::~networkStream() {
1099   close();
1100 }
1101 
1102 void networkStream::close() {
1103   if (_socket != -1) {
1104     flush();
1105     os::socket_close(_socket);
1106     _socket = -1;
1107   }
1108 }
1109 
1110 bool networkStream::connect(const char *ip, short port) {
1111 
1112   struct sockaddr_in server;
1113   server.sin_family = AF_INET;
1114   server.sin_port = htons(port);
1115 
1116   server.sin_addr.s_addr = inet_addr(ip);
1117   if (server.sin_addr.s_addr == (uint32_t)-1) {
1118     struct hostent* host = os::get_host_by_name((char*)ip);
1119     if (host != NULL) {
1120       memcpy(&server.sin_addr, host->h_addr_list[0], host->h_length);
1121     } else {
1122       return false;
1123     }
1124   }
1125 
1126 
1127   int result = os::connect(_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_in));
1128   return (result >= 0);
1129 }
1130 
1131 #endif
1132 
1133 void logStream::write(const char* s, size_t len) {
1134   if (len > 0 && s[len - 1] == '\n') {
1135     _current_line.write(s, len - 1);
1136     _log_func(_current_line.as_string());
1137     _current_line.reset();
1138   } else {
1139     _current_line.write(s, len);
1140   }
1141   update_position(s, len);
1142 }
--- EOF ---