Sat, 11 Dec 2010 13:20:56 -0500
7003748: Decode C stack frames when symbols are presented (PhoneHome project)
Summary: Implemented in-process C native stack frame decoding when symbols are available.
Reviewed-by: coleenp, never
1 /*
2 * Copyright (c) 1997, 2010, 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 */
25 #include "precompiled.hpp"
26 #include "compiler/compileLog.hpp"
27 #include "oops/oop.inline.hpp"
28 #include "runtime/arguments.hpp"
29 #include "runtime/hpi.hpp"
30 #include "utilities/defaultStream.hpp"
31 #include "utilities/ostream.hpp"
32 #include "utilities/top.hpp"
33 #include "utilities/xmlstream.hpp"
34 #ifdef TARGET_OS_FAMILY_linux
35 # include "hpi_linux.hpp"
36 # include "os_linux.inline.hpp"
37 #endif
38 #ifdef TARGET_OS_FAMILY_solaris
39 # include "hpi_solaris.hpp"
40 # include "os_solaris.inline.hpp"
41 #endif
42 #ifdef TARGET_OS_FAMILY_windows
43 # include "hpi_windows.hpp"
44 # include "os_windows.inline.hpp"
45 #endif
47 extern "C" void jio_print(const char* s); // Declarationtion of jvm method
49 outputStream::outputStream(int width) {
50 _width = width;
51 _position = 0;
52 _newlines = 0;
53 _precount = 0;
54 _indentation = 0;
55 }
57 outputStream::outputStream(int width, bool has_time_stamps) {
58 _width = width;
59 _position = 0;
60 _newlines = 0;
61 _precount = 0;
62 _indentation = 0;
63 if (has_time_stamps) _stamp.update();
64 }
66 void outputStream::update_position(const char* s, size_t len) {
67 for (size_t i = 0; i < len; i++) {
68 char ch = s[i];
69 if (ch == '\n') {
70 _newlines += 1;
71 _precount += _position + 1;
72 _position = 0;
73 } else if (ch == '\t') {
74 int tw = 8 - (_position & 7);
75 _position += tw;
76 _precount -= tw-1; // invariant: _precount + _position == total count
77 } else {
78 _position += 1;
79 }
80 }
81 }
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 const char* result;
90 if (add_cr) buflen--;
91 if (!strchr(format, '%')) {
92 // constant format string
93 result = format;
94 result_len = strlen(result);
95 if (add_cr && result_len >= buflen) result_len = buflen-1; // truncate
96 } else if (format[0] == '%' && format[1] == 's' && format[2] == '\0') {
97 // trivial copy-through format string
98 result = va_arg(ap, const char*);
99 result_len = strlen(result);
100 if (add_cr && result_len >= buflen) result_len = buflen-1; // truncate
101 } else if (vsnprintf(buffer, buflen, format, ap) >= 0) {
102 result = buffer;
103 result_len = strlen(result);
104 } else {
105 DEBUG_ONLY(warning("increase O_BUFLEN in ostream.hpp -- output truncated");)
106 result = buffer;
107 result_len = buflen - 1;
108 buffer[result_len] = 0;
109 }
110 if (add_cr) {
111 if (result != buffer) {
112 strncpy(buffer, result, buflen);
113 result = buffer;
114 }
115 buffer[result_len++] = '\n';
116 buffer[result_len] = 0;
117 }
118 return result;
119 }
121 void outputStream::print(const char* format, ...) {
122 char buffer[O_BUFLEN];
123 va_list ap;
124 va_start(ap, format);
125 size_t len;
126 const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, false, len);
127 write(str, len);
128 va_end(ap);
129 }
131 void outputStream::print_cr(const char* format, ...) {
132 char buffer[O_BUFLEN];
133 va_list ap;
134 va_start(ap, format);
135 size_t len;
136 const char* str = do_vsnprintf(buffer, O_BUFLEN, format, ap, true, len);
137 write(str, len);
138 va_end(ap);
139 }
141 void outputStream::vprint(const char *format, va_list argptr) {
142 char buffer[O_BUFLEN];
143 size_t len;
144 const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, false, len);
145 write(str, len);
146 }
148 void outputStream::vprint_cr(const char* format, va_list argptr) {
149 char buffer[O_BUFLEN];
150 size_t len;
151 const char* str = do_vsnprintf(buffer, O_BUFLEN, format, argptr, true, len);
152 write(str, len);
153 }
155 void outputStream::fill_to(int col) {
156 int need_fill = col - position();
157 sp(need_fill);
158 }
160 void outputStream::move_to(int col, int slop, int min_space) {
161 if (position() >= col + slop)
162 cr();
163 int need_fill = col - position();
164 if (need_fill < min_space)
165 need_fill = min_space;
166 sp(need_fill);
167 }
169 void outputStream::put(char ch) {
170 assert(ch != 0, "please fix call site");
171 char buf[] = { ch, '\0' };
172 write(buf, 1);
173 }
175 #define SP_USE_TABS false
177 void outputStream::sp(int count) {
178 if (count < 0) return;
179 if (SP_USE_TABS && count >= 8) {
180 int target = position() + count;
181 while (count >= 8) {
182 this->write("\t", 1);
183 count -= 8;
184 }
185 count = target - position();
186 }
187 while (count > 0) {
188 int nw = (count > 8) ? 8 : count;
189 this->write(" ", nw);
190 count -= nw;
191 }
192 }
194 void outputStream::cr() {
195 this->write("\n", 1);
196 }
198 void outputStream::stamp() {
199 if (! _stamp.is_updated()) {
200 _stamp.update(); // start at 0 on first call to stamp()
201 }
203 // outputStream::stamp() may get called by ostream_abort(), use snprintf
204 // to avoid allocating large stack buffer in print().
205 char buf[40];
206 jio_snprintf(buf, sizeof(buf), "%.3f", _stamp.seconds());
207 print_raw(buf);
208 }
210 void outputStream::stamp(bool guard,
211 const char* prefix,
212 const char* suffix) {
213 if (!guard) {
214 return;
215 }
216 print_raw(prefix);
217 stamp();
218 print_raw(suffix);
219 }
221 void outputStream::date_stamp(bool guard,
222 const char* prefix,
223 const char* suffix) {
224 if (!guard) {
225 return;
226 }
227 print_raw(prefix);
228 static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz";
229 static const int buffer_length = 32;
230 char buffer[buffer_length];
231 const char* iso8601_result = os::iso8601_time(buffer, buffer_length);
232 if (iso8601_result != NULL) {
233 print_raw(buffer);
234 } else {
235 print_raw(error_time);
236 }
237 print_raw(suffix);
238 return;
239 }
241 void outputStream::indent() {
242 while (_position < _indentation) sp();
243 }
245 void outputStream::print_jlong(jlong value) {
246 // N.B. Same as INT64_FORMAT
247 print(os::jlong_format_specifier(), value);
248 }
250 void outputStream::print_julong(julong value) {
251 // N.B. Same as UINT64_FORMAT
252 print(os::julong_format_specifier(), value);
253 }
255 stringStream::stringStream(size_t initial_size) : outputStream() {
256 buffer_length = initial_size;
257 buffer = NEW_RESOURCE_ARRAY(char, buffer_length);
258 buffer_pos = 0;
259 buffer_fixed = false;
260 }
262 // useful for output to fixed chunks of memory, such as performance counters
263 stringStream::stringStream(char* fixed_buffer, size_t fixed_buffer_size) : outputStream() {
264 buffer_length = fixed_buffer_size;
265 buffer = fixed_buffer;
266 buffer_pos = 0;
267 buffer_fixed = true;
268 }
270 void stringStream::write(const char* s, size_t len) {
271 size_t write_len = len; // number of non-null bytes to write
272 size_t end = buffer_pos + len + 1; // position after write and final '\0'
273 if (end > buffer_length) {
274 if (buffer_fixed) {
275 // if buffer cannot resize, silently truncate
276 end = buffer_length;
277 write_len = end - buffer_pos - 1; // leave room for the final '\0'
278 } else {
279 // For small overruns, double the buffer. For larger ones,
280 // increase to the requested size.
281 if (end < buffer_length * 2) {
282 end = buffer_length * 2;
283 }
284 char* oldbuf = buffer;
285 buffer = NEW_RESOURCE_ARRAY(char, end);
286 strncpy(buffer, oldbuf, buffer_pos);
287 buffer_length = end;
288 }
289 }
290 // invariant: buffer is always null-terminated
291 guarantee(buffer_pos + write_len + 1 <= buffer_length, "stringStream oob");
292 buffer[buffer_pos + write_len] = 0;
293 strncpy(buffer + buffer_pos, s, write_len);
294 buffer_pos += write_len;
296 // Note that the following does not depend on write_len.
297 // This means that position and count get updated
298 // even when overflow occurs.
299 update_position(s, len);
300 }
302 char* stringStream::as_string() {
303 char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
304 strncpy(copy, buffer, buffer_pos);
305 copy[buffer_pos] = 0; // terminating null
306 return copy;
307 }
309 stringStream::~stringStream() {}
311 xmlStream* xtty;
312 outputStream* tty;
313 outputStream* gclog_or_tty;
314 extern Mutex* tty_lock;
316 fileStream::fileStream(const char* file_name) {
317 _file = fopen(file_name, "w");
318 _need_close = true;
319 }
321 void fileStream::write(const char* s, size_t len) {
322 if (_file != NULL) {
323 // Make an unused local variable to avoid warning from gcc 4.x compiler.
324 size_t count = fwrite(s, 1, len, _file);
325 }
326 update_position(s, len);
327 }
329 fileStream::~fileStream() {
330 if (_file != NULL) {
331 if (_need_close) fclose(_file);
332 _file = NULL;
333 }
334 }
336 void fileStream::flush() {
337 fflush(_file);
338 }
340 fdStream::fdStream(const char* file_name) {
341 _fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
342 _need_close = true;
343 }
345 fdStream::~fdStream() {
346 if (_fd != -1) {
347 if (_need_close) close(_fd);
348 _fd = -1;
349 }
350 }
352 void fdStream::write(const char* s, size_t len) {
353 if (_fd != -1) {
354 // Make an unused local variable to avoid warning from gcc 4.x compiler.
355 size_t count = ::write(_fd, s, (int)len);
356 }
357 update_position(s, len);
358 }
360 defaultStream* defaultStream::instance = NULL;
361 int defaultStream::_output_fd = 1;
362 int defaultStream::_error_fd = 2;
363 FILE* defaultStream::_output_stream = stdout;
364 FILE* defaultStream::_error_stream = stderr;
366 #define LOG_MAJOR_VERSION 160
367 #define LOG_MINOR_VERSION 1
369 void defaultStream::init() {
370 _inited = true;
371 if (LogVMOutput || LogCompilation) {
372 init_log();
373 }
374 }
376 bool defaultStream::has_log_file() {
377 // lazily create log file (at startup, LogVMOutput is false even
378 // if +LogVMOutput is used, because the flags haven't been parsed yet)
379 // For safer printing during fatal error handling, do not init logfile
380 // if a VM error has been reported.
381 if (!_inited && !is_error_reported()) init();
382 return _log_file != NULL;
383 }
385 static const char* make_log_name(const char* log_name, const char* force_directory) {
386 const char* basename = log_name;
387 char file_sep = os::file_separator()[0];
388 const char* cp;
389 for (cp = log_name; *cp != '\0'; cp++) {
390 if (*cp == '/' || *cp == file_sep) {
391 basename = cp+1;
392 }
393 }
394 const char* nametail = log_name;
396 // Compute buffer length
397 size_t buffer_length;
398 if (force_directory != NULL) {
399 buffer_length = strlen(force_directory) + strlen(os::file_separator()) +
400 strlen(basename) + 1;
401 } else {
402 buffer_length = strlen(log_name) + 1;
403 }
405 const char* star = strchr(basename, '*');
406 int star_pos = (star == NULL) ? -1 : (star - nametail);
408 char pid[32];
409 if (star_pos >= 0) {
410 jio_snprintf(pid, sizeof(pid), "%u", os::current_process_id());
411 buffer_length += strlen(pid);
412 }
414 // Create big enough buffer.
415 char *buf = NEW_C_HEAP_ARRAY(char, buffer_length);
417 strcpy(buf, "");
418 if (force_directory != NULL) {
419 strcat(buf, force_directory);
420 strcat(buf, os::file_separator());
421 nametail = basename; // completely skip directory prefix
422 }
424 if (star_pos >= 0) {
425 // convert foo*bar.log to foo123bar.log
426 int buf_pos = (int) strlen(buf);
427 strncpy(&buf[buf_pos], nametail, star_pos);
428 strcpy(&buf[buf_pos + star_pos], pid);
429 nametail += star_pos + 1; // skip prefix and star
430 }
432 strcat(buf, nametail); // append rest of name, or all of name
433 return buf;
434 }
436 void defaultStream::init_log() {
437 // %%% Need a MutexLocker?
438 const char* log_name = LogFile != NULL ? LogFile : "hotspot.log";
439 const char* try_name = make_log_name(log_name, NULL);
440 fileStream* file = new(ResourceObj::C_HEAP) fileStream(try_name);
441 if (!file->is_open()) {
442 // Try again to open the file.
443 char warnbuf[O_BUFLEN*2];
444 jio_snprintf(warnbuf, sizeof(warnbuf),
445 "Warning: Cannot open log file: %s\n", try_name);
446 // Note: This feature is for maintainer use only. No need for L10N.
447 jio_print(warnbuf);
448 FREE_C_HEAP_ARRAY(char, try_name);
449 try_name = make_log_name("hs_pid*.log", os::get_temp_directory());
450 jio_snprintf(warnbuf, sizeof(warnbuf),
451 "Warning: Forcing option -XX:LogFile=%s\n", try_name);
452 jio_print(warnbuf);
453 delete file;
454 file = new(ResourceObj::C_HEAP) fileStream(try_name);
455 FREE_C_HEAP_ARRAY(char, try_name);
456 }
457 if (file->is_open()) {
458 _log_file = file;
459 xmlStream* xs = new(ResourceObj::C_HEAP) xmlStream(file);
460 _outer_xmlStream = xs;
461 if (this == tty) xtty = xs;
462 // Write XML header.
463 xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
464 // (For now, don't bother to issue a DTD for this private format.)
465 jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
466 // %%% Should be: jlong time_ms = os::start_time_milliseconds(), if
467 // we ever get round to introduce that method on the os class
468 xs->head("hotspot_log version='%d %d'"
469 " process='%d' time_ms='"INT64_FORMAT"'",
470 LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
471 os::current_process_id(), time_ms);
472 // Write VM version header immediately.
473 xs->head("vm_version");
474 xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr();
475 xs->tail("name");
476 xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr();
477 xs->tail("release");
478 xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr();
479 xs->tail("info");
480 xs->tail("vm_version");
481 // Record information about the command-line invocation.
482 xs->head("vm_arguments"); // Cf. Arguments::print_on()
483 if (Arguments::num_jvm_flags() > 0) {
484 xs->head("flags");
485 Arguments::print_jvm_flags_on(xs->text());
486 xs->tail("flags");
487 }
488 if (Arguments::num_jvm_args() > 0) {
489 xs->head("args");
490 Arguments::print_jvm_args_on(xs->text());
491 xs->tail("args");
492 }
493 if (Arguments::java_command() != NULL) {
494 xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command());
495 xs->tail("command");
496 }
497 if (Arguments::sun_java_launcher() != NULL) {
498 xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher());
499 xs->tail("launcher");
500 }
501 if (Arguments::system_properties() != NULL) {
502 xs->head("properties");
503 // Print it as a java-style property list.
504 // System properties don't generally contain newlines, so don't bother with unparsing.
505 for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
506 xs->text()->print_cr("%s=%s", p->key(), p->value());
507 }
508 xs->tail("properties");
509 }
510 xs->tail("vm_arguments");
511 // tty output per se is grouped under the <tty>...</tty> element.
512 xs->head("tty");
513 // All further non-markup text gets copied to the tty:
514 xs->_text = this; // requires friend declaration!
515 } else {
516 delete(file);
517 // and leave xtty as NULL
518 LogVMOutput = false;
519 DisplayVMOutput = true;
520 LogCompilation = false;
521 }
522 }
524 // finish_log() is called during normal VM shutdown. finish_log_on_error() is
525 // called by ostream_abort() after a fatal error.
526 //
527 void defaultStream::finish_log() {
528 xmlStream* xs = _outer_xmlStream;
529 xs->done("tty");
531 // Other log forks are appended here, at the End of Time:
532 CompileLog::finish_log(xs->out()); // write compile logging, if any, now
534 xs->done("hotspot_log");
535 xs->flush();
537 fileStream* file = _log_file;
538 _log_file = NULL;
540 delete _outer_xmlStream;
541 _outer_xmlStream = NULL;
543 file->flush();
544 delete file;
545 }
547 void defaultStream::finish_log_on_error(char *buf, int buflen) {
548 xmlStream* xs = _outer_xmlStream;
550 if (xs && xs->out()) {
552 xs->done_raw("tty");
554 // Other log forks are appended here, at the End of Time:
555 CompileLog::finish_log_on_error(xs->out(), buf, buflen); // write compile logging, if any, now
557 xs->done_raw("hotspot_log");
558 xs->flush();
560 fileStream* file = _log_file;
561 _log_file = NULL;
562 _outer_xmlStream = NULL;
564 if (file) {
565 file->flush();
567 // Can't delete or close the file because delete and fclose aren't
568 // async-safe. We are about to die, so leave it to the kernel.
569 // delete file;
570 }
571 }
572 }
574 intx defaultStream::hold(intx writer_id) {
575 bool has_log = has_log_file(); // check before locking
576 if (// impossible, but who knows?
577 writer_id == NO_WRITER ||
579 // bootstrap problem
580 tty_lock == NULL ||
582 // can't grab a lock or call Thread::current() if TLS isn't initialized
583 ThreadLocalStorage::thread() == NULL ||
585 // developer hook
586 !SerializeVMOutput ||
588 // VM already unhealthy
589 is_error_reported() ||
591 // safepoint == global lock (for VM only)
592 (SafepointSynchronize::is_synchronizing() &&
593 Thread::current()->is_VM_thread())
594 ) {
595 // do not attempt to lock unless we know the thread and the VM is healthy
596 return NO_WRITER;
597 }
598 if (_writer == writer_id) {
599 // already held, no need to re-grab the lock
600 return NO_WRITER;
601 }
602 tty_lock->lock_without_safepoint_check();
603 // got the lock
604 if (writer_id != _last_writer) {
605 if (has_log) {
606 _log_file->bol();
607 // output a hint where this output is coming from:
608 _log_file->print_cr("<writer thread='"INTX_FORMAT"'/>", writer_id);
609 }
610 _last_writer = writer_id;
611 }
612 _writer = writer_id;
613 return writer_id;
614 }
616 void defaultStream::release(intx holder) {
617 if (holder == NO_WRITER) {
618 // nothing to release: either a recursive lock, or we scribbled (too bad)
619 return;
620 }
621 if (_writer != holder) {
622 return; // already unlocked, perhaps via break_tty_lock_for_safepoint
623 }
624 _writer = NO_WRITER;
625 tty_lock->unlock();
626 }
629 // Yuck: jio_print does not accept char*/len.
630 static void call_jio_print(const char* s, size_t len) {
631 char buffer[O_BUFLEN+100];
632 if (len > sizeof(buffer)-1) {
633 warning("increase O_BUFLEN in ostream.cpp -- output truncated");
634 len = sizeof(buffer)-1;
635 }
636 strncpy(buffer, s, len);
637 buffer[len] = '\0';
638 jio_print(buffer);
639 }
642 void defaultStream::write(const char* s, size_t len) {
643 intx thread_id = os::current_thread_id();
644 intx holder = hold(thread_id);
646 if (DisplayVMOutput &&
647 (_outer_xmlStream == NULL || !_outer_xmlStream->inside_attrs())) {
648 // print to output stream. It can be redirected by a vfprintf hook
649 if (s[len] == '\0') {
650 jio_print(s);
651 } else {
652 call_jio_print(s, len);
653 }
654 }
656 // print to log file
657 if (has_log_file()) {
658 int nl0 = _newlines;
659 xmlTextStream::write(s, len);
660 // flush the log file too, if there were any newlines
661 if (nl0 != _newlines){
662 flush();
663 }
664 } else {
665 update_position(s, len);
666 }
668 release(holder);
669 }
671 intx ttyLocker::hold_tty() {
672 if (defaultStream::instance == NULL) return defaultStream::NO_WRITER;
673 intx thread_id = os::current_thread_id();
674 return defaultStream::instance->hold(thread_id);
675 }
677 void ttyLocker::release_tty(intx holder) {
678 if (holder == defaultStream::NO_WRITER) return;
679 defaultStream::instance->release(holder);
680 }
682 void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
683 if (defaultStream::instance != NULL &&
684 defaultStream::instance->writer() == holder) {
685 if (xtty != NULL) {
686 xtty->print_cr("<!-- safepoint while printing -->");
687 }
688 defaultStream::instance->release(holder);
689 }
690 // (else there was no lock to break)
691 }
693 void ostream_init() {
694 if (defaultStream::instance == NULL) {
695 defaultStream::instance = new(ResourceObj::C_HEAP) defaultStream();
696 tty = defaultStream::instance;
698 // We want to ensure that time stamps in GC logs consider time 0
699 // the time when the JVM is initialized, not the first time we ask
700 // for a time stamp. So, here, we explicitly update the time stamp
701 // of tty.
702 tty->time_stamp().update_to(1);
703 }
704 }
706 void ostream_init_log() {
707 // For -Xloggc:<file> option - called in runtime/thread.cpp
708 // Note : this must be called AFTER ostream_init()
710 gclog_or_tty = tty; // default to tty
711 if (Arguments::gc_log_filename() != NULL) {
712 fileStream * gclog = new(ResourceObj::C_HEAP)
713 fileStream(Arguments::gc_log_filename());
714 if (gclog->is_open()) {
715 // now we update the time stamp of the GC log to be synced up
716 // with tty.
717 gclog->time_stamp().update_to(tty->time_stamp().ticks());
718 gclog_or_tty = gclog;
719 }
720 }
722 // If we haven't lazily initialized the logfile yet, do it now,
723 // to avoid the possibility of lazy initialization during a VM
724 // crash, which can affect the stability of the fatal error handler.
725 defaultStream::instance->has_log_file();
726 }
728 // ostream_exit() is called during normal VM exit to finish log files, flush
729 // output and free resource.
730 void ostream_exit() {
731 static bool ostream_exit_called = false;
732 if (ostream_exit_called) return;
733 ostream_exit_called = true;
734 if (gclog_or_tty != tty) {
735 delete gclog_or_tty;
736 }
737 {
738 // we temporaly disable PrintMallocFree here
739 // as otherwise it'll lead to using of almost deleted
740 // tty or defaultStream::instance in logging facility
741 // of HeapFree(), see 6391258
742 DEBUG_ONLY(FlagSetting fs(PrintMallocFree, false);)
743 if (tty != defaultStream::instance) {
744 delete tty;
745 }
746 if (defaultStream::instance != NULL) {
747 delete defaultStream::instance;
748 }
749 }
750 tty = NULL;
751 xtty = NULL;
752 gclog_or_tty = NULL;
753 defaultStream::instance = NULL;
754 }
756 // ostream_abort() is called by os::abort() when VM is about to die.
757 void ostream_abort() {
758 // Here we can't delete gclog_or_tty and tty, just flush their output
759 if (gclog_or_tty) gclog_or_tty->flush();
760 if (tty) tty->flush();
762 if (defaultStream::instance != NULL) {
763 static char buf[4096];
764 defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
765 }
766 }
768 staticBufferStream::staticBufferStream(char* buffer, size_t buflen,
769 outputStream *outer_stream) {
770 _buffer = buffer;
771 _buflen = buflen;
772 _outer_stream = outer_stream;
773 }
775 void staticBufferStream::write(const char* c, size_t len) {
776 _outer_stream->print_raw(c, (int)len);
777 }
779 void staticBufferStream::flush() {
780 _outer_stream->flush();
781 }
783 void staticBufferStream::print(const char* format, ...) {
784 va_list ap;
785 va_start(ap, format);
786 size_t len;
787 const char* str = do_vsnprintf(_buffer, _buflen, format, ap, false, len);
788 write(str, len);
789 va_end(ap);
790 }
792 void staticBufferStream::print_cr(const char* format, ...) {
793 va_list ap;
794 va_start(ap, format);
795 size_t len;
796 const char* str = do_vsnprintf(_buffer, _buflen, format, ap, true, len);
797 write(str, len);
798 va_end(ap);
799 }
801 void staticBufferStream::vprint(const char *format, va_list argptr) {
802 size_t len;
803 const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, false, len);
804 write(str, len);
805 }
807 void staticBufferStream::vprint_cr(const char* format, va_list argptr) {
808 size_t len;
809 const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, true, len);
810 write(str, len);
811 }
813 bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
814 buffer_length = initial_size;
815 buffer = NEW_C_HEAP_ARRAY(char, buffer_length);
816 buffer_pos = 0;
817 buffer_fixed = false;
818 buffer_max = bufmax;
819 }
821 bufferedStream::bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax) : outputStream() {
822 buffer_length = fixed_buffer_size;
823 buffer = fixed_buffer;
824 buffer_pos = 0;
825 buffer_fixed = true;
826 buffer_max = bufmax;
827 }
829 void bufferedStream::write(const char* s, size_t len) {
831 if(buffer_pos + len > buffer_max) {
832 flush();
833 }
835 size_t end = buffer_pos + len;
836 if (end >= buffer_length) {
837 if (buffer_fixed) {
838 // if buffer cannot resize, silently truncate
839 len = buffer_length - buffer_pos - 1;
840 } else {
841 // For small overruns, double the buffer. For larger ones,
842 // increase to the requested size.
843 if (end < buffer_length * 2) {
844 end = buffer_length * 2;
845 }
846 buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end);
847 buffer_length = end;
848 }
849 }
850 memcpy(buffer + buffer_pos, s, len);
851 buffer_pos += len;
852 update_position(s, len);
853 }
855 char* bufferedStream::as_string() {
856 char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
857 strncpy(copy, buffer, buffer_pos);
858 copy[buffer_pos] = 0; // terminating null
859 return copy;
860 }
862 bufferedStream::~bufferedStream() {
863 if (!buffer_fixed) {
864 FREE_C_HEAP_ARRAY(char, buffer);
865 }
866 }
868 #ifndef PRODUCT
870 #if defined(SOLARIS) || defined(LINUX)
871 #include <sys/types.h>
872 #include <sys/socket.h>
873 #include <netinet/in.h>
874 #include <arpa/inet.h>
875 #endif
877 // Network access
878 networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
880 _socket = -1;
882 hpi::initialize_socket_library();
884 int result = hpi::socket(AF_INET, SOCK_STREAM, 0);
885 if (result <= 0) {
886 assert(false, "Socket could not be created!");
887 } else {
888 _socket = result;
889 }
890 }
892 int networkStream::read(char *buf, size_t len) {
893 return hpi::recv(_socket, buf, (int)len, 0);
894 }
896 void networkStream::flush() {
897 if (size() != 0) {
898 int result = hpi::raw_send(_socket, (char *)base(), (int)size(), 0);
899 assert(result != -1, "connection error");
900 assert(result == (int)size(), "didn't send enough data");
901 }
902 reset();
903 }
905 networkStream::~networkStream() {
906 close();
907 }
909 void networkStream::close() {
910 if (_socket != -1) {
911 flush();
912 hpi::socket_close(_socket);
913 _socket = -1;
914 }
915 }
917 bool networkStream::connect(const char *ip, short port) {
919 struct sockaddr_in server;
920 server.sin_family = AF_INET;
921 server.sin_port = htons(port);
923 server.sin_addr.s_addr = inet_addr(ip);
924 if (server.sin_addr.s_addr == (uint32_t)-1) {
925 #ifdef _WINDOWS
926 struct hostent* host = hpi::get_host_by_name((char*)ip);
927 #else
928 struct hostent* host = gethostbyname(ip);
929 #endif
930 if (host != NULL) {
931 memcpy(&server.sin_addr, host->h_addr_list[0], host->h_length);
932 } else {
933 return false;
934 }
935 }
938 int result = hpi::connect(_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_in));
939 return (result >= 0);
940 }
942 #endif