ostream.cpp 48.1 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26
#include "precompiled.hpp"
#include "compiler/compileLog.hpp"
27
#include "gc_implementation/shared/gcId.hpp"
28 29
#include "oops/oop.inline.hpp"
#include "runtime/arguments.hpp"
P
phh 已提交
30
#include "runtime/mutexLocker.hpp"
31
#include "runtime/os.hpp"
32
#include "runtime/vmThread.hpp"
33 34 35 36 37 38 39 40 41 42 43 44 45
#include "utilities/defaultStream.hpp"
#include "utilities/ostream.hpp"
#include "utilities/top.hpp"
#include "utilities/xmlstream.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif
46 47 48
#ifdef TARGET_OS_FAMILY_aix
# include "os_aix.inline.hpp"
#endif
N
never 已提交
49 50 51
#ifdef TARGET_OS_FAMILY_bsd
# include "os_bsd.inline.hpp"
#endif
D
duke 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

extern "C" void jio_print(const char* s); // Declarationtion of jvm method

outputStream::outputStream(int width) {
  _width       = width;
  _position    = 0;
  _newlines    = 0;
  _precount    = 0;
  _indentation = 0;
}

outputStream::outputStream(int width, bool has_time_stamps) {
  _width       = width;
  _position    = 0;
  _newlines    = 0;
  _precount    = 0;
  _indentation = 0;
  if (has_time_stamps)  _stamp.update();
}

void outputStream::update_position(const char* s, size_t len) {
  for (size_t i = 0; i < len; i++) {
    char ch = s[i];
    if (ch == '\n') {
      _newlines += 1;
      _precount += _position + 1;
      _position = 0;
    } else if (ch == '\t') {
80 81 82
      int tw = 8 - (_position & 7);
      _position += tw;
      _precount -= tw-1;  // invariant:  _precount + _position == total count
D
duke 已提交
83 84 85 86 87 88 89 90 91 92 93 94
    } else {
      _position += 1;
    }
  }
}

// Execute a vsprintf, using the given buffer if necessary.
// Return a pointer to the formatted string.
const char* outputStream::do_vsnprintf(char* buffer, size_t buflen,
                                       const char* format, va_list ap,
                                       bool add_cr,
                                       size_t& result_len) {
95 96
  assert(buflen >= 2, "buffer too small");

D
duke 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109
  const char* result;
  if (add_cr)  buflen--;
  if (!strchr(format, '%')) {
    // constant format string
    result = format;
    result_len = strlen(result);
    if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
  } else if (format[0] == '%' && format[1] == 's' && format[2] == '\0') {
    // trivial copy-through format string
    result = va_arg(ap, const char*);
    result_len = strlen(result);
    if (add_cr && result_len >= buflen)  result_len = buflen-1;  // truncate
  } else {
110 111
    int written = os::vsnprintf(buffer, buflen, format, ap);
    assert(written >= 0, "vsnprintf encoding error");
D
duke 已提交
112
    result = buffer;
113 114 115 116 117 118
    if ((size_t)written < buflen) {
      result_len = written;
    } else {
      DEBUG_ONLY(warning("increase O_BUFLEN in ostream.hpp -- output truncated");)
      result_len = buflen - 1;
    }
D
duke 已提交
119 120 121
  }
  if (add_cr) {
    if (result != buffer) {
122
      memcpy(buffer, result, result_len);
D
duke 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
      result = buffer;
    }
    buffer[result_len++] = '\n';
    buffer[result_len] = 0;
  }
  return result;
}

void outputStream::print(const char* format, ...) {
  char buffer[O_BUFLEN];
  va_list ap;
  va_start(ap, format);
  size_t len;
  const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, false, len);
  write(str, len);
  va_end(ap);
}

void outputStream::print_cr(const char* format, ...) {
  char buffer[O_BUFLEN];
  va_list ap;
  va_start(ap, format);
  size_t len;
  const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, true, len);
  write(str, len);
  va_end(ap);
}

void outputStream::vprint(const char *format, va_list argptr) {
  char buffer[O_BUFLEN];
  size_t len;
  const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, false, len);
  write(str, len);
}

void outputStream::vprint_cr(const char* format, va_list argptr) {
  char buffer[O_BUFLEN];
  size_t len;
  const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, true, len);
  write(str, len);
}

void outputStream::fill_to(int col) {
166 167 168 169 170 171 172 173 174 175 176
  int need_fill = col - position();
  sp(need_fill);
}

void outputStream::move_to(int col, int slop, int min_space) {
  if (position() >= col + slop)
    cr();
  int need_fill = col - position();
  if (need_fill < min_space)
    need_fill = min_space;
  sp(need_fill);
D
duke 已提交
177 178 179 180 181 182 183 184
}

void outputStream::put(char ch) {
  assert(ch != 0, "please fix call site");
  char buf[] = { ch, '\0' };
  write(buf, 1);
}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
#define SP_USE_TABS false

void outputStream::sp(int count) {
  if (count < 0)  return;
  if (SP_USE_TABS && count >= 8) {
    int target = position() + count;
    while (count >= 8) {
      this->write("\t", 1);
      count -= 8;
    }
    count = target - position();
  }
  while (count > 0) {
    int nw = (count > 8) ? 8 : count;
    this->write("        ", nw);
    count -= nw;
  }
D
duke 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
}

void outputStream::cr() {
  this->write("\n", 1);
}

void outputStream::stamp() {
  if (! _stamp.is_updated()) {
    _stamp.update(); // start at 0 on first call to stamp()
  }

  // outputStream::stamp() may get called by ostream_abort(), use snprintf
  // to avoid allocating large stack buffer in print().
  char buf[40];
  jio_snprintf(buf, sizeof(buf), "%.3f", _stamp.seconds());
  print_raw(buf);
}

220 221 222 223 224 225 226 227 228 229 230
void outputStream::stamp(bool guard,
                         const char* prefix,
                         const char* suffix) {
  if (!guard) {
    return;
  }
  print_raw(prefix);
  stamp();
  print_raw(suffix);
}

D
duke 已提交
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
void outputStream::date_stamp(bool guard,
                              const char* prefix,
                              const char* suffix) {
  if (!guard) {
    return;
  }
  print_raw(prefix);
  static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz";
  static const int buffer_length = 32;
  char buffer[buffer_length];
  const char* iso8601_result = os::iso8601_time(buffer, buffer_length);
  if (iso8601_result != NULL) {
    print_raw(buffer);
  } else {
    print_raw(error_time);
  }
  print_raw(suffix);
  return;
}

251 252 253 254 255 256 257 258
void outputStream::gclog_stamp(const GCId& gc_id) {
  date_stamp(PrintGCDateStamps);
  stamp(PrintGCTimeStamps);
  if (PrintGCID) {
    print("#%u: ", gc_id.id());
  }
}

259
outputStream& outputStream::indent() {
D
duke 已提交
260
  while (_position < _indentation) sp();
261
  return *this;
D
duke 已提交
262 263 264
}

