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