1193323Sed//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This implements support for bulk buffered stream output.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#include "llvm/Support/raw_ostream.h"
15249423Sdim#include "llvm/ADT/STLExtras.h"
16249423Sdim#include "llvm/ADT/SmallVector.h"
17218893Sdim#include "llvm/ADT/StringExtras.h"
18193323Sed#include "llvm/Config/config.h"
19193323Sed#include "llvm/Support/Compiler.h"
20198090Srdivacky#include "llvm/Support/ErrorHandling.h"
21249423Sdim#include "llvm/Support/Format.h"
22249423Sdim#include "llvm/Support/Process.h"
23249423Sdim#include "llvm/Support/Program.h"
24234353Sdim#include "llvm/Support/system_error.h"
25203954Srdivacky#include <cctype>
26208599Srdivacky#include <cerrno>
27198090Srdivacky#include <sys/stat.h>
28198090Srdivacky#include <sys/types.h>
29193323Sed
30193323Sed#if defined(HAVE_UNISTD_H)
31193323Sed# include <unistd.h>
32193323Sed#endif
33193323Sed#if defined(HAVE_FCNTL_H)
34193323Sed# include <fcntl.h>
35193323Sed#endif
36218893Sdim#if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
37218893Sdim#  include <sys/uio.h>
38218893Sdim#endif
39193323Sed
40218893Sdim#if defined(__CYGWIN__)
41218893Sdim#include <io.h>
42218893Sdim#endif
43218893Sdim
44193323Sed#if defined(_MSC_VER)
45193323Sed#include <io.h>
46193323Sed#include <fcntl.h>
47193323Sed#ifndef STDIN_FILENO
48193323Sed# define STDIN_FILENO 0
49193323Sed#endif
50193323Sed#ifndef STDOUT_FILENO
51193323Sed# define STDOUT_FILENO 1
52193323Sed#endif
53193323Sed#ifndef STDERR_FILENO
54193323Sed# define STDERR_FILENO 2
55193323Sed#endif
56193323Sed#endif
57193323Sed
58193323Sedusing namespace llvm;
59193323Sed
60198090Srdivackyraw_ostream::~raw_ostream() {
61198090Srdivacky  // raw_ostream's subclasses should take care to flush the buffer
62198090Srdivacky  // in their destructors.
63198090Srdivacky  assert(OutBufCur == OutBufStart &&
64198090Srdivacky         "raw_ostream destructor called with non-empty buffer!");
65193323Sed
66198090Srdivacky  if (BufferMode == InternalBuffer)
67198090Srdivacky    delete [] OutBufStart;
68198090Srdivacky}
69198090Srdivacky
70193323Sed// An out of line virtual method to provide a home for the class vtable.
71193323Sedvoid raw_ostream::handle() {}
72193323Sed
73201360Srdivackysize_t raw_ostream::preferred_buffer_size() const {
74198090Srdivacky  // BUFSIZ is intended to be a reasonable default.
75198090Srdivacky  return BUFSIZ;
76198090Srdivacky}
77198090Srdivacky
78198090Srdivackyvoid raw_ostream::SetBuffered() {
79198090Srdivacky  // Ask the subclass to determine an appropriate buffer size.
80198090Srdivacky  if (size_t Size = preferred_buffer_size())
81198090Srdivacky    SetBufferSize(Size);
82198090Srdivacky  else
83198090Srdivacky    // It may return 0, meaning this stream should be unbuffered.
84198090Srdivacky    SetUnbuffered();
85198090Srdivacky}
86198090Srdivacky
87206083Srdivackyvoid raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
88226633Sdim                                   BufferKind Mode) {
89206083Srdivacky  assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
90198090Srdivacky          (Mode != Unbuffered && BufferStart && Size)) &&
91198090Srdivacky         "stream must be unbuffered or have at least one byte");
92198090Srdivacky  // Make sure the current buffer is free of content (we can't flush here; the
93198090Srdivacky  // child buffer management logic will be in write_impl).
94198090Srdivacky  assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
95198090Srdivacky
96198090Srdivacky  if (BufferMode == InternalBuffer)
97198090Srdivacky    delete [] OutBufStart;
98198090Srdivacky  OutBufStart = BufferStart;
99198090Srdivacky  OutBufEnd = OutBufStart+Size;
100198090Srdivacky  OutBufCur = OutBufStart;
101198090Srdivacky  BufferMode = Mode;
102198090Srdivacky
103198090Srdivacky  assert(OutBufStart <= OutBufEnd && "Invalid size!");
104198090Srdivacky}
105198090Srdivacky
106193323Sedraw_ostream &raw_ostream::operator<<(unsigned long N) {
107193323Sed  // Zero is a special case.
108193323Sed  if (N == 0)
109193323Sed    return *this << '0';
110206083Srdivacky
111193323Sed  char NumberBuffer[20];
112193323Sed  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
113193323Sed  char *CurPtr = EndPtr;
114206083Srdivacky
115193323Sed  while (N) {
116193323Sed    *--CurPtr = '0' + char(N % 10);
117193323Sed    N /= 10;
118193323Sed  }
119193323Sed  return write(CurPtr, EndPtr-CurPtr);
120193323Sed}
121193323Sed
122193323Sedraw_ostream &raw_ostream::operator<<(long N) {
123193323Sed  if (N <  0) {
124193323Sed    *this << '-';
125226633Sdim    // Avoid undefined behavior on LONG_MIN with a cast.
126226633Sdim    N = -(unsigned long)N;
127193323Sed  }
128206083Srdivacky
129193323Sed  return this->operator<<(static_cast<unsigned long>(N));
130193323Sed}
131193323Sed
132193323Sedraw_ostream &raw_ostream::operator<<(unsigned long long N) {
133198090Srdivacky  // Output using 32-bit div/mod when possible.
134198090Srdivacky  if (N == static_cast<unsigned long>(N))
135198090Srdivacky    return this->operator<<(static_cast<unsigned long>(N));
136198090Srdivacky
137193323Sed  char NumberBuffer[20];
138193323Sed  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
139193323Sed  char *CurPtr = EndPtr;
140206083Srdivacky
141193323Sed  while (N) {
142193323Sed    *--CurPtr = '0' + char(N % 10);
143193323Sed    N /= 10;
144193323Sed  }
145193323Sed  return write(CurPtr, EndPtr-CurPtr);
146193323Sed}
147193323Sed
148193323Sedraw_ostream &raw_ostream::operator<<(long long N) {
149212904Sdim  if (N < 0) {
150193323Sed    *this << '-';
151212904Sdim    // Avoid undefined behavior on INT64_MIN with a cast.
152212904Sdim    N = -(unsigned long long)N;
153193323Sed  }
154206083Srdivacky
155193323Sed  return this->operator<<(static_cast<unsigned long long>(N));
156193323Sed}
157193323Sed
158198090Srdivackyraw_ostream &raw_ostream::write_hex(unsigned long long N) {
159193323Sed  // Zero is a special case.
160193323Sed  if (N == 0)
161193323Sed    return *this << '0';
162193323Sed
163193323Sed  char NumberBuffer[20];
164193323Sed  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
165193323Sed  char *CurPtr = EndPtr;
166193323Sed
167193323Sed  while (N) {
168198090Srdivacky    uintptr_t x = N % 16;
169193323Sed    *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
170193323Sed    N /= 16;
171193323Sed  }
172193323Sed
173193323Sed  return write(CurPtr, EndPtr-CurPtr);
174193323Sed}
175193323Sed
176218893Sdimraw_ostream &raw_ostream::write_escaped(StringRef Str,
177218893Sdim                                        bool UseHexEscapes) {
178198396Srdivacky  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
179198396Srdivacky    unsigned char c = Str[i];
180198396Srdivacky
181198396Srdivacky    switch (c) {
182198396Srdivacky    case '\\':
183198396Srdivacky      *this << '\\' << '\\';
184198396Srdivacky      break;
185198396Srdivacky    case '\t':
186198396Srdivacky      *this << '\\' << 't';
187198396Srdivacky      break;
188198396Srdivacky    case '\n':
189198396Srdivacky      *this << '\\' << 'n';
190198396Srdivacky      break;
191198396Srdivacky    case '"':
192198396Srdivacky      *this << '\\' << '"';
193198396Srdivacky      break;
194198396Srdivacky    default:
195198396Srdivacky      if (std::isprint(c)) {
196198396Srdivacky        *this << c;
197198396Srdivacky        break;
198198396Srdivacky      }
199198396Srdivacky
200218893Sdim      // Write out the escaped representation.
201218893Sdim      if (UseHexEscapes) {
202218893Sdim        *this << '\\' << 'x';
203218893Sdim        *this << hexdigit((c >> 4 & 0xF));
204218893Sdim        *this << hexdigit((c >> 0) & 0xF);
205218893Sdim      } else {
206218893Sdim        // Always use a full 3-character octal escape.
207218893Sdim        *this << '\\';
208218893Sdim        *this << char('0' + ((c >> 6) & 7));
209218893Sdim        *this << char('0' + ((c >> 3) & 7));
210218893Sdim        *this << char('0' + ((c >> 0) & 7));
211218893Sdim      }
212198396Srdivacky    }
213198396Srdivacky  }
214198396Srdivacky
215198396Srdivacky  return *this;
216198396Srdivacky}
217198396Srdivacky
218198090Srdivackyraw_ostream &raw_ostream::operator<<(const void *P) {
219198090Srdivacky  *this << '0' << 'x';
220198090Srdivacky
221198090Srdivacky  return write_hex((uintptr_t) P);
222198090Srdivacky}
223198090Srdivacky
224198090Srdivackyraw_ostream &raw_ostream::operator<<(double N) {
225221345Sdim#ifdef _WIN32
226221345Sdim  // On MSVCRT and compatible, output of %e is incompatible to Posix
227221345Sdim  // by default. Number of exponent digits should be at least 2. "%+03d"
228221345Sdim  // FIXME: Implement our formatter to here or Support/Format.h!
229221345Sdim  int fpcl = _fpclass(N);
230221345Sdim
231221345Sdim  // negative zero
232221345Sdim  if (fpcl == _FPCLASS_NZ)
233221345Sdim    return *this << "-0.000000e+00";
234221345Sdim
235221345Sdim  char buf[16];
236221345Sdim  unsigned len;
237221345Sdim  len = snprintf(buf, sizeof(buf), "%e", N);
238221345Sdim  if (len <= sizeof(buf) - 2) {
239221345Sdim    if (len >= 5 && buf[len - 5] == 'e' && buf[len - 3] == '0') {
240221345Sdim      int cs = buf[len - 4];
241221345Sdim      if (cs == '+' || cs == '-') {
242221345Sdim        int c1 = buf[len - 2];
243221345Sdim        int c0 = buf[len - 1];
244249423Sdim        if (isdigit(static_cast<unsigned char>(c1)) &&
245249423Sdim            isdigit(static_cast<unsigned char>(c0))) {
246221345Sdim          // Trim leading '0': "...e+012" -> "...e+12\0"
247221345Sdim          buf[len - 3] = c1;
248221345Sdim          buf[len - 2] = c0;
249221345Sdim          buf[--len] = 0;
250221345Sdim        }
251221345Sdim      }
252221345Sdim    }
253221345Sdim    return this->operator<<(buf);
254221345Sdim  }
255221345Sdim#endif
256203954Srdivacky  return this->operator<<(format("%e", N));
257198090Srdivacky}
258198090Srdivacky
259198090Srdivacky
260198090Srdivacky
261193323Sedvoid raw_ostream::flush_nonempty() {
262193323Sed  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
263198090Srdivacky  size_t Length = OutBufCur - OutBufStart;
264198090Srdivacky  OutBufCur = OutBufStart;
265198090Srdivacky  write_impl(OutBufStart, Length);
266193323Sed}
267193323Sed
268193323Sedraw_ostream &raw_ostream::write(unsigned char C) {
269193323Sed  // Group exceptional cases into a single branch.
270243830Sdim  if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
271243830Sdim    if (LLVM_UNLIKELY(!OutBufStart)) {
272198090Srdivacky      if (BufferMode == Unbuffered) {
273198090Srdivacky        write_impl(reinterpret_cast<char*>(&C), 1);
274198090Srdivacky        return *this;
275198090Srdivacky      }
276198090Srdivacky      // Set up a buffer and start over.
277198090Srdivacky      SetBuffered();
278198090Srdivacky      return write(C);
279193323Sed    }
280198090Srdivacky
281198090Srdivacky    flush_nonempty();
282193323Sed  }
283193323Sed
284193323Sed  *OutBufCur++ = C;
285193323Sed  return *this;
286193323Sed}
287193323Sed
288198090Srdivackyraw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
289193323Sed  // Group exceptional cases into a single branch.
290243830Sdim  if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
291243830Sdim    if (LLVM_UNLIKELY(!OutBufStart)) {
292198090Srdivacky      if (BufferMode == Unbuffered) {
293198090Srdivacky        write_impl(Ptr, Size);
294198090Srdivacky        return *this;
295198090Srdivacky      }
296198090Srdivacky      // Set up a buffer and start over.
297198090Srdivacky      SetBuffered();
298198090Srdivacky      return write(Ptr, Size);
299193323Sed    }
300198090Srdivacky
301221345Sdim    size_t NumBytes = OutBufEnd - OutBufCur;
302221345Sdim
303221345Sdim    // If the buffer is empty at this point we have a string that is larger
304221345Sdim    // than the buffer. Directly write the chunk that is a multiple of the
305221345Sdim    // preferred buffer size and put the remainder in the buffer.
306243830Sdim    if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
307221345Sdim      size_t BytesToWrite = Size - (Size % NumBytes);
308221345Sdim      write_impl(Ptr, BytesToWrite);
309249423Sdim      size_t BytesRemaining = Size - BytesToWrite;
310249423Sdim      if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
311249423Sdim        // Too much left over to copy into our buffer.
312249423Sdim        return write(Ptr + BytesToWrite, BytesRemaining);
313249423Sdim      }
314249423Sdim      copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
315221345Sdim      return *this;
316221345Sdim    }
317221345Sdim
318221345Sdim    // We don't have enough space in the buffer to fit the string in. Insert as
319221345Sdim    // much as possible, flush and start over with the remainder.
320221345Sdim    copy_to_buffer(Ptr, NumBytes);
321221345Sdim    flush_nonempty();
322221345Sdim    return write(Ptr + NumBytes, Size - NumBytes);
323193323Sed  }
324198090Srdivacky
325198090Srdivacky  copy_to_buffer(Ptr, Size);
326198090Srdivacky
327198090Srdivacky  return *this;
328198090Srdivacky}
329198090Srdivacky
330198090Srdivackyvoid raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
331198090Srdivacky  assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
332198090Srdivacky
333193323Sed  // Handle short strings specially, memcpy isn't very good at very short
334193323Sed  // strings.
335193323Sed  switch (Size) {
336193323Sed  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
337193323Sed  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
338193323Sed  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
339193323Sed  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
340193323Sed  case 0: break;
341193323Sed  default:
342198090Srdivacky    memcpy(OutBufCur, Ptr, Size);
343193323Sed    break;
344193323Sed  }
345198090Srdivacky
346193323Sed  OutBufCur += Size;
347193323Sed}
348193323Sed
349193323Sed// Formatted output.
350193323Sedraw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
351193323Sed  // If we have more than a few bytes left in our output buffer, try
352193323Sed  // formatting directly onto its end.
353198090Srdivacky  size_t NextBufferSize = 127;
354198090Srdivacky  size_t BufferBytesLeft = OutBufEnd - OutBufCur;
355198090Srdivacky  if (BufferBytesLeft > 3) {
356198090Srdivacky    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
357206083Srdivacky
358193323Sed    // Common case is that we have plenty of space.
359198090Srdivacky    if (BytesUsed <= BufferBytesLeft) {
360193323Sed      OutBufCur += BytesUsed;
361193323Sed      return *this;
362193323Sed    }
363206083Srdivacky
364193323Sed    // Otherwise, we overflowed and the return value tells us the size to try
365193323Sed    // again with.
366193323Sed    NextBufferSize = BytesUsed;
367193323Sed  }
368206083Srdivacky
369193323Sed  // If we got here, we didn't have enough space in the output buffer for the
370193323Sed  // string.  Try printing into a SmallVector that is resized to have enough
371193323Sed  // space.  Iterate until we win.
372193323Sed  SmallVector<char, 128> V;
373206083Srdivacky
374193323Sed  while (1) {
375193323Sed    V.resize(NextBufferSize);
376206083Srdivacky
377193323Sed    // Try formatting into the SmallVector.
378198090Srdivacky    size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
379206083Srdivacky
380193323Sed    // If BytesUsed fit into the vector, we win.
381193323Sed    if (BytesUsed <= NextBufferSize)
382198090Srdivacky      return write(V.data(), BytesUsed);
383206083Srdivacky
384193323Sed    // Otherwise, try again with a new size.
385193323Sed    assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
386193323Sed    NextBufferSize = BytesUsed;
387193323Sed  }
388193323Sed}
389193323Sed
390198090Srdivacky/// indent - Insert 'NumSpaces' spaces.
391198090Srdivackyraw_ostream &raw_ostream::indent(unsigned NumSpaces) {
392198090Srdivacky  static const char Spaces[] = "                                "
393198090Srdivacky                               "                                "
394198090Srdivacky                               "                ";
395198090Srdivacky
396198090Srdivacky  // Usually the indentation is small, handle it with a fastpath.
397198090Srdivacky  if (NumSpaces < array_lengthof(Spaces))
398198090Srdivacky    return write(Spaces, NumSpaces);
399206083Srdivacky
400198090Srdivacky  while (NumSpaces) {
401198090Srdivacky    unsigned NumToWrite = std::min(NumSpaces,
402198090Srdivacky                                   (unsigned)array_lengthof(Spaces)-1);
403198090Srdivacky    write(Spaces, NumToWrite);
404198090Srdivacky    NumSpaces -= NumToWrite;
405198090Srdivacky  }
406198090Srdivacky  return *this;
407198090Srdivacky}
408198090Srdivacky
409198090Srdivacky
410193323Sed//===----------------------------------------------------------------------===//
411193323Sed//  Formatted Output
412193323Sed//===----------------------------------------------------------------------===//
413193323Sed
414193323Sed// Out of line virtual method.
415193323Sedvoid format_object_base::home() {
416193323Sed}
417193323Sed
418193323Sed//===----------------------------------------------------------------------===//
419193323Sed//  raw_fd_ostream
420193323Sed//===----------------------------------------------------------------------===//
421193323Sed
422193323Sed/// raw_fd_ostream - Open the specified file for writing. If an error
423193323Sed/// occurs, information about the error is put into ErrorInfo, and the
424193323Sed/// stream should be immediately destroyed; the string will be empty
425193323Sed/// if no error occurred.
426198090Srdivackyraw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
427218893Sdim                               unsigned Flags)
428218893Sdim  : Error(false), UseAtomicWrites(false), pos(0)
429218893Sdim{
430204792Srdivacky  assert(Filename != 0 && "Filename is null");
431198090Srdivacky  // Verify that we don't have both "append" and "excl".
432198090Srdivacky  assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
433198090Srdivacky         "Cannot specify both 'excl' and 'append' file creation flags!");
434206083Srdivacky
435193323Sed  ErrorInfo.clear();
436193323Sed
437212904Sdim  // Handle "-" as stdout. Note that when we do this, we consider ourself
438212904Sdim  // the owner of stdout. This means that we can do things like close the
439212904Sdim  // file descriptor when we're done and set the "binary" flag globally.
440193323Sed  if (Filename[0] == '-' && Filename[1] == 0) {
441193323Sed    FD = STDOUT_FILENO;
442193323Sed    // If user requested binary then put stdout into binary mode if
443193323Sed    // possible.
444198090Srdivacky    if (Flags & F_Binary)
445193323Sed      sys::Program::ChangeStdoutToBinary();
446212904Sdim    // Close stdout when we're done, to detect any output errors.
447212904Sdim    ShouldClose = true;
448193323Sed    return;
449193323Sed  }
450206083Srdivacky
451198090Srdivacky  int OpenFlags = O_WRONLY|O_CREAT;
452193323Sed#ifdef O_BINARY
453198090Srdivacky  if (Flags & F_Binary)
454198090Srdivacky    OpenFlags |= O_BINARY;
455193323Sed#endif
456206083Srdivacky
457198090Srdivacky  if (Flags & F_Append)
458198090Srdivacky    OpenFlags |= O_APPEND;
459198090Srdivacky  else
460198090Srdivacky    OpenFlags |= O_TRUNC;
461198090Srdivacky  if (Flags & F_Excl)
462198090Srdivacky    OpenFlags |= O_EXCL;
463206083Srdivacky
464208599Srdivacky  while ((FD = open(Filename, OpenFlags, 0664)) < 0) {
465208599Srdivacky    if (errno != EINTR) {
466208599Srdivacky      ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
467208599Srdivacky      ShouldClose = false;
468208599Srdivacky      return;
469208599Srdivacky    }
470193323Sed  }
471208599Srdivacky
472208599Srdivacky  // Ok, we successfully opened the file, so it'll need to be closed.
473208599Srdivacky  ShouldClose = true;
474193323Sed}
475193323Sed
476218893Sdim/// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
477218893Sdim/// ShouldClose is true, this closes the file when the stream is destroyed.
478218893Sdimraw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
479218893Sdim  : raw_ostream(unbuffered), FD(fd),
480218893Sdim    ShouldClose(shouldClose), Error(false), UseAtomicWrites(false) {
481218893Sdim#ifdef O_BINARY
482218893Sdim  // Setting STDOUT and STDERR to binary mode is necessary in Win32
483218893Sdim  // to avoid undesirable linefeed conversion.
484218893Sdim  if (fd == STDOUT_FILENO || fd == STDERR_FILENO)
485218893Sdim    setmode(fd, O_BINARY);
486218893Sdim#endif
487218893Sdim
488218893Sdim  // Get the starting position.
489218893Sdim  off_t loc = ::lseek(FD, 0, SEEK_CUR);
490218893Sdim  if (loc == (off_t)-1)
491218893Sdim    pos = 0;
492218893Sdim  else
493218893Sdim    pos = static_cast<uint64_t>(loc);
494218893Sdim}
495218893Sdim
496193323Sedraw_fd_ostream::~raw_fd_ostream() {
497212904Sdim  if (FD >= 0) {
498212904Sdim    flush();
499212904Sdim    if (ShouldClose)
500212904Sdim      while (::close(FD) != 0)
501212904Sdim        if (errno != EINTR) {
502212904Sdim          error_detected();
503212904Sdim          break;
504212904Sdim        }
505212904Sdim  }
506212904Sdim
507221345Sdim#ifdef __MINGW32__
508221345Sdim  // On mingw, global dtors should not call exit().
509221345Sdim  // report_fatal_error() invokes exit(). We know report_fatal_error()
510221345Sdim  // might not write messages to stderr when any errors were detected
511221345Sdim  // on FD == 2.
512221345Sdim  if (FD == 2) return;
513221345Sdim#endif
514221345Sdim
515212904Sdim  // If there are any pending errors, report them now. Clients wishing
516212904Sdim  // to avoid report_fatal_error calls should check for errors with
517212904Sdim  // has_error() and clear the error flag with clear_error() before
518212904Sdim  // destructing raw_ostream objects which may have errors.
519212904Sdim  if (has_error())
520249423Sdim    report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
521193323Sed}
522193323Sed
523198090Srdivacky
524198090Srdivackyvoid raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
525206083Srdivacky  assert(FD >= 0 && "File already closed.");
526193323Sed  pos += Size;
527208599Srdivacky
528208599Srdivacky  do {
529218893Sdim    ssize_t ret;
530208599Srdivacky
531218893Sdim    // Check whether we should attempt to use atomic writes.
532243830Sdim    if (LLVM_LIKELY(!UseAtomicWrites)) {
533218893Sdim      ret = ::write(FD, Ptr, Size);
534218893Sdim    } else {
535218893Sdim      // Use ::writev() where available.
536218893Sdim#if defined(HAVE_WRITEV)
537239462Sdim      const void *Addr = static_cast<const void *>(Ptr);
538239462Sdim      struct iovec IOV = {const_cast<void *>(Addr), Size };
539218893Sdim      ret = ::writev(FD, &IOV, 1);
540218893Sdim#else
541218893Sdim      ret = ::write(FD, Ptr, Size);
542218893Sdim#endif
543218893Sdim    }
544218893Sdim
545208599Srdivacky    if (ret < 0) {
546208599Srdivacky      // If it's a recoverable error, swallow it and retry the write.
547208599Srdivacky      //
548208599Srdivacky      // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
549208599Srdivacky      // raw_ostream isn't designed to do non-blocking I/O. However, some
550208599Srdivacky      // programs, such as old versions of bjam, have mistakenly used
551208599Srdivacky      // O_NONBLOCK. For compatibility, emulate blocking semantics by
552208599Srdivacky      // spinning until the write succeeds. If you don't want spinning,
553208599Srdivacky      // don't use O_NONBLOCK file descriptors with raw_ostream.
554208599Srdivacky      if (errno == EINTR || errno == EAGAIN
555208599Srdivacky#ifdef EWOULDBLOCK
556208599Srdivacky          || errno == EWOULDBLOCK
557208599Srdivacky#endif
558208599Srdivacky          )
559208599Srdivacky        continue;
560208599Srdivacky
561208599Srdivacky      // Otherwise it's a non-recoverable error. Note it and quit.
562208599Srdivacky      error_detected();
563208599Srdivacky      break;
564208599Srdivacky    }
565208599Srdivacky
566208599Srdivacky    // The write may have written some or all of the data. Update the
567208599Srdivacky    // size and buffer pointer to reflect the remainder that needs
568208599Srdivacky    // to be written. If there are no bytes left, we're done.
569208599Srdivacky    Ptr += ret;
570208599Srdivacky    Size -= ret;
571208599Srdivacky  } while (Size > 0);
572193323Sed}
573193323Sed
574193323Sedvoid raw_fd_ostream::close() {
575206083Srdivacky  assert(ShouldClose);
576193323Sed  ShouldClose = false;
577193323Sed  flush();
578208599Srdivacky  while (::close(FD) != 0)
579208599Srdivacky    if (errno != EINTR) {
580208599Srdivacky      error_detected();
581208599Srdivacky      break;
582208599Srdivacky    }
583193323Sed  FD = -1;
584193323Sed}
585193323Sed
586193323Seduint64_t raw_fd_ostream::seek(uint64_t off) {
587193323Sed  flush();
588198090Srdivacky  pos = ::lseek(FD, off, SEEK_SET);
589198090Srdivacky  if (pos != off)
590198090Srdivacky    error_detected();
591206083Srdivacky  return pos;
592193323Sed}
593193323Sed
594201360Srdivackysize_t raw_fd_ostream::preferred_buffer_size() const {
595210299Sed#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
596207618Srdivacky  // Windows and Minix have no st_blksize.
597198090Srdivacky  assert(FD >= 0 && "File not yet open!");
598198090Srdivacky  struct stat statbuf;
599201360Srdivacky  if (fstat(FD, &statbuf) != 0)
600201360Srdivacky    return 0;
601206083Srdivacky
602201360Srdivacky  // If this is a terminal, don't use buffering. Line buffering
603201360Srdivacky  // would be a more traditional thing to do, but it's not worth
604201360Srdivacky  // the complexity.
605201360Srdivacky  if (S_ISCHR(statbuf.st_mode) && isatty(FD))
606201360Srdivacky    return 0;
607201360Srdivacky  // Return the preferred block size.
608201360Srdivacky  return statbuf.st_blksize;
609210299Sed#else
610210299Sed  return raw_ostream::preferred_buffer_size();
611198090Srdivacky#endif
612198090Srdivacky}
613198090Srdivacky
614193574Sedraw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
615193574Sed                                         bool bg) {
616193574Sed  if (sys::Process::ColorNeedsFlush())
617193574Sed    flush();
618193574Sed  const char *colorcode =
619193574Sed    (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
620193574Sed    : sys::Process::OutputColor(colors, bold, bg);
621193574Sed  if (colorcode) {
622198090Srdivacky    size_t len = strlen(colorcode);
623193574Sed    write(colorcode, len);
624193574Sed    // don't account colors towards output characters
625193574Sed    pos -= len;
626193574Sed  }
627193574Sed  return *this;
628193574Sed}
629193574Sed
630193574Sedraw_ostream &raw_fd_ostream::resetColor() {
631193574Sed  if (sys::Process::ColorNeedsFlush())
632193574Sed    flush();
633193574Sed  const char *colorcode = sys::Process::ResetColor();
634193574Sed  if (colorcode) {
635198090Srdivacky    size_t len = strlen(colorcode);
636193574Sed    write(colorcode, len);
637193574Sed    // don't account colors towards output characters
638193574Sed    pos -= len;
639193574Sed  }
640193574Sed  return *this;
641193574Sed}
642193574Sed
643234982Sdimraw_ostream &raw_fd_ostream::reverseColor() {
644234982Sdim  if (sys::Process::ColorNeedsFlush())
645234982Sdim    flush();
646234982Sdim  const char *colorcode = sys::Process::OutputReverse();
647234982Sdim  if (colorcode) {
648234982Sdim    size_t len = strlen(colorcode);
649234982Sdim    write(colorcode, len);
650234982Sdim    // don't account colors towards output characters
651234982Sdim    pos -= len;
652234982Sdim  }
653234982Sdim  return *this;
654234982Sdim}
655234982Sdim
656198090Srdivackybool raw_fd_ostream::is_displayed() const {
657198090Srdivacky  return sys::Process::FileDescriptorIsDisplayed(FD);
658198090Srdivacky}
659198090Srdivacky
660239462Sdimbool raw_fd_ostream::has_colors() const {
661239462Sdim  return sys::Process::FileDescriptorHasColors(FD);
662239462Sdim}
663239462Sdim
664193323Sed//===----------------------------------------------------------------------===//
665212904Sdim//  outs(), errs(), nulls()
666193323Sed//===----------------------------------------------------------------------===//
667193323Sed
668193323Sed/// outs() - This returns a reference to a raw_ostream for standard output.
669193323Sed/// Use it like: outs() << "foo" << "bar";
670193323Sedraw_ostream &llvm::outs() {
671212904Sdim  // Set buffer settings to model stdout behavior.
672212904Sdim  // Delete the file descriptor when the program exists, forcing error
673212904Sdim  // detection. If you don't want this behavior, don't use outs().
674212904Sdim  static raw_fd_ostream S(STDOUT_FILENO, true);
675193323Sed  return S;
676193323Sed}
677193323Sed
678193323Sed/// errs() - This returns a reference to a raw_ostream for standard error.
679193323Sed/// Use it like: errs() << "foo" << "bar";
680193323Sedraw_ostream &llvm::errs() {
681212904Sdim  // Set standard error to be unbuffered by default.
682212904Sdim  static raw_fd_ostream S(STDERR_FILENO, false, true);
683193323Sed  return S;
684193323Sed}
685193323Sed
686198090Srdivacky/// nulls() - This returns a reference to a raw_ostream which discards output.
687198090Srdivackyraw_ostream &llvm::nulls() {
688198090Srdivacky  static raw_null_ostream S;
689198090Srdivacky  return S;
690193323Sed}
691193323Sed
692193323Sed
693193323Sed//===----------------------------------------------------------------------===//
694193323Sed//  raw_string_ostream
695193323Sed//===----------------------------------------------------------------------===//
696193323Sed
697193323Sedraw_string_ostream::~raw_string_ostream() {
698193323Sed  flush();
699193323Sed}
700193323Sed
701198090Srdivackyvoid raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
702193323Sed  OS.append(Ptr, Size);
703193323Sed}
704193323Sed
705193323Sed//===----------------------------------------------------------------------===//
706193323Sed//  raw_svector_ostream
707193323Sed//===----------------------------------------------------------------------===//
708193323Sed
709198090Srdivacky// The raw_svector_ostream implementation uses the SmallVector itself as the
710198090Srdivacky// buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
711198090Srdivacky// always pointing past the end of the vector, but within the vector
712198090Srdivacky// capacity. This allows raw_ostream to write directly into the correct place,
713198090Srdivacky// and we only need to set the vector size when the data is flushed.
714198090Srdivacky
715198090Srdivackyraw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
716198090Srdivacky  // Set up the initial external buffer. We make sure that the buffer has at
717198090Srdivacky  // least 128 bytes free; raw_ostream itself only requires 64, but we want to
718198090Srdivacky  // make sure that we don't grow the buffer unnecessarily on destruction (when
719198090Srdivacky  // the data is flushed). See the FIXME below.
720198090Srdivacky  OS.reserve(OS.size() + 128);
721198090Srdivacky  SetBuffer(OS.end(), OS.capacity() - OS.size());
722198090Srdivacky}
723198090Srdivacky
724193323Sedraw_svector_ostream::~raw_svector_ostream() {
725198090Srdivacky  // FIXME: Prevent resizing during this flush().
726193323Sed  flush();
727193323Sed}
728193323Sed
729202878Srdivacky/// resync - This is called when the SmallVector we're appending to is changed
730202878Srdivacky/// outside of the raw_svector_ostream's control.  It is only safe to do this
731202878Srdivacky/// if the raw_svector_ostream has previously been flushed.
732202878Srdivackyvoid raw_svector_ostream::resync() {
733202878Srdivacky  assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
734202878Srdivacky
735202878Srdivacky  if (OS.capacity() - OS.size() < 64)
736202878Srdivacky    OS.reserve(OS.capacity() * 2);
737202878Srdivacky  SetBuffer(OS.end(), OS.capacity() - OS.size());
738202878Srdivacky}
739202878Srdivacky
740198090Srdivackyvoid raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
741203954Srdivacky  // If we're writing bytes from the end of the buffer into the smallvector, we
742203954Srdivacky  // don't need to copy the bytes, just commit the bytes because they are
743203954Srdivacky  // already in the right place.
744203954Srdivacky  if (Ptr == OS.end()) {
745203954Srdivacky    assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
746203954Srdivacky    OS.set_size(OS.size() + Size);
747203954Srdivacky  } else {
748203954Srdivacky    assert(GetNumBytesInBuffer() == 0 &&
749203954Srdivacky           "Should be writing from buffer if some bytes in it");
750203954Srdivacky    // Otherwise, do copy the bytes.
751203954Srdivacky    OS.append(Ptr, Ptr+Size);
752203954Srdivacky  }
753198090Srdivacky
754198090Srdivacky  // Grow the vector if necessary.
755198090Srdivacky  if (OS.capacity() - OS.size() < 64)
756198090Srdivacky    OS.reserve(OS.capacity() * 2);
757198090Srdivacky
758198090Srdivacky  // Update the buffer position.
759198090Srdivacky  SetBuffer(OS.end(), OS.capacity() - OS.size());
760193323Sed}
761193323Sed
762201360Srdivackyuint64_t raw_svector_ostream::current_pos() const {
763201360Srdivacky   return OS.size();
764201360Srdivacky}
765193323Sed
766198090SrdivackyStringRef raw_svector_ostream::str() {
767198090Srdivacky  flush();
768198090Srdivacky  return StringRef(OS.begin(), OS.size());
769193323Sed}
770198090Srdivacky
771198090Srdivacky//===----------------------------------------------------------------------===//
772198090Srdivacky//  raw_null_ostream
773198090Srdivacky//===----------------------------------------------------------------------===//
774198090Srdivacky
775198090Srdivackyraw_null_ostream::~raw_null_ostream() {
776198090Srdivacky#ifndef NDEBUG
777198090Srdivacky  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
778198090Srdivacky  // with raw_null_ostream, but it's better to have raw_null_ostream follow
779198090Srdivacky  // the rules than to change the rules just for raw_null_ostream.
780198090Srdivacky  flush();
781198090Srdivacky#endif
782198090Srdivacky}
783198090Srdivacky
784198090Srdivackyvoid raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
785198090Srdivacky}
786198090Srdivacky
787201360Srdivackyuint64_t raw_null_ostream::current_pos() const {
788198090Srdivacky  return 0;
789198090Srdivacky}
790