void outputStream::print_jlong(jlong value) {
265
  print(JLONG_FORMAT, value);
D
duke 已提交
266 267 268
}

void outputStream::print_julong(julong value) {
269
  print(JULONG_FORMAT, value);
D
duke 已提交
270 271
}

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
/**
 * This prints out hex data in a 'windbg' or 'xxd' form, where each line is:
 *   <hex-address>: 8 * <hex-halfword> <ascii translation (optional)>
 * example:
 * 0000000: 7f44 4f46 0102 0102 0000 0000 0000 0000  .DOF............
 * 0000010: 0000 0000 0000 0040 0000 0020 0000 0005  .......@... ....
 * 0000020: 0000 0000 0000 0040 0000 0000 0000 015d  .......@.......]
 * ...
 *
 * indent is applied to each line.  Ends with a CR.
 */
void outputStream::print_data(void* data, size_t len, bool with_ascii) {
  size_t limit = (len + 16) / 16 * 16;
  for (size_t i = 0; i < limit; ++i) {
    if (i % 16 == 0) {
287
      indent().print(SIZE_FORMAT_HEX_W(07) ":", i);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    }
    if (i % 2 == 0) {
      print(" ");
    }
    if (i < len) {
      print("%02x", ((unsigned char*)data)[i]);
    } else {
      print("  ");
    }
    if ((i + 1) % 16 == 0) {
      if (with_ascii) {
        print("  ");
        for (size_t j = 0; j < 16; ++j) {
          size_t idx = i + j - 15;
          if (idx < len) {
            char c = ((char*)data)[idx];
            print("%c", c >= 32 && c <= 126 ? c : '.');
          }
        }
      }
308
      cr();
309 310 311 312
    }
  }
}

D
duke 已提交
313 314 315 316 317
stringStream::stringStream(size_t initial_size) : outputStream() {
  buffer_length = initial_size;
  buffer        = NEW_RESOURCE_ARRAY(char, buffer_length);
  buffer_pos    = 0;
  buffer_fixed  = false;
318
  DEBUG_ONLY(rm = Thread::current()->current_resource_mark();)
D
duke 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
}

// useful for output to fixed chunks of memory, such as performance counters
stringStream::stringStream(char* fixed_buffer, size_t fixed_buffer_size) : outputStream() {
  buffer_length = fixed_buffer_size;
  buffer        = fixed_buffer;
  buffer_pos    = 0;
  buffer_fixed  = true;
}

void stringStream::write(const char* s, size_t len) {
  size_t write_len = len;               // number of non-null bytes to write
  size_t end = buffer_pos + len + 1;    // position after write and final '\0'
  if (end > buffer_length) {
    if (buffer_fixed) {
      // if buffer cannot resize, silently truncate
      end = buffer_length;
      write_len = end - buffer_pos - 1; // leave room for the final '\0'
    } else {
      // For small overruns, double the buffer.  For larger ones,
      // increase to the requested size.
      if (end < buffer_length * 2) {
        end = buffer_length * 2;
      }
      char* oldbuf = buffer;
344 345
      assert(rm == NULL || Thread::current()->current_resource_mark() == rm,
             "stringStream is re-allocated with a different ResourceMark");
D
duke 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
      buffer = NEW_RESOURCE_ARRAY(char, end);
      strncpy(buffer, oldbuf, buffer_pos);
      buffer_length = end;
    }
  }
  // invariant: buffer is always null-terminated
  guarantee(buffer_pos + write_len + 1 <= buffer_length, "stringStream oob");
  buffer[buffer_pos + write_len] = 0;
  strncpy(buffer + buffer_pos, s, write_len);
  buffer_pos += write_len;

  // Note that the following does not depend on write_len.
  // This means that position and count get updated
  // even when overflow occurs.
  update_position(s, len);
}

char* stringStream::as_string() {
364
  char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos + 1);
D
duke 已提交
365 366 367 368 369 370 371 372 373 374
  strncpy(copy, buffer, buffer_pos);
  copy[buffer_pos] = 0;  // terminating null
  return copy;
}

stringStream::~stringStream() {}

xmlStream*   xtty;
outputStream* tty;
outputStream* gclog_or_tty;
375
CDS_ONLY(fileStream* classlist_file;) // Only dump the classes that can be stored into the CDS archive
D
duke 已提交
376 377
extern Mutex* tty_lock;

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
#define EXTRACHARLEN   32
#define CURRENTAPPX    ".current"
// convert YYYY-MM-DD HH:MM:SS to YYYY-MM-DD_HH-MM-SS
char* get_datetime_string(char *buf, size_t len) {
  os::local_time_string(buf, len);
  int i = (int)strlen(buf);
  while (i-- >= 0) {
    if (buf[i] == ' ') buf[i] = '_';
    else if (buf[i] == ':') buf[i] = '-';
  }
  return buf;
}

static const char* make_log_name_internal(const char* log_name, const char* force_directory,
                                                int pid, const char* tms) {
  const char* basename = log_name;
  char file_sep = os::file_separator()[0];
  const char* cp;
  char  pid_text[32];

  for (cp = log_name; *cp != '\0'; cp++) {
    if (*cp == '/' || *cp == file_sep) {
      basename = cp + 1;
    }
  }
  const char* nametail = log_name;
  // Compute buffer length
  size_t buffer_length;
  if (force_directory != NULL) {
    buffer_length = strlen(force_directory) + strlen(os::file_separator()) +
                    strlen(basename) + 1;
  } else {
    buffer_length = strlen(log_name) + 1;
  }

  const char* pts = strstr(basename, "%p");
  int pid_pos = (pts == NULL) ? -1 : (pts - nametail);

  if (pid_pos >= 0) {
    jio_snprintf(pid_text, sizeof(pid_text), "pid%u", pid);
    buffer_length += strlen(pid_text);
  }

  pts = strstr(basename, "%t");
  int tms_pos = (pts == NULL) ? -1 : (pts - nametail);
  if (tms_pos >= 0) {
    buffer_length += strlen(tms);
  }

B
brutisso 已提交
427 428 429 430 431
  // File name is too long.
  if (buffer_length > JVM_MAXPATHLEN) {
    return NULL;
  }

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  // Create big enough buffer.
  char *buf = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);

  strcpy(buf, "");
  if (force_directory != NULL) {
    strcat(buf, force_directory);
    strcat(buf, os::file_separator());
    nametail = basename;       // completely skip directory prefix
  }

  // who is first, %p or %t?
  int first = -1, second = -1;
  const char *p1st = NULL;
  const char *p2nd = NULL;

  if (pid_pos >= 0 && tms_pos >= 0) {
    // contains both %p and %t
    if (pid_pos < tms_pos) {
      // case foo%pbar%tmonkey.log
      first  = pid_pos;
      p1st   = pid_text;
      second = tms_pos;
      p2nd   = tms;
    } else {
      // case foo%tbar%pmonkey.log
      first  = tms_pos;
      p1st   = tms;
      second = pid_pos;
      p2nd   = pid_text;
    }
  } else if (pid_pos >= 0) {
    // contains %p only
    first  = pid_pos;
    p1st   = pid_text;
  } else if (tms_pos >= 0) {
    // contains %t only
    first  = tms_pos;
    p1st   = tms;
  }

  int buf_pos = (int)strlen(buf);
  const char* tail = nametail;

  if (first >= 0) {
    tail = nametail + first + 2;
    strncpy(&buf[buf_pos], nametail, first);
    strcpy(&buf[buf_pos + first], p1st);
    buf_pos = (int)strlen(buf);
    if (second >= 0) {
      strncpy(&buf[buf_pos], tail, second - first - 2);
      strcpy(&buf[buf_pos + second - first - 2], p2nd);
      tail = nametail + second + 2;
    }
  }
  strcat(buf, tail);      // append rest of name, or all of name
  return buf;
}

