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