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