490 491
// log_name comes from -XX:LogFile=log_name, -Xloggc:log_name or
// -XX:DumpLoadedClassList=<file_name>
492
// in log_name, %p => pid1234 and
493 494 495 496 497 498 499 500 501 502 503 504
//              %t => YYYY-MM-DD_HH-MM-SS
static const char* make_log_name(const char* log_name, const char* force_directory) {
  char timestr[32];
  get_datetime_string(timestr, sizeof(timestr));
  return make_log_name_internal(log_name, force_directory, os::current_process_id(),
                                timestr);
}

#ifndef PRODUCT
void test_loggc_filename() {
  int pid;
  char  tms[32];
B
brutisso 已提交
505
  char  i_result[JVM_MAXPATHLEN];
506 507 508 509 510
  const char* o_result;
  get_datetime_string(tms, sizeof(tms));
  pid = os::current_process_id();

  // test.log
B
brutisso 已提交
511
  jio_snprintf(i_result, JVM_MAXPATHLEN, "test.log", tms);
512 513 514 515 516
  o_result = make_log_name_internal("test.log", NULL, pid, tms);
  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test.log\", NULL)");
  FREE_C_HEAP_ARRAY(char, o_result, mtInternal);

  // test-%t-%p.log
B
brutisso 已提交
517
  jio_snprintf(i_result, JVM_MAXPATHLEN, "test-%s-pid%u.log", tms, pid);
518 519 520 521 522
  o_result = make_log_name_internal("test-%t-%p.log", NULL, pid, tms);
  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test-%%t-%%p.log\", NULL)");
  FREE_C_HEAP_ARRAY(char, o_result, mtInternal);

  // test-%t%p.log
B
brutisso 已提交
523
  jio_snprintf(i_result, JVM_MAXPATHLEN, "test-%spid%u.log", tms, pid);
524 525 526 527 528
  o_result = make_log_name_internal("test-%t%p.log", NULL, pid, tms);
  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"test-%%t%%p.log\", NULL)");
  FREE_C_HEAP_ARRAY(char, o_result, mtInternal);

  // %p%t.log
B
brutisso 已提交
529
  jio_snprintf(i_result, JVM_MAXPATHLEN, "pid%u%s.log", pid, tms);
530 531 532 533 534
  o_result = make_log_name_internal("%p%t.log", NULL, pid, tms);
  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%p%%t.log\", NULL)");
  FREE_C_HEAP_ARRAY(char, o_result, mtInternal);

  // %p-test.log
B
brutisso 已提交
535
  jio_snprintf(i_result, JVM_MAXPATHLEN, "pid%u-test.log", pid);
536 537 538 539 540
  o_result = make_log_name_internal("%p-test.log", NULL, pid, tms);
  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%p-test.log\", NULL)");
  FREE_C_HEAP_ARRAY(char, o_result, mtInternal);

  // %t.log
B
brutisso 已提交
541
  jio_snprintf(i_result, JVM_MAXPATHLEN, "%s.log", tms);
542 543 544
  o_result = make_log_name_internal("%t.log", NULL, pid, tms);
  assert(strcmp(i_result, o_result) == 0, "failed on testing make_log_name(\"%%t.log\", NULL)");
  FREE_C_HEAP_ARRAY(char, o_result, mtInternal);
B
brutisso 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586

  {
    // longest filename
    char longest_name[JVM_MAXPATHLEN];
    memset(longest_name, 'a', sizeof(longest_name));
    longest_name[JVM_MAXPATHLEN - 1] = '\0';
    o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms);
    assert(strcmp(longest_name, o_result) == 0, err_msg("longest name does not match. expected '%s' but got '%s'", longest_name, o_result));
    FREE_C_HEAP_ARRAY(char, o_result, mtInternal);
  }

  {
    // too long file name
    char too_long_name[JVM_MAXPATHLEN + 100];
    int too_long_length = sizeof(too_long_name);
    memset(too_long_name, 'a', too_long_length);
    too_long_name[too_long_length - 1] = '\0';
    o_result = make_log_name_internal((const char*)&too_long_name, NULL, pid, tms);
    assert(o_result == NULL, err_msg("Too long file name should return NULL, but got '%s'", o_result));
  }

  {
    // too long with timestamp
    char longest_name[JVM_MAXPATHLEN];
    memset(longest_name, 'a', JVM_MAXPATHLEN);
    longest_name[JVM_MAXPATHLEN - 3] = '%';
    longest_name[JVM_MAXPATHLEN - 2] = 't';
    longest_name[JVM_MAXPATHLEN - 1] = '\0';
    o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms);
    assert(o_result == NULL, err_msg("Too long file name after timestamp expansion should return NULL, but got '%s'", o_result));
  }

  {
    // too long with pid
    char longest_name[JVM_MAXPATHLEN];
    memset(longest_name, 'a', JVM_MAXPATHLEN);
    longest_name[JVM_MAXPATHLEN - 3] = '%';
    longest_name[JVM_MAXPATHLEN - 2] = 'p';
    longest_name[JVM_MAXPATHLEN - 1] = '\0';
    o_result = make_log_name_internal((const char*)&longest_name, NULL, pid, tms);
    assert(o_result == NULL, err_msg("Too long file name after pid expansion should return NULL, but got '%s'", o_result));
  }
587
}
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698

//////////////////////////////////////////////////////////////////////////////
// Test os::vsnprintf and friends.

void check_snprintf_result(int expected, size_t limit, int actual, bool expect_count) {
  if (expect_count || ((size_t)expected < limit)) {
    assert(expected == actual, "snprintf result not expected value");
  } else {
    // Make this check more permissive for jdk8u, don't assert that actual == 0.
    // e.g. jio_vsnprintf_wrapper and jio_snprintf return -1 when expected >= limit
    if (expected >= (int) limit) {
      assert(actual == -1, "snprintf result should be -1 for expected >= limit");
    } else {
      assert(actual > 0, "snprintf result should be >0 for expected < limit");
    }
  }
}

