src/share/vm/utilities/ostream.cpp

Tue, 24 Jun 2008 16:00:14 -0700

author
never
date
Tue, 24 Jun 2008 16:00:14 -0700
changeset 657
2a1a77d3458f
parent 537
f96100ac3d12
child 670
9c2ecc2ffb12
child 786
fab5f738c515
permissions
-rw-r--r--

6718676: putback for 6604014 is incomplete
Reviewed-by: kvn, jrose

     1 /*
     2  * Copyright 1997-2007 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::date_stamp(bool guard,
   192                               const char* prefix,
   193                               const char* suffix) {
   194   if (!guard) {
   195     return;
   196   }
   197   print_raw(prefix);
   198   static const char error_time[] = "yyyy-mm-ddThh:mm:ss.mmm+zzzz";
   199   static const int buffer_length = 32;
   200   char buffer[buffer_length];
   201   const char* iso8601_result = os::iso8601_time(buffer, buffer_length);
   202   if (iso8601_result != NULL) {
   203     print_raw(buffer);
   204   } else {
   205     print_raw(error_time);
   206   }
   207   print_raw(suffix);
   208   return;
   209 }
   211 void outputStream::indent() {
   212   while (_position < _indentation) sp();
   213 }
   215 void outputStream::print_jlong(jlong value) {
   216   // N.B. Same as INT64_FORMAT
   217   print(os::jlong_format_specifier(), value);
   218 }
   220 void outputStream::print_julong(julong value) {
   221   // N.B. Same as UINT64_FORMAT
   222   print(os::julong_format_specifier(), value);
   223 }
   225 stringStream::stringStream(size_t initial_size) : outputStream() {
   226   buffer_length = initial_size;
   227   buffer        = NEW_RESOURCE_ARRAY(char, buffer_length);
   228   buffer_pos    = 0;
   229   buffer_fixed  = false;
   230 }
   232 // useful for output to fixed chunks of memory, such as performance counters
   233 stringStream::stringStream(char* fixed_buffer, size_t fixed_buffer_size) : outputStream() {
   234   buffer_length = fixed_buffer_size;
   235   buffer        = fixed_buffer;
   236   buffer_pos    = 0;
   237   buffer_fixed  = true;
   238 }
   240 void stringStream::write(const char* s, size_t len) {
   241   size_t write_len = len;               // number of non-null bytes to write
   242   size_t end = buffer_pos + len + 1;    // position after write and final '\0'
   243   if (end > buffer_length) {
   244     if (buffer_fixed) {
   245       // if buffer cannot resize, silently truncate
   246       end = buffer_length;
   247       write_len = end - buffer_pos - 1; // leave room for the final '\0'
   248     } else {
   249       // For small overruns, double the buffer.  For larger ones,
   250       // increase to the requested size.
   251       if (end < buffer_length * 2) {
   252         end = buffer_length * 2;
   253       }
   254       char* oldbuf = buffer;
   255       buffer = NEW_RESOURCE_ARRAY(char, end);
   256       strncpy(buffer, oldbuf, buffer_pos);
   257       buffer_length = end;
   258     }
   259   }
   260   // invariant: buffer is always null-terminated
   261   guarantee(buffer_pos + write_len + 1 <= buffer_length, "stringStream oob");
   262   buffer[buffer_pos + write_len] = 0;
   263   strncpy(buffer + buffer_pos, s, write_len);
   264   buffer_pos += write_len;
   266   // Note that the following does not depend on write_len.
   267   // This means that position and count get updated
   268   // even when overflow occurs.
   269   update_position(s, len);
   270 }
   272 char* stringStream::as_string() {
   273   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
   274   strncpy(copy, buffer, buffer_pos);
   275   copy[buffer_pos] = 0;  // terminating null
   276   return copy;
   277 }
   279 stringStream::~stringStream() {}
   281 xmlStream*   xtty;
   282 outputStream* tty;
   283 outputStream* gclog_or_tty;
   284 extern Mutex* tty_lock;
   286 fileStream::fileStream(const char* file_name) {
   287   _file = fopen(file_name, "w");
   288   _need_close = true;
   289 }
   291 void fileStream::write(const char* s, size_t len) {
   292   if (_file != NULL)  fwrite(s, 1, len, _file);
   293   update_position(s, len);
   294 }
   296 fileStream::~fileStream() {
   297   if (_file != NULL) {
   298     if (_need_close) fclose(_file);
   299     _file = NULL;
   300   }
   301 }
   303 void fileStream::flush() {
   304   fflush(_file);
   305 }
   307 fdStream::fdStream(const char* file_name) {
   308   _fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
   309   _need_close = true;
   310 }
   312 fdStream::~fdStream() {
   313   if (_fd != -1) {
   314     if (_need_close) close(_fd);
   315     _fd = -1;
   316   }
   317 }
   319 void fdStream::write(const char* s, size_t len) {
   320   if (_fd != -1) ::write(_fd, s, (int)len);
   321   update_position(s, len);
   322 }
   324 defaultStream* defaultStream::instance = NULL;
   325 int defaultStream::_output_fd = 1;
   326 int defaultStream::_error_fd  = 2;
   327 FILE* defaultStream::_output_stream = stdout;
   328 FILE* defaultStream::_error_stream  = stderr;
   330 #define LOG_MAJOR_VERSION 160
   331 #define LOG_MINOR_VERSION 1
   333 void defaultStream::init() {
   334   _inited = true;
   335   if (LogVMOutput || LogCompilation) {
   336     init_log();
   337   }
   338 }
   340 bool defaultStream::has_log_file() {
   341   // lazily create log file (at startup, LogVMOutput is false even
   342   // if +LogVMOutput is used, because the flags haven't been parsed yet)
   343   // For safer printing during fatal error handling, do not init logfile
   344   // if a VM error has been reported.
   345   if (!_inited && !is_error_reported())  init();
   346   return _log_file != NULL;
   347 }
   349 static const char* make_log_name(const char* log_name, const char* force_directory, char* buf) {
   350   const char* basename = log_name;
   351   char file_sep = os::file_separator()[0];
   352   const char* cp;
   353   for (cp = log_name; *cp != '\0'; cp++) {
   354     if (*cp == '/' || *cp == file_sep) {
   355       basename = cp+1;
   356     }
   357   }
   358   const char* nametail = log_name;
   360   strcpy(buf, "");
   361   if (force_directory != NULL) {
   362     strcat(buf, force_directory);
   363     strcat(buf, os::file_separator());
   364     nametail = basename;       // completely skip directory prefix
   365   }
   367   const char* star = strchr(basename, '*');
   368   int star_pos = (star == NULL) ? -1 : (star - nametail);
   370   if (star_pos >= 0) {
   371     // convert foo*bar.log to foo123bar.log
   372     int buf_pos = (int) strlen(buf);
   373     strncpy(&buf[buf_pos], nametail, star_pos);
   374     sprintf(&buf[buf_pos + star_pos], "%u", os::current_process_id());
   375     nametail += star_pos + 1;  // skip prefix and star
   376   }
   378   strcat(buf, nametail);      // append rest of name, or all of name
   379   return buf;
   380 }
   382 void defaultStream::init_log() {
   383   // %%% Need a MutexLocker?
   384   const char* log_name = LogFile != NULL ? LogFile : "hotspot.log";
   385   char buf[O_BUFLEN*2];
   386   const char* try_name = make_log_name(log_name, NULL, buf);
   387   fileStream* file = new(ResourceObj::C_HEAP) fileStream(try_name);
   388   if (!file->is_open()) {
   389     // Try again to open the file.
   390     char warnbuf[O_BUFLEN*2];
   391     sprintf(warnbuf, "Warning:  Cannot open log file: %s\n", try_name);
   392     // Note:  This feature is for maintainer use only.  No need for L10N.
   393     jio_print(warnbuf);
   394     try_name = make_log_name("hs_pid*.log", os::get_temp_directory(), buf);
   395     sprintf(warnbuf, "Warning:  Forcing option -XX:LogFile=%s\n", try_name);
   396     jio_print(warnbuf);
   397     delete file;
   398     file = new(ResourceObj::C_HEAP) fileStream(try_name);
   399   }
   400   if (file->is_open()) {
   401     _log_file = file;
   402     xmlStream* xs = new(ResourceObj::C_HEAP) xmlStream(file);
   403     _outer_xmlStream = xs;
   404     if (this == tty)  xtty = xs;
   405     // Write XML header.
   406     xs->print_cr("<?xml version='1.0' encoding='UTF-8'?>");
   407     // (For now, don't bother to issue a DTD for this private format.)
   408     jlong time_ms = os::javaTimeMillis() - tty->time_stamp().milliseconds();
   409     // %%% Should be: jlong time_ms = os::start_time_milliseconds(), if
   410     // we ever get round to introduce that method on the os class
   411     xs->head("hotspot_log version='%d %d'"
   412              " process='%d' time_ms='"INT64_FORMAT"'",
   413              LOG_MAJOR_VERSION, LOG_MINOR_VERSION,
   414              os::current_process_id(), time_ms);
   415     // Write VM version header immediately.
   416     xs->head("vm_version");
   417     xs->head("name"); xs->text("%s", VM_Version::vm_name()); xs->cr();
   418     xs->tail("name");
   419     xs->head("release"); xs->text("%s", VM_Version::vm_release()); xs->cr();
   420     xs->tail("release");
   421     xs->head("info"); xs->text("%s", VM_Version::internal_vm_info_string()); xs->cr();
   422     xs->tail("info");
   423     xs->tail("vm_version");
   424     // Record information about the command-line invocation.
   425     xs->head("vm_arguments");  // Cf. Arguments::print_on()
   426     if (Arguments::num_jvm_flags() > 0) {
   427       xs->head("flags");
   428       Arguments::print_jvm_flags_on(xs->text());
   429       xs->tail("flags");
   430     }
   431     if (Arguments::num_jvm_args() > 0) {
   432       xs->head("args");
   433       Arguments::print_jvm_args_on(xs->text());
   434       xs->tail("args");
   435     }
   436     if (Arguments::java_command() != NULL) {
   437       xs->head("command"); xs->text()->print_cr("%s", Arguments::java_command());
   438       xs->tail("command");
   439     }
   440     if (Arguments::sun_java_launcher() != NULL) {
   441       xs->head("launcher"); xs->text()->print_cr("%s", Arguments::sun_java_launcher());
   442       xs->tail("launcher");
   443     }
   444     if (Arguments::system_properties() !=  NULL) {
   445       xs->head("properties");
   446       // Print it as a java-style property list.
   447       // System properties don't generally contain newlines, so don't bother with unparsing.
   448       for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
   449         xs->text()->print_cr("%s=%s", p->key(), p->value());
   450       }
   451       xs->tail("properties");
   452     }
   453     xs->tail("vm_arguments");
   454     // tty output per se is grouped under the <tty>...</tty> element.
   455     xs->head("tty");
   456     // All further non-markup text gets copied to the tty:
   457     xs->_text = this;  // requires friend declaration!
   458   } else {
   459     delete(file);
   460     // and leave xtty as NULL
   461     LogVMOutput = false;
   462     DisplayVMOutput = true;
   463     LogCompilation = false;
   464   }
   465 }
   467 // finish_log() is called during normal VM shutdown. finish_log_on_error() is
   468 // called by ostream_abort() after a fatal error.
   469 //
   470 void defaultStream::finish_log() {
   471   xmlStream* xs = _outer_xmlStream;
   472   xs->done("tty");
   474   // Other log forks are appended here, at the End of Time:
   475   CompileLog::finish_log(xs->out());  // write compile logging, if any, now
   477   xs->done("hotspot_log");
   478   xs->flush();
   480   fileStream* file = _log_file;
   481   _log_file = NULL;
   483   delete _outer_xmlStream;
   484   _outer_xmlStream = NULL;
   486   file->flush();
   487   delete file;
   488 }
   490 void defaultStream::finish_log_on_error(char *buf, int buflen) {
   491   xmlStream* xs = _outer_xmlStream;
   493   if (xs && xs->out()) {
   495     xs->done_raw("tty");
   497     // Other log forks are appended here, at the End of Time:
   498     CompileLog::finish_log_on_error(xs->out(), buf, buflen);  // write compile logging, if any, now
   500     xs->done_raw("hotspot_log");
   501     xs->flush();
   503     fileStream* file = _log_file;
   504     _log_file = NULL;
   505     _outer_xmlStream = NULL;
   507     if (file) {
   508       file->flush();
   510       // Can't delete or close the file because delete and fclose aren't
   511       // async-safe. We are about to die, so leave it to the kernel.
   512       // delete file;
   513     }
   514   }
   515 }
   517 intx defaultStream::hold(intx writer_id) {
   518   bool has_log = has_log_file();  // check before locking
   519   if (// impossible, but who knows?
   520       writer_id == NO_WRITER ||
   522       // bootstrap problem
   523       tty_lock == NULL ||
   525       // can't grab a lock or call Thread::current() if TLS isn't initialized
   526       ThreadLocalStorage::thread() == NULL ||
   528       // developer hook
   529       !SerializeVMOutput ||
   531       // VM already unhealthy
   532       is_error_reported() ||
   534       // safepoint == global lock (for VM only)
   535       (SafepointSynchronize::is_synchronizing() &&
   536        Thread::current()->is_VM_thread())
   537       ) {
   538     // do not attempt to lock unless we know the thread and the VM is healthy
   539     return NO_WRITER;
   540   }
   541   if (_writer == writer_id) {
   542     // already held, no need to re-grab the lock
   543     return NO_WRITER;
   544   }
   545   tty_lock->lock_without_safepoint_check();
   546   // got the lock
   547   if (writer_id != _last_writer) {
   548     if (has_log) {
   549       _log_file->bol();
   550       // output a hint where this output is coming from:
   551       _log_file->print_cr("<writer thread='"INTX_FORMAT"'/>", writer_id);
   552     }
   553     _last_writer = writer_id;
   554   }
   555   _writer = writer_id;
   556   return writer_id;
   557 }
   559 void defaultStream::release(intx holder) {
   560   if (holder == NO_WRITER) {
   561     // nothing to release:  either a recursive lock, or we scribbled (too bad)
   562     return;
   563   }
   564   if (_writer != holder) {
   565     return;  // already unlocked, perhaps via break_tty_lock_for_safepoint
   566   }
   567   _writer = NO_WRITER;
   568   tty_lock->unlock();
   569 }
   572 // Yuck:  jio_print does not accept char*/len.
   573 static void call_jio_print(const char* s, size_t len) {
   574   char buffer[O_BUFLEN+100];
   575   if (len > sizeof(buffer)-1) {
   576     warning("increase O_BUFLEN in ostream.cpp -- output truncated");
   577     len = sizeof(buffer)-1;
   578   }
   579   strncpy(buffer, s, len);
   580   buffer[len] = '\0';
   581   jio_print(buffer);
   582 }
   585 void defaultStream::write(const char* s, size_t len) {
   586   intx thread_id = os::current_thread_id();
   587   intx holder = hold(thread_id);
   589   if (DisplayVMOutput &&
   590       (_outer_xmlStream == NULL || !_outer_xmlStream->inside_attrs())) {
   591     // print to output stream. It can be redirected by a vfprintf hook
   592     if (s[len] == '\0') {
   593       jio_print(s);
   594     } else {
   595       call_jio_print(s, len);
   596     }
   597   }
   599   // print to log file
   600   if (has_log_file()) {
   601     int nl0 = _newlines;
   602     xmlTextStream::write(s, len);
   603     // flush the log file too, if there were any newlines
   604     if (nl0 != _newlines){
   605       flush();
   606     }
   607   } else {
   608     update_position(s, len);
   609   }
   611   release(holder);
   612 }
   614 intx ttyLocker::hold_tty() {
   615   if (defaultStream::instance == NULL)  return defaultStream::NO_WRITER;
   616   intx thread_id = os::current_thread_id();
   617   return defaultStream::instance->hold(thread_id);
   618 }
   620 void ttyLocker::release_tty(intx holder) {
   621   if (holder == defaultStream::NO_WRITER)  return;
   622   defaultStream::instance->release(holder);
   623 }
   625 void ttyLocker::break_tty_lock_for_safepoint(intx holder) {
   626   if (defaultStream::instance != NULL &&
   627       defaultStream::instance->writer() == holder) {
   628     if (xtty != NULL) {
   629       xtty->print_cr("<!-- safepoint while printing -->");
   630     }
   631     defaultStream::instance->release(holder);
   632   }
   633   // (else there was no lock to break)
   634 }
   636 void ostream_init() {
   637   if (defaultStream::instance == NULL) {
   638     defaultStream::instance = new(ResourceObj::C_HEAP) defaultStream();
   639     tty = defaultStream::instance;
   641     // We want to ensure that time stamps in GC logs consider time 0
   642     // the time when the JVM is initialized, not the first time we ask
   643     // for a time stamp. So, here, we explicitly update the time stamp
   644     // of tty.
   645     tty->time_stamp().update_to(1);
   646   }
   647 }
   649 void ostream_init_log() {
   650   // For -Xloggc:<file> option - called in runtime/thread.cpp
   651   // Note : this must be called AFTER ostream_init()
   653   gclog_or_tty = tty; // default to tty
   654   if (Arguments::gc_log_filename() != NULL) {
   655     fileStream * gclog = new(ResourceObj::C_HEAP)
   656                            fileStream(Arguments::gc_log_filename());
   657     if (gclog->is_open()) {
   658       // now we update the time stamp of the GC log to be synced up
   659       // with tty.
   660       gclog->time_stamp().update_to(tty->time_stamp().ticks());
   661       gclog_or_tty = gclog;
   662     }
   663   }
   665   // If we haven't lazily initialized the logfile yet, do it now,
   666   // to avoid the possibility of lazy initialization during a VM
   667   // crash, which can affect the stability of the fatal error handler.
   668   defaultStream::instance->has_log_file();
   669 }
   671 // ostream_exit() is called during normal VM exit to finish log files, flush
   672 // output and free resource.
   673 void ostream_exit() {
   674   static bool ostream_exit_called = false;
   675   if (ostream_exit_called)  return;
   676   ostream_exit_called = true;
   677   if (gclog_or_tty != tty) {
   678       delete gclog_or_tty;
   679   }
   680   {
   681       // we temporaly disable PrintMallocFree here
   682       // as otherwise it'll lead to using of almost deleted
   683       // tty or defaultStream::instance in logging facility
   684       // of HeapFree(), see 6391258
   685       DEBUG_ONLY(FlagSetting fs(PrintMallocFree, false);)
   686       if (tty != defaultStream::instance) {
   687           delete tty;
   688       }
   689       if (defaultStream::instance != NULL) {
   690           delete defaultStream::instance;
   691       }
   692   }
   693   tty = NULL;
   694   xtty = NULL;
   695   gclog_or_tty = NULL;
   696   defaultStream::instance = NULL;
   697 }
   699 // ostream_abort() is called by os::abort() when VM is about to die.
   700 void ostream_abort() {
   701   // Here we can't delete gclog_or_tty and tty, just flush their output
   702   if (gclog_or_tty) gclog_or_tty->flush();
   703   if (tty) tty->flush();
   705   if (defaultStream::instance != NULL) {
   706     static char buf[4096];
   707     defaultStream::instance->finish_log_on_error(buf, sizeof(buf));
   708   }
   709 }
   711 staticBufferStream::staticBufferStream(char* buffer, size_t buflen,
   712                                        outputStream *outer_stream) {
   713   _buffer = buffer;
   714   _buflen = buflen;
   715   _outer_stream = outer_stream;
   716 }
   718 void staticBufferStream::write(const char* c, size_t len) {
   719   _outer_stream->print_raw(c, (int)len);
   720 }
   722 void staticBufferStream::flush() {
   723   _outer_stream->flush();
   724 }
   726 void staticBufferStream::print(const char* format, ...) {
   727   va_list ap;
   728   va_start(ap, format);
   729   size_t len;
   730   const char* str = do_vsnprintf(_buffer, _buflen, format, ap, false, len);
   731   write(str, len);
   732   va_end(ap);
   733 }
   735 void staticBufferStream::print_cr(const char* format, ...) {
   736   va_list ap;
   737   va_start(ap, format);
   738   size_t len;
   739   const char* str = do_vsnprintf(_buffer, _buflen, format, ap, true, len);
   740   write(str, len);
   741   va_end(ap);
   742 }
   744 void staticBufferStream::vprint(const char *format, va_list argptr) {
   745   size_t len;
   746   const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, false, len);
   747   write(str, len);
   748 }
   750 void staticBufferStream::vprint_cr(const char* format, va_list argptr) {
   751   size_t len;
   752   const char* str = do_vsnprintf(_buffer, _buflen, format, argptr, true, len);
   753   write(str, len);
   754 }
   756 bufferedStream::bufferedStream(size_t initial_size, size_t bufmax) : outputStream() {
   757   buffer_length = initial_size;
   758   buffer        = NEW_C_HEAP_ARRAY(char, buffer_length);
   759   buffer_pos    = 0;
   760   buffer_fixed  = false;
   761   buffer_max    = bufmax;
   762 }
   764 bufferedStream::bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax) : outputStream() {
   765   buffer_length = fixed_buffer_size;
   766   buffer        = fixed_buffer;
   767   buffer_pos    = 0;
   768   buffer_fixed  = true;
   769   buffer_max    = bufmax;
   770 }
   772 void bufferedStream::write(const char* s, size_t len) {
   774   if(buffer_pos + len > buffer_max) {
   775     flush();
   776   }
   778   size_t end = buffer_pos + len;
   779   if (end >= buffer_length) {
   780     if (buffer_fixed) {
   781       // if buffer cannot resize, silently truncate
   782       len = buffer_length - buffer_pos - 1;
   783     } else {
   784       // For small overruns, double the buffer.  For larger ones,
   785       // increase to the requested size.
   786       if (end < buffer_length * 2) {
   787         end = buffer_length * 2;
   788       }
   789       buffer = REALLOC_C_HEAP_ARRAY(char, buffer, end);
   790       buffer_length = end;
   791     }
   792   }
   793   memcpy(buffer + buffer_pos, s, len);
   794   buffer_pos += len;
   795   update_position(s, len);
   796 }
   798 char* bufferedStream::as_string() {
   799   char* copy = NEW_RESOURCE_ARRAY(char, buffer_pos+1);
   800   strncpy(copy, buffer, buffer_pos);
   801   copy[buffer_pos] = 0;  // terminating null
   802   return copy;
   803 }
   805 bufferedStream::~bufferedStream() {
   806   if (!buffer_fixed) {
   807     FREE_C_HEAP_ARRAY(char, buffer);
   808   }
   809 }
   811 #ifndef PRODUCT
   813 #if defined(SOLARIS) || defined(LINUX)
   814 #include <sys/types.h>
   815 #include <sys/socket.h>
   816 #include <netinet/in.h>
   817 #include <arpa/inet.h>
   818 #endif
   820 // Network access
   821 networkStream::networkStream() : bufferedStream(1024*10, 1024*10) {
   823   _socket = -1;
   825   hpi::initialize_socket_library();
   827   int result = hpi::socket(AF_INET, SOCK_STREAM, 0);
   828   if (result <= 0) {
   829     assert(false, "Socket could not be created!");
   830   } else {
   831     _socket = result;
   832   }
   833 }
   835 int networkStream::read(char *buf, size_t len) {
   836   return hpi::recv(_socket, buf, (int)len, 0);
   837 }
   839 void networkStream::flush() {
   840   if (size() != 0) {
   841     int result = hpi::raw_send(_socket, (char *)base(), (int)size(), 0);
   842     assert(result != -1, "connection error");
   843     assert(result == (int)size(), "didn't send enough data");
   844   }
   845   reset();
   846 }
   848 networkStream::~networkStream() {
   849   close();
   850 }
   852 void networkStream::close() {
   853   if (_socket != -1) {
   854     flush();
   855     hpi::socket_close(_socket);
   856     _socket = -1;
   857   }
   858 }
   860 bool networkStream::connect(const char *ip, short port) {
   862   struct sockaddr_in server;
   863   server.sin_family = AF_INET;
   864   server.sin_port = htons(port);
   866   server.sin_addr.s_addr = inet_addr(ip);
   867   if (server.sin_addr.s_addr == (uint32_t)-1) {
   868 #ifdef _WINDOWS
   869     struct hostent* host = hpi::get_host_by_name((char*)ip);
   870 #else
   871     struct hostent* host = gethostbyname(ip);
   872 #endif
   873     if (host != NULL) {
   874       memcpy(&server.sin_addr, host->h_addr_list[0], host->h_length);
   875     } else {
   876       return false;
   877     }
   878   }
   881   int result = hpi::connect(_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_in));
   882   return (result >= 0);
   883 }
   885 #endif

mercurial