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"
21263508Sdim#include "llvm/Support/FileSystem.h"
22249423Sdim#include "llvm/Support/Format.h"
23249423Sdim#include "llvm/Support/Process.h"
24249423Sdim#include "llvm/Support/Program.h"
25234353Sdim#include "llvm/Support/system_error.h"
26203954Srdivacky#include <cctype>
27208599Srdivacky#include <cerrno>
28198090Srdivacky#include <sys/stat.h>
29193323Sed
30263508Sdim// <fcntl.h> may provide O_BINARY.
31263508Sdim#if defined(HAVE_FCNTL_H)
32263508Sdim# include <fcntl.h>
33263508Sdim#endif
34263508Sdim
35193323Sed#if defined(HAVE_UNISTD_H)
36193323Sed# include <unistd.h>
37193323Sed#endif
38218893Sdim#if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
39218893Sdim#  include <sys/uio.h>
40218893Sdim#endif
41193323Sed
42218893Sdim#if defined(__CYGWIN__)
43218893Sdim#include <io.h>
44218893Sdim#endif
45218893Sdim
46193323Sed#if defined(_MSC_VER)
47193323Sed#include <io.h>
48193323Sed#ifndef STDIN_FILENO
49193323Sed# define STDIN_FILENO 0
50193323Sed#endif
51193323Sed#ifndef STDOUT_FILENO
52193323Sed# define STDOUT_FILENO 1
53193323Sed#endif
54193323Sed#ifndef STDERR_FILENO
55193323Sed# define STDERR_FILENO 2
56193323Sed#endif
57193323Sed#endif
58193323Sed
59193323Sedusing namespace llvm;
60193323Sed
61198090Srdivackyraw_ostream::~raw_ostream() {
62198090Srdivacky  // raw_ostream's subclasses should take care to flush the buffer
63198090Srdivacky  // in their destructors.
64198090Srdivacky  assert(OutBufCur == OutBufStart &&
65198090Srdivacky         "raw_ostream destructor called with non-empty buffer!");
66193323Sed
67198090Srdivacky  if (BufferMode == InternalBuffer)
68198090Srdivacky    delete [] OutBufStart;
69198090Srdivacky}
70198090Srdivacky
71193323Sed// An out of line virtual method to provide a home for the class vtable.
72193323Sedvoid raw_ostream::handle() {}
73193323Sed
74201360Srdivackysize_t raw_ostream::preferred_buffer_size() const {
75198090Srdivacky  // BUFSIZ is intended to be a reasonable default.
76198090Srdivacky  return BUFSIZ;
77198090Srdivacky}
78198090Srdivacky
79198090Srdivackyvoid raw_ostream::SetBuffered() {
80198090Srdivacky  // Ask the subclass to determine an appropriate buffer size.
81198090Srdivacky  if (size_t Size = preferred_buffer_size())
82198090Srdivacky    SetBufferSize(Size);
83198090Srdivacky  else
84198090Srdivacky    // It may return 0, meaning this stream should be unbuffered.
85198090Srdivacky    SetUnbuffered();
86198090Srdivacky}
87198090Srdivacky
88206083Srdivackyvoid raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
89226633Sdim                                   BufferKind Mode) {
90206083Srdivacky  assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
91198090Srdivacky          (Mode != Unbuffered && BufferStart && Size)) &&
92198090Srdivacky         "stream must be unbuffered or have at least one byte");
93198090Srdivacky  // Make sure the current buffer is free of content (we can't flush here; the
94198090Srdivacky  // child buffer management logic will be in write_impl).
95198090Srdivacky  assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
96198090Srdivacky
97198090Srdivacky  if (BufferMode == InternalBuffer)
98198090Srdivacky    delete [] OutBufStart;
99198090Srdivacky  OutBufStart = BufferStart;
100198090Srdivacky  OutBufEnd = OutBufStart+Size;
101198090Srdivacky  OutBufCur = OutBufStart;
102198090Srdivacky  BufferMode = Mode;
103198090Srdivacky
104198090Srdivacky  assert(OutBufStart <= OutBufEnd && "Invalid size!");
105198090Srdivacky}
106198090Srdivacky
107193323Sedraw_ostream &raw_ostream::operator<<(unsigned long N) {
108193323Sed  // Zero is a special case.
109193323Sed  if (N == 0)
110193323Sed    return *this << '0';
111206083Srdivacky
112193323Sed  char NumberBuffer[20];
113193323Sed  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
114193323Sed  char *CurPtr = EndPtr;
115206083Srdivacky
116193323Sed  while (N) {
117193323Sed    *--CurPtr = '0' + char(N % 10);
118193323Sed    N /= 10;
119193323Sed  }
120193323Sed  return write(CurPtr, EndPtr-CurPtr);
121193323Sed}
122193323Sed
123193323Sedraw_ostream &raw_ostream::operator<<(long N) {
124193323Sed  if (N <  0) {
125193323Sed    *this << '-';
126226633Sdim    // Avoid undefined behavior on LONG_MIN with a cast.
127226633Sdim    N = -(unsigned long)N;
128193323Sed  }
129206083Srdivacky
130193323Sed  return this->operator<<(static_cast<unsigned long>(N));
131193323Sed}
132193323Sed
133193323Sedraw_ostream &raw_ostream::operator<<(unsigned long long N) {
134198090Srdivacky  // Output using 32-bit div/mod when possible.
135198090Srdivacky  if (N == static_cast<unsigned long>(N))
136198090Srdivacky    return this->operator<<(static_cast<unsigned long>(N));
137198090Srdivacky
138193323Sed  char NumberBuffer[20];
139193323Sed  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
140193323Sed  char *CurPtr = EndPtr;
141206083Srdivacky
142193323Sed  while (N) {
143193323Sed    *--CurPtr = '0' + char(N % 10);
144193323Sed    N /= 10;
145193323Sed  }
146193323Sed  return write(CurPtr, EndPtr-CurPtr);
147193323Sed}
148193323Sed
149193323Sedraw_ostream &raw_ostream::operator<<(long long N) {
150212904Sdim  if (N < 0) {
151193323Sed    *this << '-';
152212904Sdim    // Avoid undefined behavior on INT64_MIN with a cast.
153212904Sdim    N = -(unsigned long long)N;
154193323Sed  }
155206083Srdivacky
156193323Sed  return this->operator<<(static_cast<unsigned long long>(N));
157193323Sed}
158193323Sed
159198090Srdivackyraw_ostream &raw_ostream::write_hex(unsigned long long N) {
160193323Sed  // Zero is a special case.
161193323Sed  if (N == 0)
162193323Sed    return *this << '0';
163193323Sed
164193323Sed  char NumberBuffer[20];
165193323Sed  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
166193323Sed  char *CurPtr = EndPtr;
167193323Sed
168193323Sed  while (N) {
169198090Srdivacky    uintptr_t x = N % 16;
170193323Sed    *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
171193323Sed    N /= 16;
172193323Sed  }
173193323Sed
174193323Sed  return write(CurPtr, EndPtr-CurPtr);
175193323Sed}
176193323Sed
177218893Sdimraw_ostream &raw_ostream::write_escaped(StringRef Str,
178218893Sdim                                        bool UseHexEscapes) {
179198396Srdivacky  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
180198396Srdivacky    unsigned char c = Str[i];
181198396Srdivacky
182198396Srdivacky    switch (c) {
183198396Srdivacky    case '\\':
184198396Srdivacky      *this << '\\' << '\\';
185198396Srdivacky      break;
186198396Srdivacky    case '\t':
187198396Srdivacky      *this << '\\' << 't';
188198396Srdivacky      break;
189198396Srdivacky    case '\n':
190198396Srdivacky      *this << '\\' << 'n';
191198396Srdivacky      break;
192198396Srdivacky    case '"':
193198396Srdivacky      *this << '\\' << '"';
194198396Srdivacky      break;
195198396Srdivacky    default:
196198396Srdivacky      if (std::isprint(c)) {
197198396Srdivacky        *this << c;
198198396Srdivacky        break;
199198396Srdivacky      }
200198396Srdivacky
201218893Sdim      // Write out the escaped representation.
202218893Sdim      if (UseHexEscapes) {
203218893Sdim        *this << '\\' << 'x';
204218893Sdim        *this << hexdigit((c >> 4 & 0xF));
205218893Sdim        *this << hexdigit((c >> 0) & 0xF);
206218893Sdim      } else {
207218893Sdim        // Always use a full 3-character octal escape.
208218893Sdim        *this << '\\';
209218893Sdim        *this << char('0' + ((c >> 6) & 7));
210218893Sdim        *this << char('0' + ((c >> 3) & 7));
211218893Sdim        *this << char('0' + ((c >> 0) & 7));
212218893Sdim      }
213198396Srdivacky    }
214198396Srdivacky  }
215198396Srdivacky
216198396Srdivacky  return *this;
217198396Srdivacky}
218198396Srdivacky
219198090Srdivackyraw_ostream &raw_ostream::operator<<(const void *P) {
220198090Srdivacky  *this << '0' << 'x';
221198090Srdivacky
222198090Srdivacky  return write_hex((uintptr_t) P);
223198090Srdivacky}
224198090Srdivacky
225198090Srdivackyraw_ostream &raw_ostream::operator<<(double N) {
226221345Sdim#ifdef _WIN32
227221345Sdim  // On MSVCRT and compatible, output of %e is incompatible to Posix
228221345Sdim  // by default. Number of exponent digits should be at least 2. "%+03d"
229221345Sdim  // FIXME: Implement our formatter to here or Support/Format.h!
230221345Sdim  int fpcl = _fpclass(N);
231221345Sdim
232221345Sdim  // negative zero
233221345Sdim  if (fpcl == _FPCLASS_NZ)
234221345Sdim    return *this << "-0.000000e+00";
235221345Sdim
236221345Sdim  char buf[16];
237221345Sdim  unsigned len;
238221345Sdim  len = snprintf(buf, sizeof(buf), "%e", N);
239221345Sdim  if (len <= sizeof(buf) - 2) {
240221345Sdim    if (len >= 5 && buf[len - 5] == 'e' && buf[len - 3] == '0') {
241221345Sdim      int cs = buf[len - 4];
242221345Sdim      if (cs == '+' || cs == '-') {
243221345Sdim        int c1 = buf[len - 2];
244221345Sdim        int c0 = buf[len - 1];
245249423Sdim        if (isdigit(static_cast<unsigned char>(c1)) &&
246249423Sdim            isdigit(static_cast<unsigned char>(c0))) {
247221345Sdim          // Trim leading '0': "...e+012" -> "...e+12\0"
248221345Sdim          buf[len - 3] = c1;
249221345Sdim          buf[len - 2] = c0;
250221345Sdim          buf[--len] = 0;
251221345Sdim        }
252221345Sdim      }
253221345Sdim    }
254221345Sdim    return this->operator<<(buf);
255221345Sdim  }
256221345Sdim#endif
257203954Srdivacky  return this->operator<<(format("%e", N));
258198090Srdivacky}
259198090Srdivacky
260198090Srdivacky
261198090Srdivacky
262193323Sedvoid raw_ostream::flush_nonempty() {
263193323Sed  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
264198090Srdivacky  size_t Length = OutBufCur - OutBufStart;
265198090Srdivacky  OutBufCur = OutBufStart;
266198090Srdivacky  write_impl(OutBufStart, Length);
267193323Sed}
268193323Sed
269193323Sedraw_ostream &raw_ostream::write(unsigned char C) {
270193323Sed  // Group exceptional cases into a single branch.
271243830Sdim  if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
272243830Sdim    if (LLVM_UNLIKELY(!OutBufStart)) {
273198090Srdivacky      if (BufferMode == Unbuffered) {
274198090Srdivacky        write_impl(reinterpret_cast<char*>(&C), 1);
275198090Srdivacky        return *this;
276198090Srdivacky      }
277198090Srdivacky      // Set up a buffer and start over.
278198090Srdivacky      SetBuffered();
279198090Srdivacky      return write(C);
280193323Sed    }
281198090Srdivacky
282198090Srdivacky    flush_nonempty();
283193323Sed  }
284193323Sed
285193323Sed  *OutBufCur++ = C;
286193323Sed  return *this;
287193323Sed}
288193323Sed
289198090Srdivackyraw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
290193323Sed  // Group exceptional cases into a single branch.
291243830Sdim  if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
292243830Sdim    if (LLVM_UNLIKELY(!OutBufStart)) {
293198090Srdivacky      if (BufferMode == Unbuffered) {
294198090Srdivacky        write_impl(Ptr, Size);
295198090Srdivacky        return *this;
296198090Srdivacky      }
297198090Srdivacky      // Set up a buffer and start over.
298198090Srdivacky      SetBuffered();
299198090Srdivacky      return write(Ptr, Size);
300193323Sed    }
301198090Srdivacky
302221345Sdim    size_t NumBytes = OutBufEnd - OutBufCur;
303221345Sdim
304221345Sdim    // If the buffer is empty at this point we have a string that is larger
305221345Sdim    // than the buffer. Directly write the chunk that is a multiple of the
306221345Sdim    // preferred buffer size and put the remainder in the buffer.
307243830Sdim    if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
308221345Sdim      size_t BytesToWrite = Size - (Size % NumBytes);
309221345Sdim      write_impl(Ptr, BytesToWrite);
310249423Sdim      size_t BytesRemaining = Size - BytesToWrite;
311249423Sdim      if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
312249423Sdim        // Too much left over to copy into our buffer.
313249423Sdim        return write(Ptr + BytesToWrite, BytesRemaining);
314249423Sdim      }
315249423Sdim      copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
316221345Sdim      return *this;
317221345Sdim    }
318221345Sdim
319221345Sdim    // We don't have enough space in the buffer to fit the string in. Insert as
320221345Sdim    // much as possible, flush and start over with the remainder.
321221345Sdim    copy_to_buffer(Ptr, NumBytes);
322221345Sdim    flush_nonempty();
323221345Sdim    return write(Ptr + NumBytes, Size - NumBytes);
324193323Sed  }
325198090Srdivacky
326198090Srdivacky  copy_to_buffer(Ptr, Size);
327198090Srdivacky
328198090Srdivacky  return *this;
329198090Srdivacky}
330198090Srdivacky
331198090Srdivackyvoid raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
332198090Srdivacky  assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
333198090Srdivacky
334193323Sed  // Handle short strings specially, memcpy isn't very good at very short
335193323Sed  // strings.
336193323Sed  switch (Size) {
337193323Sed  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
338193323Sed  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
339193323Sed  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
340193323Sed  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
341193323Sed  case 0: break;
342193323Sed  default:
343198090Srdivacky    memcpy(OutBufCur, Ptr, Size);
344193323Sed    break;
345193323Sed  }
346198090Srdivacky
347193323Sed  OutBufCur += Size;
348193323Sed}
349193323Sed
350193323Sed// Formatted output.
351193323Sedraw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
352193323Sed  // If we have more than a few bytes left in our output buffer, try
353193323Sed  // formatting directly onto its end.
354198090Srdivacky  size_t NextBufferSize = 127;
355198090Srdivacky  size_t BufferBytesLeft = OutBufEnd - OutBufCur;
356198090Srdivacky  if (BufferBytesLeft > 3) {
357198090Srdivacky    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
358206083Srdivacky
359193323Sed    // Common case is that we have plenty of space.
360198090Srdivacky    if (BytesUsed <= BufferBytesLeft) {
361193323Sed      OutBufCur += BytesUsed;
362193323Sed      return *this;
363193323Sed    }
364206083Srdivacky
365193323Sed    // Otherwise, we overflowed and the return value tells us the size to try
366193323Sed    // again with.
367193323Sed    NextBufferSize = BytesUsed;
368193323Sed  }
369206083Srdivacky
370193323Sed  // If we got here, we didn't have enough space in the output buffer for the
371193323Sed  // string.  Try printing into a SmallVector that is resized to have enough
372193323Sed  // space.  Iterate until we win.
373193323Sed  SmallVector<char, 128> V;
374206083Srdivacky
375193323Sed  while (1) {
376193323Sed    V.resize(NextBufferSize);
377206083Srdivacky
378193323Sed    // Try formatting into the SmallVector.
379198090Srdivacky    size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
380206083Srdivacky
381193323Sed    // If BytesUsed fit into the vector, we win.
382193323Sed    if (BytesUsed <= NextBufferSize)
383198090Srdivacky      return write(V.data(), BytesUsed);
384206083Srdivacky
385193323Sed    // Otherwise, try again with a new size.
386193323Sed    assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
387193323Sed    NextBufferSize = BytesUsed;
388193323Sed  }
389193323Sed}
390193323Sed
391198090Srdivacky/// indent - Insert 'NumSpaces' spaces.
392198090Srdivackyraw_ostream &raw_ostream::indent(unsigned NumSpaces) {
393198090Srdivacky  static const char Spaces[] = "                                "
394198090Srdivacky                               "                                "
395198090Srdivacky                               "                ";
396198090Srdivacky
397198090Srdivacky  // Usually the indentation is small, handle it with a fastpath.
398198090Srdivacky  if (NumSpaces < array_lengthof(Spaces))
399198090Srdivacky    return write(Spaces, NumSpaces);
400206083Srdivacky
401198090Srdivacky  while (NumSpaces) {
402198090Srdivacky    unsigned NumToWrite = std::min(NumSpaces,
403198090Srdivacky                                   (unsigned)array_lengthof(Spaces)-1);
404198090Srdivacky    write(Spaces, NumToWrite);
405198090Srdivacky    NumSpaces -= NumToWrite;
406198090Srdivacky  }
407198090Srdivacky  return *this;
408198090Srdivacky}
409198090Srdivacky
410198090Srdivacky
411193323Sed//===----------------------------------------------------------------------===//
412193323Sed//  Formatted Output
413193323Sed//===----------------------------------------------------------------------===//
414193323Sed
415193323Sed// Out of line virtual method.
416193323Sedvoid format_object_base::home() {
417193323Sed}
418193323Sed
419193323Sed//===----------------------------------------------------------------------===//
420193323Sed//  raw_fd_ostream
421193323Sed//===----------------------------------------------------------------------===//
422193323Sed
423193323Sed/// raw_fd_ostream - Open the specified file for writing. If an error
424193323Sed/// occurs, information about the error is put into ErrorInfo, and the
425193323Sed/// stream should be immediately destroyed; the string will be empty
426193323Sed/// if no error occurred.
427198090Srdivackyraw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
428263508Sdim                               sys::fs::OpenFlags Flags)
429263508Sdim    : Error(false), UseAtomicWrites(false), pos(0) {
430204792Srdivacky  assert(Filename != 0 && "Filename is null");
431193323Sed  ErrorInfo.clear();
432193323Sed
433212904Sdim  // Handle "-" as stdout. Note that when we do this, we consider ourself
434212904Sdim  // the owner of stdout. This means that we can do things like close the
435212904Sdim  // file descriptor when we're done and set the "binary" flag globally.
436193323Sed  if (Filename[0] == '-' && Filename[1] == 0) {
437193323Sed    FD = STDOUT_FILENO;
438193323Sed    // If user requested binary then put stdout into binary mode if
439193323Sed    // possible.
440263508Sdim    if (Flags & sys::fs::F_Binary)
441263508Sdim      sys::ChangeStdoutToBinary();
442212904Sdim    // Close stdout when we're done, to detect any output errors.
443212904Sdim    ShouldClose = true;
444193323Sed    return;
445193323Sed  }
446206083Srdivacky
447263508Sdim  error_code EC = sys::fs::openFileForWrite(Filename, FD, Flags);
448206083Srdivacky
449263508Sdim  if (EC) {
450263508Sdim    ErrorInfo = "Error opening output file '" + std::string(Filename) + "': " +
451263508Sdim                EC.message();
452263508Sdim    ShouldClose = false;
453263508Sdim    return;
454193323Sed  }
455208599Srdivacky
456208599Srdivacky  // Ok, we successfully opened the file, so it'll need to be closed.
457208599Srdivacky  ShouldClose = true;
458193323Sed}
459193323Sed
460218893Sdim/// raw_fd_ostream ctor - FD is the file descriptor that this writes to.  If
461218893Sdim/// ShouldClose is true, this closes the file when the stream is destroyed.
462218893Sdimraw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
463218893Sdim  : raw_ostream(unbuffered), FD(fd),
464218893Sdim    ShouldClose(shouldClose), Error(false), UseAtomicWrites(false) {
465218893Sdim#ifdef O_BINARY
466218893Sdim  // Setting STDOUT and STDERR to binary mode is necessary in Win32
467218893Sdim  // to avoid undesirable linefeed conversion.
468218893Sdim  if (fd == STDOUT_FILENO || fd == STDERR_FILENO)
469218893Sdim    setmode(fd, O_BINARY);
470218893Sdim#endif
471218893Sdim
472218893Sdim  // Get the starting position.
473218893Sdim  off_t loc = ::lseek(FD, 0, SEEK_CUR);
474218893Sdim  if (loc == (off_t)-1)
475218893Sdim    pos = 0;
476218893Sdim  else
477218893Sdim    pos = static_cast<uint64_t>(loc);
478218893Sdim}
479218893Sdim
480193323Sedraw_fd_ostream::~raw_fd_ostream() {
481212904Sdim  if (FD >= 0) {
482212904Sdim    flush();
483212904Sdim    if (ShouldClose)
484212904Sdim      while (::close(FD) != 0)
485212904Sdim        if (errno != EINTR) {
486212904Sdim          error_detected();
487212904Sdim          break;
488212904Sdim        }
489212904Sdim  }
490212904Sdim
491221345Sdim#ifdef __MINGW32__
492221345Sdim  // On mingw, global dtors should not call exit().
493221345Sdim  // report_fatal_error() invokes exit(). We know report_fatal_error()
494221345Sdim  // might not write messages to stderr when any errors were detected
495221345Sdim  // on FD == 2.
496221345Sdim  if (FD == 2) return;
497221345Sdim#endif
498221345Sdim
499212904Sdim  // If there are any pending errors, report them now. Clients wishing
500212904Sdim  // to avoid report_fatal_error calls should check for errors with
501212904Sdim  // has_error() and clear the error flag with clear_error() before
502212904Sdim  // destructing raw_ostream objects which may have errors.
503212904Sdim  if (has_error())
504249423Sdim    report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
505193323Sed}
506193323Sed
507198090Srdivacky
508198090Srdivackyvoid raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
509206083Srdivacky  assert(FD >= 0 && "File already closed.");
510193323Sed  pos += Size;
511208599Srdivacky
512208599Srdivacky  do {
513218893Sdim    ssize_t ret;
514208599Srdivacky
515218893Sdim    // Check whether we should attempt to use atomic writes.
516243830Sdim    if (LLVM_LIKELY(!UseAtomicWrites)) {
517218893Sdim      ret = ::write(FD, Ptr, Size);
518218893Sdim    } else {
519218893Sdim      // Use ::writev() where available.
520218893Sdim#if defined(HAVE_WRITEV)
521239462Sdim      const void *Addr = static_cast<const void *>(Ptr);
522239462Sdim      struct iovec IOV = {const_cast<void *>(Addr), Size };
523218893Sdim      ret = ::writev(FD, &IOV, 1);
524218893Sdim#else
525218893Sdim      ret = ::write(FD, Ptr, Size);
526218893Sdim#endif
527218893Sdim    }
528218893Sdim
529208599Srdivacky    if (ret < 0) {
530208599Srdivacky      // If it's a recoverable error, swallow it and retry the write.
531208599Srdivacky      //
532208599Srdivacky      // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
533208599Srdivacky      // raw_ostream isn't designed to do non-blocking I/O. However, some
534208599Srdivacky      // programs, such as old versions of bjam, have mistakenly used
535208599Srdivacky      // O_NONBLOCK. For compatibility, emulate blocking semantics by
536208599Srdivacky      // spinning until the write succeeds. If you don't want spinning,
537208599Srdivacky      // don't use O_NONBLOCK file descriptors with raw_ostream.
538208599Srdivacky      if (errno == EINTR || errno == EAGAIN
539208599Srdivacky#ifdef EWOULDBLOCK
540208599Srdivacky          || errno == EWOULDBLOCK
541208599Srdivacky#endif
542208599Srdivacky          )
543208599Srdivacky        continue;
544208599Srdivacky
545208599Srdivacky      // Otherwise it's a non-recoverable error. Note it and quit.
546208599Srdivacky      error_detected();
547208599Srdivacky      break;
548208599Srdivacky    }
549208599Srdivacky
550208599Srdivacky    // The write may have written some or all of the data. Update the
551208599Srdivacky    // size and buffer pointer to reflect the remainder that needs
552208599Srdivacky    // to be written. If there are no bytes left, we're done.
553208599Srdivacky    Ptr += ret;
554208599Srdivacky    Size -= ret;
555208599Srdivacky  } while (Size > 0);
556193323Sed}
557193323Sed
558193323Sedvoid raw_fd_ostream::close() {
559206083Srdivacky  assert(ShouldClose);
560193323Sed  ShouldClose = false;
561193323Sed  flush();
562208599Srdivacky  while (::close(FD) != 0)
563208599Srdivacky    if (errno != EINTR) {
564208599Srdivacky      error_detected();
565208599Srdivacky      break;
566208599Srdivacky    }
567193323Sed  FD = -1;
568193323Sed}
569193323Sed
570193323Seduint64_t raw_fd_ostream::seek(uint64_t off) {
571193323Sed  flush();
572198090Srdivacky  pos = ::lseek(FD, off, SEEK_SET);
573198090Srdivacky  if (pos != off)
574198090Srdivacky    error_detected();
575206083Srdivacky  return pos;
576193323Sed}
577193323Sed
578201360Srdivackysize_t raw_fd_ostream::preferred_buffer_size() const {
579210299Sed#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
580207618Srdivacky  // Windows and Minix have no st_blksize.
581198090Srdivacky  assert(FD >= 0 && "File not yet open!");
582198090Srdivacky  struct stat statbuf;
583201360Srdivacky  if (fstat(FD, &statbuf) != 0)
584201360Srdivacky    return 0;
585206083Srdivacky
586201360Srdivacky  // If this is a terminal, don't use buffering. Line buffering
587201360Srdivacky  // would be a more traditional thing to do, but it's not worth
588201360Srdivacky  // the complexity.
589201360Srdivacky  if (S_ISCHR(statbuf.st_mode) && isatty(FD))
590201360Srdivacky    return 0;
591201360Srdivacky  // Return the preferred block size.
592201360Srdivacky  return statbuf.st_blksize;
593210299Sed#else
594210299Sed  return raw_ostream::preferred_buffer_size();
595198090Srdivacky#endif
596198090Srdivacky}
597198090Srdivacky
598193574Sedraw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
599193574Sed                                         bool bg) {
600193574Sed  if (sys::Process::ColorNeedsFlush())
601193574Sed    flush();
602193574Sed  const char *colorcode =
603193574Sed    (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
604193574Sed    : sys::Process::OutputColor(colors, bold, bg);
605193574Sed  if (colorcode) {
606198090Srdivacky    size_t len = strlen(colorcode);
607193574Sed    write(colorcode, len);
608193574Sed    // don't account colors towards output characters
609193574Sed    pos -= len;
610193574Sed  }
611193574Sed  return *this;
612193574Sed}
613193574Sed
614193574Sedraw_ostream &raw_fd_ostream::resetColor() {
615193574Sed  if (sys::Process::ColorNeedsFlush())
616193574Sed    flush();
617193574Sed  const char *colorcode = sys::Process::ResetColor();
618193574Sed  if (colorcode) {
619198090Srdivacky    size_t len = strlen(colorcode);
620193574Sed    write(colorcode, len);
621193574Sed    // don't account colors towards output characters
622193574Sed    pos -= len;
623193574Sed  }
624193574Sed  return *this;
625193574Sed}
626193574Sed
627234982Sdimraw_ostream &raw_fd_ostream::reverseColor() {
628234982Sdim  if (sys::Process::ColorNeedsFlush())
629234982Sdim    flush();
630234982Sdim  const char *colorcode = sys::Process::OutputReverse();
631234982Sdim  if (colorcode) {
632234982Sdim    size_t len = strlen(colorcode);
633234982Sdim    write(colorcode, len);
634234982Sdim    // don't account colors towards output characters
635234982Sdim    pos -= len;
636234982Sdim  }
637234982Sdim  return *this;
638234982Sdim}
639234982Sdim
640198090Srdivackybool raw_fd_ostream::is_displayed() const {
641198090Srdivacky  return sys::Process::FileDescriptorIsDisplayed(FD);
642198090Srdivacky}
643198090Srdivacky
644239462Sdimbool raw_fd_ostream::has_colors() const {
645239462Sdim  return sys::Process::FileDescriptorHasColors(FD);
646239462Sdim}
647239462Sdim
648193323Sed//===----------------------------------------------------------------------===//
649212904Sdim//  outs(), errs(), nulls()
650193323Sed//===----------------------------------------------------------------------===//
651193323Sed
652193323Sed/// outs() - This returns a reference to a raw_ostream for standard output.
653193323Sed/// Use it like: outs() << "foo" << "bar";
654193323Sedraw_ostream &llvm::outs() {
655212904Sdim  // Set buffer settings to model stdout behavior.
656212904Sdim  // Delete the file descriptor when the program exists, forcing error
657212904Sdim  // detection. If you don't want this behavior, don't use outs().
658212904Sdim  static raw_fd_ostream S(STDOUT_FILENO, true);
659193323Sed  return S;
660193323Sed}
661193323Sed
662193323Sed/// errs() - This returns a reference to a raw_ostream for standard error.
663193323Sed/// Use it like: errs() << "foo" << "bar";
664193323Sedraw_ostream &llvm::errs() {
665212904Sdim  // Set standard error to be unbuffered by default.
666212904Sdim  static raw_fd_ostream S(STDERR_FILENO, false, true);
667193323Sed  return S;
668193323Sed}
669193323Sed
670198090Srdivacky/// nulls() - This returns a reference to a raw_ostream which discards output.
671198090Srdivackyraw_ostream &llvm::nulls() {
672198090Srdivacky  static raw_null_ostream S;
673198090Srdivacky  return S;
674193323Sed}
675193323Sed
676193323Sed
677193323Sed//===----------------------------------------------------------------------===//
678193323Sed//  raw_string_ostream
679193323Sed//===----------------------------------------------------------------------===//
680193323Sed
681193323Sedraw_string_ostream::~raw_string_ostream() {
682193323Sed  flush();
683193323Sed}
684193323Sed
685198090Srdivackyvoid raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
686193323Sed  OS.append(Ptr, Size);
687193323Sed}
688193323Sed
689193323Sed//===----------------------------------------------------------------------===//
690193323Sed//  raw_svector_ostream
691193323Sed//===----------------------------------------------------------------------===//
692193323Sed
693198090Srdivacky// The raw_svector_ostream implementation uses the SmallVector itself as the
694198090Srdivacky// buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
695198090Srdivacky// always pointing past the end of the vector, but within the vector
696198090Srdivacky// capacity. This allows raw_ostream to write directly into the correct place,
697198090Srdivacky// and we only need to set the vector size when the data is flushed.
698198090Srdivacky
699198090Srdivackyraw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
700198090Srdivacky  // Set up the initial external buffer. We make sure that the buffer has at
701198090Srdivacky  // least 128 bytes free; raw_ostream itself only requires 64, but we want to
702198090Srdivacky  // make sure that we don't grow the buffer unnecessarily on destruction (when
703198090Srdivacky  // the data is flushed). See the FIXME below.
704198090Srdivacky  OS.reserve(OS.size() + 128);
705198090Srdivacky  SetBuffer(OS.end(), OS.capacity() - OS.size());
706198090Srdivacky}
707198090Srdivacky
708193323Sedraw_svector_ostream::~raw_svector_ostream() {
709198090Srdivacky  // FIXME: Prevent resizing during this flush().
710193323Sed  flush();
711193323Sed}
712193323Sed
713202878Srdivacky/// resync - This is called when the SmallVector we're appending to is changed
714202878Srdivacky/// outside of the raw_svector_ostream's control.  It is only safe to do this
715202878Srdivacky/// if the raw_svector_ostream has previously been flushed.
716202878Srdivackyvoid raw_svector_ostream::resync() {
717202878Srdivacky  assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
718202878Srdivacky
719202878Srdivacky  if (OS.capacity() - OS.size() < 64)
720202878Srdivacky    OS.reserve(OS.capacity() * 2);
721202878Srdivacky  SetBuffer(OS.end(), OS.capacity() - OS.size());
722202878Srdivacky}
723202878Srdivacky
724198090Srdivackyvoid raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
725203954Srdivacky  // If we're writing bytes from the end of the buffer into the smallvector, we
726203954Srdivacky  // don't need to copy the bytes, just commit the bytes because they are
727203954Srdivacky  // already in the right place.
728203954Srdivacky  if (Ptr == OS.end()) {
729203954Srdivacky    assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
730203954Srdivacky    OS.set_size(OS.size() + Size);
731203954Srdivacky  } else {
732203954Srdivacky    assert(GetNumBytesInBuffer() == 0 &&
733203954Srdivacky           "Should be writing from buffer if some bytes in it");
734203954Srdivacky    // Otherwise, do copy the bytes.
735203954Srdivacky    OS.append(Ptr, Ptr+Size);
736203954Srdivacky  }
737198090Srdivacky
738198090Srdivacky  // Grow the vector if necessary.
739198090Srdivacky  if (OS.capacity() - OS.size() < 64)
740198090Srdivacky    OS.reserve(OS.capacity() * 2);
741198090Srdivacky
742198090Srdivacky  // Update the buffer position.
743198090Srdivacky  SetBuffer(OS.end(), OS.capacity() - OS.size());
744193323Sed}
745193323Sed
746201360Srdivackyuint64_t raw_svector_ostream::current_pos() const {
747201360Srdivacky   return OS.size();
748201360Srdivacky}
749193323Sed
750198090SrdivackyStringRef raw_svector_ostream::str() {
751198090Srdivacky  flush();
752198090Srdivacky  return StringRef(OS.begin(), OS.size());
753193323Sed}
754198090Srdivacky
755198090Srdivacky//===----------------------------------------------------------------------===//
756198090Srdivacky//  raw_null_ostream
757198090Srdivacky//===----------------------------------------------------------------------===//
758198090Srdivacky
759198090Srdivackyraw_null_ostream::~raw_null_ostream() {
760198090Srdivacky#ifndef NDEBUG
761198090Srdivacky  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
762198090Srdivacky  // with raw_null_ostream, but it's better to have raw_null_ostream follow
763198090Srdivacky  // the rules than to change the rules just for raw_null_ostream.
764198090Srdivacky  flush();
765198090Srdivacky#endif
766198090Srdivacky}
767198090Srdivacky
768198090Srdivackyvoid raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
769198090Srdivacky}
770198090Srdivacky
771201360Srdivackyuint64_t raw_null_ostream::current_pos() const {
772198090Srdivacky  return 0;
773198090Srdivacky}
774