// PrintFn is expected to be int (*)(char*, size_t, const char*, ...).
// But jio_snprintf is a C-linkage function with that signature, which
// has a different type on some platforms (like Solaris).
template<typename PrintFn>
void test_snprintf(PrintFn pf, bool expect_count) {
  const char expected[] = "abcdefghijklmnopqrstuvwxyz";
  const int expected_len = sizeof(expected) - 1;
  const size_t padding_size = 10;
  char buffer[2 * (sizeof(expected) + padding_size)];
  char check_buffer[sizeof(buffer)];
  const char check_char = '1';  // Something not in expected.
  memset(check_buffer, check_char, sizeof(check_buffer));
  const size_t sizes_to_test[] = {
    sizeof(buffer) - padding_size,       // Fits, with plenty of space to spare.
    sizeof(buffer)/2,                    // Fits, with space to spare.
    sizeof(buffer)/4,                    // Doesn't fit.
    sizeof(expected) + padding_size + 1, // Fits, with a little room to spare
    sizeof(expected) + padding_size,     // Fits exactly.
    sizeof(expected) + padding_size - 1, // Doesn't quite fit.
    2,                                   // One char + terminating NUL.
    1,                                   // Only space for terminating NUL.
    0 };                                 // No space at all.
  for (unsigned i = 0; i < ARRAY_SIZE(sizes_to_test); ++i) {
    memset(buffer, check_char, sizeof(buffer)); // To catch stray writes.
    size_t test_size = sizes_to_test[i];
    ResourceMark rm;
    stringStream s;
    s.print("test_size: " SIZE_FORMAT, test_size);
    size_t prefix_size = padding_size;
    guarantee(test_size <= (sizeof(buffer) - prefix_size), "invariant");
    size_t write_size = MIN2(sizeof(expected), test_size);
    size_t suffix_size = sizeof(buffer) - prefix_size - write_size;
    char* write_start = buffer + prefix_size;
    char* write_end = write_start + write_size;

    int result = pf(write_start, test_size, "%s", expected);

    check_snprintf_result(expected_len, test_size, result, expect_count);

    // Verify expected output.
    if (test_size > 0) {
      assert(0 == strncmp(write_start, expected, write_size - 1), "strncmp failure");
      // Verify terminating NUL of output.
      assert('\0' == write_start[write_size - 1], "null terminator failure");
    } else {
      guarantee(test_size == 0, "invariant");
      guarantee(write_size == 0, "invariant");
      guarantee(prefix_size + suffix_size == sizeof(buffer), "invariant");
      guarantee(write_start == write_end, "invariant");
    }

    // Verify no scribbling on prefix or suffix.
    assert(0 == strncmp(buffer, check_buffer, prefix_size), "prefix scribble");
    assert(0 == strncmp(write_end, check_buffer, suffix_size), "suffix scribble");
  }

  // Special case of 0-length buffer with empty (except for terminator) output.
  check_snprintf_result(0, 0, pf(NULL, 0, "%s", ""), expect_count);
  check_snprintf_result(0, 0, pf(NULL, 0, ""), expect_count);
}

// This is probably equivalent to os::snprintf, but we're being
// explicit about what we're testing here.
static int vsnprintf_wrapper(char* buf, size_t len, const char* fmt, ...) {
  va_list args;
  va_start(args, fmt);
  int result = os::vsnprintf(buf, len, fmt, args);
  va_end(args);
  return result;
}

// These are declared in jvm.h; test here, with related functions.
extern "C" {
int jio_vsnprintf(char*, size_t, const char*, va_list);
int jio_snprintf(char*, size_t, const char*, ...);
}

// This is probably equivalent to jio_snprintf, but we're being
// explicit about what we're testing here.
static int jio_vsnprintf_wrapper(char* buf, size_t len, const char* fmt, ...) {
  va_list args;
  va_start(args, fmt);
  int result = jio_vsnprintf(buf, len, fmt, args);
  va_end(args);
  return result;
}

void test_snprintf() {
  test_snprintf(vsnprintf_wrapper, true);
  test_snprintf(os::snprintf, true);
  test_snprintf(jio_vsnprintf_wrapper, false); // jio_vsnprintf returns -1 on error including exceeding buffer size
  test_snprintf(jio_snprintf, false);          // jio_snprintf calls jio_vsnprintf
}
699 700
#endif // PRODUCT

D
duke 已提交
701 702
fileStream::fileStream(const char* file_name) {
  _file = fopen(file_name, "w");
703 704 705 706 707 708
  if (_file != NULL) {
    _need_close = true;
  } else {
    warning("Cannot open file %s due to %s\n", file_name, strerror(errno));
    _need_close = false;
  }
D
duke 已提交
709 710
}

711 712
fileStream::fileStream(const char* file_name, const char* opentype) {
  _file = fopen(file_name, opentype);
713 714 715 716 717 718
  if (_file != NULL) {
    _need_close = true;
  } else {
    warning("Cannot open file %s due to %s\n", file_name, strerror(errno));
    _need_close = false;
  }
719 720
}

D
duke 已提交
721
void fileStream::write(const char* s, size_t len) {
722 723 724 725
  if (_file != NULL)  {
    // Make an unused local variable to avoid warning from gcc 4.x compiler.
    size_t count = fwrite(s, 1, len, _file);
  }
D
duke 已提交
726 727 728
  update_position(s, len);
}

729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
long fileStream::fileSize() {
  long size = -1;
  if (_file != NULL) {
    long pos  = ::ftell(_file);
    if (::fseek(_file, 0, SEEK_END) == 0) {
      size = ::ftell(_file);
    }
    ::fseek(_file, pos, SEEK_SET);
  }
  return size;
}

char* fileStream::readln(char *data, int count ) {
  char * ret = ::fgets(data, count, _file);
  //Get rid of annoying \n char
  data[::strlen(data)-1] = '\0';
  return ret;
}

D
duke 已提交
748 749 750
fileStream::~fileStream() {
  if (_file != NULL) {
    if (_need_close) fclose(_file);
751
    _file      = NULL;
D
duke 已提交
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
  }
}

void fileStream::flush() {
  fflush(_file);
}

fdStream::fdStream(const char* file_name) {
  _fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  _need_close = true;
}

fdStream::~fdStream() {
  if (_fd != -1) {
    if (_need_close) close(_fd);
    _fd = -1;
  }
}

void fdStream::write(const char* s, size_t len) {
772 773 774 775
  if (_fd != -1) {
    // Make an unused local variable to avoid warning from gcc 4.x compiler.
    size_t count = ::write(_fd, s, (int)len);
  }
D
duke 已提交
776 777 778
  update_position(s, len);
}

779 780 781 782
// dump vm version, os version, platform info, build id,
// memory usage and command line flags into header
void gcLogFileStream::dump_loggc_header() {
  if (is_open()) {
783
    print_cr("%s", Abstract_VM_Version::internal_vm_info_string());
784 785 786 787 788 789 790
    os::print_memory_info(this);
    print("CommandLine flags: ");
    CommandLineFlags::printSetFlags(this);
  }
}

