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