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