gcLogFileStream::~gcLogFileStream() {
791 792
  if (_file != NULL) {
    if (_need_close) fclose(_file);
793 794 795
    _file = NULL;
  }
  if (_file_name != NULL) {
Z
zgu 已提交
796
    FREE_C_HEAP_ARRAY(char, _file_name, mtInternal);
797 798
    _file_name = NULL;
  }
P
phh 已提交
799 800

  delete _file_lock;
801 802
}

P
phh 已提交
803
gcLogFileStream::gcLogFileStream(const char* file_name) : _file_lock(NULL) {
804
  _cur_file_num = 0;
805
  _bytes_written = 0L;
806
  _file_name = make_log_name(file_name, NULL);
807

B
brutisso 已提交
808 809 810 811 812 813 814
  if (_file_name == NULL) {
    warning("Cannot open file %s: file name is too long.\n", file_name);
    _need_close = false;
    UseGCLogFileRotation = false;
    return;
  }

815 816
  // gc log file rotation
  if (UseGCLogFileRotation && NumberOfGCLogFiles > 1) {
B
brutisso 已提交
817
    char tempbuf[JVM_MAXPATHLEN];
818 819 820 821 822 823 824 825
    jio_snprintf(tempbuf, sizeof(tempbuf), "%s.%d" CURRENTAPPX, _file_name, _cur_file_num);
    _file = fopen(tempbuf, "w");
  } else {
    _file = fopen(_file_name, "w");
  }
  if (_file != NULL) {
    _need_close = true;
    dump_loggc_header();
P
phh 已提交
826 827 828 829

    if (UseGCLogFileRotation) {
      _file_lock = new Mutex(Mutex::leaf, "GCLogFile");
    }
830 831 832 833
  } else {
    warning("Cannot open file %s due to %s\n", _file_name, strerror(errno));
    _need_close = false;
  }
834 835
}

836
void gcLogFileStream::write(const char* s, size_t len) {
837
  if (_file != NULL) {
P
phh 已提交
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
    // we can't use Thread::current() here because thread may be NULL
    // in early stage(ostream_init_log)
    Thread* thread = ThreadLocalStorage::thread();

    // avoid the mutex in the following cases
    // 1) ThreadLocalStorage::thread() hasn't been initialized
    // 2) _file_lock is not in use.
    // 3) current() is VMThread and its reentry flag is set
    if (!thread || !_file_lock || (thread->is_VM_thread()
                               && ((VMThread* )thread)->is_gclog_reentry())) {
      size_t count = fwrite(s, 1, len, _file);
      _bytes_written += count;
    }
    else {
      MutexLockerEx ml(_file_lock, Mutex::_no_safepoint_check_flag);
      size_t count = fwrite(s, 1, len, _file);
      _bytes_written += count;
    }
856 857 858 859
  }
  update_position(s, len);
}

P
phh 已提交
860
// rotate_log must be called from VMThread at a safepoint. In case need change parameters
861 862
// for gc log rotation from thread other than VMThread, a sub type of VM_Operation
// should be created and be submitted to VMThread's operation queue. DO NOT call this
P
phh 已提交
863 864 865 866
// function directly. It is safe to rotate log through VMThread because
// no mutator threads run concurrently with the VMThread, and GC threads that run
// concurrently with the VMThread are synchronized in write and rotate_log via _file_lock.
// rotate_log can write log entries, so write supports reentry for it.
867
void gcLogFileStream::rotate_log(bool force, outputStream* out) {
P
phh 已提交
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
 #ifdef ASSERT
   Thread *thread = Thread::current();
   assert(thread == NULL ||
          (thread->is_VM_thread() && SafepointSynchronize::is_at_safepoint()),
          "Must be VMThread at safepoint");
 #endif

  VMThread* vmthread = VMThread::vm_thread();
  {
    // nop if _file_lock is NULL.
    MutexLockerEx ml(_file_lock, Mutex::_no_safepoint_check_flag);
    vmthread->set_gclog_reentry(true);
    rotate_log_impl(force, out);
    vmthread->set_gclog_reentry(false);
  }
}

void gcLogFileStream::rotate_log_impl(bool force, outputStream* out) {
B
brutisso 已提交
886
  char time_msg[O_BUFLEN];
887
  char time_str[EXTRACHARLEN];
B
brutisso 已提交
888 889
  char current_file_name[JVM_MAXPATHLEN];
  char renamed_file_name[JVM_MAXPATHLEN];
890

891
  if (!should_rotate(force)) {
892 893 894
    return;
  }

895 896 897
  if (NumberOfGCLogFiles == 1) {
    // rotate in same file
    rewind();
898
    _bytes_written = 0L;
899 900 901
    jio_snprintf(time_msg, sizeof(time_msg), "File  %s rotated at %s\n",
                 _file_name, os::local_time_string((char *)time_str, sizeof(time_str)));
    write(time_msg, strlen(time_msg));
902 903

    if (out != NULL) {
904
      out->print("%s", time_msg);
905 906
    }

907
    dump_loggc_header();
908 909 910
    return;
  }

911 912 913 914 915 916 917 918 919 920 921
#if defined(_WINDOWS)
#ifndef F_OK
#define F_OK 0
#endif
#endif // _WINDOWS

  // rotate file in names extended_filename.0, extended_filename.1, ...,
  // extended_filename.<NumberOfGCLogFiles - 1>. Current rotation file name will
  // have a form of extended_filename.<i>.current where i is the current rotation
  // file number. After it reaches max file size, the file will be saved and renamed
  // with .current removed from its tail.
922
  if (_file != NULL) {
B
brutisso 已提交
923
    jio_snprintf(renamed_file_name, JVM_MAXPATHLEN, "%s.%d",
924
                 _file_name, _cur_file_num);
B
brutisso 已提交
925 926 927 928 929 930
    int result = jio_snprintf(current_file_name, JVM_MAXPATHLEN,
                              "%s.%d" CURRENTAPPX, _file_name, _cur_file_num);
    if (result >= JVM_MAXPATHLEN) {
      warning("Cannot create new log file name: %s: file name is too long.\n", current_file_name);
      return;
    }
931 932 933 934 935 936

    const char* msg = force ? "GC log rotation request has been received."
                            : "GC log file has reached the maximum size.";
    jio_snprintf(time_msg, sizeof(time_msg), "%s %s Saved as %s\n",
                     os::local_time_string((char *)time_str, sizeof(time_str)),
                                                         msg, renamed_file_name);
937 938
    write(time_msg, strlen(time_msg));

939
    if (out != NULL) {
940
      out->print("%s", time_msg);
941 942
    }

943 944
    fclose(_file);
    _file = NULL;
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964

    bool can_rename = true;
    if (access(current_file_name, F_OK) != 0) {
      // current file does not exist?
      warning("No source file exists, cannot rename\n");
      can_rename = false;
    }
    if (can_rename) {
      if (access(renamed_file_name, F_OK) == 0) {
        if (remove(renamed_file_name) != 0) {
          warning("Could not delete existing file %s\n", renamed_file_name);
          can_rename = false;
        }
      } else {
        // file does not exist, ok to rename
      }
    }
    if (can_rename && rename(current_file_name, renamed_file_name) != 0) {
      warning("Could not rename %s to %s\n", _file_name, renamed_file_name);
    }
965
  }
966 967 968

  _cur_file_num++;
  if (_cur_file_num > NumberOfGCLogFiles - 1) _cur_file_num = 0;
B
brutisso 已提交
969
  int result = jio_snprintf(current_file_name,  JVM_MAXPATHLEN, "%s.%d" CURRENTAPPX,
970
               _file_name, _cur_file_num);
B
brutisso 已提交
971 972 973 974 975
  if (result >= JVM_MAXPATHLEN) {
    warning("Cannot create new log file name: %s: file name is too long.\n", current_file_name);
    return;
  }

976 977
  _file = fopen(current_file_name, "w");

978
  if (_file != NULL) {
979
    _bytes_written = 0L;
980
    _need_close = true;
981
    // reuse current_file_name for time_msg
B
brutisso 已提交
982
    jio_snprintf(current_file_name, JVM_MAXPATHLEN,
983 984
                 "%s.%d", _file_name, _cur_file_num);
    jio_snprintf(time_msg, sizeof(time_msg), "%s GC log file created %s\n",
B
brutisso 已提交
985
                 os::local_time_string((char *)time_str, sizeof(time_str)), current_file_name);
986
    write(time_msg, strlen(time_msg));
987 988

    if (out != NULL) {
989
      out->print("%s", time_msg);
990 991
    }

992 993 994 995 996 997 998
    dump_loggc_header();
    // remove the existing file
    if (access(current_file_name, F_OK) == 0) {
      if (remove(current_file_name) != 0) {
        warning("Could not delete existing file %s\n", current_file_name);
      }
    }
999
  } else {
1000 1001
    warning("failed to open rotation log file %s due to %s\n"
            "Turned off GC log file rotation\n",
1002 1003
                  _file_name, strerror(errno));
    _need_close = false;
1004
    FLAG_SET_DEFAULT(UseGCLogFileRotation, false);
1005 1006 1007
  }
}

