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