raw_ostream.cpp revision 212904
1252439Srpaulo//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2252439Srpaulo//
3252439Srpaulo//                     The LLVM Compiler Infrastructure
4252439Srpaulo//
5252439Srpaulo// This file is distributed under the University of Illinois Open Source
6252439Srpaulo// License. See LICENSE.TXT for details.
7252439Srpaulo//
8252439Srpaulo//===----------------------------------------------------------------------===//
9252439Srpaulo//
10252439Srpaulo// This implements support for bulk buffered stream output.
11252439Srpaulo//
12252439Srpaulo//===----------------------------------------------------------------------===//
13252439Srpaulo
14252439Srpaulo#include "llvm/Support/raw_ostream.h"
15252439Srpaulo#include "llvm/Support/Format.h"
16252439Srpaulo#include "llvm/System/Program.h"
17252439Srpaulo#include "llvm/System/Process.h"
18252439Srpaulo#include "llvm/ADT/SmallVector.h"
19252439Srpaulo#include "llvm/Config/config.h"
20252439Srpaulo#include "llvm/Support/Compiler.h"
21252439Srpaulo#include "llvm/Support/ErrorHandling.h"
22252439Srpaulo#include "llvm/System/Signals.h"
23252439Srpaulo#include "llvm/ADT/STLExtras.h"
24252439Srpaulo#include <cctype>
25252439Srpaulo#include <cerrno>
26252439Srpaulo#include <sys/stat.h>
27252439Srpaulo#include <sys/types.h>
28252439Srpaulo
29252439Srpaulo#if defined(HAVE_UNISTD_H)
30252439Srpaulo# include <unistd.h>
31252439Srpaulo#endif
32280520Sandrew#if defined(HAVE_FCNTL_H)
33280520Sandrew# include <fcntl.h>
34280520Sandrew#endif
35280520Sandrew
36280520Sandrew#if defined(_MSC_VER)
37252439Srpaulo#include <io.h>
38252439Srpaulo#include <fcntl.h>
39252439Srpaulo#ifndef STDIN_FILENO
40252439Srpaulo# define STDIN_FILENO 0
41252439Srpaulo#endif
42252439Srpaulo#ifndef STDOUT_FILENO
43280520Sandrew# define STDOUT_FILENO 1
44280520Sandrew#endif
45252439Srpaulo#ifndef STDERR_FILENO
46252439Srpaulo# define STDERR_FILENO 2
47252439Srpaulo#endif
48252439Srpaulo#endif
49252439Srpaulo
50252439Srpaulousing namespace llvm;
51252439Srpaulo
52252439Srpauloraw_ostream::~raw_ostream() {
53252439Srpaulo  // raw_ostream's subclasses should take care to flush the buffer
54252439Srpaulo  // in their destructors.
55252439Srpaulo  assert(OutBufCur == OutBufStart &&
56252439Srpaulo         "raw_ostream destructor called with non-empty buffer!");
57252439Srpaulo
58252439Srpaulo  if (BufferMode == InternalBuffer)
59252439Srpaulo    delete [] OutBufStart;
60252439Srpaulo}
61252439Srpaulo
62252439Srpaulo// An out of line virtual method to provide a home for the class vtable.
63252439Srpaulovoid raw_ostream::handle() {}
64252439Srpaulo
65252439Srpaulosize_t raw_ostream::preferred_buffer_size() const {
66252439Srpaulo  // BUFSIZ is intended to be a reasonable default.
67252439Srpaulo  return BUFSIZ;
68252439Srpaulo}
69252439Srpaulo
70252439Srpaulovoid raw_ostream::SetBuffered() {
71252439Srpaulo  // Ask the subclass to determine an appropriate buffer size.
72252439Srpaulo  if (size_t Size = preferred_buffer_size())
73252439Srpaulo    SetBufferSize(Size);
74252439Srpaulo  else
75252439Srpaulo    // It may return 0, meaning this stream should be unbuffered.
76252439Srpaulo    SetUnbuffered();
77252439Srpaulo}
78252439Srpaulo
79252439Srpaulovoid raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
80252439Srpaulo                                    BufferKind Mode) {
81252439Srpaulo  assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
82252439Srpaulo          (Mode != Unbuffered && BufferStart && Size)) &&
83252439Srpaulo         "stream must be unbuffered or have at least one byte");
84252439Srpaulo  // Make sure the current buffer is free of content (we can't flush here; the
85252439Srpaulo  // child buffer management logic will be in write_impl).
86252439Srpaulo  assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
87252439Srpaulo
88252439Srpaulo  if (BufferMode == InternalBuffer)
89252439Srpaulo    delete [] OutBufStart;
90252439Srpaulo  OutBufStart = BufferStart;
91252439Srpaulo  OutBufEnd = OutBufStart+Size;
92252439Srpaulo  OutBufCur = OutBufStart;
93252439Srpaulo  BufferMode = Mode;
94252439Srpaulo
95252439Srpaulo  assert(OutBufStart <= OutBufEnd && "Invalid size!");
96252439Srpaulo}
97252439Srpaulo
98252439Srpauloraw_ostream &raw_ostream::operator<<(unsigned long N) {
99252439Srpaulo  // Zero is a special case.
100252439Srpaulo  if (N == 0)
101252439Srpaulo    return *this << '0';
102252439Srpaulo
103252439Srpaulo  char NumberBuffer[20];
104281890Sloos  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
105281890Sloos  char *CurPtr = EndPtr;
106281890Sloos
107281890Sloos  while (N) {
108281890Sloos    *--CurPtr = '0' + char(N % 10);
109281890Sloos    N /= 10;
110252439Srpaulo  }
111252439Srpaulo  return write(CurPtr, EndPtr-CurPtr);
112252439Srpaulo}
113252439Srpaulo
114252439Srpauloraw_ostream &raw_ostream::operator<<(long N) {
115252439Srpaulo  if (N <  0) {
116252439Srpaulo    *this << '-';
117252439Srpaulo    N = -N;
118252439Srpaulo  }
119252439Srpaulo
120252439Srpaulo  return this->operator<<(static_cast<unsigned long>(N));
121252439Srpaulo}
122252439Srpaulo
123252439Srpauloraw_ostream &raw_ostream::operator<<(unsigned long long N) {
124252439Srpaulo  // Output using 32-bit div/mod when possible.
125252439Srpaulo  if (N == static_cast<unsigned long>(N))
126252439Srpaulo    return this->operator<<(static_cast<unsigned long>(N));
127252439Srpaulo
128252439Srpaulo  char NumberBuffer[20];
129252439Srpaulo  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
130252439Srpaulo  char *CurPtr = EndPtr;
131252439Srpaulo
132252439Srpaulo  while (N) {
133252439Srpaulo    *--CurPtr = '0' + char(N % 10);
134252439Srpaulo    N /= 10;
135252439Srpaulo  }
136252439Srpaulo  return write(CurPtr, EndPtr-CurPtr);
137252439Srpaulo}
138252439Srpaulo
139252439Srpauloraw_ostream &raw_ostream::operator<<(long long N) {
140252439Srpaulo  if (N < 0) {
141252439Srpaulo    *this << '-';
142252439Srpaulo    // Avoid undefined behavior on INT64_MIN with a cast.
143252439Srpaulo    N = -(unsigned long long)N;
144252439Srpaulo  }
145252439Srpaulo
146252439Srpaulo  return this->operator<<(static_cast<unsigned long long>(N));
147252439Srpaulo}
148252439Srpaulo
149252439Srpauloraw_ostream &raw_ostream::write_hex(unsigned long long N) {
150252439Srpaulo  // Zero is a special case.
151252439Srpaulo  if (N == 0)
152252439Srpaulo    return *this << '0';
153252439Srpaulo
154252439Srpaulo  char NumberBuffer[20];
155252439Srpaulo  char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
156252439Srpaulo  char *CurPtr = EndPtr;
157252439Srpaulo
158252439Srpaulo  while (N) {
159252439Srpaulo    uintptr_t x = N % 16;
160252439Srpaulo    *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
161252439Srpaulo    N /= 16;
162252439Srpaulo  }
163252439Srpaulo
164252439Srpaulo  return write(CurPtr, EndPtr-CurPtr);
165252439Srpaulo}
166252439Srpaulo
167252439Srpauloraw_ostream &raw_ostream::write_escaped(StringRef Str) {
168252439Srpaulo  for (unsigned i = 0, e = Str.size(); i != e; ++i) {
169252439Srpaulo    unsigned char c = Str[i];
170252439Srpaulo
171252439Srpaulo    switch (c) {
172252439Srpaulo    case '\\':
173252439Srpaulo      *this << '\\' << '\\';
174252439Srpaulo      break;
175252439Srpaulo    case '\t':
176252439Srpaulo      *this << '\\' << 't';
177252439Srpaulo      break;
178252439Srpaulo    case '\n':
179252439Srpaulo      *this << '\\' << 'n';
180252439Srpaulo      break;
181252439Srpaulo    case '"':
182252439Srpaulo      *this << '\\' << '"';
183252439Srpaulo      break;
184252439Srpaulo    default:
185252439Srpaulo      if (std::isprint(c)) {
186252439Srpaulo        *this << c;
187252439Srpaulo        break;
188252439Srpaulo      }
189252439Srpaulo
190252439Srpaulo      // Always expand to a 3-character octal escape.
191252439Srpaulo      *this << '\\';
192252439Srpaulo      *this << char('0' + ((c >> 6) & 7));
193252439Srpaulo      *this << char('0' + ((c >> 3) & 7));
194252439Srpaulo      *this << char('0' + ((c >> 0) & 7));
195252439Srpaulo    }
196252439Srpaulo  }
197252439Srpaulo
198252439Srpaulo  return *this;
199252439Srpaulo}
200252439Srpaulo
201252439Srpauloraw_ostream &raw_ostream::operator<<(const void *P) {
202252439Srpaulo  *this << '0' << 'x';
203252439Srpaulo
204252439Srpaulo  return write_hex((uintptr_t) P);
205252439Srpaulo}
206252439Srpaulo
207252439Srpauloraw_ostream &raw_ostream::operator<<(double N) {
208252439Srpaulo  return this->operator<<(format("%e", N));
209252439Srpaulo}
210252439Srpaulo
211252439Srpaulo
212252439Srpaulo
213252439Srpaulovoid raw_ostream::flush_nonempty() {
214252439Srpaulo  assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
215252439Srpaulo  size_t Length = OutBufCur - OutBufStart;
216252439Srpaulo  OutBufCur = OutBufStart;
217252439Srpaulo  write_impl(OutBufStart, Length);
218252439Srpaulo}
219252439Srpaulo
220252439Srpauloraw_ostream &raw_ostream::write(unsigned char C) {
221252439Srpaulo  // Group exceptional cases into a single branch.
222252439Srpaulo  if (BUILTIN_EXPECT(OutBufCur >= OutBufEnd, false)) {
223252439Srpaulo    if (BUILTIN_EXPECT(!OutBufStart, false)) {
224252439Srpaulo      if (BufferMode == Unbuffered) {
225252439Srpaulo        write_impl(reinterpret_cast<char*>(&C), 1);
226252439Srpaulo        return *this;
227252439Srpaulo      }
228252439Srpaulo      // Set up a buffer and start over.
229252439Srpaulo      SetBuffered();
230252439Srpaulo      return write(C);
231252439Srpaulo    }
232252439Srpaulo
233252439Srpaulo    flush_nonempty();
234252439Srpaulo  }
235252439Srpaulo
236252439Srpaulo  *OutBufCur++ = C;
237252439Srpaulo  return *this;
238252439Srpaulo}
239252439Srpaulo
240252439Srpauloraw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
241252439Srpaulo  // Group exceptional cases into a single branch.
242252439Srpaulo  if (BUILTIN_EXPECT(OutBufCur+Size > OutBufEnd, false)) {
243252439Srpaulo    if (BUILTIN_EXPECT(!OutBufStart, false)) {
244252439Srpaulo      if (BufferMode == Unbuffered) {
245252439Srpaulo        write_impl(Ptr, Size);
246252439Srpaulo        return *this;
247252439Srpaulo      }
248252439Srpaulo      // Set up a buffer and start over.
249252439Srpaulo      SetBuffered();
250252439Srpaulo      return write(Ptr, Size);
251252439Srpaulo    }
252252439Srpaulo
253252439Srpaulo    // Write out the data in buffer-sized blocks until the remainder
254252439Srpaulo    // fits within the buffer.
255252439Srpaulo    do {
256252439Srpaulo      size_t NumBytes = OutBufEnd - OutBufCur;
257252439Srpaulo      copy_to_buffer(Ptr, NumBytes);
258252439Srpaulo      flush_nonempty();
259252439Srpaulo      Ptr += NumBytes;
260252439Srpaulo      Size -= NumBytes;
261252439Srpaulo    } while (OutBufCur+Size > OutBufEnd);
262252439Srpaulo  }
263252439Srpaulo
264252439Srpaulo  copy_to_buffer(Ptr, Size);
265252439Srpaulo
266252439Srpaulo  return *this;
267252439Srpaulo}
268252439Srpaulo
269252439Srpaulovoid raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
270252439Srpaulo  assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
271252439Srpaulo
272252439Srpaulo  // Handle short strings specially, memcpy isn't very good at very short
273252439Srpaulo  // strings.
274252439Srpaulo  switch (Size) {
275252439Srpaulo  case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
276252439Srpaulo  case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
277252439Srpaulo  case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
278252439Srpaulo  case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
279252439Srpaulo  case 0: break;
280252439Srpaulo  default:
281252439Srpaulo    memcpy(OutBufCur, Ptr, Size);
282252439Srpaulo    break;
283252439Srpaulo  }
284252439Srpaulo
285252439Srpaulo  OutBufCur += Size;
286252439Srpaulo}
287252439Srpaulo
288252439Srpaulo// Formatted output.
289252439Srpauloraw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
290252439Srpaulo  // If we have more than a few bytes left in our output buffer, try
291252439Srpaulo  // formatting directly onto its end.
292252439Srpaulo  size_t NextBufferSize = 127;
293252439Srpaulo  size_t BufferBytesLeft = OutBufEnd - OutBufCur;
294252439Srpaulo  if (BufferBytesLeft > 3) {
295252439Srpaulo    size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
296252439Srpaulo
297252439Srpaulo    // Common case is that we have plenty of space.
298252439Srpaulo    if (BytesUsed <= BufferBytesLeft) {
299252439Srpaulo      OutBufCur += BytesUsed;
300252439Srpaulo      return *this;
301252439Srpaulo    }
302252439Srpaulo
303252439Srpaulo    // Otherwise, we overflowed and the return value tells us the size to try
304252439Srpaulo    // again with.
305252439Srpaulo    NextBufferSize = BytesUsed;
306252439Srpaulo  }
307252439Srpaulo
308252439Srpaulo  // If we got here, we didn't have enough space in the output buffer for the
309252439Srpaulo  // string.  Try printing into a SmallVector that is resized to have enough
310252439Srpaulo  // space.  Iterate until we win.
311252439Srpaulo  SmallVector<char, 128> V;
312252439Srpaulo
313252439Srpaulo  while (1) {
314252439Srpaulo    V.resize(NextBufferSize);
315252439Srpaulo
316252439Srpaulo    // Try formatting into the SmallVector.
317252439Srpaulo    size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
318252439Srpaulo
319252439Srpaulo    // If BytesUsed fit into the vector, we win.
320252439Srpaulo    if (BytesUsed <= NextBufferSize)
321252439Srpaulo      return write(V.data(), BytesUsed);
322252439Srpaulo
323252439Srpaulo    // Otherwise, try again with a new size.
324252439Srpaulo    assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
325252439Srpaulo    NextBufferSize = BytesUsed;
326252439Srpaulo  }
327252439Srpaulo}
328252439Srpaulo
329252439Srpaulo/// indent - Insert 'NumSpaces' spaces.
330252439Srpauloraw_ostream &raw_ostream::indent(unsigned NumSpaces) {
331252439Srpaulo  static const char Spaces[] = "                                "
332252439Srpaulo                               "                                "
333252439Srpaulo                               "                ";
334252439Srpaulo
335252439Srpaulo  // Usually the indentation is small, handle it with a fastpath.
336252439Srpaulo  if (NumSpaces < array_lengthof(Spaces))
337252439Srpaulo    return write(Spaces, NumSpaces);
338252439Srpaulo
339252439Srpaulo  while (NumSpaces) {
340252439Srpaulo    unsigned NumToWrite = std::min(NumSpaces,
341252439Srpaulo                                   (unsigned)array_lengthof(Spaces)-1);
342252439Srpaulo    write(Spaces, NumToWrite);
343252439Srpaulo    NumSpaces -= NumToWrite;
344252439Srpaulo  }
345252439Srpaulo  return *this;
346252439Srpaulo}
347252439Srpaulo
348252439Srpaulo
349252439Srpaulo//===----------------------------------------------------------------------===//
350252439Srpaulo//  Formatted Output
351252439Srpaulo//===----------------------------------------------------------------------===//
352252439Srpaulo
353252439Srpaulo// Out of line virtual method.
354252439Srpaulovoid format_object_base::home() {
355252439Srpaulo}
356252439Srpaulo
357252439Srpaulo//===----------------------------------------------------------------------===//
358252439Srpaulo//  raw_fd_ostream
359252439Srpaulo//===----------------------------------------------------------------------===//
360252439Srpaulo
361252439Srpaulo/// raw_fd_ostream - Open the specified file for writing. If an error
362252439Srpaulo/// occurs, information about the error is put into ErrorInfo, and the
363252439Srpaulo/// stream should be immediately destroyed; the string will be empty
364252439Srpaulo/// if no error occurred.
365252439Srpauloraw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
366252439Srpaulo                               unsigned Flags) : Error(false), pos(0) {
367252439Srpaulo  assert(Filename != 0 && "Filename is null");
368252439Srpaulo  // Verify that we don't have both "append" and "excl".
369252439Srpaulo  assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
370252439Srpaulo         "Cannot specify both 'excl' and 'append' file creation flags!");
371252439Srpaulo
372252439Srpaulo  ErrorInfo.clear();
373252439Srpaulo
374252439Srpaulo  // Handle "-" as stdout. Note that when we do this, we consider ourself
375252439Srpaulo  // the owner of stdout. This means that we can do things like close the
376252439Srpaulo  // file descriptor when we're done and set the "binary" flag globally.
377252439Srpaulo  if (Filename[0] == '-' && Filename[1] == 0) {
378252439Srpaulo    FD = STDOUT_FILENO;
379252439Srpaulo    // If user requested binary then put stdout into binary mode if
380252439Srpaulo    // possible.
381256959Sloos    if (Flags & F_Binary)
382256959Sloos      sys::Program::ChangeStdoutToBinary();
383256959Sloos    // Close stdout when we're done, to detect any output errors.
384256959Sloos    ShouldClose = true;
385256959Sloos    return;
386256959Sloos  }
387256959Sloos
388256959Sloos  int OpenFlags = O_WRONLY|O_CREAT;
389256959Sloos#ifdef O_BINARY
390256959Sloos  if (Flags & F_Binary)
391256959Sloos    OpenFlags |= O_BINARY;
392256959Sloos#endif
393256959Sloos
394256959Sloos  if (Flags & F_Append)
395256959Sloos    OpenFlags |= O_APPEND;
396256959Sloos  else
397257062Sloos    OpenFlags |= O_TRUNC;
398257062Sloos  if (Flags & F_Excl)
399257062Sloos    OpenFlags |= O_EXCL;
400257062Sloos
401257062Sloos  while ((FD = open(Filename, OpenFlags, 0664)) < 0) {
402257062Sloos    if (errno != EINTR) {
403257062Sloos      ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
404257062Sloos      ShouldClose = false;
405252439Srpaulo      return;
406252439Srpaulo    }
407252439Srpaulo  }
408252439Srpaulo
409252439Srpaulo  // Ok, we successfully opened the file, so it'll need to be closed.
410252439Srpaulo  ShouldClose = true;
411252439Srpaulo}
412252439Srpaulo
413252439Srpauloraw_fd_ostream::~raw_fd_ostream() {
414252439Srpaulo  if (FD >= 0) {
415252439Srpaulo    flush();
416252439Srpaulo    if (ShouldClose)
417252439Srpaulo      while (::close(FD) != 0)
418252439Srpaulo        if (errno != EINTR) {
419252439Srpaulo          error_detected();
420252439Srpaulo          break;
421252439Srpaulo        }
422252439Srpaulo  }
423252439Srpaulo
424252439Srpaulo  // If there are any pending errors, report them now. Clients wishing
425252439Srpaulo  // to avoid report_fatal_error calls should check for errors with
426252439Srpaulo  // has_error() and clear the error flag with clear_error() before
427252439Srpaulo  // destructing raw_ostream objects which may have errors.
428252439Srpaulo  if (has_error())
429252439Srpaulo    report_fatal_error("IO failure on output stream.");
430252439Srpaulo}
431252439Srpaulo
432252439Srpaulo
433252439Srpaulovoid raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
434252439Srpaulo  assert(FD >= 0 && "File already closed.");
435252439Srpaulo  pos += Size;
436252439Srpaulo
437252439Srpaulo  do {
438252439Srpaulo    ssize_t ret = ::write(FD, Ptr, Size);
439252439Srpaulo
440281859Sloos    if (ret < 0) {
441252439Srpaulo      // If it's a recoverable error, swallow it and retry the write.
442252439Srpaulo      //
443252439Srpaulo      // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
444252439Srpaulo      // raw_ostream isn't designed to do non-blocking I/O. However, some
445252439Srpaulo      // programs, such as old versions of bjam, have mistakenly used
446252439Srpaulo      // O_NONBLOCK. For compatibility, emulate blocking semantics by
447252439Srpaulo      // spinning until the write succeeds. If you don't want spinning,
448252439Srpaulo      // don't use O_NONBLOCK file descriptors with raw_ostream.
449252439Srpaulo      if (errno == EINTR || errno == EAGAIN
450252439Srpaulo#ifdef EWOULDBLOCK
451252439Srpaulo          || errno == EWOULDBLOCK
452252439Srpaulo#endif
453252439Srpaulo          )
454252439Srpaulo        continue;
455252439Srpaulo
456252439Srpaulo      // Otherwise it's a non-recoverable error. Note it and quit.
457252439Srpaulo      error_detected();
458252439Srpaulo      break;
459252439Srpaulo    }
460252439Srpaulo
461252439Srpaulo    // The write may have written some or all of the data. Update the
462252439Srpaulo    // size and buffer pointer to reflect the remainder that needs
463252439Srpaulo    // to be written. If there are no bytes left, we're done.
464252439Srpaulo    Ptr += ret;
465252439Srpaulo    Size -= ret;
466252439Srpaulo  } while (Size > 0);
467252439Srpaulo}
468252439Srpaulo
469252439Srpaulovoid raw_fd_ostream::close() {
470252439Srpaulo  assert(ShouldClose);
471252439Srpaulo  ShouldClose = false;
472252439Srpaulo  flush();
473252439Srpaulo  while (::close(FD) != 0)
474252439Srpaulo    if (errno != EINTR) {
475      error_detected();
476      break;
477    }
478  FD = -1;
479}
480
481uint64_t raw_fd_ostream::seek(uint64_t off) {
482  flush();
483  pos = ::lseek(FD, off, SEEK_SET);
484  if (pos != off)
485    error_detected();
486  return pos;
487}
488
489size_t raw_fd_ostream::preferred_buffer_size() const {
490#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
491  // Windows and Minix have no st_blksize.
492  assert(FD >= 0 && "File not yet open!");
493  struct stat statbuf;
494  if (fstat(FD, &statbuf) != 0)
495    return 0;
496
497  // If this is a terminal, don't use buffering. Line buffering
498  // would be a more traditional thing to do, but it's not worth
499  // the complexity.
500  if (S_ISCHR(statbuf.st_mode) && isatty(FD))
501    return 0;
502  // Return the preferred block size.
503  return statbuf.st_blksize;
504#else
505  return raw_ostream::preferred_buffer_size();
506#endif
507}
508
509raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
510                                         bool bg) {
511  if (sys::Process::ColorNeedsFlush())
512    flush();
513  const char *colorcode =
514    (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
515    : sys::Process::OutputColor(colors, bold, bg);
516  if (colorcode) {
517    size_t len = strlen(colorcode);
518    write(colorcode, len);
519    // don't account colors towards output characters
520    pos -= len;
521  }
522  return *this;
523}
524
525raw_ostream &raw_fd_ostream::resetColor() {
526  if (sys::Process::ColorNeedsFlush())
527    flush();
528  const char *colorcode = sys::Process::ResetColor();
529  if (colorcode) {
530    size_t len = strlen(colorcode);
531    write(colorcode, len);
532    // don't account colors towards output characters
533    pos -= len;
534  }
535  return *this;
536}
537
538bool raw_fd_ostream::is_displayed() const {
539  return sys::Process::FileDescriptorIsDisplayed(FD);
540}
541
542//===----------------------------------------------------------------------===//
543//  outs(), errs(), nulls()
544//===----------------------------------------------------------------------===//
545
546/// outs() - This returns a reference to a raw_ostream for standard output.
547/// Use it like: outs() << "foo" << "bar";
548raw_ostream &llvm::outs() {
549  // Set buffer settings to model stdout behavior.
550  // Delete the file descriptor when the program exists, forcing error
551  // detection. If you don't want this behavior, don't use outs().
552  static raw_fd_ostream S(STDOUT_FILENO, true);
553  return S;
554}
555
556/// errs() - This returns a reference to a raw_ostream for standard error.
557/// Use it like: errs() << "foo" << "bar";
558raw_ostream &llvm::errs() {
559  // Set standard error to be unbuffered by default.
560  static raw_fd_ostream S(STDERR_FILENO, false, true);
561  return S;
562}
563
564/// nulls() - This returns a reference to a raw_ostream which discards output.
565raw_ostream &llvm::nulls() {
566  static raw_null_ostream S;
567  return S;
568}
569
570
571//===----------------------------------------------------------------------===//
572//  raw_string_ostream
573//===----------------------------------------------------------------------===//
574
575raw_string_ostream::~raw_string_ostream() {
576  flush();
577}
578
579void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
580  OS.append(Ptr, Size);
581}
582
583//===----------------------------------------------------------------------===//
584//  raw_svector_ostream
585//===----------------------------------------------------------------------===//
586
587// The raw_svector_ostream implementation uses the SmallVector itself as the
588// buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
589// always pointing past the end of the vector, but within the vector
590// capacity. This allows raw_ostream to write directly into the correct place,
591// and we only need to set the vector size when the data is flushed.
592
593raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
594  // Set up the initial external buffer. We make sure that the buffer has at
595  // least 128 bytes free; raw_ostream itself only requires 64, but we want to
596  // make sure that we don't grow the buffer unnecessarily on destruction (when
597  // the data is flushed). See the FIXME below.
598  OS.reserve(OS.size() + 128);
599  SetBuffer(OS.end(), OS.capacity() - OS.size());
600}
601
602raw_svector_ostream::~raw_svector_ostream() {
603  // FIXME: Prevent resizing during this flush().
604  flush();
605}
606
607/// resync - This is called when the SmallVector we're appending to is changed
608/// outside of the raw_svector_ostream's control.  It is only safe to do this
609/// if the raw_svector_ostream has previously been flushed.
610void raw_svector_ostream::resync() {
611  assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
612
613  if (OS.capacity() - OS.size() < 64)
614    OS.reserve(OS.capacity() * 2);
615  SetBuffer(OS.end(), OS.capacity() - OS.size());
616}
617
618void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
619  // If we're writing bytes from the end of the buffer into the smallvector, we
620  // don't need to copy the bytes, just commit the bytes because they are
621  // already in the right place.
622  if (Ptr == OS.end()) {
623    assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
624    OS.set_size(OS.size() + Size);
625  } else {
626    assert(GetNumBytesInBuffer() == 0 &&
627           "Should be writing from buffer if some bytes in it");
628    // Otherwise, do copy the bytes.
629    OS.append(Ptr, Ptr+Size);
630  }
631
632  // Grow the vector if necessary.
633  if (OS.capacity() - OS.size() < 64)
634    OS.reserve(OS.capacity() * 2);
635
636  // Update the buffer position.
637  SetBuffer(OS.end(), OS.capacity() - OS.size());
638}
639
640uint64_t raw_svector_ostream::current_pos() const {
641   return OS.size();
642}
643
644StringRef raw_svector_ostream::str() {
645  flush();
646  return StringRef(OS.begin(), OS.size());
647}
648
649//===----------------------------------------------------------------------===//
650//  raw_null_ostream
651//===----------------------------------------------------------------------===//
652
653raw_null_ostream::~raw_null_ostream() {
654#ifndef NDEBUG
655  // ~raw_ostream asserts that the buffer is empty. This isn't necessary
656  // with raw_null_ostream, but it's better to have raw_null_ostream follow
657  // the rules than to change the rules just for raw_null_ostream.
658  flush();
659#endif
660}
661
662void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
663}
664
665uint64_t raw_null_ostream::current_pos() const {
666  return 0;
667}
668
669//===----------------------------------------------------------------------===//
670//  tool_output_file
671//===----------------------------------------------------------------------===//
672
673tool_output_file::CleanupInstaller::CleanupInstaller(const char *filename)
674  : Filename(filename), Keep(false) {
675  // Arrange for the file to be deleted if the process is killed.
676  if (Filename != "-")
677    sys::RemoveFileOnSignal(sys::Path(Filename));
678}
679
680tool_output_file::CleanupInstaller::~CleanupInstaller() {
681  // Delete the file if the client hasn't told us not to.
682  if (!Keep && Filename != "-")
683    sys::Path(Filename).eraseFromDisk();
684
685  // Ok, the file is successfully written and closed, or deleted. There's no
686  // further need to clean it up on signals.
687  if (Filename != "-")
688    sys::DontRemoveFileOnSignal(sys::Path(Filename));
689}
690
691tool_output_file::tool_output_file(const char *filename, std::string &ErrorInfo,
692                                   unsigned Flags)
693  : Installer(filename),
694    OS(filename, ErrorInfo, Flags) {
695  // If open fails, no cleanup is needed.
696  if (!ErrorInfo.empty())
697    Installer.Keep = true;
698}
699