blob: 106864dd0590e3992c39edddd8082fc7c1b118c1 [file] [log] [blame]
Chris Lattner84b94f72008-08-17 01:35:29 +00001//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements support for bulk buffered stream output.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
Chris Lattner22b52c92008-08-23 19:23:10 +000016#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/StringExtras.h"
Chris Lattnerd564f292008-08-22 15:45:00 +000018#include "llvm/Config/config.h"
Daniel Dunbar437b8a52009-03-17 21:15:18 +000019#include "llvm/Support/Compiler.h"
Daniel Dunbardcb50b92009-07-15 08:11:46 +000020#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Support/Format.h"
22#include "llvm/Support/Process.h"
23#include "llvm/Support/Program.h"
Michael J. Spencera2755f82011-12-13 23:16:49 +000024#include "llvm/Support/system_error.h"
Benjamin Krameref14f802010-01-29 15:19:06 +000025#include <cctype>
Benjamin Kramerce84a252010-05-05 15:17:47 +000026#include <cerrno>
Dan Gohman84487b92009-08-13 17:27:29 +000027#include <sys/stat.h>
28#include <sys/types.h>
Chris Lattner84b94f72008-08-17 01:35:29 +000029
Chris Lattnerd564f292008-08-22 15:45:00 +000030#if defined(HAVE_UNISTD_H)
31# include <unistd.h>
32#endif
33#if defined(HAVE_FCNTL_H)
34# include <fcntl.h>
35#endif
Daniel Dunbar4fed8872011-02-03 03:32:32 +000036#if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
37# include <sys/uio.h>
38#endif
Argyrios Kyrtzidisb97ff822008-08-17 09:25:21 +000039
NAKAMURA Takumife84f392010-10-19 01:21:55 +000040#if defined(__CYGWIN__)
41#include <io.h>
42#endif
43
Argyrios Kyrtzidisb97ff822008-08-17 09:25:21 +000044#if defined(_MSC_VER)
Chris Lattner84b94f72008-08-17 01:35:29 +000045#include <io.h>
Cedric Venet0f7b5662008-08-24 11:56:40 +000046#include <fcntl.h>
Owen Anderson93719642008-08-21 00:14:44 +000047#ifndef STDIN_FILENO
48# define STDIN_FILENO 0
49#endif
50#ifndef STDOUT_FILENO
51# define STDOUT_FILENO 1
52#endif
53#ifndef STDERR_FILENO
54# define STDERR_FILENO 2
55#endif
Chris Lattner84b94f72008-08-17 01:35:29 +000056#endif
57
Chris Lattnerd564f292008-08-22 15:45:00 +000058using namespace llvm;
59
Dan Gohman58fcef92009-07-15 23:25:33 +000060raw_ostream::~raw_ostream() {
Dan Gohman1b763292009-07-27 20:49:44 +000061 // raw_ostream's subclasses should take care to flush the buffer
62 // in their destructors.
63 assert(OutBufCur == OutBufStart &&
64 "raw_ostream destructor called with non-empty buffer!");
65
Daniel Dunbar317a6cd2009-08-18 23:42:36 +000066 if (BufferMode == InternalBuffer)
67 delete [] OutBufStart;
Dan Gohman58fcef92009-07-15 23:25:33 +000068}
Chris Lattnerd564f292008-08-22 15:45:00 +000069
Chris Lattner84b94f72008-08-17 01:35:29 +000070// An out of line virtual method to provide a home for the class vtable.
71void raw_ostream::handle() {}
72
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +000073size_t raw_ostream::preferred_buffer_size() const {
Dan Gohman84487b92009-08-13 17:27:29 +000074 // BUFSIZ is intended to be a reasonable default.
75 return BUFSIZ;
76}
77
78void raw_ostream::SetBuffered() {
79 // Ask the subclass to determine an appropriate buffer size.
Dan Gohman17710222009-08-15 02:05:19 +000080 if (size_t Size = preferred_buffer_size())
81 SetBufferSize(Size);
82 else
83 // It may return 0, meaning this stream should be unbuffered.
84 SetUnbuffered();
Dan Gohman84487b92009-08-13 17:27:29 +000085}
86
Dan Gohmanb452d4e2010-03-24 19:38:02 +000087void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
Nick Lewycky7bfd86d2011-08-28 03:30:02 +000088 BufferKind Mode) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +000089 assert(((Mode == Unbuffered && BufferStart == 0 && Size == 0) ||
Daniel Dunbar316b4a02009-09-15 20:31:46 +000090 (Mode != Unbuffered && BufferStart && Size)) &&
91 "stream must be unbuffered or have at least one byte");
Daniel Dunbar317a6cd2009-08-18 23:42:36 +000092 // Make sure the current buffer is free of content (we can't flush here; the
93 // child buffer management logic will be in write_impl).
94 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
Dan Gohman54401d42009-08-13 15:58:55 +000095
Daniel Dunbar317a6cd2009-08-18 23:42:36 +000096 if (BufferMode == InternalBuffer)
97 delete [] OutBufStart;
98 OutBufStart = BufferStart;
Dan Gohman54401d42009-08-13 15:58:55 +000099 OutBufEnd = OutBufStart+Size;
100 OutBufCur = OutBufStart;
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000101 BufferMode = Mode;
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000102
103 assert(OutBufStart <= OutBufEnd && "Invalid size!");
Dan Gohman54401d42009-08-13 15:58:55 +0000104}
105
Owen Andersond2850532008-08-21 20:58:52 +0000106raw_ostream &raw_ostream::operator<<(unsigned long N) {
107 // Zero is a special case.
108 if (N == 0)
109 return *this << '0';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000110
Owen Andersond2850532008-08-21 20:58:52 +0000111 char NumberBuffer[20];
112 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
113 char *CurPtr = EndPtr;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000114
Owen Andersond2850532008-08-21 20:58:52 +0000115 while (N) {
116 *--CurPtr = '0' + char(N % 10);
117 N /= 10;
118 }
119 return write(CurPtr, EndPtr-CurPtr);
120}
121
122raw_ostream &raw_ostream::operator<<(long N) {
123 if (N < 0) {
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000124 *this << '-';
Eli Friedman53ba2082011-10-13 22:49:56 +0000125 // Avoid undefined behavior on LONG_MIN with a cast.
126 N = -(unsigned long)N;
Owen Andersond2850532008-08-21 20:58:52 +0000127 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000128
Owen Andersond2850532008-08-21 20:58:52 +0000129 return this->operator<<(static_cast<unsigned long>(N));
130}
131
132raw_ostream &raw_ostream::operator<<(unsigned long long N) {
Daniel Dunbar465de3e2009-08-19 16:25:25 +0000133 // Output using 32-bit div/mod when possible.
Daniel Dunbara94f58a2009-07-29 06:45:14 +0000134 if (N == static_cast<unsigned long>(N))
135 return this->operator<<(static_cast<unsigned long>(N));
136
Daniel Dunbar465de3e2009-08-19 16:25:25 +0000137 char NumberBuffer[20];
138 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
139 char *CurPtr = EndPtr;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000140
Daniel Dunbar465de3e2009-08-19 16:25:25 +0000141 while (N) {
142 *--CurPtr = '0' + char(N % 10);
143 N /= 10;
144 }
145 return write(CurPtr, EndPtr-CurPtr);
Owen Andersond2850532008-08-21 20:58:52 +0000146}
147
148raw_ostream &raw_ostream::operator<<(long long N) {
Chris Lattner3db3bb02010-08-03 16:41:24 +0000149 if (N < 0) {
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000150 *this << '-';
Chris Lattner3db3bb02010-08-03 16:41:24 +0000151 // Avoid undefined behavior on INT64_MIN with a cast.
152 N = -(unsigned long long)N;
Owen Andersond2850532008-08-21 20:58:52 +0000153 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000154
Owen Andersond2850532008-08-21 20:58:52 +0000155 return this->operator<<(static_cast<unsigned long long>(N));
156}
157
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000158raw_ostream &raw_ostream::write_hex(unsigned long long N) {
Daniel Dunbar87862182009-03-16 22:08:44 +0000159 // Zero is a special case.
160 if (N == 0)
161 return *this << '0';
162
163 char NumberBuffer[20];
164 char *EndPtr = NumberBuffer+sizeof(NumberBuffer);
165 char *CurPtr = EndPtr;
166
167 while (N) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000168 uintptr_t x = N % 16;
Daniel Dunbar87862182009-03-16 22:08:44 +0000169 *--CurPtr = (x < 10 ? '0' + x : 'a' + x - 10);
170 N /= 16;
171 }
172
173 return write(CurPtr, EndPtr-CurPtr);
Chris Lattner0c19df42008-08-23 22:23:09 +0000174}
175
Daniel Dunbar65dc8912010-11-27 07:59:50 +0000176raw_ostream &raw_ostream::write_escaped(StringRef Str,
177 bool UseHexEscapes) {
Daniel Dunbar4108c432009-10-17 20:43:08 +0000178 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
179 unsigned char c = Str[i];
180
181 switch (c) {
182 case '\\':
183 *this << '\\' << '\\';
184 break;
185 case '\t':
186 *this << '\\' << 't';
187 break;
188 case '\n':
189 *this << '\\' << 'n';
190 break;
191 case '"':
192 *this << '\\' << '"';
193 break;
194 default:
195 if (std::isprint(c)) {
196 *this << c;
197 break;
198 }
199
Daniel Dunbar65dc8912010-11-27 07:59:50 +0000200 // Write out the escaped representation.
201 if (UseHexEscapes) {
202 *this << '\\' << 'x';
203 *this << hexdigit((c >> 4 & 0xF));
204 *this << hexdigit((c >> 0) & 0xF);
205 } else {
206 // Always use a full 3-character octal escape.
207 *this << '\\';
208 *this << char('0' + ((c >> 6) & 7));
209 *this << char('0' + ((c >> 3) & 7));
210 *this << char('0' + ((c >> 0) & 7));
211 }
Daniel Dunbar4108c432009-10-17 20:43:08 +0000212 }
213 }
214
215 return *this;
216}
217
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000218raw_ostream &raw_ostream::operator<<(const void *P) {
219 *this << '0' << 'x';
220
221 return write_hex((uintptr_t) P);
222}
223
Chris Lattner06fa1762009-08-24 03:52:50 +0000224raw_ostream &raw_ostream::operator<<(double N) {
NAKAMURA Takumibac0d762011-03-18 09:30:10 +0000225#ifdef _WIN32
226 // On MSVCRT and compatible, output of %e is incompatible to Posix
227 // by default. Number of exponent digits should be at least 2. "%+03d"
228 // FIXME: Implement our formatter to here or Support/Format.h!
229 int fpcl = _fpclass(N);
230
231 // negative zero
232 if (fpcl == _FPCLASS_NZ)
233 return *this << "-0.000000e+00";
234
235 char buf[16];
236 unsigned len;
237 len = snprintf(buf, sizeof(buf), "%e", N);
238 if (len <= sizeof(buf) - 2) {
239 if (len >= 5 && buf[len - 5] == 'e' && buf[len - 3] == '0') {
240 int cs = buf[len - 4];
241 if (cs == '+' || cs == '-') {
242 int c1 = buf[len - 2];
243 int c0 = buf[len - 1];
244 if (isdigit(c1) && isdigit(c0)) {
245 // Trim leading '0': "...e+012" -> "...e+12\0"
246 buf[len - 3] = c1;
247 buf[len - 2] = c0;
248 buf[--len] = 0;
249 }
250 }
251 }
252 return this->operator<<(buf);
253 }
254#endif
Benjamin Kramer6bee24a2010-01-29 14:40:33 +0000255 return this->operator<<(format("%e", N));
Chris Lattner06fa1762009-08-24 03:52:50 +0000256}
257
258
259
Daniel Dunbard24535f2009-03-16 22:55:06 +0000260void raw_ostream::flush_nonempty() {
261 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000262 size_t Length = OutBufCur - OutBufStart;
263 OutBufCur = OutBufStart;
264 write_impl(OutBufStart, Length);
Daniel Dunbard24535f2009-03-16 22:55:06 +0000265}
266
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000267raw_ostream &raw_ostream::write(unsigned char C) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000268 // Group exceptional cases into a single branch.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000269 if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
270 if (LLVM_UNLIKELY(!OutBufStart)) {
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000271 if (BufferMode == Unbuffered) {
Dan Gohman23f90c12009-08-18 20:09:59 +0000272 write_impl(reinterpret_cast<char*>(&C), 1);
273 return *this;
274 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000275 // Set up a buffer and start over.
276 SetBuffered();
277 return write(C);
Dan Gohman23f90c12009-08-18 20:09:59 +0000278 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000279
280 flush_nonempty();
Daniel Dunbar2d603da2009-03-17 01:13:35 +0000281 }
282
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000283 *OutBufCur++ = C;
Daniel Dunbar87862182009-03-16 22:08:44 +0000284 return *this;
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000285}
Chris Lattner0c19df42008-08-23 22:23:09 +0000286
Dan Gohmanf199ad62009-07-16 15:24:40 +0000287raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000288 // Group exceptional cases into a single branch.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000289 if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
290 if (LLVM_UNLIKELY(!OutBufStart)) {
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000291 if (BufferMode == Unbuffered) {
Dan Gohman52022c22009-08-13 15:44:52 +0000292 write_impl(Ptr, Size);
293 return *this;
294 }
295 // Set up a buffer and start over.
Dan Gohman84487b92009-08-13 17:27:29 +0000296 SetBuffered();
Dan Gohman52022c22009-08-13 15:44:52 +0000297 return write(Ptr, Size);
298 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000299
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000300 size_t NumBytes = OutBufEnd - OutBufCur;
301
Benjamin Krameracf08422011-03-04 18:18:16 +0000302 // If the buffer is empty at this point we have a string that is larger
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000303 // than the buffer. Directly write the chunk that is a multiple of the
304 // preferred buffer size and put the remainder in the buffer.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000305 if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000306 size_t BytesToWrite = Size - (Size % NumBytes);
307 write_impl(Ptr, BytesToWrite);
308 copy_to_buffer(Ptr + BytesToWrite, Size - BytesToWrite);
Benjamin Krameracf08422011-03-04 18:18:16 +0000309 return *this;
310 }
311
312 // We don't have enough space in the buffer to fit the string in. Insert as
313 // much as possible, flush and start over with the remainder.
Benjamin Krameracf08422011-03-04 18:18:16 +0000314 copy_to_buffer(Ptr, NumBytes);
315 flush_nonempty();
316 return write(Ptr + NumBytes, Size - NumBytes);
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000317 }
Dan Gohman52022c22009-08-13 15:44:52 +0000318
319 copy_to_buffer(Ptr, Size);
320
321 return *this;
322}
323
324void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
Dan Gohmanc04a00a2009-08-13 20:32:03 +0000325 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
Dan Gohman98205552009-08-13 18:38:15 +0000326
Owen Andersond2850532008-08-21 20:58:52 +0000327 // Handle short strings specially, memcpy isn't very good at very short
328 // strings.
329 switch (Size) {
330 case 4: OutBufCur[3] = Ptr[3]; // FALL THROUGH
331 case 3: OutBufCur[2] = Ptr[2]; // FALL THROUGH
332 case 2: OutBufCur[1] = Ptr[1]; // FALL THROUGH
333 case 1: OutBufCur[0] = Ptr[0]; // FALL THROUGH
334 case 0: break;
335 default:
Dan Gohman52022c22009-08-13 15:44:52 +0000336 memcpy(OutBufCur, Ptr, Size);
Owen Andersond2850532008-08-21 20:58:52 +0000337 break;
338 }
Daniel Dunbar3da6a702009-03-10 16:21:55 +0000339
Dan Gohman52022c22009-08-13 15:44:52 +0000340 OutBufCur += Size;
Owen Andersond2850532008-08-21 20:58:52 +0000341}
342
Chris Lattner22b52c92008-08-23 19:23:10 +0000343// Formatted output.
344raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000345 // If we have more than a few bytes left in our output buffer, try
346 // formatting directly onto its end.
Dan Gohmanf199ad62009-07-16 15:24:40 +0000347 size_t NextBufferSize = 127;
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000348 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
349 if (BufferBytesLeft > 3) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000350 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000351
Chris Lattner22b52c92008-08-23 19:23:10 +0000352 // Common case is that we have plenty of space.
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000353 if (BytesUsed <= BufferBytesLeft) {
Chris Lattner22b52c92008-08-23 19:23:10 +0000354 OutBufCur += BytesUsed;
355 return *this;
356 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000357
Chris Lattner22b52c92008-08-23 19:23:10 +0000358 // Otherwise, we overflowed and the return value tells us the size to try
359 // again with.
360 NextBufferSize = BytesUsed;
361 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000362
Chris Lattner22b52c92008-08-23 19:23:10 +0000363 // If we got here, we didn't have enough space in the output buffer for the
364 // string. Try printing into a SmallVector that is resized to have enough
365 // space. Iterate until we win.
366 SmallVector<char, 128> V;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000367
Chris Lattner22b52c92008-08-23 19:23:10 +0000368 while (1) {
369 V.resize(NextBufferSize);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000370
Chris Lattner22b52c92008-08-23 19:23:10 +0000371 // Try formatting into the SmallVector.
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000372 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000373
Chris Lattner22b52c92008-08-23 19:23:10 +0000374 // If BytesUsed fit into the vector, we win.
Chris Lattner2bfc72e2008-10-26 19:20:47 +0000375 if (BytesUsed <= NextBufferSize)
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000376 return write(V.data(), BytesUsed);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000377
Chris Lattner22b52c92008-08-23 19:23:10 +0000378 // Otherwise, try again with a new size.
379 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
380 NextBufferSize = BytesUsed;
381 }
382}
383
Chris Lattnere6db2c32009-08-22 23:10:29 +0000384/// indent - Insert 'NumSpaces' spaces.
385raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
Dan Gohmanf88f52e2009-08-24 04:13:01 +0000386 static const char Spaces[] = " "
387 " "
388 " ";
Chris Lattnere6db2c32009-08-22 23:10:29 +0000389
390 // Usually the indentation is small, handle it with a fastpath.
Dan Gohmanc9fa0512009-08-24 04:43:38 +0000391 if (NumSpaces < array_lengthof(Spaces))
Chris Lattnere6db2c32009-08-22 23:10:29 +0000392 return write(Spaces, NumSpaces);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000393
Chris Lattnere6db2c32009-08-22 23:10:29 +0000394 while (NumSpaces) {
Dan Gohmanc9fa0512009-08-24 04:43:38 +0000395 unsigned NumToWrite = std::min(NumSpaces,
396 (unsigned)array_lengthof(Spaces)-1);
Chris Lattnere6db2c32009-08-22 23:10:29 +0000397 write(Spaces, NumToWrite);
398 NumSpaces -= NumToWrite;
399 }
400 return *this;
401}
402
403
Chris Lattner22b52c92008-08-23 19:23:10 +0000404//===----------------------------------------------------------------------===//
405// Formatted Output
406//===----------------------------------------------------------------------===//
407
408// Out of line virtual method.
409void format_object_base::home() {
410}
411
Chris Lattner84b94f72008-08-17 01:35:29 +0000412//===----------------------------------------------------------------------===//
413// raw_fd_ostream
414//===----------------------------------------------------------------------===//
415
Daniel Dunbar1ca20df2008-10-21 19:53:10 +0000416/// raw_fd_ostream - Open the specified file for writing. If an error
417/// occurs, information about the error is put into ErrorInfo, and the
418/// stream should be immediately destroyed; the string will be empty
419/// if no error occurred.
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000420raw_fd_ostream::raw_fd_ostream(const char *Filename, std::string &ErrorInfo,
Daniel Dunbar4fed8872011-02-03 03:32:32 +0000421 unsigned Flags)
422 : Error(false), UseAtomicWrites(false), pos(0)
423{
Chris Lattner67838322010-03-05 00:49:08 +0000424 assert(Filename != 0 && "Filename is null");
Dan Gohman61a87962009-08-25 15:34:52 +0000425 // Verify that we don't have both "append" and "excl".
426 assert((!(Flags & F_Excl) || !(Flags & F_Append)) &&
427 "Cannot specify both 'excl' and 'append' file creation flags!");
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000428
Daniel Dunbar1ca20df2008-10-21 19:53:10 +0000429 ErrorInfo.clear();
430
Dan Gohmanc825cee2010-08-18 22:26:19 +0000431 // Handle "-" as stdout. Note that when we do this, we consider ourself
432 // the owner of stdout. This means that we can do things like close the
433 // file descriptor when we're done and set the "binary" flag globally.
Chris Lattnerd5bc0682008-08-17 03:53:23 +0000434 if (Filename[0] == '-' && Filename[1] == 0) {
435 FD = STDOUT_FILENO;
Daniel Dunbared90e702008-11-13 05:01:07 +0000436 // If user requested binary then put stdout into binary mode if
437 // possible.
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000438 if (Flags & F_Binary)
Daniel Dunbared90e702008-11-13 05:01:07 +0000439 sys::Program::ChangeStdoutToBinary();
Dan Gohmanc825cee2010-08-18 22:26:19 +0000440 // Close stdout when we're done, to detect any output errors.
441 ShouldClose = true;
Chris Lattnerd5bc0682008-08-17 03:53:23 +0000442 return;
443 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000444
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000445 int OpenFlags = O_WRONLY|O_CREAT;
Daniel Dunbared90e702008-11-13 05:01:07 +0000446#ifdef O_BINARY
Benjamin Kramerb451afb2009-08-23 08:57:52 +0000447 if (Flags & F_Binary)
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000448 OpenFlags |= O_BINARY;
Daniel Dunbared90e702008-11-13 05:01:07 +0000449#endif
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000450
Dan Gohman61a87962009-08-25 15:34:52 +0000451 if (Flags & F_Append)
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000452 OpenFlags |= O_APPEND;
453 else
Dan Gohman61a87962009-08-25 15:34:52 +0000454 OpenFlags |= O_TRUNC;
455 if (Flags & F_Excl)
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000456 OpenFlags |= O_EXCL;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000457
Dan Gohmand3511162010-05-06 02:06:20 +0000458 while ((FD = open(Filename, OpenFlags, 0664)) < 0) {
459 if (errno != EINTR) {
460 ErrorInfo = "Error opening output file '" + std::string(Filename) + "'";
461 ShouldClose = false;
462 return;
463 }
Chris Lattner84b94f72008-08-17 01:35:29 +0000464 }
Dan Gohmand3511162010-05-06 02:06:20 +0000465
466 // Ok, we successfully opened the file, so it'll need to be closed.
467 ShouldClose = true;
Chris Lattner84b94f72008-08-17 01:35:29 +0000468}
469
Francois Picheta3037c32010-10-14 20:30:58 +0000470/// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If
471/// ShouldClose is true, this closes the file when the stream is destroyed.
472raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
473 : raw_ostream(unbuffered), FD(fd),
Daniel Dunbar4fed8872011-02-03 03:32:32 +0000474 ShouldClose(shouldClose), Error(false), UseAtomicWrites(false) {
Francois Picheta3037c32010-10-14 20:30:58 +0000475#ifdef O_BINARY
476 // Setting STDOUT and STDERR to binary mode is necessary in Win32
477 // to avoid undesirable linefeed conversion.
478 if (fd == STDOUT_FILENO || fd == STDERR_FILENO)
479 setmode(fd, O_BINARY);
480#endif
Michael J. Spencerb7479902011-01-17 15:53:12 +0000481
482 // Get the starting position.
483 off_t loc = ::lseek(FD, 0, SEEK_CUR);
484 if (loc == (off_t)-1)
485 pos = 0;
486 else
487 pos = static_cast<uint64_t>(loc);
Francois Picheta3037c32010-10-14 20:30:58 +0000488}
489
Chris Lattner84b94f72008-08-17 01:35:29 +0000490raw_fd_ostream::~raw_fd_ostream() {
Dan Gohman38adfdd2010-08-20 16:34:20 +0000491 if (FD >= 0) {
492 flush();
493 if (ShouldClose)
494 while (::close(FD) != 0)
495 if (errno != EINTR) {
496 error_detected();
497 break;
498 }
499 }
500
NAKAMURA Takumi76e68ea2011-03-16 02:53:39 +0000501#ifdef __MINGW32__
502 // On mingw, global dtors should not call exit().
503 // report_fatal_error() invokes exit(). We know report_fatal_error()
504 // might not write messages to stderr when any errors were detected
505 // on FD == 2.
506 if (FD == 2) return;
507#endif
508
Dan Gohman38adfdd2010-08-20 16:34:20 +0000509 // If there are any pending errors, report them now. Clients wishing
510 // to avoid report_fatal_error calls should check for errors with
511 // has_error() and clear the error flag with clear_error() before
512 // destructing raw_ostream objects which may have errors.
513 if (has_error())
514 report_fatal_error("IO failure on output stream.");
Chris Lattnerce3b2c32010-08-17 23:11:56 +0000515}
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000516
Dan Gohman44790e72010-08-18 01:34:52 +0000517
Dan Gohmanf199ad62009-07-16 15:24:40 +0000518void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000519 assert(FD >= 0 && "File already closed.");
Daniel Dunbardb7a36c2009-03-16 23:29:31 +0000520 pos += Size;
Dan Gohmanef969f32010-05-06 01:27:36 +0000521
Benjamin Kramerce84a252010-05-05 15:17:47 +0000522 do {
Daniel Dunbar4fed8872011-02-03 03:32:32 +0000523 ssize_t ret;
524
525 // Check whether we should attempt to use atomic writes.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000526 if (LLVM_LIKELY(!UseAtomicWrites)) {
Daniel Dunbar4fed8872011-02-03 03:32:32 +0000527 ret = ::write(FD, Ptr, Size);
528 } else {
529 // Use ::writev() where available.
530#if defined(HAVE_WRITEV)
Galina Kistanova7da65782012-07-12 20:45:36 +0000531 const void *Addr = static_cast<const void *>(Ptr);
532 struct iovec IOV = {const_cast<void *>(Addr), Size };
Daniel Dunbar4fed8872011-02-03 03:32:32 +0000533 ret = ::writev(FD, &IOV, 1);
534#else
535 ret = ::write(FD, Ptr, Size);
536#endif
537 }
Dan Gohmanef969f32010-05-06 01:27:36 +0000538
539 if (ret < 0) {
540 // If it's a recoverable error, swallow it and retry the write.
Dan Gohmandea53102010-05-18 15:25:14 +0000541 //
542 // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
543 // raw_ostream isn't designed to do non-blocking I/O. However, some
544 // programs, such as old versions of bjam, have mistakenly used
545 // O_NONBLOCK. For compatibility, emulate blocking semantics by
546 // spinning until the write succeeds. If you don't want spinning,
547 // don't use O_NONBLOCK file descriptors with raw_ostream.
Dan Gohmand3511162010-05-06 02:06:20 +0000548 if (errno == EINTR || errno == EAGAIN
549#ifdef EWOULDBLOCK
550 || errno == EWOULDBLOCK
551#endif
552 )
Dan Gohmanef969f32010-05-06 01:27:36 +0000553 continue;
554
555 // Otherwise it's a non-recoverable error. Note it and quit.
556 error_detected();
557 break;
558 }
559
560 // The write may have written some or all of the data. Update the
561 // size and buffer pointer to reflect the remainder that needs
562 // to be written. If there are no bytes left, we're done.
563 Ptr += ret;
564 Size -= ret;
565 } while (Size > 0);
Chris Lattner84b94f72008-08-17 01:35:29 +0000566}
567
Dan Gohman44790e72010-08-18 01:34:52 +0000568void raw_fd_ostream::close() {
569 assert(ShouldClose);
570 ShouldClose = false;
571 flush();
572 while (::close(FD) != 0)
573 if (errno != EINTR) {
574 error_detected();
575 break;
576 }
577 FD = -1;
578}
579
Ted Kremeneka2669922009-01-26 21:42:04 +0000580uint64_t raw_fd_ostream::seek(uint64_t off) {
581 flush();
Daniel Dunbardcb50b92009-07-15 08:11:46 +0000582 pos = ::lseek(FD, off, SEEK_SET);
Dan Gohman213e87b2009-07-15 16:43:01 +0000583 if (pos != off)
Dan Gohman58fcef92009-07-15 23:25:33 +0000584 error_detected();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000585 return pos;
Ted Kremeneka2669922009-01-26 21:42:04 +0000586}
587
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000588size_t raw_fd_ostream::preferred_buffer_size() const {
Chris Lattnerca97c922010-07-07 15:52:27 +0000589#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
Chris Lattnerc86cdc72010-04-09 20:45:04 +0000590 // Windows and Minix have no st_blksize.
Dan Gohman84487b92009-08-13 17:27:29 +0000591 assert(FD >= 0 && "File not yet open!");
592 struct stat statbuf;
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000593 if (fstat(FD, &statbuf) != 0)
594 return 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000595
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000596 // If this is a terminal, don't use buffering. Line buffering
597 // would be a more traditional thing to do, but it's not worth
598 // the complexity.
599 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
600 return 0;
601 // Return the preferred block size.
602 return statbuf.st_blksize;
Dan Gohmanfeaeb362010-05-28 16:50:01 +0000603#else
Dan Gohman84487b92009-08-13 17:27:29 +0000604 return raw_ostream::preferred_buffer_size();
Dan Gohmanfeaeb362010-05-28 16:50:01 +0000605#endif
Dan Gohman84487b92009-08-13 17:27:29 +0000606}
607
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000608raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
609 bool bg) {
610 if (sys::Process::ColorNeedsFlush())
611 flush();
612 const char *colorcode =
613 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
614 : sys::Process::OutputColor(colors, bold, bg);
615 if (colorcode) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000616 size_t len = strlen(colorcode);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000617 write(colorcode, len);
618 // don't account colors towards output characters
619 pos -= len;
620 }
621 return *this;
622}
623
624raw_ostream &raw_fd_ostream::resetColor() {
625 if (sys::Process::ColorNeedsFlush())
626 flush();
627 const char *colorcode = sys::Process::ResetColor();
628 if (colorcode) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000629 size_t len = strlen(colorcode);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000630 write(colorcode, len);
631 // don't account colors towards output characters
632 pos -= len;
633 }
634 return *this;
635}
636
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000637raw_ostream &raw_fd_ostream::reverseColor() {
638 if (sys::Process::ColorNeedsFlush())
639 flush();
640 const char *colorcode = sys::Process::OutputReverse();
641 if (colorcode) {
642 size_t len = strlen(colorcode);
643 write(colorcode, len);
644 // don't account colors towards output characters
645 pos -= len;
646 }
647 return *this;
648}
649
Dan Gohmane5929232009-09-11 20:46:33 +0000650bool raw_fd_ostream::is_displayed() const {
651 return sys::Process::FileDescriptorIsDisplayed(FD);
652}
653
Daniel Dunbar04b45832012-07-20 18:29:41 +0000654bool raw_fd_ostream::has_colors() const {
655 return sys::Process::FileDescriptorHasColors(FD);
656}
657
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000658//===----------------------------------------------------------------------===//
Dan Gohmane9a46912010-08-20 16:44:56 +0000659// outs(), errs(), nulls()
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000660//===----------------------------------------------------------------------===//
Chris Lattner84b94f72008-08-17 01:35:29 +0000661
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000662/// outs() - This returns a reference to a raw_ostream for standard output.
663/// Use it like: outs() << "foo" << "bar";
Owen Anderson93719642008-08-21 00:14:44 +0000664raw_ostream &llvm::outs() {
Dan Gohman443f2d62010-08-20 16:39:41 +0000665 // Set buffer settings to model stdout behavior.
Dan Gohmane9a46912010-08-20 16:44:56 +0000666 // Delete the file descriptor when the program exists, forcing error
667 // detection. If you don't want this behavior, don't use outs().
668 static raw_fd_ostream S(STDOUT_FILENO, true);
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000669 return S;
670}
671
672/// errs() - This returns a reference to a raw_ostream for standard error.
673/// Use it like: errs() << "foo" << "bar";
Owen Anderson93719642008-08-21 00:14:44 +0000674raw_ostream &llvm::errs() {
Dan Gohman443f2d62010-08-20 16:39:41 +0000675 // Set standard error to be unbuffered by default.
676 static raw_fd_ostream S(STDERR_FILENO, false, true);
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000677 return S;
678}
679
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000680/// nulls() - This returns a reference to a raw_ostream which discards output.
681raw_ostream &llvm::nulls() {
682 static raw_null_ostream S;
683 return S;
684}
685
Douglas Gregorb231e572009-04-20 07:34:17 +0000686
Chris Lattner205af962008-08-23 22:43:04 +0000687//===----------------------------------------------------------------------===//
688// raw_string_ostream
689//===----------------------------------------------------------------------===//
690
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000691raw_string_ostream::~raw_string_ostream() {
692 flush();
693}
694
Dan Gohmanf199ad62009-07-16 15:24:40 +0000695void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbardb7a36c2009-03-16 23:29:31 +0000696 OS.append(Ptr, Size);
Chris Lattner205af962008-08-23 22:43:04 +0000697}
698
699//===----------------------------------------------------------------------===//
700// raw_svector_ostream
701//===----------------------------------------------------------------------===//
702
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000703// The raw_svector_ostream implementation uses the SmallVector itself as the
704// buffer for the raw_ostream. We guarantee that the raw_ostream buffer is
705// always pointing past the end of the vector, but within the vector
706// capacity. This allows raw_ostream to write directly into the correct place,
707// and we only need to set the vector size when the data is flushed.
708
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000709raw_svector_ostream::raw_svector_ostream(SmallVectorImpl<char> &O) : OS(O) {
Daniel Dunbare813cba2009-08-19 18:40:58 +0000710 // Set up the initial external buffer. We make sure that the buffer has at
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000711 // least 128 bytes free; raw_ostream itself only requires 64, but we want to
712 // make sure that we don't grow the buffer unnecessarily on destruction (when
713 // the data is flushed). See the FIXME below.
Daniel Dunbare813cba2009-08-19 18:40:58 +0000714 OS.reserve(OS.size() + 128);
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000715 SetBuffer(OS.end(), OS.capacity() - OS.size());
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000716}
717
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000718raw_svector_ostream::~raw_svector_ostream() {
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000719 // FIXME: Prevent resizing during this flush().
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000720 flush();
721}
722
Chris Lattner1386a882010-01-22 21:16:10 +0000723/// resync - This is called when the SmallVector we're appending to is changed
724/// outside of the raw_svector_ostream's control. It is only safe to do this
725/// if the raw_svector_ostream has previously been flushed.
726void raw_svector_ostream::resync() {
727 assert(GetNumBytesInBuffer() == 0 && "Didn't flush before mutating vector");
728
729 if (OS.capacity() - OS.size() < 64)
730 OS.reserve(OS.capacity() * 2);
Chris Lattner8fa0e352010-01-22 19:17:48 +0000731 SetBuffer(OS.end(), OS.capacity() - OS.size());
732}
733
Dan Gohmanf199ad62009-07-16 15:24:40 +0000734void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
Chris Lattner115158f2010-02-15 02:18:26 +0000735 // If we're writing bytes from the end of the buffer into the smallvector, we
736 // don't need to copy the bytes, just commit the bytes because they are
737 // already in the right place.
738 if (Ptr == OS.end()) {
739 assert(OS.size() + Size <= OS.capacity() && "Invalid write_impl() call!");
740 OS.set_size(OS.size() + Size);
741 } else {
742 assert(GetNumBytesInBuffer() == 0 &&
743 "Should be writing from buffer if some bytes in it");
744 // Otherwise, do copy the bytes.
745 OS.append(Ptr, Ptr+Size);
746 }
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000747
748 // Grow the vector if necessary.
749 if (OS.capacity() - OS.size() < 64)
750 OS.reserve(OS.capacity() * 2);
751
752 // Update the buffer position.
753 SetBuffer(OS.end(), OS.capacity() - OS.size());
Chris Lattner205af962008-08-23 22:43:04 +0000754}
755
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000756uint64_t raw_svector_ostream::current_pos() const {
757 return OS.size();
758}
Douglas Gregorb231e572009-04-20 07:34:17 +0000759
Daniel Dunbare813cba2009-08-19 18:40:58 +0000760StringRef raw_svector_ostream::str() {
761 flush();
762 return StringRef(OS.begin(), OS.size());
763}
764
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000765//===----------------------------------------------------------------------===//
766// raw_null_ostream
767//===----------------------------------------------------------------------===//
768
Dan Gohman4b66b472009-07-27 21:46:02 +0000769raw_null_ostream::~raw_null_ostream() {
770#ifndef NDEBUG
771 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
772 // with raw_null_ostream, but it's better to have raw_null_ostream follow
773 // the rules than to change the rules just for raw_null_ostream.
774 flush();
775#endif
776}
777
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000778void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
779}
780
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000781uint64_t raw_null_ostream::current_pos() const {
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000782 return 0;
783}