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