raw_ostream.cpp revision 201360
1238730Sdelphij//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2238730Sdelphij//
3238730Sdelphij//                     The LLVM Compiler Infrastructure
4238730Sdelphij//
5238730Sdelphij// This file is distributed under the University of Illinois Open Source
6238730Sdelphij// License. See LICENSE.TXT for details.
7238730Sdelphij//
8238730Sdelphij//===----------------------------------------------------------------------===//
960786Sps//
1060786Sps// This implements support for bulk buffered stream output.
11238730Sdelphij//
1260786Sps//===----------------------------------------------------------------------===//
1360786Sps
1460786Sps#include "llvm/Support/raw_ostream.h"
1560786Sps#include "llvm/Support/Format.h"
1660786Sps#include "llvm/System/Program.h"
1760786Sps#include "llvm/System/Process.h"
1860786Sps#include "llvm/ADT/SmallVector.h"
1960786Sps#include "llvm/Config/config.h"
2060786Sps#include "llvm/Support/Compiler.h"
2160786Sps#include "llvm/Support/ErrorHandling.h"
2260786Sps#include "llvm/ADT/STLExtras.h"
2360786Sps#include "llvm/ADT/StringExtras.h"
2460786Sps#include <sys/stat.h>
2560786Sps#include <sys/types.h>
2660786Sps
2760786Sps#if defined(HAVE_UNISTD_H)
2860786Sps# include <unistd.h>
2960786Sps#endif
3060786Sps#if defined(HAVE_FCNTL_H)
3160786Sps# include <fcntl.h>
3260786Sps#endif
3360786Sps
3460786Sps#if defined(_MSC_VER)
3560786Sps#include <io.h>
3660786Sps#include <fcntl.h>
3760786Sps#ifndef STDIN_FILENO
3860786Sps# define STDIN_FILENO 0
3960786Sps#endif
4060786Sps#ifndef STDOUT_FILENO
4160786Sps# define STDOUT_FILENO 1
4260786Sps#endif
4360786Sps#ifndef STDERR_FILENO
4460786Sps# define STDERR_FILENO 2
4560786Sps#endif
4660786Sps#endif
4760786Sps
4860786Spsusing namespace llvm;
4960786Sps
5060786Spsraw_ostream::~raw_ostream() {
5160786Sps  // raw_ostream's subclasses should take care to flush the buffer
5260786Sps  // in their destructors.
5360786Sps  assert(OutBufCur == OutBufStart &&
5460786Sps         "raw_ostream destructor called with non-empty buffer!");
5560786Sps
5660786Sps  if (BufferMode == InternalBuffer)
5760786Sps    delete [] OutBufStart;
5860786Sps
5960786Sps  // If there are any pending errors, report them now. Clients wishing
6060786Sps  // to avoid llvm_report_error calls should check for errors with
6160786Sps  // has_error() and clear the error flag with clear_error() before
6260786Sps  // destructing raw_ostream objects which may have errors.
6360786Sps  if (Error)
6460786Sps    llvm_report_error("IO failure on output stream.");
6589019Sps}
6689019Sps
67191930Sdelphij// An out of line virtual method to provide a home for the class vtable.
68237613Sdelphijvoid raw_ostream::handle() {}
6960786Sps
7060786Spssize_t raw_ostream::preferred_buffer_size() const {
7160786Sps  // BUFSIZ is intended to be a reasonable default.
7260786Sps  return BUFSIZ;
7360786Sps}
7460786Sps
7560786Spsvoid raw_ostream::SetBuffered() {
7660786Sps  // Ask the subclass to determine an appropriate buffer size.
7760786Sps  if (size_t Size = preferred_buffer_size())
7860786Sps    SetBufferSize(Size);
7960786Sps  else
8060786Sps    // It may return 0, meaning this stream should be unbuffered.
81237613Sdelphij    SetUnbuffered();
8260786Sps}
8360786Sps
8460786Spsvoid raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
8560786Sps                                    BufferKind Mode) {
8660786Sps  assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
8760786Sps          (Mode != Unbuffered && BufferStart && Size)) &&
8860786Sps         "stream must be unbuffered or have at least one byte");
8960786Sps  // Make sure the current buffer is free of content (we can't flush here; the
9060786Sps  // child buffer management logic will be in write_impl).
9160786Sps  assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
9260786Sps
9360786Sps  if (BufferMode == InternalBuffer)
9460786Sps    delete [] OutBufStart;
9560786Sps  OutBufStart = BufferStart;
9660786Sps  OutBufEnd = OutBufStart+Size;
9760786Sps  OutBufCur = OutBufStart;
9860786Sps  BufferMode = Mode;
9960786Sps
10060786Sps  assert(OutBufStart <= OutBufEnd && "Invalid size!");
101221715Sdelphij}
10260786Sps
10360786Spsraw_ostream &raw_ostream::operator<<(unsigned long N) {
10460786Sps  // Zero is a special case.
10560786Sps  if (N == 0)
10660786Sps    return *this << '0';
10760786Sps
10860786Sps  char NumberBuffer[20];
10960786Sps  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
11089019Sps  char *CurPtr = EndPtr;
11160786Sps
11260786Sps  while (N) {
11360786Sps    *--CurPtr = '0' + char(N % 10);
11460786Sps    N /= 10;
11560786Sps  }
11660786Sps  return write(CurPtr, EndPtr-CurPtr);
11760786Sps}
11860786Sps
11960786Spsraw_ostream &raw_ostream::operator<<(long N) {
12060786Sps  if (N <  0) {
12160786Sps    *this << '-';
12260786Sps    N = -N;
12360786Sps  }
12460786Sps
12560786Sps  return this->operator<<(static_cast<unsigned long>(N));
12660786Sps}
12760786Sps
12860786Spsraw_ostream &raw_ostream::operator<<(unsigned long long N) {
12960786Sps  // Output using 32-bit div/mod when possible.
13060786Sps  if (N == static_cast<unsigned long>(N))
13160786Sps    return this->operator<<(static_cast<unsigned long>(N));
13260786Sps
13360786Sps  char NumberBuffer[20];
134  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
135  char *CurPtr = EndPtr;
136
137  while (N) {
138    *--CurPtr = '0' + char(N % 10);
139    N /= 10;
140  }
141  return write(CurPtr, EndPtr-CurPtr);
142}
143
144raw_ostream &raw_ostream::operator<<(long long N) {
145  if (N <  0) {
146    *this << '-';
147    N = -N;
148  }
149
150  return this->operator<<(static_cast<unsigned long long>(N));
151}
152
153raw_ostream &raw_ostream::write_hex(unsigned long long N) {
154  // Zero is a special case.
155  if (N == 0)
156    return *this << '0';
157
158  char NumberBuffer[20];
159  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
160  char *CurPtr = EndPtr;
161
162  while (N) {
163    uintptr_t x = N % 16;
164    *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
165    N /= 16;
166  }
167
168  return write(CurPtr, EndPtr-CurPtr);
169}
170
171raw_ostream &raw_ostream::write_escaped(StringRef Str) {
172  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
173    unsigned char c = Str[i];
174
175    switch (c) {
176    case '\\':
177      *this << '\\' << '\\';
178      break;
179    case '\t':
180      *this << '\\' << 't';
181      break;
182    case '\n':
183      *this << '\\' << 'n';
184      break;
185    case '"':
186      *this << '\\' << '"';
187      break;
188    default:
189      if (std::isprint(c)) {
190        *this << c;
191        break;
192      }
193
194      // Always expand to a 3-character octal escape.
195      *this << '\\';
196      *this << char('0' + ((c >> 6) & 7));
197      *this << char('0' + ((c >> 3) & 7));
198      *this << char('0' + ((c >> 0) & 7));
199    }
200  }
201
202  return *this;
203}
204
205raw_ostream &raw_ostream::operator<<(const void *P) {
206  *this << '0' << 'x';
207
208  return write_hex((uintptr_t) P);
209}
210
211raw_ostream &raw_ostream::operator<<(double N) {
212  return this->operator<<(ftostr(N));
213}
214
215
216
217void raw_ostream::flush_nonempty() {
218  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
219  size_t Length = OutBufCur - OutBufStart;
220  OutBufCur = OutBufStart;
221  write_impl(OutBufStart, Length);
222}
223
224raw_ostream &raw_ostream::write(unsigned char C) {
225  // Group exceptional cases into a single branch.
226  if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
227    if (BUILTIN_EXPECT(!OutBufStart, false)) {
228      if (BufferMode == Unbuffered) {
229        write_impl(reinterpret_cast<char*>(&C), 1);
230        return *this;
231      }
232      // Set up a buffer and start over.
233      SetBuffered();
234      return write(C);
235    }
236
237    flush_nonempty();
238  }
239
240  *OutBufCur++ = C;
241  return *this;
242}
243
244raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
245  // Group exceptional cases into a single branch.
246  if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
247    if (BUILTIN_EXPECT(!OutBufStart, false)) {
248      if (BufferMode == Unbuffered) {
249        write_impl(Ptr, Size);
250        return *this;
251      }
252      // Set up a buffer and start over.
253      SetBuffered();
254      return write(Ptr, Size);
255    }
256
257    // Write out the data in buffer-sized blocks until the remainder
258    // fits within the buffer.
259    do {
260      size_t NumBytes = OutBufEnd - OutBufCur;
261      copy_to_buffer(Ptr, NumBytes);
262      flush_nonempty();
263      Ptr += NumBytes;
264      Size -= NumBytes;
265    } while (OutBufCur+Size > OutBufEnd);
266  }
267
268  copy_to_buffer(Ptr, Size);
269
270  return *this;
271}
272
273void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
274  assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
275
276  // Handle short strings specially, memcpy isn't very good at very short
277  // strings.
278  switch (Size) {
279  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
280  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
281  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
282  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
283  case 0: break;
284  default:
285    memcpy(OutBufCur, Ptr, Size);
286    break;
287  }
288
289  OutBufCur += Size;
290}
291
292// Formatted output.
293raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
294  // If we have more than a few bytes left in our output buffer, try
295  // formatting directly onto its end.
296  size_t NextBufferSize = 127;
297  size_t BufferBytesLeft = OutBufEnd - OutBufCur;
298  if (BufferBytesLeft > 3) {
299    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
300
301    // Common case is that we have plenty of space.
302    if (BytesUsed <= BufferBytesLeft) {
303      OutBufCur += BytesUsed;
304      return *this;
305    }
306
307    // Otherwise, we overflowed and the return value tells us the size to try
308    // again with.
309    NextBufferSize = BytesUsed;
310  }
311
312  // If we got here, we didn't have enough space in the output buffer for the
313  // string.  Try printing into a SmallVector that is resized to have enough
314  // space.  Iterate until we win.
315  SmallVector<char, 128> V;
316
317  while (1) {
318    V.resize(NextBufferSize);
319
320    // Try formatting into the SmallVector.
321    size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
322
323    // If BytesUsed fit into the vector, we win.
324    if (BytesUsed <= NextBufferSize)
325      return write(V.data(), BytesUsed);
326
327    // Otherwise, try again with a new size.
328    assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
329    NextBufferSize = BytesUsed;
330  }
331}
332
333/// indent - Insert 'NumSpaces' spaces.
334raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
335  static const char Spaces[] = "                                "
336                               "                                "
337                               "                ";
338
339  // Usually the indentation is small, handle it with a fastpath.
340  if (NumSpaces < array_lengthof(Spaces))
341    return write(Spaces, NumSpaces);
342
343  while (NumSpaces) {
344    unsigned NumToWrite = std::min(NumSpaces,
345                                   (unsigned)array_lengthof(Spaces)-1);
346    write(Spaces, NumToWrite);
347    NumSpaces -= NumToWrite;
348  }
349  return *this;
350}
351
352
353//===----------------------------------------------------------------------===//
354//  Formatted Output
355//===----------------------------------------------------------------------===//
356
357// Out of line virtual method.
358void format_object_base::home() {
359}
360
361//===----------------------------------------------------------------------===//
362//  raw_fd_ostream
363//===----------------------------------------------------------------------===//
364
365/// raw_fd_ostream - Open the specified file for writing. If an error
366/// occurs, information about the error is put into ErrorInfo, and the
367/// stream should be immediately destroyed; the string will be empty
368/// if no error occurred.
369raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
370                               unsigned Flags) : pos(0) {
371  // Verify that we don't have both "append" and "excl".
372  assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
373         "Cannot specify both 'excl' and 'append' file creation flags!");
374
375  ErrorInfo.clear();
376
377  // Handle "-" as stdout.
378  if (Filename[0] == '-' && Filename[1] == 0) {
379    FD = STDOUT_FILENO;
380    // If user requested binary then put stdout into binary mode if
381    // possible.
382    if (Flags & F_Binary)
383      sys::Program::ChangeStdoutToBinary();
384    ShouldClose = false;
385    return;
386  }
387
388  int OpenFlags = O_WRONLY|O_CREAT;
389#ifdef O_BINARY
390  if (Flags & F_Binary)
391    OpenFlags |= O_BINARY;
392#endif
393
394  if (Flags & F_Append)
395    OpenFlags |= O_APPEND;
396  else
397    OpenFlags |= O_TRUNC;
398  if (Flags & F_Excl)
399    OpenFlags |= O_EXCL;
400
401  FD = open(Filename, OpenFlags, 0664);
402  if (FD < 0) {
403    ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
404    ShouldClose = false;
405  } else {
406    ShouldClose = true;
407  }
408}
409
410raw_fd_ostream::~raw_fd_ostream() {
411  if (FD < 0) return;
412  flush();
413  if (ShouldClose)
414    if (::close(FD) != 0)
415      error_detected();
416}
417
418
419void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
420  assert (FD >= 0 && "File already closed.");
421  pos += Size;
422  if (::write(FD, Ptr, Size) != (ssize_t) Size)
423    error_detected();
424}
425
426void raw_fd_ostream::close() {
427  assert (ShouldClose);
428  ShouldClose = false;
429  flush();
430  if (::close(FD) != 0)
431    error_detected();
432  FD = -1;
433}
434
435uint64_t raw_fd_ostream::seek(uint64_t off) {
436  flush();
437  pos = ::lseek(FD, off, SEEK_SET);
438  if (pos != off)
439    error_detected();
440  return pos;
441}
442
443size_t raw_fd_ostream::preferred_buffer_size() const {
444#if !defined(_MSC_VER) && !defined(__MINGW32__) // Windows has no st_blksize.
445  assert(FD >= 0 && "File not yet open!");
446  struct stat statbuf;
447  if (fstat(FD, &statbuf) != 0)
448    return 0;
449
450  // If this is a terminal, don't use buffering. Line buffering
451  // would be a more traditional thing to do, but it's not worth
452  // the complexity.
453  if (S_ISCHR(statbuf.st_mode) && isatty(FD))
454    return 0;
455  // Return the preferred block size.
456  return statbuf.st_blksize;
457#endif
458  return raw_ostream::preferred_buffer_size();
459}
460
461raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
462                                         bool bg) {
463  if (sys::Process::ColorNeedsFlush())
464    flush();
465  const char *colorcode =
466    (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
467    : sys::Process::OutputColor(colors, bold, bg);
468  if (colorcode) {
469    size_t len = strlen(colorcode);
470    write(colorcode, len);
471    // don't account colors towards output characters
472    pos -= len;
473  }
474  return *this;
475}
476
477raw_ostream &raw_fd_ostream::resetColor() {
478  if (sys::Process::ColorNeedsFlush())
479    flush();
480  const char *colorcode = sys::Process::ResetColor();
481  if (colorcode) {
482    size_t len = strlen(colorcode);
483    write(colorcode, len);
484    // don't account colors towards output characters
485    pos -= len;
486  }
487  return *this;
488}
489
490bool raw_fd_ostream::is_displayed() const {
491  return sys::Process::FileDescriptorIsDisplayed(FD);
492}
493
494//===----------------------------------------------------------------------===//
495//  raw_stdout/err_ostream
496//===----------------------------------------------------------------------===//
497
498// Set buffer settings to model stdout and stderr behavior.
499// Set standard error to be unbuffered by default.
500raw_stdout_ostream::raw_stdout_ostream():raw_fd_ostream(STDOUT_FILENO, false) {}
501raw_stderr_ostream::raw_stderr_ostream():raw_fd_ostream(STDERR_FILENO, false,
502                                                        true) {}
503
504// An out of line virtual method to provide a home for the class vtable.
505void raw_stdout_ostream::handle() {}
506void raw_stderr_ostream::handle() {}
507
508/// outs() - This returns a reference to a raw_ostream for standard output.
509/// Use it like: outs() << "foo" << "bar";
510raw_ostream &llvm::outs() {
511  static raw_stdout_ostream S;
512  return S;
513}
514
515/// errs() - This returns a reference to a raw_ostream for standard error.
516/// Use it like: errs() << "foo" << "bar";
517raw_ostream &llvm::errs() {
518  static raw_stderr_ostream S;
519  return S;
520}
521
522/// nulls() - This returns a reference to a raw_ostream which discards output.
523raw_ostream &llvm::nulls() {
524  static raw_null_ostream S;
525  return S;
526}
527
528
529//===----------------------------------------------------------------------===//
530//  raw_string_ostream
531//===----------------------------------------------------------------------===//
532
533raw_string_ostream::~raw_string_ostream() {
534  flush();
535}
536
537void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
538  OS.append(Ptr, Size);
539}
540
541//===----------------------------------------------------------------------===//
542//  raw_svector_ostream
543//===----------------------------------------------------------------------===//
544
545// The raw_svector_ostream implementation uses the SmallVector itself as the
546// buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
547// always pointing past the end of the vector, but within the vector
548// capacity. This allows raw_ostream to write directly into the correct place,
549// and we only need to set the vector size when the data is flushed.
550
551raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
552  // Set up the initial external buffer. We make sure that the buffer has at
553  // least 128 bytes free; raw_ostream itself only requires 64, but we want to
554  // make sure that we don't grow the buffer unnecessarily on destruction (when
555  // the data is flushed). See the FIXME below.
556  OS.reserve(OS.size() + 128);
557  SetBuffer(OS.end(), OS.capacity() - OS.size());
558}
559
560raw_svector_ostream::~raw_svector_ostream() {
561  // FIXME: Prevent resizing during this flush().
562  flush();
563}
564
565void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
566  assert(Ptr == OS.end() && OS.size() + Size <= OS.capacity() &&
567         "Invalid write_impl() call!");
568
569  // We don't need to copy the bytes, just commit the bytes to the
570  // SmallVector.
571  OS.set_size(OS.size() + Size);
572
573  // Grow the vector if necessary.
574  if (OS.capacity() - OS.size() < 64)
575    OS.reserve(OS.capacity() * 2);
576
577  // Update the buffer position.
578  SetBuffer(OS.end(), OS.capacity() - OS.size());
579}
580
581uint64_t raw_svector_ostream::current_pos() const {
582   return OS.size();
583}
584
585StringRef raw_svector_ostream::str() {
586  flush();
587  return StringRef(OS.begin(), OS.size());
588}
589
590//===----------------------------------------------------------------------===//
591//  raw_null_ostream
592//===----------------------------------------------------------------------===//
593
594raw_null_ostream::~raw_null_ostream() {
595#ifndef NDEBUG
596  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
597  // with raw_null_ostream, but it's better to have raw_null_ostream follow
598  // the rules than to change the rules just for raw_null_ostream.
599  flush();
600#endif
601}
602
603void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
604}
605
606uint64_t raw_null_ostream::current_pos() const {
607  return 0;
608}
609