blob: 8101bc1d2f3a1661cb54b0016f904e113fca136c [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"
Rafael Espindola6d354812013-07-16 19:44:17 +000021#include "llvm/Support/FileSystem.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Support/Format.h"
Nick Kledzike6480372014-09-25 20:30:58 +000023#include "llvm/Support/MathExtras.h"
Zachary Turner733be512016-10-11 19:24:45 +000024#include "llvm/Support/NativeFormatting.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Support/Process.h"
26#include "llvm/Support/Program.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000027#include <algorithm>
Benjamin Krameref14f802010-01-29 15:19:06 +000028#include <cctype>
Benjamin Kramerce84a252010-05-05 15:17:47 +000029#include <cerrno>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000030#include <cstdio>
31#include <iterator>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000032#include <sys/stat.h>
Zachary Turner733be512016-10-11 19:24:45 +000033#include <system_error>
Chris Lattner84b94f72008-08-17 01:35:29 +000034
NAKAMURA Takumi212c80a2013-07-17 02:21:10 +000035// <fcntl.h> may provide O_BINARY.
36#if defined(HAVE_FCNTL_H)
37# include <fcntl.h>
38#endif
39
Chris Lattnerd564f292008-08-22 15:45:00 +000040#if defined(HAVE_UNISTD_H)
41# include <unistd.h>
42#endif
Daniel Dunbar4fed8872011-02-03 03:32:32 +000043#if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
44# include <sys/uio.h>
45#endif
Argyrios Kyrtzidisb97ff822008-08-17 09:25:21 +000046
NAKAMURA Takumife84f392010-10-19 01:21:55 +000047#if defined(__CYGWIN__)
48#include <io.h>
49#endif
50
Argyrios Kyrtzidisb97ff822008-08-17 09:25:21 +000051#if defined(_MSC_VER)
Chris Lattner84b94f72008-08-17 01:35:29 +000052#include <io.h>
Owen Anderson93719642008-08-21 00:14:44 +000053#ifndef STDIN_FILENO
54# define STDIN_FILENO 0
55#endif
56#ifndef STDOUT_FILENO
57# define STDOUT_FILENO 1
58#endif
59#ifndef STDERR_FILENO
60# define STDERR_FILENO 2
61#endif
Chris Lattner84b94f72008-08-17 01:35:29 +000062#endif
63
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +000064#ifdef LLVM_ON_WIN32
65#include "Windows/WindowsSupport.h"
66#endif
67
Chris Lattnerd564f292008-08-22 15:45:00 +000068using namespace llvm;
69
Dan Gohman58fcef92009-07-15 23:25:33 +000070raw_ostream::~raw_ostream() {
Dan Gohman1b763292009-07-27 20:49:44 +000071 // raw_ostream's subclasses should take care to flush the buffer
72 // in their destructors.
73 assert(OutBufCur == OutBufStart &&
74 "raw_ostream destructor called with non-empty buffer!");
75
Daniel Dunbar317a6cd2009-08-18 23:42:36 +000076 if (BufferMode == InternalBuffer)
77 delete [] OutBufStart;
Dan Gohman58fcef92009-07-15 23:25:33 +000078}
Chris Lattnerd564f292008-08-22 15:45:00 +000079
Chris Lattner84b94f72008-08-17 01:35:29 +000080// An out of line virtual method to provide a home for the class vtable.
81void raw_ostream::handle() {}
82
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +000083size_t raw_ostream::preferred_buffer_size() const {
Dan Gohman84487b92009-08-13 17:27:29 +000084 // BUFSIZ is intended to be a reasonable default.
85 return BUFSIZ;
86}
87
88void raw_ostream::SetBuffered() {
89 // Ask the subclass to determine an appropriate buffer size.
Dan Gohman17710222009-08-15 02:05:19 +000090 if (size_t Size = preferred_buffer_size())
91 SetBufferSize(Size);
92 else
93 // It may return 0, meaning this stream should be unbuffered.
94 SetUnbuffered();
Dan Gohman84487b92009-08-13 17:27:29 +000095}
96
Dan Gohmanb452d4e2010-03-24 19:38:02 +000097void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
Nick Lewycky7bfd86d2011-08-28 03:30:02 +000098 BufferKind Mode) {
Craig Topper2617dcc2014-04-15 06:32:26 +000099 assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
100 (Mode != Unbuffered && BufferStart && Size != 0)) &&
Daniel Dunbar316b4a02009-09-15 20:31:46 +0000101 "stream must be unbuffered or have at least one byte");
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000102 // Make sure the current buffer is free of content (we can't flush here; the
103 // child buffer management logic will be in write_impl).
104 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
Dan Gohman54401d42009-08-13 15:58:55 +0000105
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000106 if (BufferMode == InternalBuffer)
107 delete [] OutBufStart;
108 OutBufStart = BufferStart;
Dan Gohman54401d42009-08-13 15:58:55 +0000109 OutBufEnd = OutBufStart+Size;
110 OutBufCur = OutBufStart;
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000111 BufferMode = Mode;
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000112
113 assert(OutBufStart <= OutBufEnd && "Invalid size!");
Dan Gohman54401d42009-08-13 15:58:55 +0000114}
115
Owen Andersond2850532008-08-21 20:58:52 +0000116raw_ostream &raw_ostream::operator<<(unsigned long N) {
Zachary Turner9d58e362016-10-17 21:25:41 +0000117 write_ulong(*this, N, 0);
Zachary Turner733be512016-10-11 19:24:45 +0000118 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000119}
120
121raw_ostream &raw_ostream::operator<<(long N) {
Zachary Turner9d58e362016-10-17 21:25:41 +0000122 write_long(*this, N, 0);
Zachary Turner733be512016-10-11 19:24:45 +0000123 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000124}
125
126raw_ostream &raw_ostream::operator<<(unsigned long long N) {
Zachary Turner9d58e362016-10-17 21:25:41 +0000127 write_ulonglong(*this, N, 0);
Zachary Turner733be512016-10-11 19:24:45 +0000128 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000129}
130
131raw_ostream &raw_ostream::operator<<(long long N) {
Zachary Turner9d58e362016-10-17 21:25:41 +0000132 write_longlong(*this, N, 0);
Zachary Turner733be512016-10-11 19:24:45 +0000133 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000134}
135
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000136raw_ostream &raw_ostream::write_hex(unsigned long long N) {
Zachary Turner9d58e362016-10-17 21:25:41 +0000137 llvm::write_hex(*this, N, 0, false, false);
Zachary Turner733be512016-10-11 19:24:45 +0000138 return *this;
Chris Lattner0c19df42008-08-23 22:23:09 +0000139}
140
Daniel Dunbar65dc8912010-11-27 07:59:50 +0000141raw_ostream &raw_ostream::write_escaped(StringRef Str,
142 bool UseHexEscapes) {
Craig Topper775fb732016-02-04 06:51:41 +0000143 for (unsigned char c : Str) {
Daniel Dunbar4108c432009-10-17 20:43:08 +0000144 switch (c) {
145 case '\\':
146 *this << '\\' << '\\';
147 break;
148 case '\t':
149 *this << '\\' << 't';
150 break;
151 case '\n':
152 *this << '\\' << 'n';
153 break;
154 case '"':
155 *this << '\\' << '"';
156 break;
157 default:
158 if (std::isprint(c)) {
159 *this << c;
160 break;
161 }
162
Daniel Dunbar65dc8912010-11-27 07:59:50 +0000163 // Write out the escaped representation.
164 if (UseHexEscapes) {
165 *this << '\\' << 'x';
166 *this << hexdigit((c >> 4 & 0xF));
167 *this << hexdigit((c >> 0) & 0xF);
168 } else {
169 // Always use a full 3-character octal escape.
170 *this << '\\';
171 *this << char('0' + ((c >> 6) & 7));
172 *this << char('0' + ((c >> 3) & 7));
173 *this << char('0' + ((c >> 0) & 7));
174 }
Daniel Dunbar4108c432009-10-17 20:43:08 +0000175 }
176 }
177
178 return *this;
179}
180
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000181raw_ostream &raw_ostream::operator<<(const void *P) {
Zachary Turner9d58e362016-10-17 21:25:41 +0000182 llvm::write_hex(*this, (uintptr_t)P, 0, false, true);
Zachary Turner733be512016-10-11 19:24:45 +0000183 return *this;
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000184}
185
Chris Lattner06fa1762009-08-24 03:52:50 +0000186raw_ostream &raw_ostream::operator<<(double N) {
Zachary Turner9d58e362016-10-17 21:25:41 +0000187 llvm::write_double(*this, N, 0, 0, FloatStyle::Exponent);
Zachary Turner733be512016-10-11 19:24:45 +0000188 return *this;
Chris Lattner06fa1762009-08-24 03:52:50 +0000189}
190
Daniel Dunbard24535f2009-03-16 22:55:06 +0000191void raw_ostream::flush_nonempty() {
192 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000193 size_t Length = OutBufCur - OutBufStart;
194 OutBufCur = OutBufStart;
195 write_impl(OutBufStart, Length);
Daniel Dunbard24535f2009-03-16 22:55:06 +0000196}
197
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000198raw_ostream &raw_ostream::write(unsigned char C) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000199 // Group exceptional cases into a single branch.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000200 if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
201 if (LLVM_UNLIKELY(!OutBufStart)) {
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000202 if (BufferMode == Unbuffered) {
Dan Gohman23f90c12009-08-18 20:09:59 +0000203 write_impl(reinterpret_cast<char*>(&C), 1);
204 return *this;
205 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000206 // Set up a buffer and start over.
207 SetBuffered();
208 return write(C);
Dan Gohman23f90c12009-08-18 20:09:59 +0000209 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000210
211 flush_nonempty();
Daniel Dunbar2d603da2009-03-17 01:13:35 +0000212 }
213
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000214 *OutBufCur++ = C;
Daniel Dunbar87862182009-03-16 22:08:44 +0000215 return *this;
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000216}
Chris Lattner0c19df42008-08-23 22:23:09 +0000217
Dan Gohmanf199ad62009-07-16 15:24:40 +0000218raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000219 // Group exceptional cases into a single branch.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000220 if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
221 if (LLVM_UNLIKELY(!OutBufStart)) {
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000222 if (BufferMode == Unbuffered) {
Dan Gohman52022c22009-08-13 15:44:52 +0000223 write_impl(Ptr, Size);
224 return *this;
225 }
226 // Set up a buffer and start over.
Dan Gohman84487b92009-08-13 17:27:29 +0000227 SetBuffered();
Dan Gohman52022c22009-08-13 15:44:52 +0000228 return write(Ptr, Size);
229 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000230
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000231 size_t NumBytes = OutBufEnd - OutBufCur;
232
Benjamin Krameracf08422011-03-04 18:18:16 +0000233 // If the buffer is empty at this point we have a string that is larger
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000234 // than the buffer. Directly write the chunk that is a multiple of the
235 // preferred buffer size and put the remainder in the buffer.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000236 if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
Michael Ilseman5be22a12014-12-12 21:48:03 +0000237 assert(NumBytes != 0 && "undefined behavior");
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000238 size_t BytesToWrite = Size - (Size % NumBytes);
239 write_impl(Ptr, BytesToWrite);
Matt Beaumont-Gaya182be82013-03-12 23:55:24 +0000240 size_t BytesRemaining = Size - BytesToWrite;
241 if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
242 // Too much left over to copy into our buffer.
243 return write(Ptr + BytesToWrite, BytesRemaining);
244 }
245 copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
Benjamin Krameracf08422011-03-04 18:18:16 +0000246 return *this;
247 }
248
249 // We don't have enough space in the buffer to fit the string in. Insert as
250 // much as possible, flush and start over with the remainder.
Benjamin Krameracf08422011-03-04 18:18:16 +0000251 copy_to_buffer(Ptr, NumBytes);
252 flush_nonempty();
253 return write(Ptr + NumBytes, Size - NumBytes);
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000254 }
Dan Gohman52022c22009-08-13 15:44:52 +0000255
256 copy_to_buffer(Ptr, Size);
257
258 return *this;
259}
260
261void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
Dan Gohmanc04a00a2009-08-13 20:32:03 +0000262 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
Dan Gohman98205552009-08-13 18:38:15 +0000263
Owen Andersond2850532008-08-21 20:58:52 +0000264 // Handle short strings specially, memcpy isn't very good at very short
265 // strings.
266 switch (Size) {
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000267 case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
268 case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
269 case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
270 case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
Owen Andersond2850532008-08-21 20:58:52 +0000271 case 0: break;
272 default:
Dan Gohman52022c22009-08-13 15:44:52 +0000273 memcpy(OutBufCur, Ptr, Size);
Owen Andersond2850532008-08-21 20:58:52 +0000274 break;
275 }
Daniel Dunbar3da6a702009-03-10 16:21:55 +0000276
Dan Gohman52022c22009-08-13 15:44:52 +0000277 OutBufCur += Size;
Owen Andersond2850532008-08-21 20:58:52 +0000278}
279
Chris Lattner22b52c92008-08-23 19:23:10 +0000280// Formatted output.
281raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000282 // If we have more than a few bytes left in our output buffer, try
283 // formatting directly onto its end.
Dan Gohmanf199ad62009-07-16 15:24:40 +0000284 size_t NextBufferSize = 127;
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000285 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
286 if (BufferBytesLeft > 3) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000287 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000288
Chris Lattner22b52c92008-08-23 19:23:10 +0000289 // Common case is that we have plenty of space.
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000290 if (BytesUsed <= BufferBytesLeft) {
Chris Lattner22b52c92008-08-23 19:23:10 +0000291 OutBufCur += BytesUsed;
292 return *this;
293 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000294
Chris Lattner22b52c92008-08-23 19:23:10 +0000295 // Otherwise, we overflowed and the return value tells us the size to try
296 // again with.
297 NextBufferSize = BytesUsed;
298 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000299
Chris Lattner22b52c92008-08-23 19:23:10 +0000300 // If we got here, we didn't have enough space in the output buffer for the
301 // string. Try printing into a SmallVector that is resized to have enough
302 // space. Iterate until we win.
303 SmallVector<char, 128> V;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000304
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000305 while (true) {
Chris Lattner22b52c92008-08-23 19:23:10 +0000306 V.resize(NextBufferSize);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000307
Chris Lattner22b52c92008-08-23 19:23:10 +0000308 // Try formatting into the SmallVector.
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000309 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000310
Chris Lattner22b52c92008-08-23 19:23:10 +0000311 // If BytesUsed fit into the vector, we win.
Chris Lattner2bfc72e2008-10-26 19:20:47 +0000312 if (BytesUsed <= NextBufferSize)
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000313 return write(V.data(), BytesUsed);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000314
Chris Lattner22b52c92008-08-23 19:23:10 +0000315 // Otherwise, try again with a new size.
316 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
317 NextBufferSize = BytesUsed;
318 }
319}
320
Nick Kledzike6480372014-09-25 20:30:58 +0000321raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
322 unsigned Len = FS.Str.size();
323 int PadAmount = FS.Width - Len;
324 if (FS.RightJustify && (PadAmount > 0))
325 this->indent(PadAmount);
326 this->operator<<(FS.Str);
327 if (!FS.RightJustify && (PadAmount > 0))
328 this->indent(PadAmount);
329 return *this;
330}
331
332raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
333 if (FN.Hex) {
Zachary Turner9d58e362016-10-17 21:25:41 +0000334 llvm::write_hex(*this, FN.HexValue, FN.Width, FN.Upper, FN.HexPrefix);
Nick Kledzike6480372014-09-25 20:30:58 +0000335 } else {
Zachary Turner9d58e362016-10-17 21:25:41 +0000336 llvm::write_longlong(*this, FN.DecValue, FN.Width);
Nick Kledzike6480372014-09-25 20:30:58 +0000337 }
Zachary Turner733be512016-10-11 19:24:45 +0000338 return *this;
Nick Kledzike6480372014-09-25 20:30:58 +0000339}
340
Chris Lattnere6db2c32009-08-22 23:10:29 +0000341/// indent - Insert 'NumSpaces' spaces.
342raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
Dan Gohmanf88f52e2009-08-24 04:13:01 +0000343 static const char Spaces[] = " "
344 " "
345 " ";
Chris Lattnere6db2c32009-08-22 23:10:29 +0000346
347 // Usually the indentation is small, handle it with a fastpath.
Dan Gohmanc9fa0512009-08-24 04:43:38 +0000348 if (NumSpaces < array_lengthof(Spaces))
Chris Lattnere6db2c32009-08-22 23:10:29 +0000349 return write(Spaces, NumSpaces);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000350
Chris Lattnere6db2c32009-08-22 23:10:29 +0000351 while (NumSpaces) {
Dan Gohmanc9fa0512009-08-24 04:43:38 +0000352 unsigned NumToWrite = std::min(NumSpaces,
353 (unsigned)array_lengthof(Spaces)-1);
Chris Lattnere6db2c32009-08-22 23:10:29 +0000354 write(Spaces, NumToWrite);
355 NumSpaces -= NumToWrite;
356 }
357 return *this;
358}
359
Chris Lattner22b52c92008-08-23 19:23:10 +0000360//===----------------------------------------------------------------------===//
361// Formatted Output
362//===----------------------------------------------------------------------===//
363
364// Out of line virtual method.
365void format_object_base::home() {
366}
367
Chris Lattner84b94f72008-08-17 01:35:29 +0000368//===----------------------------------------------------------------------===//
369// raw_fd_ostream
370//===----------------------------------------------------------------------===//
371
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000372static int getFD(StringRef Filename, std::error_code &EC,
373 sys::fs::OpenFlags Flags) {
Dan Gohmanc825cee2010-08-18 22:26:19 +0000374 // Handle "-" as stdout. Note that when we do this, we consider ourself
375 // the owner of stdout. This means that we can do things like close the
376 // file descriptor when we're done and set the "binary" flag globally.
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000377 if (Filename == "-") {
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000378 EC = std::error_code();
Daniel Dunbared90e702008-11-13 05:01:07 +0000379 // If user requested binary then put stdout into binary mode if
380 // possible.
Rafael Espindola90c7f1c2014-02-24 18:20:12 +0000381 if (!(Flags & sys::fs::F_Text))
Rafael Espindolacb2eca02013-06-12 20:58:35 +0000382 sys::ChangeStdoutToBinary();
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000383 return STDOUT_FILENO;
Chris Lattnerd5bc0682008-08-17 03:53:23 +0000384 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000385
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000386 int FD;
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000387 EC = sys::fs::openFileForWrite(Filename, FD, Flags);
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000388 if (EC)
389 return -1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000390
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000391 return FD;
Chris Lattner84b94f72008-08-17 01:35:29 +0000392}
393
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000394raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
395 sys::fs::OpenFlags Flags)
396 : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
397
Rafael Espindola62e6ec02015-04-09 16:59:07 +0000398/// FD is the file descriptor that this writes to. If ShouldClose is true, this
399/// closes the file when the stream is destroyed.
Francois Picheta3037c32010-10-14 20:30:58 +0000400raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
Rafael Espindola37b70152015-04-14 15:00:34 +0000401 : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
Rafael Espindola3f210fc2015-12-16 22:59:06 +0000402 Error(false) {
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000403 if (FD < 0 ) {
404 ShouldClose = false;
405 return;
406 }
Michael J. Spencerb7479902011-01-17 15:53:12 +0000407
408 // Get the starting position.
409 off_t loc = ::lseek(FD, 0, SEEK_CUR);
Rafael Espindolaa9b84ab2015-04-13 11:09:48 +0000410#ifdef LLVM_ON_WIN32
411 // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
412 sys::fs::file_status Status;
413 std::error_code EC = status(FD, Status);
414 SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
415#else
Rafael Espindola74d2f612015-04-10 18:15:51 +0000416 SupportsSeeking = loc != (off_t)-1;
Rafael Espindolaa9b84ab2015-04-13 11:09:48 +0000417#endif
Rafael Espindola74d2f612015-04-10 18:15:51 +0000418 if (!SupportsSeeking)
Michael J. Spencerb7479902011-01-17 15:53:12 +0000419 pos = 0;
420 else
421 pos = static_cast<uint64_t>(loc);
Francois Picheta3037c32010-10-14 20:30:58 +0000422}
423
Chris Lattner84b94f72008-08-17 01:35:29 +0000424raw_fd_ostream::~raw_fd_ostream() {
Dan Gohman38adfdd2010-08-20 16:34:20 +0000425 if (FD >= 0) {
426 flush();
David Majnemer51c2afc2014-10-07 05:48:40 +0000427 if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
428 error_detected();
Dan Gohman38adfdd2010-08-20 16:34:20 +0000429 }
430
NAKAMURA Takumi76e68ea2011-03-16 02:53:39 +0000431#ifdef __MINGW32__
432 // On mingw, global dtors should not call exit().
433 // report_fatal_error() invokes exit(). We know report_fatal_error()
434 // might not write messages to stderr when any errors were detected
435 // on FD == 2.
436 if (FD == 2) return;
437#endif
438
Dan Gohman38adfdd2010-08-20 16:34:20 +0000439 // If there are any pending errors, report them now. Clients wishing
440 // to avoid report_fatal_error calls should check for errors with
441 // has_error() and clear the error flag with clear_error() before
442 // destructing raw_ostream objects which may have errors.
443 if (has_error())
Chad Rosier7ce810c2013-03-27 18:30:00 +0000444 report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
Chris Lattnerce3b2c32010-08-17 23:11:56 +0000445}
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000446
Dan Gohmanf199ad62009-07-16 15:24:40 +0000447void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000448 assert(FD >= 0 && "File already closed.");
Daniel Dunbardb7a36c2009-03-16 23:29:31 +0000449 pos += Size;
Dan Gohmanef969f32010-05-06 01:27:36 +0000450
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +0000451#ifndef LLVM_ON_WIN32
452 bool ShouldWriteInChunks = false;
453#else
454 // Writing a large size of output to Windows console returns ENOMEM. It seems
455 // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
456 // the latter has a size limit (66000 bytes or less, depending on heap usage).
Reid Kleckner5fb7a582016-01-11 23:33:03 +0000457 bool ShouldWriteInChunks = !!::_isatty(FD) && !RunningWindows8OrGreater();
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +0000458#endif
459
Benjamin Kramerce84a252010-05-05 15:17:47 +0000460 do {
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +0000461 size_t ChunkSize = Size;
462 if (ChunkSize > 32767 && ShouldWriteInChunks)
463 ChunkSize = 32767;
464
465 ssize_t ret = ::write(FD, Ptr, ChunkSize);
Dan Gohmanef969f32010-05-06 01:27:36 +0000466
467 if (ret < 0) {
468 // If it's a recoverable error, swallow it and retry the write.
Dan Gohmandea53102010-05-18 15:25:14 +0000469 //
470 // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
471 // raw_ostream isn't designed to do non-blocking I/O. However, some
472 // programs, such as old versions of bjam, have mistakenly used
473 // O_NONBLOCK. For compatibility, emulate blocking semantics by
474 // spinning until the write succeeds. If you don't want spinning,
475 // don't use O_NONBLOCK file descriptors with raw_ostream.
Dan Gohmand3511162010-05-06 02:06:20 +0000476 if (errno == EINTR || errno == EAGAIN
477#ifdef EWOULDBLOCK
478 || errno == EWOULDBLOCK
479#endif
480 )
Dan Gohmanef969f32010-05-06 01:27:36 +0000481 continue;
482
483 // Otherwise it's a non-recoverable error. Note it and quit.
484 error_detected();
485 break;
486 }
487
488 // The write may have written some or all of the data. Update the
489 // size and buffer pointer to reflect the remainder that needs
490 // to be written. If there are no bytes left, we're done.
491 Ptr += ret;
492 Size -= ret;
493 } while (Size > 0);
Chris Lattner84b94f72008-08-17 01:35:29 +0000494}
495
Dan Gohman44790e72010-08-18 01:34:52 +0000496void raw_fd_ostream::close() {
497 assert(ShouldClose);
498 ShouldClose = false;
499 flush();
David Majnemer51c2afc2014-10-07 05:48:40 +0000500 if (sys::Process::SafelyCloseFileDescriptor(FD))
501 error_detected();
Dan Gohman44790e72010-08-18 01:34:52 +0000502 FD = -1;
503}
504
Ted Kremeneka2669922009-01-26 21:42:04 +0000505uint64_t raw_fd_ostream::seek(uint64_t off) {
Yaron Keren7cf7f802016-02-23 07:17:58 +0000506 assert(SupportsSeeking && "Stream does not support seeking!");
Ted Kremeneka2669922009-01-26 21:42:04 +0000507 flush();
Daniel Dunbardcb50b92009-07-15 08:11:46 +0000508 pos = ::lseek(FD, off, SEEK_SET);
Rafael Espindola642a2212015-04-14 22:54:16 +0000509 if (pos == (uint64_t)-1)
Dan Gohman58fcef92009-07-15 23:25:33 +0000510 error_detected();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000511 return pos;
Ted Kremeneka2669922009-01-26 21:42:04 +0000512}
513
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000514void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
515 uint64_t Offset) {
Rafael Espindola37b70152015-04-14 15:00:34 +0000516 uint64_t Pos = tell();
517 seek(Offset);
518 write(Ptr, Size);
519 seek(Pos);
520}
521
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000522size_t raw_fd_ostream::preferred_buffer_size() const {
Chris Lattnerca97c922010-07-07 15:52:27 +0000523#if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
Chris Lattnerc86cdc72010-04-09 20:45:04 +0000524 // Windows and Minix have no st_blksize.
Dan Gohman84487b92009-08-13 17:27:29 +0000525 assert(FD >= 0 && "File not yet open!");
526 struct stat statbuf;
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000527 if (fstat(FD, &statbuf) != 0)
528 return 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000529
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000530 // If this is a terminal, don't use buffering. Line buffering
531 // would be a more traditional thing to do, but it's not worth
532 // the complexity.
533 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
534 return 0;
535 // Return the preferred block size.
536 return statbuf.st_blksize;
Dan Gohmanfeaeb362010-05-28 16:50:01 +0000537#else
Dan Gohman84487b92009-08-13 17:27:29 +0000538 return raw_ostream::preferred_buffer_size();
Dan Gohmanfeaeb362010-05-28 16:50:01 +0000539#endif
Dan Gohman84487b92009-08-13 17:27:29 +0000540}
541
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000542raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
543 bool bg) {
544 if (sys::Process::ColorNeedsFlush())
545 flush();
546 const char *colorcode =
547 (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
548 : sys::Process::OutputColor(colors, bold, bg);
549 if (colorcode) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000550 size_t len = strlen(colorcode);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000551 write(colorcode, len);
552 // don't account colors towards output characters
553 pos -= len;
554 }
555 return *this;
556}
557
558raw_ostream &raw_fd_ostream::resetColor() {
559 if (sys::Process::ColorNeedsFlush())
560 flush();
561 const char *colorcode = sys::Process::ResetColor();
562 if (colorcode) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000563 size_t len = strlen(colorcode);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000564 write(colorcode, len);
565 // don't account colors towards output characters
566 pos -= len;
567 }
568 return *this;
569}
570
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000571raw_ostream &raw_fd_ostream::reverseColor() {
572 if (sys::Process::ColorNeedsFlush())
573 flush();
574 const char *colorcode = sys::Process::OutputReverse();
575 if (colorcode) {
576 size_t len = strlen(colorcode);
577 write(colorcode, len);
578 // don't account colors towards output characters
579 pos -= len;
580 }
581 return *this;
582}
583
Dan Gohmane5929232009-09-11 20:46:33 +0000584bool raw_fd_ostream::is_displayed() const {
585 return sys::Process::FileDescriptorIsDisplayed(FD);
586}
587
Daniel Dunbar04b45832012-07-20 18:29:41 +0000588bool raw_fd_ostream::has_colors() const {
589 return sys::Process::FileDescriptorHasColors(FD);
590}
591
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000592//===----------------------------------------------------------------------===//
Dan Gohmane9a46912010-08-20 16:44:56 +0000593// outs(), errs(), nulls()
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000594//===----------------------------------------------------------------------===//
Chris Lattner84b94f72008-08-17 01:35:29 +0000595
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000596/// outs() - This returns a reference to a raw_ostream for standard output.
597/// Use it like: outs() << "foo" << "bar";
Owen Anderson93719642008-08-21 00:14:44 +0000598raw_ostream &llvm::outs() {
Justin Lebarc75d5662016-02-19 00:18:46 +0000599 // Set buffer settings to model stdout behavior. Delete the file descriptor
600 // when the program exits, forcing error detection. This means that if you
601 // ever call outs(), you can't open another raw_fd_ostream on stdout, as we'll
602 // close stdout twice and print an error the second time.
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000603 std::error_code EC;
604 static raw_fd_ostream S("-", EC, sys::fs::F_None);
605 assert(!EC);
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000606 return S;
607}
608
609/// errs() - This returns a reference to a raw_ostream for standard error.
610/// Use it like: errs() << "foo" << "bar";
Owen Anderson93719642008-08-21 00:14:44 +0000611raw_ostream &llvm::errs() {
Dan Gohman443f2d62010-08-20 16:39:41 +0000612 // Set standard error to be unbuffered by default.
613 static raw_fd_ostream S(STDERR_FILENO, false, true);
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000614 return S;
615}
616
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000617/// nulls() - This returns a reference to a raw_ostream which discards output.
618raw_ostream &llvm::nulls() {
619 static raw_null_ostream S;
620 return S;
621}
622
Chris Lattner205af962008-08-23 22:43:04 +0000623//===----------------------------------------------------------------------===//
624// raw_string_ostream
625//===----------------------------------------------------------------------===//
626
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000627raw_string_ostream::~raw_string_ostream() {
628 flush();
629}
630
Dan Gohmanf199ad62009-07-16 15:24:40 +0000631void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbardb7a36c2009-03-16 23:29:31 +0000632 OS.append(Ptr, Size);
Chris Lattner205af962008-08-23 22:43:04 +0000633}
634
635//===----------------------------------------------------------------------===//
636// raw_svector_ostream
637//===----------------------------------------------------------------------===//
638
Yaron Keren3d1173b2015-08-13 06:19:52 +0000639uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000640
Yaron Keren3d1173b2015-08-13 06:19:52 +0000641void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
642 OS.append(Ptr, Ptr + Size);
Nick Lewyckye2f6fb52015-08-13 18:10:19 +0000643}
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000644
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000645void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
646 uint64_t Offset) {
Yaron Keren3d1173b2015-08-13 06:19:52 +0000647 memcpy(OS.data() + Offset, Ptr, Size);
Daniel Dunbare813cba2009-08-19 18:40:58 +0000648}
649
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000650//===----------------------------------------------------------------------===//
651// raw_null_ostream
652//===----------------------------------------------------------------------===//
653
Dan Gohman4b66b472009-07-27 21:46:02 +0000654raw_null_ostream::~raw_null_ostream() {
655#ifndef NDEBUG
656 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
657 // with raw_null_ostream, but it's better to have raw_null_ostream follow
658 // the rules than to change the rules just for raw_null_ostream.
659 flush();
660#endif
661}
662
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000663void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
664}
665
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000666uint64_t raw_null_ostream::current_pos() const {
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000667 return 0;
668}
Rafael Espindola37b70152015-04-14 15:00:34 +0000669
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000670void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
671 uint64_t Offset) {}