D
duke 已提交
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
defaultStream* defaultStream::instance = NULL;
int defaultStream::_output_fd = 1;
int defaultStream::_error_fd  = 2;
FILE* defaultStream::_output_stream = stdout;
FILE* defaultStream::_error_stream  = stderr;

#define LOG_MAJOR_VERSION 160
#define LOG_MINOR_VERSION 1

void defaultStream::init() {
  _inited = true;
  if (LogVMOutput || LogCompilation) {
    init_log();
  }
}

bool defaultStream::has_log_file() {
  // lazily create log file (at startup, LogVMOutput is false even
  // if +LogVMOutput is used, because the flags haven't been parsed yet)
  // For safer printing during fatal error handling, do not init logfile
  // if a VM error has been reported.
  if (!_inited && !is_error_reported())  init();
  return _log_file != NULL;
}

B
brutisso 已提交
1033
fileStream* defaultStream::open_file(const char* log_name) {
1034
  const char* try_name = make_log_name(log_name, NULL);
B
brutisso 已提交
1035 1036 1037
  if (try_name == NULL) {
    warning("Cannot open file %s: file name is too long.\n", log_name);
    return NULL;
D
duke 已提交
1038
  }
B
brutisso 已提交
1039 1040

  fileStream* file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name);
1041
  FREE_C_HEAP_ARRAY(char, try_name, mtInternal);
B
brutisso 已提交
1042 1043 1044
  if (file->is_open()) {
    return file;
  }
1045

B
brutisso 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
  // Try again to open the file in the temp directory.
  delete file;
  char warnbuf[O_BUFLEN*2];
  jio_snprintf(warnbuf, sizeof(warnbuf), "Warning:  Cannot open log file: %s\n", log_name);
  // Note:  This feature is for maintainer use only.  No need for L10N.
  jio_print(warnbuf);
  try_name = make_log_name(log_name, os::get_temp_directory());
  if (try_name == NULL) {
    warning("Cannot open file %s: file name is too long for directory %s.\n", log_name, os::get_temp_directory());
    return NULL;
  }

  jio_snprintf(warnbuf, sizeof(warnbuf),
               "Warning:  Forcing option -XX:LogFile=%s\n", try_name);
  jio_print(warnbuf);
1061

B
brutisso 已提交
1062 1063
  file = new(ResourceObj::C_HEAP, mtInternal) fileStream(try_name);
  FREE_C_HEAP_ARRAY(char, try_name, mtInternal);
D
duke 已提交
1064
  if (file->is_open()) {
B
brutisso 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    return file;
  }

  delete file;
  return NULL;
}

void defaultStream::init_log() {
  // %%% Need a MutexLocker?
  const char* log_name = LogFile != NULL ? LogFile : "hotspot_%p.log";
  fileStream* file = open_file(log_name);

  if (file != NULL) {
D
duke 已提交
1078
    _log_file = file;
B
brutisso 已提交
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    _outer_xmlStream = new(ResourceObj::C_HEAP, mtInternal) xmlStream(file);
    start_log();
  } else {
    // and leave xtty as NULL
    LogVMOutput = false;
    DisplayVMOutput = true;
    LogCompilation = false;
  }
}

void defaultStream::start_log() {
  xmlStream*xs = _outer_xmlStream;
D
duke 已提交
1091 1092 1093 1094 1095 1096 1097 1098
    if (this == tty)  xtty = xs;
    // Write XML header.
    xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
    // (For now, don't bother to issue a DTD for this private format.)
    jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
    // %%% Should be: jlong time_ms = os::start_time_milliseconds(), if
    // we ever get round to introduce that method on the os class
    xs->head("hotspot_log version='%d %d'"
1099
             " process='%d' time_ms='" INT64_FORMAT "'",
D
duke 已提交
1100
             LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
1101
             os::current_process_id(), (int64_t)time_ms);
D
duke 已提交
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
    // Write VM version header immediately.
    xs->head("vm_version");
    xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr();
    xs->tail("name");
    xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr();
    xs->tail("release");
    xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr();
    xs->tail("info");
    xs->tail("vm_version");
    // Record information about the command-line invocation.
    xs->head("vm_arguments");  // Cf. Arguments::print_on()
    if (Arguments::num_jvm_flags() > 0) {
      xs->head("flags");
      Arguments::print_jvm_flags_on(xs->text());
      xs->tail("flags");
    }
    if (Arguments::num_jvm_args() > 0) {
      xs->head("args");
      Arguments::print_jvm_args_on(xs->text());
      xs->tail("args");
    }
    if (Arguments::java_command() != NULL) {
      xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command());
      xs->tail("command");
    }
    if (Arguments::sun_java_launcher() != NULL) {
      xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher());
      xs->tail("launcher");
    }
    if (Arguments::system_properties() !=  NULL) {
      xs->head("properties");
      // Print it as a java-style property list.
      // System properties don't generally contain newlines, so don't bother with unparsing.
      for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
        xs->text()->print_cr("%s=%s", p->key(), p->value());
      }
      xs->tail("properties");
    }
    xs->tail("vm_arguments");
    // tty output per se is grouped under the <tty>...</tty> element.
    xs->head("tty");
    // All further non-markup text gets copied to the tty:
    xs->_text = this;  // requires friend declaration!
}

