1 /*
   2  * Copyright (c) 1997, 2014, 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 #ifndef SHARE_VM_UTILITIES_OSTREAM_HPP
  26 #define SHARE_VM_UTILITIES_OSTREAM_HPP
  27 
  28 #include "memory/allocation.hpp"
  29 #include "runtime/timer.hpp"
  30 #include "runtime/task.hpp"
  31 
  32 class GCId;
  33 DEBUG_ONLY(class ResourceMark;)
  34 
  35 // Output streams for printing
  36 //
  37 // Printing guidelines:
  38 // Where possible, please use tty->print() and tty->print_cr().
  39 // For product mode VM warnings use warning() which internally uses tty.
  40 // In places where tty is not initialized yet or too much overhead,
  41 // we may use jio_printf:
  42 //     jio_fprintf(defaultStream::output_stream(), "Message");
  43 // This allows for redirection via -XX:+DisplayVMOutputToStdout and
  44 // -XX:+DisplayVMOutputToStderr
  45 class outputStream : public ResourceObj {
  46  protected:
  47    int _indentation; // current indentation
  48    int _width;       // width of the page
  49    int _position;    // position on the current line
  50    int _newlines;    // number of '\n' output so far
  51    julong _precount; // number of chars output, less _position
  52    TimeStamp _stamp; // for time stamps
  53 
  54    void update_position(const char* s, size_t len);
  55    static const char* do_vsnprintf(char* buffer, size_t buflen,
  56                                    const char* format, va_list ap,
  57                                    bool add_cr,
  58                                    size_t& result_len)  ATTRIBUTE_PRINTF(3, 0);
  59 
  60  public:
  61    // creation
  62    outputStream(int width = 80);
  63    outputStream(int width, bool has_time_stamps);
  64 
  65    // indentation
  66    outputStream& indent();
  67    void inc() { _indentation++; };
  68    void dec() { _indentation--; };
  69    void inc(int n) { _indentation += n; };
  70    void dec(int n) { _indentation -= n; };
  71    int  indentation() const    { return _indentation; }
  72    void set_indentation(int i) { _indentation = i;    }
  73    void fill_to(int col);
  74    void move_to(int col, int slop = 6, int min_space = 2);
  75 
  76    // sizing
  77    int width()    const { return _width;    }
  78    int position() const { return _position; }
  79    int newlines() const { return _newlines; }
  80    julong count() const { return _precount + _position; }
  81    void set_count(julong count) { _precount = count - _position; }
  82    void set_position(int pos)   { _position = pos; }
  83 
  84    // printing
  85    void print(const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
  86    void print_cr(const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
  87    void vprint(const char *format, va_list argptr) ATTRIBUTE_PRINTF(2, 0);
  88    void vprint_cr(const char* format, va_list argptr) ATTRIBUTE_PRINTF(2, 0);
  89    void print_raw(const char* str)            { write(str, strlen(str)); }
  90    void print_raw(const char* str, int len)   { write(str,         len); }
  91    void print_raw_cr(const char* str)         { write(str, strlen(str)); cr(); }
  92    void print_raw_cr(const char* str, int len){ write(str,         len); cr(); }
  93    void print_data(void* data, size_t len, bool with_ascii);
  94    void put(char ch);
  95    void sp(int count = 1);
  96    void cr();
  97    void bol() { if (_position > 0)  cr(); }
  98 
  99    // Time stamp
 100    TimeStamp& time_stamp() { return _stamp; }
 101    void stamp();
 102    void stamp(bool guard, const char* prefix, const char* suffix);
 103    void stamp(bool guard) {
 104      stamp(guard, "", ": ");
 105    }
 106    // Date stamp
 107    void date_stamp(bool guard, const char* prefix, const char* suffix);
 108    // A simplified call that includes a suffix of ": "
 109    void date_stamp(bool guard) {
 110      date_stamp(guard, "", ": ");
 111    }
 112    void gclog_stamp(const GCId& gc_id);
 113 
 114    // portable printing of 64 bit integers
 115    void print_jlong(jlong value);
 116    void print_julong(julong value);
 117 
 118    // flushing
 119    virtual void flush() {}
 120    virtual void write(const char* str, size_t len) = 0;
 121    virtual void rotate_log(bool force, outputStream* out = NULL) {} // GC log rotation
 122    virtual ~outputStream() {}   // close properly on deletion
 123 
 124    void dec_cr() { dec(); cr(); }
 125    void inc_cr() { inc(); cr(); }
 126 };
 127 
 128 // standard output
 129 // ANSI C++ name collision
 130 extern outputStream* tty;           // tty output
 131 extern outputStream* gclog_or_tty;  // stream for gc log if -Xloggc:<f>, or tty
 132 
 133 class streamIndentor : public StackObj {
 134  private:
 135   outputStream* _str;
 136   int _amount;
 137 
 138  public:
 139   streamIndentor(outputStream* str, int amt = 2) : _str(str), _amount(amt) {
 140     _str->inc(_amount);
 141   }
 142   ~streamIndentor() { _str->dec(_amount); }
 143 };
 144 
 145 
 146 // advisory locking for the shared tty stream:
 147 class ttyLocker: StackObj {
 148   friend class ttyUnlocker;
 149  private:
 150   intx _holder;
 151 
 152  public:
 153   static intx  hold_tty();                // returns a "holder" token
 154   static void  release_tty(intx holder);  // must witness same token
 155   static bool  release_tty_if_locked();   // returns true if lock was released
 156   static void  break_tty_lock_for_safepoint(intx holder);
 157 
 158   ttyLocker()  { _holder = hold_tty(); }
 159   ~ttyLocker() { release_tty(_holder); }
 160 };
 161 
 162 // Release the tty lock if it's held and reacquire it if it was
 163 // locked.  Used to avoid lock ordering problems.
 164 class ttyUnlocker: StackObj {
 165  private:
 166   bool _was_locked;
 167  public:
 168   ttyUnlocker()  {
 169     _was_locked = ttyLocker::release_tty_if_locked();
 170   }
 171   ~ttyUnlocker() {
 172     if (_was_locked) {
 173       ttyLocker::hold_tty();
 174     }
 175   }
 176 };
 177 
 178 // for writing to strings; buffer will expand automatically
 179 class stringStream : public outputStream {
 180  protected:
 181   char*  buffer;
 182   size_t buffer_pos;
 183   size_t buffer_length;
 184   bool   buffer_fixed;
 185   DEBUG_ONLY(ResourceMark* rm;)
 186  public:
 187   stringStream(size_t initial_bufsize = 256);
 188   stringStream(char* fixed_buffer, size_t fixed_buffer_size);
 189   ~stringStream();
 190   virtual void write(const char* c, size_t len);
 191   size_t      size() { return buffer_pos; }
 192   const char* base() { return buffer; }
 193   void  reset() { buffer_pos = 0; _precount = 0; _position = 0; }
 194   char* as_string();
 195 };
 196 
 197 class fileStream : public outputStream {
 198  protected:
 199   FILE* _file;
 200   bool  _need_close;
 201  public:
 202   fileStream() { _file = NULL; _need_close = false; }
 203   fileStream(const char* file_name);
 204   fileStream(const char* file_name, const char* opentype);
 205   fileStream(FILE* file, bool need_close = false) { _file = file; _need_close = need_close; }
 206   ~fileStream();
 207   bool is_open() const { return _file != NULL; }
 208   void set_need_close(bool b) { _need_close = b;}
 209   virtual void write(const char* c, size_t len);
 210   size_t read(void *data, size_t size, size_t count) { return ::fread(data, size, count, _file); }
 211   char* readln(char *data, int count);
 212   int eof() { return feof(_file); }
 213   long fileSize();
 214   void rewind() { ::rewind(_file); }
 215   void flush();
 216 };
 217 
 218 CDS_ONLY(extern fileStream*   classlist_file;)
 219 
 220 // unlike fileStream, fdStream does unbuffered I/O by calling
 221 // open() and write() directly. It is async-safe, but output
 222 // from multiple thread may be mixed together. Used by fatal
 223 // error handler.
 224 class fdStream : public outputStream {
 225  protected:
 226   int  _fd;
 227   bool _need_close;
 228  public:
 229   fdStream(const char* file_name);
 230   fdStream(int fd = -1) { _fd = fd; _need_close = false; }
 231   ~fdStream();
 232   bool is_open() const { return _fd != -1; }
 233   void set_fd(int fd) { _fd = fd; _need_close = false; }
 234   int fd() const { return _fd; }
 235   virtual void write(const char* c, size_t len);
 236   void flush() {};
 237 };
 238 
 239 class Mutex;
 240 class GCLogEvent;
 241 
 242 class gcLogFileStream : public fileStream {
 243  protected:
 244   const char*  _file_name;
 245   jlong  _bytes_written;
 246   uintx  _cur_file_num;             // current logfile rotation number, from 0 to NumberOfGCLogFiles-1
 247  private:
 248   GCLogEvent* _reader;
 249   GCLogEvent* _writer;
 250   Mutex* _lock;
 251 
 252  public:
 253   gcLogFileStream(const char* file_name);
 254   ~gcLogFileStream();
 255   // write asynchronously
 256   virtual void write(const char* c, size_t len);
 257   // really write to file system.
 258   void write_blocking(const char* c, size_t len);
 259   virtual void rotate_log(bool force, outputStream* out = NULL);
 260   void flush_log();
 261   void dump_loggc_header();
 262 
 263   /* If "force" sets true, force log file rotation from outside JVM */
 264   bool should_rotate(bool force) {
 265     return force ||
 266              ((GCLogFileSize != 0) && ((uintx)_bytes_written >= GCLogFileSize));
 267   }
 268 
 269 };
 270 
 271 class GCLogFlusher: public PeriodicTask {
 272   gcLogFileStream * _ostream;
 273   elapsedTimer _accumulatedTime;
 274 public:
 275   GCLogFlusher(int interval, gcLogFileStream* ostream):PeriodicTask(interval), _ostream(ostream) {}
 276 
 277   virtual void task() {
 278     TraceTime t("GCLogFlusher", &_accumulatedTime, true, PrintGCLogFlushTime);
 279     _ostream->flush_log();
 280   }
 281 
 282   elapsedTimer getAccumulatedTime() {
 283     return _accumulatedTime;
 284   }
 285 };
 286 
 287 #ifndef PRODUCT
 288 // unit test for checking -Xloggc:<filename> parsing result
 289 void test_loggc_filename();
 290 void test_snprintf();
 291 #endif
 292 
 293 void ostream_init();
 294 void ostream_init_log();
 295 void ostream_exit();
 296 void ostream_abort();
 297 
 298 // staticBufferStream uses a user-supplied buffer for all formatting.
 299 // Used for safe formatting during fatal error handling.  Not MT safe.
 300 // Do not share the stream between multiple threads.
 301 class staticBufferStream : public outputStream {
 302  private:
 303   char* _buffer;
 304   size_t _buflen;
 305   outputStream* _outer_stream;
 306  public:
 307   staticBufferStream(char* buffer, size_t buflen,
 308                      outputStream *outer_stream);
 309   ~staticBufferStream() {};
 310   virtual void write(const char* c, size_t len);
 311   void flush();
 312   void print(const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
 313   void print_cr(const char* format, ...) ATTRIBUTE_PRINTF(2, 3);
 314   void vprint(const char *format, va_list argptr) ATTRIBUTE_PRINTF(2, 0);
 315   void vprint_cr(const char* format, va_list argptr) ATTRIBUTE_PRINTF(2, 0);
 316 };
 317 
 318 // In the non-fixed buffer case an underlying buffer will be created and
 319 // managed in C heap. Not MT-safe.
 320 class bufferedStream : public outputStream {
 321  protected:
 322   char*  buffer;
 323   size_t buffer_pos;
 324   size_t buffer_max;
 325   size_t buffer_length;
 326   bool   buffer_fixed;
 327  public:
 328   bufferedStream(size_t initial_bufsize = 256, size_t bufmax = 1024*1024*10);
 329   bufferedStream(char* fixed_buffer, size_t fixed_buffer_size, size_t bufmax = 1024*1024*10);
 330   ~bufferedStream();
 331   virtual void write(const char* c, size_t len);
 332   size_t      size() { return buffer_pos; }
 333   const char* base() { return buffer; }
 334   void  reset() { buffer_pos = 0; _precount = 0; _position = 0; }
 335   char* as_string();
 336 };
 337 
 338 #define O_BUFLEN 2000   // max size of output of individual print() methods
 339 
 340 #ifndef PRODUCT
 341 
 342 class networkStream : public bufferedStream {
 343 
 344   private:
 345     int _socket;
 346 
 347   public:
 348     networkStream();
 349     ~networkStream();
 350 
 351     bool connect(const char *host, short port);
 352     bool is_open() const { return _socket != -1; }
 353     int read(char *buf, size_t len);
 354     void close();
 355     virtual void flush();
 356 };
 357 
 358 #endif
 359 
 360 #endif // SHARE_VM_UTILITIES_OSTREAM_HPP