ostream.cpp revision 7462:a0dd995271c4
1/*
2 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "compiler/compileLog.hpp"
27#include "gc_implementation/shared/gcId.hpp"
28#include "oops/oop.inline.hpp"
29#include "runtime/arguments.hpp"
30#include "runtime/os.hpp"
31#include "runtime/vm_version.hpp"
32#include "utilities/defaultStream.hpp"
33#include "utilities/ostream.hpp"
34#include "utilities/top.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}
46
47outputStream::outputStream(int width, bool has_time_stamps) {
48  _width       = width;
49  _position    = 0;
50  _newlines    = 0;
51  _precount    = 0;
52  _indentation = 0;
53  if (has_time_stamps)  _stamp.update();
54}
55
56void outputStream::update_position(const char* s, size_t len) {
57  for (size_t i = 0; i < len; i++) {
58    char ch = s[i];
59    if (ch == '\n') {
60      _newlines += 1;
61      _precount += _position + 1;
62      _position = 0;
63    } else if (ch == '\t') {
64      int tw = 8 - (_position & 7);
65      _position += tw;
66      _precount -= tw-1;  // invariant:  _precount + _position == total count
67    } else {
68      _position += 1;
69    }
70  }
71}
72
73// Execute a vsprintf, using the given buffer if necessary.
74// Return a pointer to the formatted string.
75const char* outputStream::do_vsnprintf(char* buffer, size_t buflen,
76                                       const char* format, va_list ap,
77                                       bool add_cr,
78                                       size_t& result_len) {
79  assert(buflen >= 2, "buffer too small");
80
81  const char* result;
82  if (add_cr)  buflen--;
83  if (!strchr(format, '%')) {
84    // constant format string
85    result = format;
86    result_len = strlen(result);
87    if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
88  } else if (format[0] == '%' && format[1] == 's' && format[2] == '\0') {
89    // trivial copy-through format string
90    result = va_arg(ap, const char*);
91    result_len = strlen(result);
92    if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
93  } else {
94    // Handle truncation:
95    // posix: upon truncation, vsnprintf returns number of bytes which
96    //   would have been written (excluding terminating zero) had the buffer
97    //   been large enough
98    // windows: upon truncation, vsnprintf returns -1
99    const int written = vsnprintf(buffer, buflen, format, ap);
100    result = buffer;
101    if (written < (int) buflen && written >= 0) {
102      result_len = written;
103    } else {
104      DEBUG_ONLY(warning("increase O_BUFLEN in ostream.hpp -- output truncated");)
105      result_len = buflen - 1;
106      buffer[result_len] = 0;
107    }
108  }
109  if (add_cr) {
110    if (result != buffer) {
111      strncpy(buffer, result, buflen);
112      result = buffer;
113    }
114    buffer[result_len++] = '\n';
115    buffer[result_len] = 0;
116  }
117  return result;
118}
119
120void outputStream::print(const char* format, ...) {
121  char buffer[O_BUFLEN];
122  va_list ap;
123  va_start(ap, format);
124  size_t len;
125  const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, false, len);
126  write(str, len);
127  va_end(ap);
128}
129
130void outputStream::print_cr(const char* format, ...) {
131  char buffer[O_BUFLEN];
132  va_list ap;
133  va_start(ap, format);
134  size_t len;
135  const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, true, len);
136  write(str, len);
137  va_end(ap);
138}
139
140void outputStream::vprint(const char *format, va_list argptr) {
141  char buffer[O_BUFLEN];
142  size_t len;
143  const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, false, len);
144  write(str, len);
145}
146
147void outputStream::vprint_cr(const char* format, va_list argptr) {
148  char buffer[O_BUFLEN];
149  size_t len;
150  const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, true, len);
151  write(str, len);
152}
153
154void outputStream::fill_to(int col) {
155  int need_fill = col - position();
156  sp(need_fill);
157}
158
159void outputStream::move_to(int col, int slop, int min_space) {
160  if (position() >= col + slop)
161    cr();
162  int need_fill = col - position();
163  if (need_fill < min_space)
164    need_fill = min_space;
165  sp(need_fill);
166}
167
168void outputStream::put(char ch) {
169  assert(ch != 0, "please fix call site");
170  char buf[] = { ch, '\0' };
171  write(buf, 1);
172}
173
174#define SP_USE_TABS false
175
176void outputStream::sp(int count) {
177  if (count < 0)  return;
178  if (SP_USE_TABS && count >= 8) {
179    int target = position() + count;
180    while (count >= 8) {
181      this->write("\t", 1);
182      count -= 8;
183    }
184    count = target - position();
185  }
186  while (count > 0) {
187    int nw = (count > 8) ? 8 : count;
188    this->write("        ", nw);
189    count -= nw;
190  }
191}
192
193void outputStream::cr() {
194  this->write("\n", 1);
195}
196
197void outputStream::stamp() {
198  if (! _stamp.is_updated()) {
199    _stamp.update(); // start at 0 on first call to stamp()
200  }
201
202  // outputStream::stamp() may get called by ostream_abort(), use snprintf
203  // to avoid allocating large stack buffer in print().
204  char buf[40];
205  jio_snprintf(buf, sizeof(buf), "%.3f", _stamp.seconds());
206  print_raw(buf);
207}
208
209void outputStream::stamp(bool guard,
210                         const char* prefix,
211                         const char* suffix) {
212  if (!guard) {
213    return;
214  }
215  print_raw(prefix);
216  stamp();
217  print_raw(suffix);
218}
219
220void outputStream::date_stamp(bool guard,
221                              const char* prefix,
222                              const char* suffix) {
223  if (!guard) {
224    return;
225  }
226  print_raw(prefix);
227  static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz";
228  static const int buffer_length = 32;
229  char buffer[buffer_length];
230  const char* iso8601_result = os::iso8601_time(buffer, buffer_length);
231  if (iso8601_result != NULL) {
232    print_raw(buffer);
233  } else {
234    print_raw(error_time);
235  }
236  print_raw(suffix);
237  return;
238}
239
240void outputStream::gclog_stamp(const GCId& gc_id) {
241  date_stamp(PrintGCDateStamps);
242  stamp(PrintGCTimeStamps);
243  if (PrintGCID) {
244    print("#%u: ", gc_id.id());
245  }
246}
247
248outputStream& outputStream::indent() {
249  while (_position < _indentation) sp();
250  return *this;
251}
252
253void outputStream::print_jlong(jlong value) {
254  print(JLONG_FORMAT, value);
255}
256
257void outputStream::print_julong(julong value) {
258  print(JULONG_FORMAT, value);
259}
260
261/**
262 * This prints out hex data in a 'windbg' or 'xxd' form, where each line is:
263 *   <hex-address>: 8 * <hex-halfword> <ascii translation (optional)>
264 * example:
265 * 0000000: 7f44 4f46 0102 0102 0000 0000 0000 0000  .DOF............
266 * 0000010: 0000 0000 0000 0040 0000 0020 0000 0005  .......@... ....
267 * 0000020: 0000 0000 0000 0040 0000 0000 0000 015d  .......@.......]
268 * ...
269 *
270 * indent is applied to each line.  Ends with a CR.
271 */
272void outputStream::print_data(void* data, size_t len, bool with_ascii) {
273  size_t limit = (len + 16) / 16 * 16;
274  for (size_t i = 0; i < limit; ++i) {
275    if (i % 16 == 0) {
276      indent().print(INTPTR_FORMAT_W(07)":", i);
277    }
278    if (i % 2 == 0) {
279      print(" ");
280    }
281    if (i < len) {
282      print("%02x", ((unsigned char*)data)[i]);
283    } else {
284      print("  ");
285    }
286    if ((i + 1) % 16 == 0) {
287      if (with_ascii) {
288        print("  ");
289        for (size_t j = 0; j < 16; ++j) {
290          size_t idx = i + j - 15;
291          if (idx < len) {
292            char c = ((char*)data)[idx];
293            print("%c", c >= 32 && c <= 126 ? c : '.');
294          }
295        }
296      }
297      cr();
298    }
299  }
300}
301
302stringStream::stringStream(size_t initial_size) : outputStream() {
303  buffer_length = initial_size;
304  buffer        = NEW_RESOURCE_ARRAY(char, buffer_length);
305  buffer_pos    = 0;
306  buffer_fixed  = false;
307  DEBUG_ONLY(rm = Thread::current()->current_resource_mark();)
308}
309
310// useful for output to fixed chunks of memory, such as performance counters
311stringStream::stringStream(char* fixed_buffer, size_t fixed_buffer_size) : outputStream() {
312  buffer_length = fixed_buffer_size;
313  buffer        = fixed_buffer;
314  buffer_pos    = 0;
315  buffer_fixed  = true;
316}
317
318void stringStream::write(const char* s, size_t len) {
319  size_t write_len = len;               // number of non-null bytes to write
320  size_t end = buffer_pos + len + 1;    // position after write and final '\0'
321  if (end > buffer_length) {
322    if (buffer_fixed) {
323      // if buffer cannot resize, silently truncate
324      end = buffer_length;
325      write_len = end - buffer_pos - 1; // leave room for the final '\0'
326    } else {
327      // For small overruns, double the buffer.  For larger ones,
328      // increase to the requested size.
329      if (end < buffer_length * 2) {
330        end = buffer_length * 2;
331      }
332      char* oldbuf = buffer;
333      assert(rm == NULL || Thread::current()->current_resource_mark() == rm,
334             "stringStream is re-allocated with a different ResourceMark");
335      buffer = NEW_RESOURCE_ARRAY(char, end);
336      strncpy(buffer, oldbuf, buffer_pos);
337      buffer_length = end;
338    }
339  }
340  // invariant: buffer is always null-terminated
341  guarantee(buffer_pos + write_len + 1 <= buffer_length, "stringStream oob");
342  buffer[buffer_pos + write_len] = 0;
343  strncpy(buffer + buffer_pos, s, write_len);
344  buffer_pos += write_len;
345
346  // Note that the following does not depend on write_len.
347  // This means that position and count get updated
348  // even when overflow occurs.
349  update_position(s, len);
350}
351
352char* stringStream::as_string() {
353  char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos + 1);
354  strncpy(copy, buffer, buffer_pos);
355  copy[buffer_pos] = 0;  // terminating null
356  return copy;
357}
358
359stringStream::~stringStream() {}
360
361xmlStream*   xtty;
362outputStream* tty;
363outputStream* gclog_or_tty;
364CDS_ONLY(fileStream* classlist_file;) // Only dump the classes that can be stored into the CDS archive
365extern Mutex* tty_lock;
366
367#define EXTRACHARLEN   32
368#define CURRENTAPPX    ".current"
369#define FILENAMEBUFLEN  1024
370// convert YYYY-MM-DD HH:MM:SS to YYYY-MM-DD_HH-MM-SS
371char* get_datetime_string(char *buf, size_t len) {
372  os::local_time_string(buf, len);
373  int i = (int)strlen(buf);
374  while (i-- >= 0) {
375    if (buf[i] == ' ') buf[i] = '_';
376    else if (buf[i] == ':') buf[i] = '-';
377  }
378  return buf;
379}
380
381static const char* make_log_name_internal(const char* log_name, const char* force_directory,
382                                                int pid, const char* tms) {
383  const char* basename = log_name;
384  char file_sep = os::file_separator()[0];
385  const char* cp;
386  char  pid_text[32];
387
388  for (cp = log_name; *cp != '\0'; cp++) {
389    if (*cp == '/' || *cp == file_sep) {
390      basename = cp + 1;
391    }
392  }
393  const char* nametail = log_name;
394  // Compute buffer length
395  size_t buffer_length;
396  if (force_directory != NULL) {
397    buffer_length = strlen(force_directory) + strlen(os::file_separator()) +
398                    strlen(basename) + 1;
399  } else {
400    buffer_length = strlen(log_name) + 1;
401  }
402
403  // const char* star = strchr(basename, '*');
404  const char* pts = strstr(basename, "%p");
405  int pid_pos = (pts == NULL) ? -1 : (pts - nametail);
406
407  if (pid_pos >= 0) {
408    jio_snprintf(pid_text, sizeof(pid_text), "pid%u", pid);
409    buffer_length += strlen(pid_text);
410  }
411
412  pts = strstr(basename, "%t");
413  int tms_pos = (pts == NULL) ? -1 : (pts - nametail);
414  if (tms_pos >= 0) {
415    buffer_length += strlen(tms);
416  }
417
418  // Create big enough buffer.
419  char *buf = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
420
421  strcpy(buf, "");
422  if (force_directory != NULL) {
423    strcat(buf, force_directory);
424    strcat(buf, os::file_separator());
425    nametail = basename;       // completely skip directory prefix
426  }
427
428  // who is first, %p or %t?
429  int first = -1, second = -1;
430  const char *p1st = NULL;
431  const char *p2nd = NULL;
432
433  if (pid_pos >= 0 && tms_pos >= 0) {
434    // contains both %p and %t
435    if (pid_pos < tms_pos) {
436      // case foo%pbar%tmonkey.log
437      first  = pid_pos;
438      p1st   = pid_text;
439      second = tms_pos;
440      p2nd   = tms;
441    } else {
442      // case foo%tbar%pmonkey.log
443      first  = tms_pos;
444      p1st   = tms;
445      second = pid_pos;
446      p2nd   = pid_text;
447    }
448  } else if (pid_pos >= 0) {
449    // contains %p only
450    first  = pid_pos;
451    p1st   = pid_text;
452  } else if (tms_pos >= 0) {
453    // contains %t only
454    first  = tms_pos;
455    p1st   = tms;
456  }
457
458  int buf_pos = (int)strlen(buf);
459  const char* tail = nametail;
460
461  if (first >= 0) {
462    tail = nametail + first + 2;
463    strncpy(&buf[buf_pos], nametail, first);
464    strcpy(&buf[buf_pos + first], p1st);
465    buf_pos = (int)strlen(buf);
466    if (second >= 0) {
467      strncpy(&buf[buf_pos], tail, second - first - 2);
468      strcpy(&buf[buf_pos + second - first - 2], p2nd);
469      tail = nametail + second + 2;
470    }
471  }
472  strcat(buf, tail);      // append rest of name, or all of name
473  return buf;
474}
475
476// log_name comes from -XX:LogFile=log_name, -Xloggc:log_name or
477// -XX:DumpLoadedClassList=<file_name>
478// in log_name, %p => pid1234 and
479//              %t => YYYY-MM-DD_HH-MM-SS
480static const char* make_log_name(const char* log_name, const char* force_directory) {
481  char timestr[32];
482  get_datetime_string(timestr, sizeof(timestr));
483  return make_log_name_internal(log_name, force_directory, os::current_process_id(),
484                                timestr);
485}
486
487#ifndef PRODUCT
488void test_loggc_filename() {
489  int pid;
490  char  tms[32];
491  char  i_result[FILENAMEBUFLEN];
492  const char* o_result;
493  get_datetime_string(tms, sizeof(tms));
494  pid = os::current_process_id();
495
496  // test.log
497  jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "test.log", tms);
498  o_result = make_log_name_internal("test.log", NULL, pid, tms);
499  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test.log\", NULL)");
500  FREE_C_HEAP_ARRAY(char, o_result);
501
502  // test-%t-%p.log
503  jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "test-%s-pid%u.log", tms, pid);
504  o_result = make_log_name_internal("test-%t-%p.log", NULL, pid, tms);
505  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test-%%t-%%p.log\", NULL)");
506  FREE_C_HEAP_ARRAY(char, o_result);
507
508  // test-%t%p.log
509  jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "test-%spid%u.log", tms, pid);
510  o_result = make_log_name_internal("test-%t%p.log", NULL, pid, tms);
511  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test-%%t%%p.log\", NULL)");
512  FREE_C_HEAP_ARRAY(char, o_result);
513
514  // %p%t.log
515  jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "pid%u%s.log", pid, tms);
516  o_result = make_log_name_internal("%p%t.log", NULL, pid, tms);
517  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%p%%t.log\", NULL)");
518  FREE_C_HEAP_ARRAY(char, o_result);
519
520  // %p-test.log
521  jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "pid%u-test.log", pid);
522  o_result = make_log_name_internal("%p-test.log", NULL, pid, tms);
523  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%p-test.log\", NULL)");
524  FREE_C_HEAP_ARRAY(char, o_result);
525
526  // %t.log
527  jio_snprintf(i_result, sizeof(char)*FILENAMEBUFLEN, "%s.log", tms);
528  o_result = make_log_name_internal("%t.log", NULL, pid, tms);
529  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%t.log\", NULL)");
530  FREE_C_HEAP_ARRAY(char, o_result);
531}
532#endif // PRODUCT
533
534fileStream::fileStream(const char* file_name) {
535  _file = fopen(file_name, "w");
536  if (_file != NULL) {
537    _need_close = true;
538  } else {
539    warning("Cannot open file %s due to %s\n", file_name, strerror(errno));
540    _need_close = false;
541  }
542}
543
544fileStream::fileStream(const char* file_name, const char* opentype) {
545  _file = fopen(file_name, opentype);
546  if (_file != NULL) {
547    _need_close = true;
548  } else {
549    warning("Cannot open file %s due to %s\n", file_name, strerror(errno));
550    _need_close = false;
551  }
552}
553
554void fileStream::write(const char* s, size_t len) {
555  if (_file != NULL)  {
556    // Make an unused local variable to avoid warning from gcc 4.x compiler.
557    size_t count = fwrite(s, 1, len, _file);
558  }
559  update_position(s, len);
560}
561
562long fileStream::fileSize() {
563  long size = -1;
564  if (_file != NULL) {
565    long pos  = ::ftell(_file);
566    if (::fseek(_file, 0, SEEK_END) == 0) {
567      size = ::ftell(_file);
568    }
569    ::fseek(_file, pos, SEEK_SET);
570  }
571  return size;
572}
573
574char* fileStream::readln(char *data, int count ) {
575  char * ret = ::fgets(data, count, _file);
576  //Get rid of annoying \n char
577  data[::strlen(data)-1] = '\0';
578  return ret;
579}
580
581fileStream::~fileStream() {
582  if (_file != NULL) {
583    if (_need_close) fclose(_file);
584    _file      = NULL;
585  }
586}
587
588void fileStream::flush() {
589  fflush(_file);
590}
591
592fdStream::fdStream(const char* file_name) {
593  _fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
594  _need_close = true;
595}
596
597fdStream::~fdStream() {
598  if (_fd != -1) {
599    if (_need_close) close(_fd);
600    _fd = -1;
601  }
602}
603
604void fdStream::write(const char* s, size_t len) {
605  if (_fd != -1) {
606    // Make an unused local variable to avoid warning from gcc 4.x compiler.
607    size_t count = ::write(_fd, s, (int)len);
608  }
609  update_position(s, len);
610}
611
612// dump vm version, os version, platform info, build id,
613// memory usage and command line flags into header
614void gcLogFileStream::dump_loggc_header() {
615  if (is_open()) {
616    print_cr("%s", Abstract_VM_Version::internal_vm_info_string());
617    os::print_memory_info(this);
618    print("CommandLine flags: ");
619    CommandLineFlags::printSetFlags(this);
620  }
621}
622
623gcLogFileStream::~gcLogFileStream() {
624  if (_file != NULL) {
625    if (_need_close) fclose(_file);
626    _file = NULL;
627  }
628  if (_file_name != NULL) {
629    FREE_C_HEAP_ARRAY(char, _file_name);
630    _file_name = NULL;
631  }
632}
633
634gcLogFileStream::gcLogFileStream(const char* file_name) {
635  _cur_file_num = 0;
636  _bytes_written = 0L;
637  _file_name = make_log_name(file_name, NULL);
638
639  // gc log file rotation
640  if (UseGCLogFileRotation && NumberOfGCLogFiles > 1) {
641    char tempbuf[FILENAMEBUFLEN];
642    jio_snprintf(tempbuf, sizeof(tempbuf), "%s.%d" CURRENTAPPX, _file_name, _cur_file_num);
643    _file = fopen(tempbuf, "w");
644  } else {
645    _file = fopen(_file_name, "w");
646  }
647  if (_file != NULL) {
648    _need_close = true;
649    dump_loggc_header();
650  } else {
651    warning("Cannot open file %s due to %s\n", _file_name, strerror(errno));
652    _need_close = false;
653  }
654}
655
656void gcLogFileStream::write(const char* s, size_t len) {
657  if (_file != NULL) {
658    size_t count = fwrite(s, 1, len, _file);
659    _bytes_written += count;
660  }
661  update_position(s, len);
662}
663
664// rotate_log must be called from VMThread at safepoint. In case need change parameters
665// for gc log rotation from thread other than VMThread, a sub type of VM_Operation
666// should be created and be submitted to VMThread's operation queue. DO NOT call this
667// function directly. Currently, it is safe to rotate log at safepoint through VMThread.
668// That is, no mutator threads and concurrent GC threads run parallel with VMThread to
669// write to gc log file at safepoint. If in future, changes made for mutator threads or
670// concurrent GC threads to run parallel with VMThread at safepoint, write and rotate_log
671// must be synchronized.
672void gcLogFileStream::rotate_log(bool force, outputStream* out) {
673  char time_msg[FILENAMEBUFLEN];
674  char time_str[EXTRACHARLEN];
675  char current_file_name[FILENAMEBUFLEN];
676  char renamed_file_name[FILENAMEBUFLEN];
677
678  if (!should_rotate(force)) {
679    return;
680  }
681
682#ifdef ASSERT
683  Thread *thread = Thread::current();
684  assert(thread == NULL ||
685         (thread->is_VM_thread() && SafepointSynchronize::is_at_safepoint()),
686         "Must be VMThread at safepoint");
687#endif
688  if (NumberOfGCLogFiles == 1) {
689    // rotate in same file
690    rewind();
691    _bytes_written = 0L;
692    jio_snprintf(time_msg, sizeof(time_msg), "File  %s rotated at %s\n",
693                 _file_name, os::local_time_string((char *)time_str, sizeof(time_str)));
694    write(time_msg, strlen(time_msg));
695
696    if (out != NULL) {
697      out->print("%s", time_msg);
698    }
699
700    dump_loggc_header();
701    return;
702  }
703
704#if defined(_WINDOWS)
705#ifndef F_OK
706#define F_OK 0
707#endif
708#endif // _WINDOWS
709
710  // rotate file in names extended_filename.0, extended_filename.1, ...,
711  // extended_filename.<NumberOfGCLogFiles - 1>. Current rotation file name will
712  // have a form of extended_filename.<i>.current where i is the current rotation
713  // file number. After it reaches max file size, the file will be saved and renamed
714  // with .current removed from its tail.
715  size_t filename_len = strlen(_file_name);
716  if (_file != NULL) {
717    jio_snprintf(renamed_file_name, filename_len + EXTRACHARLEN, "%s.%d",
718                 _file_name, _cur_file_num);
719    jio_snprintf(current_file_name, filename_len + EXTRACHARLEN, "%s.%d" CURRENTAPPX,
720                 _file_name, _cur_file_num);
721
722    const char* msg = force ? "GC log rotation request has been received."
723                            : "GC log file has reached the maximum size.";
724    jio_snprintf(time_msg, sizeof(time_msg), "%s %s Saved as %s\n",
725                     os::local_time_string((char *)time_str, sizeof(time_str)),
726                                                         msg, renamed_file_name);
727    write(time_msg, strlen(time_msg));
728
729    if (out != NULL) {
730      out->print("%s", time_msg);
731    }
732
733    fclose(_file);
734    _file = NULL;
735
736    bool can_rename = true;
737    if (access(current_file_name, F_OK) != 0) {
738      // current file does not exist?
739      warning("No source file exists, cannot rename\n");
740      can_rename = false;
741    }
742    if (can_rename) {
743      if (access(renamed_file_name, F_OK) == 0) {
744        if (remove(renamed_file_name) != 0) {
745          warning("Could not delete existing file %s\n", renamed_file_name);
746          can_rename = false;
747        }
748      } else {
749        // file does not exist, ok to rename
750      }
751    }
752    if (can_rename && rename(current_file_name, renamed_file_name) != 0) {
753      warning("Could not rename %s to %s\n", _file_name, renamed_file_name);
754    }
755  }
756
757  _cur_file_num++;
758  if (_cur_file_num > NumberOfGCLogFiles - 1) _cur_file_num = 0;
759  jio_snprintf(current_file_name,  filename_len + EXTRACHARLEN, "%s.%d" CURRENTAPPX,
760               _file_name, _cur_file_num);
761  _file = fopen(current_file_name, "w");
762
763  if (_file != NULL) {
764    _bytes_written = 0L;
765    _need_close = true;
766    // reuse current_file_name for time_msg
767    jio_snprintf(current_file_name, filename_len + EXTRACHARLEN,
768                 "%s.%d", _file_name, _cur_file_num);
769    jio_snprintf(time_msg, sizeof(time_msg), "%s GC log file created %s\n",
770                           os::local_time_string((char *)time_str, sizeof(time_str)),
771                           current_file_name);
772    write(time_msg, strlen(time_msg));
773
774    if (out != NULL) {
775      out->print("%s", time_msg);
776    }
777
778    dump_loggc_header();
779    // remove the existing file
780    if (access(current_file_name, F_OK) == 0) {
781      if (remove(current_file_name) != 0) {
782        warning("Could not delete existing file %s\n", current_file_name);
783      }
784    }
785  } else {
786    warning("failed to open rotation log file %s due to %s\n"
787            "Turned off GC log file rotation\n",
788                  _file_name, strerror(errno));
789    _need_close = false;
790    FLAG_SET_DEFAULT(UseGCLogFileRotation, false);
791  }
792}
793
794defaultStream* defaultStream::instance = NULL;
795int defaultStream::_output_fd = 1;
796int defaultStream::_error_fd  = 2;
797FILE* defaultStream::_output_stream = stdout;
798FILE* defaultStream::_error_stream  = stderr;
799
800#define LOG_MAJOR_VERSION 160
801#define LOG_MINOR_VERSION 1
802
803void defaultStream::init() {
804  _inited = true;
805  if (LogVMOutput || LogCompilation) {
806    init_log();
807  }
808}
809
810bool defaultStream::has_log_file() {
811  // lazily create log file (at startup, LogVMOutput is false even
812  // if +LogVMOutput is used, because the flags haven't been parsed yet)
813  // For safer printing during fatal error handling, do not init logfile
814  // if a VM error has been reported.
815  if (!_inited && !is_error_reported())  init();
816  return _log_file != NULL;
817}
818
819void defaultStream::init_log() {
820  // %%% Need a MutexLocker?
821  const char* log_name = LogFile != NULL ? LogFile : "hotspot_%p.log";
822  const char* try_name = make_log_name(log_name, NULL);
823  fileStream* file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name);
824  if (!file->is_open()) {
825    // Try again to open the file.
826    char warnbuf[O_BUFLEN*2];
827    jio_snprintf(warnbuf, sizeof(warnbuf),
828                 "Warning:  Cannot open log file: %s\n", try_name);
829    // Note:  This feature is for maintainer use only.  No need for L10N.
830    jio_print(warnbuf);
831    FREE_C_HEAP_ARRAY(char, try_name);
832    try_name = make_log_name(log_name, os::get_temp_directory());
833    jio_snprintf(warnbuf, sizeof(warnbuf),
834                 "Warning:  Forcing option -XX:LogFile=%s\n", try_name);
835    jio_print(warnbuf);
836    delete file;
837    file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name);
838  }
839  FREE_C_HEAP_ARRAY(char, try_name);
840
841  if (file->is_open()) {
842    _log_file = file;
843    xmlStream* xs = new(ResourceObj::C_HEAP, mtInternal) xmlStream(file);
844    _outer_xmlStream = xs;
845    if (this == tty)  xtty = xs;
846    // Write XML header.
847    xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
848    // (For now, don't bother to issue a DTD for this private format.)
849    jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
850    // %%% Should be: jlong time_ms = os::start_time_milliseconds(), if
851    // we ever get round to introduce that method on the os class
852    xs->head("hotspot_log version='%d %d'"
853             " process='%d' time_ms='"INT64_FORMAT"'",
854             LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
855             os::current_process_id(), (int64_t)time_ms);
856    // Write VM version header immediately.
857    xs->head("vm_version");
858    xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr();
859    xs->tail("name");
860    xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr();
861    xs->tail("release");
862    xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr();
863    xs->tail("info");
864    xs->tail("vm_version");
865    // Record information about the command-line invocation.
866    xs->head("vm_arguments");  // Cf. Arguments::print_on()
867    if (Arguments::num_jvm_flags() > 0) {
868      xs->head("flags");
869      Arguments::print_jvm_flags_on(xs->text());
870      xs->tail("flags");
871    }
872    if (Arguments::num_jvm_args() > 0) {
873      xs->head("args");
874      Arguments::print_jvm_args_on(xs->text());
875      xs->tail("args");
876    }
877    if (Arguments::java_command() != NULL) {
878      xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command());
879      xs->tail("command");
880    }
881    if (Arguments::sun_java_launcher() != NULL) {
882      xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher());
883      xs->tail("launcher");
884    }
885    if (Arguments::system_properties() !=  NULL) {
886      xs->head("properties");
887      // Print it as a java-style property list.
888      // System properties don't generally contain newlines, so don't bother with unparsing.
889      for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
890        xs->text()->print_cr("%s=%s", p->key(), p->value());
891      }
892      xs->tail("properties");
893    }
894    xs->tail("vm_arguments");
895    // tty output per se is grouped under the <tty>...</tty> element.
896    xs->head("tty");
897    // All further non-markup text gets copied to the tty:
898    xs->_text = this;  // requires friend declaration!
899  } else {
900    delete(file);
901    // and leave xtty as NULL
902    LogVMOutput = false;
903    DisplayVMOutput = true;
904    LogCompilation = false;
905  }
906}
907
908// finish_log() is called during normal VM shutdown. finish_log_on_error() is
909// called by ostream_abort() after a fatal error.
910//
911void defaultStream::finish_log() {
912  xmlStream* xs = _outer_xmlStream;
913  xs->done("tty");
914
915  // Other log forks are appended here, at the End of Time:
916  CompileLog::finish_log(xs->out());  // write compile logging, if any, now
917
918  xs->done("hotspot_log");
919  xs->flush();
920
921  fileStream* file = _log_file;
922  _log_file = NULL;
923
924  delete _outer_xmlStream;
925  _outer_xmlStream = NULL;
926
927  file->flush();
928  delete file;
929}
930
931void defaultStream::finish_log_on_error(char *buf, int buflen) {
932  xmlStream* xs = _outer_xmlStream;
933
934  if (xs && xs->out()) {
935
936    xs->done_raw("tty");
937
938    // Other log forks are appended here, at the End of Time:
939    CompileLog::finish_log_on_error(xs->out(), buf, buflen);  // write compile logging, if any, now
940
941    xs->done_raw("hotspot_log");
942    xs->flush();
943
944    fileStream* file = _log_file;
945    _log_file = NULL;
946    _outer_xmlStream = NULL;
947
948    if (file) {
949      file->flush();
950
951      // Can't delete or close the file because delete and fclose aren't
952      // async-safe. We are about to die, so leave it to the kernel.
953      // delete file;
954    }
955  }
956}
957
958intx defaultStream::hold(intx writer_id) {
959  bool has_log = has_log_file();  // check before locking
960  if (// impossible, but who knows?
961      writer_id == NO_WRITER ||
962
963      // bootstrap problem
964      tty_lock == NULL ||
965
966      // can't grab a lock or call Thread::current() if TLS isn't initialized
967      ThreadLocalStorage::thread() == NULL ||
968
969      // developer hook
970      !SerializeVMOutput ||
971
972      // VM already unhealthy
973      is_error_reported() ||
974
975      // safepoint == global lock (for VM only)
976      (SafepointSynchronize::is_synchronizing() &&
977       Thread::current()->is_VM_thread())
978      ) {
979    // do not attempt to lock unless we know the thread and the VM is healthy
980    return NO_WRITER;
981  }
982  if (_writer == writer_id) {
983    // already held, no need to re-grab the lock
984    return NO_WRITER;
985  }
986  tty_lock->lock_without_safepoint_check();
987  // got the lock
988  if (writer_id != _last_writer) {
989    if (has_log) {
990      _log_file->bol();
991      // output a hint where this output is coming from:
992      _log_file->print_cr("<writer thread='" UINTX_FORMAT "'/>", writer_id);
993    }
994    _last_writer = writer_id;
995  }
996  _writer = writer_id;
997  return writer_id;
998}
999
1000void defaultStream::release(intx holder) {
1001  if (holder == NO_WRITER) {
1002    // nothing to release:  either a recursive lock, or we scribbled (too bad)
1003    return;
1004  }
1005  if (_writer != holder) {
1006    return;  // already unlocked, perhaps via break_tty_lock_for_safepoint
1007  }
1008  _writer = NO_WRITER;
1009  tty_lock->unlock();
1010}
1011
1012
1013// Yuck:  jio_print does not accept char*/len.
1014static void call_jio_print(const char* s, size_t len) {
1015  char buffer[O_BUFLEN+100];
1016  if (len > sizeof(buffer)-1) {
1017    warning("increase O_BUFLEN in ostream.cpp -- output truncated");
1018    len = sizeof(buffer)-1;
1019  }
1020  strncpy(buffer, s, len);
1021  buffer[len] = '\0';
1022  jio_print(buffer);
1023}
1024
1025
1026void defaultStream::write(const char* s, size_t len) {
1027  intx thread_id = os::current_thread_id();
1028  intx holder = hold(thread_id);
1029
1030  if (DisplayVMOutput &&
1031      (_outer_xmlStream == NULL || !_outer_xmlStream->inside_attrs())) {
1032    // print to output stream. It can be redirected by a vfprintf hook
1033    if (s[len] == '\0') {
1034      jio_print(s);
1035    } else {
1036      call_jio_print(s, len);
1037    }
1038  }
1039
1040  // print to log file
1041  if (has_log_file()) {
1042    int nl0 = _newlines;
1043    xmlTextStream::write(s, len);
1044    // flush the log file too, if there were any newlines
1045    if (nl0 != _newlines){
1046      flush();
1047    }
1048  } else {
1049    update_position(s, len);
1050  }
1051
1052  release(holder);
1053}
1054
1055intx ttyLocker::hold_tty() {
1056  if (defaultStream::instance == NULL)  return defaultStream::NO_WRITER;
1057  intx thread_id = os::current_thread_id();
1058  return defaultStream::instance->hold(thread_id);
1059}
1060
1061void ttyLocker::release_tty(intx holder) {
1062  if (holder == defaultStream::NO_WRITER)  return;
1063  defaultStream::instance->release(holder);
1064}
1065
1066bool ttyLocker::release_tty_if_locked() {
1067  intx thread_id = os::current_thread_id();
1068  if (defaultStream::instance->writer() == thread_id) {
1069    // release the lock and return true so callers know if was
1070    // previously held.
1071    release_tty(thread_id);
1072    return true;
1073  }
1074  return false;
1075}
1076
1077void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
1078  if (defaultStream::instance != NULL &&
1079      defaultStream::instance->writer() == holder) {
1080    if (xtty != NULL) {
1081      xtty->print_cr("<!-- safepoint while printing -->");
1082    }
1083    defaultStream::instance->release(holder);
1084  }
1085  // (else there was no lock to break)
1086}
1087
1088void ostream_init() {
1089  if (defaultStream::instance == NULL) {
1090    defaultStream::instance = new(ResourceObj::C_HEAP, mtInternal) defaultStream();
1091    tty = defaultStream::instance;
1092
1093    // We want to ensure that time stamps in GC logs consider time 0
1094    // the time when the JVM is initialized, not the first time we ask
1095    // for a time stamp. So, here, we explicitly update the time stamp
1096    // of tty.
1097    tty->time_stamp().update_to(1);
1098  }
1099}
1100
1101void ostream_init_log() {
1102  // For -Xloggc:<file> option - called in runtime/thread.cpp
1103  // Note : this must be called AFTER ostream_init()
1104
1105  gclog_or_tty = tty; // default to tty
1106  if (Arguments::gc_log_filename() != NULL) {
1107    fileStream * gclog  = new(ResourceObj::C_HEAP, mtInternal)
1108                             gcLogFileStream(Arguments::gc_log_filename());
1109    if (gclog->is_open()) {
1110      // now we update the time stamp of the GC log to be synced up
1111      // with tty.
1112      gclog->time_stamp().update_to(tty->time_stamp().ticks());
1113    }
1114    gclog_or_tty = gclog;
1115  }
1116
1117#if INCLUDE_CDS
1118  // For -XX:DumpLoadedClassList=<file> option
1119  if (DumpLoadedClassList != NULL) {
1120    const char* list_name = make_log_name(DumpLoadedClassList, NULL);
1121    classlist_file = new(ResourceObj::C_HEAP, mtInternal)
1122                         fileStream(list_name);
1123    FREE_C_HEAP_ARRAY(char, list_name);
1124  }
1125#endif
1126
1127  // If we haven't lazily initialized the logfile yet, do it now,
1128  // to avoid the possibility of lazy initialization during a VM
1129  // crash, which can affect the stability of the fatal error handler.
1130  defaultStream::instance->has_log_file();
1131}
1132
1133// ostream_exit() is called during normal VM exit to finish log files, flush
1134// output and free resource.
1135void ostream_exit() {
1136  static bool ostream_exit_called = false;
1137  if (ostream_exit_called)  return;
1138  ostream_exit_called = true;
1139#if INCLUDE_CDS
1140  if (classlist_file != NULL) {
1141    delete classlist_file;
1142  }
1143#endif
1144  if (gclog_or_tty != tty) {
1145      delete gclog_or_tty;
1146  }
1147  {
1148      // we temporaly disable PrintMallocFree here
1149      // as otherwise it'll lead to using of almost deleted
1150      // tty or defaultStream::instance in logging facility
1151      // of HeapFree(), see 6391258
1152      DEBUG_ONLY(FlagSetting fs(PrintMallocFree, false);)
1153      if (tty != defaultStream::instance) {
1154          delete tty;
1155      }
1156      if (defaultStream::instance != NULL) {
1157          delete defaultStream::instance;
1158      }
1159  }
1160  tty = NULL;
1161  xtty = NULL;
1162  gclog_or_tty = NULL;
1163  defaultStream::instance = NULL;
1164}
1165
1166// ostream_abort() is called by os::abort() when VM is about to die.
1167void ostream_abort() {
1168  // Here we can't delete gclog_or_tty and tty, just flush their output
1169  if (gclog_or_tty) gclog_or_tty->flush();
1170  if (tty) tty->flush();
1171
1172  if (defaultStream::instance != NULL) {
1173    static char buf[4096];
1174    defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
1175  }
1176}
1177
1178staticBufferStream::staticBufferStream(char* buffer, size_t buflen,
1179                                       outputStream *outer_stream) {
1180  _buffer = buffer;
1181  _buflen = buflen;
1182  _outer_stream = outer_stream;
1183  // compile task prints time stamp relative to VM start
1184  _stamp.update_to(1);
1185}
1186
1187void staticBufferStream::write(const char* c, size_t len) {
1188  _outer_stream->print_raw(c, (int)len);
1189}
1190
1191void staticBufferStream::flush() {
1192  _outer_stream->flush();
1193}
1194
1195void staticBufferStream::print(const char* format, ...) {
1196  va_list ap;
1197  va_start(ap, format);
1198  size_t len;
1199  const char* str = do_vsnprintf(_buffer, _buflen, format, ap, false, len);
1200  write(str, len);
1201  va_end(ap);
1202}
1203
1204void staticBufferStream::print_cr(const char* format, ...) {
1205  va_list ap;
1206  va_start(ap, format);
1207  size_t len;
1208  const char* str = do_vsnprintf(_buffer, _buflen, format, ap, true, len);
1209  write(str, len);
1210  va_end(ap);
1211}
1212
1213void staticBufferStream::vprint(const char *format, va_list argptr) {
1214  size_t len;
1215  const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, false, len);
1216  write(str, len);
1217}
1218
1219void staticBufferStream::vprint_cr(const char* format, va_list argptr) {
1220  size_t len;
1221  const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, true, len);
1222  write(str, len);
1223}
1224
1225bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
1226  buffer_length = initial_size;
1227  buffer        = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
1228  buffer_pos    = 0;
1229  buffer_fixed  = false;
1230  buffer_max    = bufmax;
1231}
1232
1233bufferedStream::bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax) : outputStream() {
1234  buffer_length = fixed_buffer_size;
1235  buffer        = fixed_buffer;
1236  buffer_pos    = 0;
1237  buffer_fixed  = true;
1238  buffer_max    = bufmax;
1239}
1240
1241void bufferedStream::write(const char* s, size_t len) {
1242
1243  if(buffer_pos + len > buffer_max) {
1244    flush();
1245  }
1246
1247  size_t end = buffer_pos + len;
1248  if (end >= buffer_length) {
1249    if (buffer_fixed) {
1250      // if buffer cannot resize, silently truncate
1251      len = buffer_length - buffer_pos - 1;
1252    } else {
1253      // For small overruns, double the buffer.  For larger ones,
1254      // increase to the requested size.
1255      if (end < buffer_length * 2) {
1256        end = buffer_length * 2;
1257      }
1258      buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end, mtInternal);
1259      buffer_length = end;
1260    }
1261  }
1262  memcpy(buffer + buffer_pos, s, len);
1263  buffer_pos += len;
1264  update_position(s, len);
1265}
1266
1267char* bufferedStream::as_string() {
1268  char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
1269  strncpy(copy, buffer, buffer_pos);
1270  copy[buffer_pos] = 0;  // terminating null
1271  return copy;
1272}
1273
1274bufferedStream::~bufferedStream() {
1275  if (!buffer_fixed) {
1276    FREE_C_HEAP_ARRAY(char, buffer);
1277  }
1278}
1279
1280#ifndef PRODUCT
1281
1282#if defined(SOLARIS) || defined(LINUX) || defined(AIX) || defined(_ALLBSD_SOURCE)
1283#include <sys/types.h>
1284#include <sys/socket.h>
1285#include <netinet/in.h>
1286#include <arpa/inet.h>
1287#endif
1288
1289// Network access
1290networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
1291
1292  _socket = -1;
1293
1294  int result = os::socket(AF_INET, SOCK_STREAM, 0);
1295  if (result <= 0) {
1296    assert(false, "Socket could not be created!");
1297  } else {
1298    _socket = result;
1299  }
1300}
1301
1302int networkStream::read(char *buf, size_t len) {
1303  return os::recv(_socket, buf, (int)len, 0);
1304}
1305
1306void networkStream::flush() {
1307  if (size() != 0) {
1308    int result = os::raw_send(_socket, (char *)base(), size(), 0);
1309    assert(result != -1, "connection error");
1310    assert(result == (int)size(), "didn't send enough data");
1311  }
1312  reset();
1313}
1314
1315networkStream::~networkStream() {
1316  close();
1317}
1318
1319void networkStream::close() {
1320  if (_socket != -1) {
1321    flush();
1322    os::socket_close(_socket);
1323    _socket = -1;
1324  }
1325}
1326
1327bool networkStream::connect(const char *ip, short port) {
1328
1329  struct sockaddr_in server;
1330  server.sin_family = AF_INET;
1331  server.sin_port = htons(port);
1332
1333  server.sin_addr.s_addr = inet_addr(ip);
1334  if (server.sin_addr.s_addr == (uint32_t)-1) {
1335    struct hostent* host = os::get_host_by_name((char*)ip);
1336    if (host != NULL) {
1337      memcpy(&server.sin_addr, host->h_addr_list[0], host->h_length);
1338    } else {
1339      return false;
1340    }
1341  }
1342
1343
1344  int result = os::connect(_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_in));
1345  return (result >= 0);
1346}
1347
1348#endif
1349