// finish_log() is called during normal VM shutdown. finish_log_on_error() is
// called by ostream_abort() after a fatal error.
//
void defaultStream::finish_log() {
  xmlStream* xs = _outer_xmlStream;
  xs->done("tty");

  // Other log forks are appended here, at the End of Time:
  CompileLog::finish_log(xs->out());  // write compile logging, if any, now

  xs->done("hotspot_log");
  xs->flush();

  fileStream* file = _log_file;
  _log_file = NULL;

  delete _outer_xmlStream;
  _outer_xmlStream = NULL;

  file->flush();
  delete file;
}

void defaultStream::finish_log_on_error(char *buf, int buflen) {
  xmlStream* xs = _outer_xmlStream;

  if (xs && xs->out()) {

    xs->done_raw("tty");

    // Other log forks are appended here, at the End of Time:
    CompileLog::finish_log_on_error(xs->out(), buf, buflen);  // write compile logging, if any, now

    xs->done_raw("hotspot_log");
    xs->flush();

    fileStream* file = _log_file;
    _log_file = NULL;
    _outer_xmlStream = NULL;

    if (file) {
      file->flush();

      // Can't delete or close the file because delete and fclose aren't
      // async-safe. We are about to die, so leave it to the kernel.
      // delete file;
    }
  }
}

intx defaultStream::hold(intx writer_id) {
  bool has_log = has_log_file();  // check before locking
  if (// impossible, but who knows?
      writer_id == NO_WRITER ||

      // bootstrap problem
      tty_lock == NULL ||

      // can't grab a lock or call Thread::current() if TLS isn't initialized
      ThreadLocalStorage::thread() == NULL ||

      // developer hook
      !SerializeVMOutput ||

      // VM already unhealthy
      is_error_reported() ||

      // safepoint == global lock (for VM only)
      (SafepointSynchronize::is_synchronizing() &&
       Thread::current()->is_VM_thread())
      ) {
    // do not attempt to lock unless we know the thread and the VM is healthy
    return NO_WRITER;
  }
  if (_writer == writer_id) {
    // already held, no need to re-grab the lock
    return NO_WRITER;
  }
  tty_lock->lock_without_safepoint_check();
  // got the lock
  if (writer_id != _last_writer) {
    if (has_log) {
      _log_file->bol();
      // output a hint where this output is coming from:
V
vlivanov 已提交
1231
      _log_file->print_cr("<writer thread='" UINTX_FORMAT "'/>", writer_id);
D
duke 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
    }
    _last_writer = writer_id;
  }
  _writer = writer_id;
  return writer_id;
}

void defaultStream::release(intx holder) {
  if (holder == NO_WRITER) {
    // nothing to release:  either a recursive lock, or we scribbled (too bad)
    return;
  }
  if (_writer != holder) {
    return;  // already unlocked, perhaps via break_tty_lock_for_safepoint
  }
  _writer = NO_WRITER;
  tty_lock->unlock();
}


// Yuck:  jio_print does not accept char*/len.
static void call_jio_print(const char* s, size_t len) {
  char buffer[O_BUFLEN+100];
  if (len > sizeof(buffer)-1) {
    warning("increase O_BUFLEN in ostream.cpp -- output truncated");
    len = sizeof(buffer)-1;
  }
  strncpy(buffer, s, len);
  buffer[len] = '\0';
  jio_print(buffer);
}


void defaultStream::write(const char* s, size_t len) {
  intx thread_id = os::current_thread_id();
  intx holder = hold(thread_id);

  if (DisplayVMOutput &&
      (_outer_xmlStream == NULL || !_outer_xmlStream->inside_attrs())) {
    // print to output stream. It can be redirected by a vfprintf hook
    if (s[len] == '\0') {
      jio_print(s);
    } else {
      call_jio_print(s, len);
    }
  }

  // print to log file
  if (has_log_file()) {
    int nl0 = _newlines;
    xmlTextStream::write(s, len);
    // flush the log file too, if there were any newlines
    if (nl0 != _newlines){
      flush();
    }
  } else {
    update_position(s, len);
  }

  release(holder);
}

intx ttyLocker::hold_tty() {
  if (defaultStream::instance == NULL)  return defaultStream::NO_WRITER;
  intx thread_id = os::current_thread_id();
  return defaultStream::instance->hold(thread_id);
}

void ttyLocker::release_tty(intx holder) {
  if (holder == defaultStream::NO_WRITER)  return;
  defaultStream::instance->release(holder);
}

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
bool ttyLocker::release_tty_if_locked() {
  intx thread_id = os::current_thread_id();
  if (defaultStream::instance->writer() == thread_id) {
    // release the lock and return true so callers know if was
    // previously held.
    release_tty(thread_id);
    return true;
  }
  return false;
}

D
duke 已提交
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
  if (defaultStream::instance != NULL &&
      defaultStream::instance->writer() == holder) {
    if (xtty != NULL) {
      xtty->print_cr("<!-- safepoint while printing -->");
    }
    defaultStream::instance->release(holder);
  }
  // (else there was no lock to break)
}

void ostream_init() {
  if (defaultStream::instance == NULL) {
Z
zgu 已提交
1329
    defaultStream::instance = new(ResourceObj::C_HEAP, mtInternal) defaultStream();
D
duke 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    tty = defaultStream::instance;

    // We want to ensure that time stamps in GC logs consider time 0
    // the time when the JVM is initialized, not the first time we ask
    // for a time stamp. So, here, we explicitly update the time stamp
    // of tty.
    tty->time_stamp().update_to(1);
  }
}

void ostream_init_log() {
  // For -Xloggc:<file> option - called in runtime/thread.cpp
  // Note : this must be called AFTER ostream_init()

  gclog_or_tty = tty; // default to tty
  if (Arguments::gc_log_filename() != NULL) {
1346 1347
    fileStream * gclog  = new(ResourceObj::C_HEAP, mtInternal)
                             gcLogFileStream(Arguments::gc_log_filename());
D
duke 已提交
1348 1349 1350 1351 1352
    if (gclog->is_open()) {
      // now we update the time stamp of the GC log to be synced up
      // with tty.
      gclog->time_stamp().update_to(tty->time_stamp().ticks());
    }
1353
    gclog_or_tty = gclog;
D
duke 已提交
1354 1355
  }

1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
#if INCLUDE_CDS
  // For -XX:DumpLoadedClassList=<file> option
  if (DumpLoadedClassList != NULL) {
    const char* list_name = make_log_name(DumpLoadedClassList, NULL);
    classlist_file = new(ResourceObj::C_HEAP, mtInternal)
                         fileStream(list_name);
    FREE_C_HEAP_ARRAY(char, list_name, mtInternal);
  }
#endif

D
duke 已提交
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
  // If we haven't lazily initialized the logfile yet, do it now,
  // to avoid the possibility of lazy initialization during a VM
  // crash, which can affect the stability of the fatal error handler.
  defaultStream::instance->has_log_file();
}

