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