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