// ostream_exit() is called during normal VM exit to finish log files, flush
// output and free resource.
void ostream_exit() {
  static bool ostream_exit_called = false;
  if (ostream_exit_called)  return;
  ostream_exit_called = true;
1378 1379 1380 1381 1382
#if INCLUDE_CDS
  if (classlist_file != NULL) {
    delete classlist_file;
  }
#endif
D
duke 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
  if (gclog_or_tty != tty) {
      delete gclog_or_tty;
  }
  {
      // we temporaly disable PrintMallocFree here
      // as otherwise it'll lead to using of almost deleted
      // tty or defaultStream::instance in logging facility
      // of HeapFree(), see 6391258
      DEBUG_ONLY(FlagSetting fs(PrintMallocFree, false);)
      if (tty != defaultStream::instance) {
          delete tty;
      }
      if (defaultStream::instance != NULL) {
          delete defaultStream::instance;
      }
  }
  tty = NULL;
  xtty = NULL;
  gclog_or_tty = NULL;
  defaultStream::instance = NULL;
}

// ostream_abort() is called by os::abort() when VM is about to die.
void ostream_abort() {
  // Here we can't delete gclog_or_tty and tty, just flush their output
  if (gclog_or_tty) gclog_or_tty->flush();
  if (tty) tty->flush();

  if (defaultStream::instance != NULL) {
    static char buf[4096];
    defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
  }
}

staticBufferStream::staticBufferStream(char* buffer, size_t buflen,
                                       outputStream *outer_stream) {
  _buffer = buffer;
  _buflen = buflen;
  _outer_stream = outer_stream;
1422 1423
  // compile task prints time stamp relative to VM start
  _stamp.update_to(1);
D
duke 已提交
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
}

void staticBufferStream::write(const char* c, size_t len) {
  _outer_stream->print_raw(c, (int)len);
}

void staticBufferStream::flush() {
  _outer_stream->flush();
}

void staticBufferStream::print(const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  size_t len;
  const char* str = do_vsnprintf(_buffer, _buflen, format, ap, false, len);
  write(str, len);
  va_end(ap);
}

void staticBufferStream::print_cr(const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  size_t len;
  const char* str = do_vsnprintf(_buffer, _buflen, format, ap, true, len);
  write(str, len);
  va_end(ap);
}

void staticBufferStream::vprint(const char *format, va_list argptr) {
  size_t len;
  const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, false, len);
  write(str, len);
}

void staticBufferStream::vprint_cr(const char* format, va_list argptr) {
  size_t len;
  const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, true, len);
  write(str, len);
}

1464
bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
D
duke 已提交
1465
  buffer_length = initial_size;
Z
zgu 已提交
1466
  buffer        = NEW_C_HEAP_ARRAY(char, buffer_length, mtInternal);
D
duke 已提交
1467 1468
  buffer_pos    = 0;
  buffer_fixed  = false;
1469
  buffer_max    = bufmax;
D
duke 已提交
1470 1471
}

1472
bufferedStream::bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax) : outputStream() {
D
duke 已提交
1473 1474 1475 1476
  buffer_length = fixed_buffer_size;
  buffer        = fixed_buffer;
  buffer_pos    = 0;
  buffer_fixed  = true;
1477
  buffer_max    = bufmax;
D
duke 已提交
1478 1479 1480
}

void bufferedStream::write(const char* s, size_t len) {
1481 1482 1483 1484 1485

  if(buffer_pos + len > buffer_max) {
    flush();
  }

D
duke 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
  size_t end = buffer_pos + len;
  if (end >= buffer_length) {
    if (buffer_fixed) {
      // if buffer cannot resize, silently truncate
      len = buffer_length - buffer_pos - 1;
    } else {
      // For small overruns, double the buffer.  For larger ones,
      // increase to the requested size.
      if (end < buffer_length * 2) {
        end = buffer_length * 2;
      }
Z
zgu 已提交
1497
      buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end, mtInternal);
D
duke 已提交
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
      buffer_length = end;
    }
  }
  memcpy(buffer + buffer_pos, s, len);
  buffer_pos += len;
  update_position(s, len);
}

char* bufferedStream::as_string() {
  char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
  strncpy(copy, buffer, buffer_pos);
  copy[buffer_pos] = 0;  // terminating null
  return copy;
}

bufferedStream::~bufferedStream() {
  if (!buffer_fixed) {
Z
zgu 已提交
1515
    FREE_C_HEAP_ARRAY(char, buffer, mtInternal);
D
duke 已提交
1516 1517 1518 1519 1520
  }
}

#ifndef PRODUCT

1521
#if defined(SOLARIS) || defined(LINUX) || defined(AIX) || defined(_ALLBSD_SOURCE)
D
duke 已提交
1522 1523 1524 1525 1526 1527 1528
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

// Network access
1529
networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
D
duke 已提交
1530 1531 1532

  _socket = -1;

1533
  int result = os::socket(AF_INET, SOCK_STREAM, 0);
D
duke 已提交
1534 1535 1536 1537 1538 1539 1540 1541
  if (result <= 0) {
    assert(false, "Socket could not be created!");
  } else {
    _socket = result;
  }
}

int networkStream::read(char *buf, size_t len) {
1542
  return os::recv(_socket, buf, (int)len, 0);
D
duke 已提交
1543 1544 1545 1546
}

void networkStream::flush() {
  if (size() != 0) {
1547
    int result = os::raw_send(_socket, (char *)base(), size(), 0);
1548 1549
    assert(result != -1, "connection error");
    assert(result == (int)size(), "didn't send enough data");
D
duke 已提交
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
  }
  reset();
}

networkStream::~networkStream() {
  close();
}

void networkStream::close() {
  if (_socket != -1) {
    flush();
1561
    os::socket_close(_socket);
D
duke 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
    _socket = -1;
  }
}

bool networkStream::connect(const char *ip, short port) {

  struct sockaddr_in server;
  server.sin_family = AF_INET;
  server.sin_port = htons(port);

  server.sin_addr.s_addr = inet_addr(ip);
1573
  if (server.sin_addr.s_addr == (uint32_t)-1) {
1574
    struct hostent* host = os::get_host_by_name((char*)ip);
D
duke 已提交
1575 1576 1577 1578 1579 1580 1581 1582
    if (host != NULL) {
      memcpy(&server.sin_addr, host->h_addr_list[0], host->h_length);
    } else {
      return false;
    }
  }


1583
  int result = os::connect(_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_in));
D
duke 已提交
1584 1585 1586 1587
  return (result >= 0);
}

#endif