blob: b9989371f5eabc663b717c2a293549d4f7f473c8 [file] [log] [blame]
Chris Lattner84b94f72008-08-17 01:35:29 +00001//===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner84b94f72008-08-17 01:35:29 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This implements support for bulk buffered stream output.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/ADT/STLExtras.h"
Chris Lattner22b52c92008-08-23 19:23:10 +000015#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/StringExtras.h"
Chris Lattnerd564f292008-08-22 15:45:00 +000017#include "llvm/Config/config.h"
Daniel Dunbar437b8a52009-03-17 21:15:18 +000018#include "llvm/Support/Compiler.h"
Daniel Dunbardcb50b92009-07-15 08:11:46 +000019#include "llvm/Support/ErrorHandling.h"
Rafael Espindola6d354812013-07-16 19:44:17 +000020#include "llvm/Support/FileSystem.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Support/Format.h"
Zachary Turner11db2642016-11-11 23:57:40 +000022#include "llvm/Support/FormatVariadic.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
Argyrios Kyrtzidisb97ff822008-08-17 09:25:21 +000043
NAKAMURA Takumife84f392010-10-19 01:21:55 +000044#if defined(__CYGWIN__)
45#include <io.h>
46#endif
47
Argyrios Kyrtzidisb97ff822008-08-17 09:25:21 +000048#if defined(_MSC_VER)
Chris Lattner84b94f72008-08-17 01:35:29 +000049#include <io.h>
Owen Anderson93719642008-08-21 00:14:44 +000050#ifndef STDIN_FILENO
51# define STDIN_FILENO 0
52#endif
53#ifndef STDOUT_FILENO
54# define STDOUT_FILENO 1
55#endif
56#ifndef STDERR_FILENO
57# define STDERR_FILENO 2
58#endif
Chris Lattner84b94f72008-08-17 01:35:29 +000059#endif
60
Nico Weber712e8d22018-04-29 00:45:03 +000061#ifdef _WIN32
Reid Kleckner2b8c6922018-09-05 00:08:56 +000062#include "llvm/Support/ConvertUTF.h"
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +000063#include "Windows/WindowsSupport.h"
64#endif
65
Chris Lattnerd564f292008-08-22 15:45:00 +000066using namespace llvm;
67
Rui Ueyamacac8df12019-08-07 08:08:17 +000068const raw_ostream::Colors raw_ostream::BLACK;
69const raw_ostream::Colors raw_ostream::RED;
70const raw_ostream::Colors raw_ostream::GREEN;
71const raw_ostream::Colors raw_ostream::YELLOW;
72const raw_ostream::Colors raw_ostream::BLUE;
73const raw_ostream::Colors raw_ostream::MAGENTA;
74const raw_ostream::Colors raw_ostream::CYAN;
75const raw_ostream::Colors raw_ostream::WHITE;
76const raw_ostream::Colors raw_ostream::SAVEDCOLOR;
77const raw_ostream::Colors raw_ostream::RESET;
78
Dan Gohman58fcef92009-07-15 23:25:33 +000079raw_ostream::~raw_ostream() {
Dan Gohman1b763292009-07-27 20:49:44 +000080 // raw_ostream's subclasses should take care to flush the buffer
81 // in their destructors.
82 assert(OutBufCur == OutBufStart &&
83 "raw_ostream destructor called with non-empty buffer!");
84
Daniel Dunbar317a6cd2009-08-18 23:42:36 +000085 if (BufferMode == InternalBuffer)
86 delete [] OutBufStart;
Dan Gohman58fcef92009-07-15 23:25:33 +000087}
Chris Lattnerd564f292008-08-22 15:45:00 +000088
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +000089size_t raw_ostream::preferred_buffer_size() const {
Dan Gohman84487b92009-08-13 17:27:29 +000090 // BUFSIZ is intended to be a reasonable default.
91 return BUFSIZ;
92}
93
94void raw_ostream::SetBuffered() {
95 // Ask the subclass to determine an appropriate buffer size.
Dan Gohman17710222009-08-15 02:05:19 +000096 if (size_t Size = preferred_buffer_size())
97 SetBufferSize(Size);
98 else
99 // It may return 0, meaning this stream should be unbuffered.
100 SetUnbuffered();
Dan Gohman84487b92009-08-13 17:27:29 +0000101}
102
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000103void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
Nick Lewycky7bfd86d2011-08-28 03:30:02 +0000104 BufferKind Mode) {
Craig Topper2617dcc2014-04-15 06:32:26 +0000105 assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
106 (Mode != Unbuffered && BufferStart && Size != 0)) &&
Daniel Dunbar316b4a02009-09-15 20:31:46 +0000107 "stream must be unbuffered or have at least one byte");
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000108 // Make sure the current buffer is free of content (we can't flush here; the
109 // child buffer management logic will be in write_impl).
110 assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
Dan Gohman54401d42009-08-13 15:58:55 +0000111
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000112 if (BufferMode == InternalBuffer)
113 delete [] OutBufStart;
114 OutBufStart = BufferStart;
Dan Gohman54401d42009-08-13 15:58:55 +0000115 OutBufEnd = OutBufStart+Size;
116 OutBufCur = OutBufStart;
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000117 BufferMode = Mode;
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000118
119 assert(OutBufStart <= OutBufEnd && "Invalid size!");
Dan Gohman54401d42009-08-13 15:58:55 +0000120}
121
Owen Andersond2850532008-08-21 20:58:52 +0000122raw_ostream &raw_ostream::operator<<(unsigned long N) {
Zachary Turner11db2642016-11-11 23:57:40 +0000123 write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
Zachary Turner733be512016-10-11 19:24:45 +0000124 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000125}
126
127raw_ostream &raw_ostream::operator<<(long N) {
Zachary Turner11db2642016-11-11 23:57:40 +0000128 write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
Zachary Turner733be512016-10-11 19:24:45 +0000129 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000130}
131
132raw_ostream &raw_ostream::operator<<(unsigned long long N) {
Zachary Turner11db2642016-11-11 23:57:40 +0000133 write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
Zachary Turner733be512016-10-11 19:24:45 +0000134 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000135}
136
137raw_ostream &raw_ostream::operator<<(long long N) {
Zachary Turner11db2642016-11-11 23:57:40 +0000138 write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
Zachary Turner733be512016-10-11 19:24:45 +0000139 return *this;
Owen Andersond2850532008-08-21 20:58:52 +0000140}
141
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000142raw_ostream &raw_ostream::write_hex(unsigned long long N) {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000143 llvm::write_hex(*this, N, HexPrintStyle::Lower);
Zachary Turner733be512016-10-11 19:24:45 +0000144 return *this;
Chris Lattner0c19df42008-08-23 22:23:09 +0000145}
146
Rui Ueyamacac8df12019-08-07 08:08:17 +0000147raw_ostream &raw_ostream::operator<<(Colors C) {
148 if (C == Colors::RESET)
149 resetColor();
150 else
151 changeColor(C);
152 return *this;
153}
154
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000155raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) {
156 for (int Idx = 0; Idx < 16; ++Idx) {
157 *this << format("%02" PRIX32, UUID[Idx]);
158 if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
159 *this << "-";
160 }
161 return *this;
162}
163
164
Daniel Dunbar65dc8912010-11-27 07:59:50 +0000165raw_ostream &raw_ostream::write_escaped(StringRef Str,
166 bool UseHexEscapes) {
Craig Topper775fb732016-02-04 06:51:41 +0000167 for (unsigned char c : Str) {
Daniel Dunbar4108c432009-10-17 20:43:08 +0000168 switch (c) {
169 case '\\':
170 *this << '\\' << '\\';
171 break;
172 case '\t':
173 *this << '\\' << 't';
174 break;
175 case '\n':
176 *this << '\\' << 'n';
177 break;
178 case '"':
179 *this << '\\' << '"';
180 break;
181 default:
Michael Kruse6f1da6e2018-07-26 15:31:41 +0000182 if (isPrint(c)) {
Daniel Dunbar4108c432009-10-17 20:43:08 +0000183 *this << c;
184 break;
185 }
186
Daniel Dunbar65dc8912010-11-27 07:59:50 +0000187 // Write out the escaped representation.
188 if (UseHexEscapes) {
189 *this << '\\' << 'x';
190 *this << hexdigit((c >> 4 & 0xF));
191 *this << hexdigit((c >> 0) & 0xF);
192 } else {
193 // Always use a full 3-character octal escape.
194 *this << '\\';
195 *this << char('0' + ((c >> 6) & 7));
196 *this << char('0' + ((c >> 3) & 7));
197 *this << char('0' + ((c >> 0) & 7));
198 }
Daniel Dunbar4108c432009-10-17 20:43:08 +0000199 }
200 }
201
202 return *this;
203}
204
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000205raw_ostream &raw_ostream::operator<<(const void *P) {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000206 llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
Zachary Turner733be512016-10-11 19:24:45 +0000207 return *this;
Daniel Dunbar6c9629b2009-07-30 18:21:23 +0000208}
209
Chris Lattner06fa1762009-08-24 03:52:50 +0000210raw_ostream &raw_ostream::operator<<(double N) {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000211 llvm::write_double(*this, N, FloatStyle::Exponent);
Zachary Turner733be512016-10-11 19:24:45 +0000212 return *this;
Chris Lattner06fa1762009-08-24 03:52:50 +0000213}
214
Daniel Dunbard24535f2009-03-16 22:55:06 +0000215void raw_ostream::flush_nonempty() {
216 assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000217 size_t Length = OutBufCur - OutBufStart;
218 OutBufCur = OutBufStart;
219 write_impl(OutBufStart, Length);
Daniel Dunbard24535f2009-03-16 22:55:06 +0000220}
221
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000222raw_ostream &raw_ostream::write(unsigned char C) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000223 // Group exceptional cases into a single branch.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000224 if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
225 if (LLVM_UNLIKELY(!OutBufStart)) {
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000226 if (BufferMode == Unbuffered) {
Dan Gohman23f90c12009-08-18 20:09:59 +0000227 write_impl(reinterpret_cast<char*>(&C), 1);
228 return *this;
229 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000230 // Set up a buffer and start over.
231 SetBuffered();
232 return write(C);
Dan Gohman23f90c12009-08-18 20:09:59 +0000233 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000234
235 flush_nonempty();
Daniel Dunbar2d603da2009-03-17 01:13:35 +0000236 }
237
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000238 *OutBufCur++ = C;
Daniel Dunbar87862182009-03-16 22:08:44 +0000239 return *this;
Daniel Dunbar7a9bb9e2009-03-16 22:00:17 +0000240}
Chris Lattner0c19df42008-08-23 22:23:09 +0000241
Dan Gohmanf199ad62009-07-16 15:24:40 +0000242raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000243 // Group exceptional cases into a single branch.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000244 if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
245 if (LLVM_UNLIKELY(!OutBufStart)) {
Daniel Dunbar317a6cd2009-08-18 23:42:36 +0000246 if (BufferMode == Unbuffered) {
Dan Gohman52022c22009-08-13 15:44:52 +0000247 write_impl(Ptr, Size);
248 return *this;
249 }
250 // Set up a buffer and start over.
Dan Gohman84487b92009-08-13 17:27:29 +0000251 SetBuffered();
Dan Gohman52022c22009-08-13 15:44:52 +0000252 return write(Ptr, Size);
253 }
Daniel Dunbar0cf16862009-08-19 00:23:39 +0000254
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000255 size_t NumBytes = OutBufEnd - OutBufCur;
256
Benjamin Krameracf08422011-03-04 18:18:16 +0000257 // If the buffer is empty at this point we have a string that is larger
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000258 // than the buffer. Directly write the chunk that is a multiple of the
259 // preferred buffer size and put the remainder in the buffer.
Benjamin Kramerbd7f8d02012-08-29 22:57:00 +0000260 if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
Michael Ilseman5be22a12014-12-12 21:48:03 +0000261 assert(NumBytes != 0 && "undefined behavior");
Benjamin Kramerdfb0ad32011-03-04 19:49:30 +0000262 size_t BytesToWrite = Size - (Size % NumBytes);
263 write_impl(Ptr, BytesToWrite);
Matt Beaumont-Gaya182be82013-03-12 23:55:24 +0000264 size_t BytesRemaining = Size - BytesToWrite;
265 if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
266 // Too much left over to copy into our buffer.
267 return write(Ptr + BytesToWrite, BytesRemaining);
268 }
269 copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
Benjamin Krameracf08422011-03-04 18:18:16 +0000270 return *this;
271 }
272
273 // We don't have enough space in the buffer to fit the string in. Insert as
274 // much as possible, flush and start over with the remainder.
Benjamin Krameracf08422011-03-04 18:18:16 +0000275 copy_to_buffer(Ptr, NumBytes);
276 flush_nonempty();
277 return write(Ptr + NumBytes, Size - NumBytes);
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000278 }
Dan Gohman52022c22009-08-13 15:44:52 +0000279
280 copy_to_buffer(Ptr, Size);
281
282 return *this;
283}
284
285void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
Dan Gohmanc04a00a2009-08-13 20:32:03 +0000286 assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
Dan Gohman98205552009-08-13 18:38:15 +0000287
Owen Andersond2850532008-08-21 20:58:52 +0000288 // Handle short strings specially, memcpy isn't very good at very short
289 // strings.
290 switch (Size) {
Justin Bognercd1d5aa2016-08-17 20:30:52 +0000291 case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
292 case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
293 case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
294 case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
Owen Andersond2850532008-08-21 20:58:52 +0000295 case 0: break;
296 default:
Dan Gohman52022c22009-08-13 15:44:52 +0000297 memcpy(OutBufCur, Ptr, Size);
Owen Andersond2850532008-08-21 20:58:52 +0000298 break;
299 }
Daniel Dunbar3da6a702009-03-10 16:21:55 +0000300
Dan Gohman52022c22009-08-13 15:44:52 +0000301 OutBufCur += Size;
Owen Andersond2850532008-08-21 20:58:52 +0000302}
303
Chris Lattner22b52c92008-08-23 19:23:10 +0000304// Formatted output.
305raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
Daniel Dunbar64fa3862009-03-17 01:36:56 +0000306 // If we have more than a few bytes left in our output buffer, try
307 // formatting directly onto its end.
Dan Gohmanf199ad62009-07-16 15:24:40 +0000308 size_t NextBufferSize = 127;
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000309 size_t BufferBytesLeft = OutBufEnd - OutBufCur;
310 if (BufferBytesLeft > 3) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000311 size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000312
Chris Lattner22b52c92008-08-23 19:23:10 +0000313 // Common case is that we have plenty of space.
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000314 if (BytesUsed <= BufferBytesLeft) {
Chris Lattner22b52c92008-08-23 19:23:10 +0000315 OutBufCur += BytesUsed;
316 return *this;
317 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000318
Chris Lattner22b52c92008-08-23 19:23:10 +0000319 // Otherwise, we overflowed and the return value tells us the size to try
320 // again with.
321 NextBufferSize = BytesUsed;
322 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000323
Chris Lattner22b52c92008-08-23 19:23:10 +0000324 // If we got here, we didn't have enough space in the output buffer for the
325 // string. Try printing into a SmallVector that is resized to have enough
326 // space. Iterate until we win.
327 SmallVector<char, 128> V;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000328
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000329 while (true) {
Chris Lattner22b52c92008-08-23 19:23:10 +0000330 V.resize(NextBufferSize);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000331
Chris Lattner22b52c92008-08-23 19:23:10 +0000332 // Try formatting into the SmallVector.
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000333 size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000334
Chris Lattner22b52c92008-08-23 19:23:10 +0000335 // If BytesUsed fit into the vector, we win.
Chris Lattner2bfc72e2008-10-26 19:20:47 +0000336 if (BytesUsed <= NextBufferSize)
Daniel Dunbar47a309c2009-08-23 20:31:39 +0000337 return write(V.data(), BytesUsed);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000338
Chris Lattner22b52c92008-08-23 19:23:10 +0000339 // Otherwise, try again with a new size.
340 assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
341 NextBufferSize = BytesUsed;
342 }
343}
344
Zachary Turner11db2642016-11-11 23:57:40 +0000345raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
346 SmallString<128> S;
347 Obj.format(*this);
348 return *this;
349}
350
Nick Kledzike6480372014-09-25 20:30:58 +0000351raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
Frederich Munch5e9d6d02017-07-13 16:11:08 +0000352 if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) {
353 this->operator<<(FS.Str);
354 return *this;
355 }
356 const size_t Difference = FS.Width - FS.Str.size();
357 switch (FS.Justify) {
358 case FormattedString::JustifyLeft:
359 this->operator<<(FS.Str);
360 this->indent(Difference);
361 break;
362 case FormattedString::JustifyRight:
363 this->indent(Difference);
364 this->operator<<(FS.Str);
365 break;
366 case FormattedString::JustifyCenter: {
367 int PadAmount = Difference / 2;
Nick Kledzike6480372014-09-25 20:30:58 +0000368 this->indent(PadAmount);
Frederich Munch5e9d6d02017-07-13 16:11:08 +0000369 this->operator<<(FS.Str);
370 this->indent(Difference - PadAmount);
371 break;
372 }
373 default:
374 llvm_unreachable("Bad Justification");
375 }
Nick Kledzike6480372014-09-25 20:30:58 +0000376 return *this;
377}
378
379raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
380 if (FN.Hex) {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000381 HexPrintStyle Style;
382 if (FN.Upper && FN.HexPrefix)
383 Style = HexPrintStyle::PrefixUpper;
384 else if (FN.Upper && !FN.HexPrefix)
385 Style = HexPrintStyle::Upper;
386 else if (!FN.Upper && FN.HexPrefix)
387 Style = HexPrintStyle::PrefixLower;
388 else
389 Style = HexPrintStyle::Lower;
390 llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
Nick Kledzike6480372014-09-25 20:30:58 +0000391 } else {
Zachary Turner5b2243e2016-10-29 00:27:22 +0000392 llvm::SmallString<16> Buffer;
393 llvm::raw_svector_ostream Stream(Buffer);
Zachary Turner11db2642016-11-11 23:57:40 +0000394 llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
Zachary Turner5b2243e2016-10-29 00:27:22 +0000395 if (Buffer.size() < FN.Width)
396 indent(FN.Width - Buffer.size());
397 (*this) << Buffer;
Nick Kledzike6480372014-09-25 20:30:58 +0000398 }
Zachary Turner733be512016-10-11 19:24:45 +0000399 return *this;
Nick Kledzike6480372014-09-25 20:30:58 +0000400}
401
Zachary Turner4a86af02016-11-10 20:16:45 +0000402raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
403 if (FB.Bytes.empty())
404 return *this;
405
Greg Claytonbde0a162016-11-09 00:15:54 +0000406 size_t LineIndex = 0;
Zachary Turner4a86af02016-11-10 20:16:45 +0000407 auto Bytes = FB.Bytes;
408 const size_t Size = Bytes.size();
409 HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower;
410 uint64_t OffsetWidth = 0;
411 if (FB.FirstByteOffset.hasValue()) {
412 // Figure out how many nibbles are needed to print the largest offset
413 // represented by this data set, so that we can align the offset field
414 // to the right width.
415 size_t Lines = Size / FB.NumPerLine;
416 uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
417 unsigned Power = 0;
418 if (MaxOffset > 0)
419 Power = llvm::Log2_64_Ceil(MaxOffset);
Zachary Turner805d43a2016-11-10 20:35:21 +0000420 OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
Zachary Turner4a86af02016-11-10 20:16:45 +0000421 }
422
423 // The width of a block of data including all spaces for group separators.
424 unsigned NumByteGroups =
425 alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
426 unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
427
428 while (!Bytes.empty()) {
429 indent(FB.IndentLevel);
430
Greg Claytonbde0a162016-11-09 00:15:54 +0000431 if (FB.FirstByteOffset.hasValue()) {
432 uint64_t Offset = FB.FirstByteOffset.getValue();
Zachary Turner4a86af02016-11-10 20:16:45 +0000433 llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
Greg Claytonbde0a162016-11-09 00:15:54 +0000434 *this << ": ";
435 }
Zachary Turner4a86af02016-11-10 20:16:45 +0000436
437 auto Line = Bytes.take_front(FB.NumPerLine);
438
439 size_t CharsPrinted = 0;
440 // Print the hex bytes for this line in groups
441 for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
442 if (I && (I % FB.ByteGroupSize) == 0) {
443 ++CharsPrinted;
Greg Claytonbde0a162016-11-09 00:15:54 +0000444 *this << " ";
Zachary Turner4a86af02016-11-10 20:16:45 +0000445 }
446 llvm::write_hex(*this, Line[I], HPS, 2);
Greg Claytonbde0a162016-11-09 00:15:54 +0000447 }
Zachary Turner4a86af02016-11-10 20:16:45 +0000448
Greg Claytonbde0a162016-11-09 00:15:54 +0000449 if (FB.ASCII) {
450 // Print any spaces needed for any bytes that we didn't print on this
451 // line so that the ASCII bytes are correctly aligned.
Zachary Turner4a86af02016-11-10 20:16:45 +0000452 assert(BlockCharWidth >= CharsPrinted);
453 indent(BlockCharWidth - CharsPrinted + 2);
454 *this << "|";
455
Greg Claytonbde0a162016-11-09 00:15:54 +0000456 // Print the ASCII char values for each byte on this line
Zachary Turner4a86af02016-11-10 20:16:45 +0000457 for (uint8_t Byte : Line) {
Michael Kruse6f1da6e2018-07-26 15:31:41 +0000458 if (isPrint(Byte))
Zachary Turner4a86af02016-11-10 20:16:45 +0000459 *this << static_cast<char>(Byte);
Greg Claytonbde0a162016-11-09 00:15:54 +0000460 else
461 *this << '.';
462 }
463 *this << '|';
464 }
Zachary Turner4a86af02016-11-10 20:16:45 +0000465
466 Bytes = Bytes.drop_front(Line.size());
467 LineIndex += Line.size();
Greg Claytonbde0a162016-11-09 00:15:54 +0000468 if (LineIndex < Size)
469 *this << '\n';
470 }
471 return *this;
472}
473
Peter Collingbourne070777d2018-05-17 22:11:43 +0000474template <char C>
475static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) {
476 static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
477 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
478 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
479 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
480 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C};
Chris Lattnere6db2c32009-08-22 23:10:29 +0000481
482 // Usually the indentation is small, handle it with a fastpath.
Peter Collingbourne070777d2018-05-17 22:11:43 +0000483 if (NumChars < array_lengthof(Chars))
484 return OS.write(Chars, NumChars);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000485
Peter Collingbourne070777d2018-05-17 22:11:43 +0000486 while (NumChars) {
487 unsigned NumToWrite = std::min(NumChars,
488 (unsigned)array_lengthof(Chars)-1);
489 OS.write(Chars, NumToWrite);
490 NumChars -= NumToWrite;
Chris Lattnere6db2c32009-08-22 23:10:29 +0000491 }
Peter Collingbourne070777d2018-05-17 22:11:43 +0000492 return OS;
493}
494
495/// indent - Insert 'NumSpaces' spaces.
496raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
497 return write_padding<' '>(*this, NumSpaces);
498}
499
500/// write_zeros - Insert 'NumZeros' nulls.
501raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) {
502 return write_padding<'\0'>(*this, NumZeros);
Chris Lattnere6db2c32009-08-22 23:10:29 +0000503}
504
Weiming Zhao1bd40002018-04-11 23:09:20 +0000505void raw_ostream::anchor() {}
506
Chris Lattner22b52c92008-08-23 19:23:10 +0000507//===----------------------------------------------------------------------===//
508// Formatted Output
509//===----------------------------------------------------------------------===//
510
511// Out of line virtual method.
512void format_object_base::home() {
513}
514
Chris Lattner84b94f72008-08-17 01:35:29 +0000515//===----------------------------------------------------------------------===//
516// raw_fd_ostream
517//===----------------------------------------------------------------------===//
518
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000519static int getFD(StringRef Filename, std::error_code &EC,
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000520 sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000521 sys::fs::OpenFlags Flags) {
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000522 assert((Access & sys::fs::FA_Write) &&
523 "Cannot make a raw_ostream from a read-only descriptor!");
524
Dan Gohmanc825cee2010-08-18 22:26:19 +0000525 // Handle "-" as stdout. Note that when we do this, we consider ourself
Yaron Keren80745c52017-03-31 12:08:45 +0000526 // the owner of stdout and may set the "binary" flag globally based on Flags.
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000527 if (Filename == "-") {
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000528 EC = std::error_code();
Daniel Dunbared90e702008-11-13 05:01:07 +0000529 // If user requested binary then put stdout into binary mode if
530 // possible.
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000531 if (!(Flags & sys::fs::OF_Text))
Rafael Espindolacb2eca02013-06-12 20:58:35 +0000532 sys::ChangeStdoutToBinary();
Yaron Keren9d27c472017-03-30 19:30:51 +0000533 return STDOUT_FILENO;
Chris Lattnerd5bc0682008-08-17 03:53:23 +0000534 }
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000535
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000536 int FD;
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000537 if (Access & sys::fs::FA_Read)
538 EC = sys::fs::openFileForReadWrite(Filename, FD, Disp, Flags);
539 else
540 EC = sys::fs::openFileForWrite(Filename, FD, Disp, Flags);
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000541 if (EC)
542 return -1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000543
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000544 return FD;
Chris Lattner84b94f72008-08-17 01:35:29 +0000545}
546
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000547raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC)
548 : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
549 sys::fs::OF_None) {}
550
551raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
552 sys::fs::CreationDisposition Disp)
553 : raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {}
554
555raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
556 sys::fs::FileAccess Access)
557 : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, Access,
558 sys::fs::OF_None) {}
559
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000560raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
561 sys::fs::OpenFlags Flags)
Zachary Turner1f67a3c2018-06-07 19:58:58 +0000562 : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
563 Flags) {}
564
565raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
566 sys::fs::CreationDisposition Disp,
567 sys::fs::FileAccess Access,
568 sys::fs::OpenFlags Flags)
569 : raw_fd_ostream(getFD(Filename, EC, Disp, Access, Flags), true) {}
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000570
Rafael Espindola62e6ec02015-04-09 16:59:07 +0000571/// FD is the file descriptor that this writes to. If ShouldClose is true, this
572/// closes the file when the stream is destroyed.
Francois Picheta3037c32010-10-14 20:30:58 +0000573raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
Rui Ueyama4d41c332019-08-02 07:22:34 +0000574 : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) {
575 if (FD < 0 ) {
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000576 ShouldClose = false;
577 return;
578 }
Reid Kleckner02aeadc2017-08-04 01:39:23 +0000579
580 // Do not attempt to close stdout or stderr. We used to try to maintain the
581 // property that tools that support writing file to stdout should not also
582 // write informational output to stdout, but in practice we were never able to
583 // maintain this invariant. Many features have been added to LLVM and clang
584 // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so
585 // users must simply be aware that mixed output and remarks is a possibility.
Yaron Keren9d27c472017-03-30 19:30:51 +0000586 if (FD <= STDERR_FILENO)
587 ShouldClose = false;
Michael J. Spencerb7479902011-01-17 15:53:12 +0000588
Reid Kleckner2b8c6922018-09-05 00:08:56 +0000589#ifdef _WIN32
590 // Check if this is a console device. This is not equivalent to isatty.
591 IsWindowsConsole =
592 ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
593#endif
594
Michael J. Spencerb7479902011-01-17 15:53:12 +0000595 // Get the starting position.
596 off_t loc = ::lseek(FD, 0, SEEK_CUR);
Nico Weber712e8d22018-04-29 00:45:03 +0000597#ifdef _WIN32
Rafael Espindolaa9b84ab2015-04-13 11:09:48 +0000598 // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
599 sys::fs::file_status Status;
600 std::error_code EC = status(FD, Status);
601 SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
602#else
Rafael Espindola74d2f612015-04-10 18:15:51 +0000603 SupportsSeeking = loc != (off_t)-1;
Rafael Espindolaa9b84ab2015-04-13 11:09:48 +0000604#endif
Rafael Espindola74d2f612015-04-10 18:15:51 +0000605 if (!SupportsSeeking)
Michael J. Spencerb7479902011-01-17 15:53:12 +0000606 pos = 0;
607 else
608 pos = static_cast<uint64_t>(loc);
Francois Picheta3037c32010-10-14 20:30:58 +0000609}
610
Chris Lattner84b94f72008-08-17 01:35:29 +0000611raw_fd_ostream::~raw_fd_ostream() {
Dan Gohman38adfdd2010-08-20 16:34:20 +0000612 if (FD >= 0) {
613 flush();
Bob Haarman9ce2d032017-10-24 01:26:22 +0000614 if (ShouldClose) {
615 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
616 error_detected(EC);
617 }
Dan Gohman38adfdd2010-08-20 16:34:20 +0000618 }
619
NAKAMURA Takumi76e68ea2011-03-16 02:53:39 +0000620#ifdef __MINGW32__
621 // On mingw, global dtors should not call exit().
622 // report_fatal_error() invokes exit(). We know report_fatal_error()
623 // might not write messages to stderr when any errors were detected
624 // on FD == 2.
625 if (FD == 2) return;
626#endif
627
Dan Gohman38adfdd2010-08-20 16:34:20 +0000628 // If there are any pending errors, report them now. Clients wishing
629 // to avoid report_fatal_error calls should check for errors with
630 // has_error() and clear the error flag with clear_error() before
631 // destructing raw_ostream objects which may have errors.
632 if (has_error())
Bob Haarman9ce2d032017-10-24 01:26:22 +0000633 report_fatal_error("IO failure on output stream: " + error().message(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000634 /*gen_crash_diag=*/false);
Chris Lattnerce3b2c32010-08-17 23:11:56 +0000635}
Chris Lattner9e6f1f12009-08-23 02:51:22 +0000636
Reid Kleckner2b8c6922018-09-05 00:08:56 +0000637#if defined(_WIN32)
638// The most reliable way to print unicode in a Windows console is with
639// WriteConsoleW. To use that, first transcode from UTF-8 to UTF-16. This
640// assumes that LLVM programs always print valid UTF-8 to the console. The data
641// might not be UTF-8 for two major reasons:
642// 1. The program is printing binary (-filetype=obj -o -), in which case it
643// would have been gibberish anyway.
644// 2. The program is printing text in a semi-ascii compatible codepage like
645// shift-jis or cp1252.
646//
647// Most LLVM programs don't produce non-ascii text unless they are quoting
648// user source input. A well-behaved LLVM program should either validate that
649// the input is UTF-8 or transcode from the local codepage to UTF-8 before
650// quoting it. If they don't, this may mess up the encoding, but this is still
651// probably the best compromise we can make.
652static bool write_console_impl(int FD, StringRef Data) {
653 SmallVector<wchar_t, 256> WideText;
654
655 // Fall back to ::write if it wasn't valid UTF-8.
656 if (auto EC = sys::windows::UTF8ToUTF16(Data, WideText))
657 return false;
658
659 // On Windows 7 and earlier, WriteConsoleW has a low maximum amount of data
660 // that can be written to the console at a time.
661 size_t MaxWriteSize = WideText.size();
662 if (!RunningWindows8OrGreater())
663 MaxWriteSize = 32767;
664
665 size_t WCharsWritten = 0;
666 do {
667 size_t WCharsToWrite =
668 std::min(MaxWriteSize, WideText.size() - WCharsWritten);
669 DWORD ActuallyWritten;
670 bool Success =
671 ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten],
672 WCharsToWrite, &ActuallyWritten,
673 /*Reserved=*/nullptr);
674
675 // The most likely reason for WriteConsoleW to fail is that FD no longer
676 // points to a console. Fall back to ::write. If this isn't the first loop
677 // iteration, something is truly wrong.
678 if (!Success)
679 return false;
680
681 WCharsWritten += ActuallyWritten;
682 } while (WCharsWritten != WideText.size());
683 return true;
684}
685#endif
686
Dan Gohmanf199ad62009-07-16 15:24:40 +0000687void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000688 assert(FD >= 0 && "File already closed.");
Daniel Dunbardb7a36c2009-03-16 23:29:31 +0000689 pos += Size;
Dan Gohmanef969f32010-05-06 01:27:36 +0000690
Reid Kleckner2b8c6922018-09-05 00:08:56 +0000691#if defined(_WIN32)
692 // If this is a Windows console device, try re-encoding from UTF-8 to UTF-16
693 // and using WriteConsoleW. If that fails, fall back to plain write().
694 if (IsWindowsConsole)
695 if (write_console_impl(FD, StringRef(Ptr, Size)))
696 return;
697#endif
698
Owen Reynoldsa489d112018-08-06 16:21:41 +0000699 // The maximum write size is limited to INT32_MAX. A write
700 // greater than SSIZE_MAX is implementation-defined in POSIX,
701 // and Windows _write requires 32 bit input.
702 size_t MaxWriteSize = INT32_MAX;
Rui Ueyama412b29e2017-10-31 17:37:20 +0000703
Saleem Abdulrasool8199dad2017-06-20 20:51:51 +0000704#if defined(__linux__)
Rui Ueyama412b29e2017-10-31 17:37:20 +0000705 // It is observed that Linux returns EINVAL for a very large write (>2G).
706 // Make it a reasonably small value.
707 MaxWriteSize = 1024 * 1024 * 1024;
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +0000708#endif
709
Benjamin Kramerce84a252010-05-05 15:17:47 +0000710 do {
Rui Ueyama412b29e2017-10-31 17:37:20 +0000711 size_t ChunkSize = std::min(Size, MaxWriteSize);
Yunzhong Gaofb2a9c42016-01-06 00:50:06 +0000712 ssize_t ret = ::write(FD, Ptr, ChunkSize);
Dan Gohmanef969f32010-05-06 01:27:36 +0000713
714 if (ret < 0) {
715 // If it's a recoverable error, swallow it and retry the write.
Dan Gohmandea53102010-05-18 15:25:14 +0000716 //
717 // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
718 // raw_ostream isn't designed to do non-blocking I/O. However, some
719 // programs, such as old versions of bjam, have mistakenly used
720 // O_NONBLOCK. For compatibility, emulate blocking semantics by
721 // spinning until the write succeeds. If you don't want spinning,
722 // don't use O_NONBLOCK file descriptors with raw_ostream.
Dan Gohmand3511162010-05-06 02:06:20 +0000723 if (errno == EINTR || errno == EAGAIN
724#ifdef EWOULDBLOCK
725 || errno == EWOULDBLOCK
726#endif
727 )
Dan Gohmanef969f32010-05-06 01:27:36 +0000728 continue;
729
730 // Otherwise it's a non-recoverable error. Note it and quit.
Bob Haarman9ce2d032017-10-24 01:26:22 +0000731 error_detected(std::error_code(errno, std::generic_category()));
Dan Gohmanef969f32010-05-06 01:27:36 +0000732 break;
733 }
734
735 // The write may have written some or all of the data. Update the
736 // size and buffer pointer to reflect the remainder that needs
737 // to be written. If there are no bytes left, we're done.
738 Ptr += ret;
739 Size -= ret;
740 } while (Size > 0);
Chris Lattner84b94f72008-08-17 01:35:29 +0000741}
742
Dan Gohman44790e72010-08-18 01:34:52 +0000743void raw_fd_ostream::close() {
744 assert(ShouldClose);
745 ShouldClose = false;
746 flush();
Bob Haarman9ce2d032017-10-24 01:26:22 +0000747 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
748 error_detected(EC);
Dan Gohman44790e72010-08-18 01:34:52 +0000749 FD = -1;
750}
751
Ted Kremeneka2669922009-01-26 21:42:04 +0000752uint64_t raw_fd_ostream::seek(uint64_t off) {
Yaron Keren7cf7f802016-02-23 07:17:58 +0000753 assert(SupportsSeeking && "Stream does not support seeking!");
Ted Kremeneka2669922009-01-26 21:42:04 +0000754 flush();
Nico Weber712e8d22018-04-29 00:45:03 +0000755#ifdef _WIN32
Peter Collingbourne8db7e5e2016-12-09 05:20:43 +0000756 pos = ::_lseeki64(FD, off, SEEK_SET);
757#elif defined(HAVE_LSEEK64)
758 pos = ::lseek64(FD, off, SEEK_SET);
759#else
Peter Collingbournef74fcdd2016-12-09 05:04:30 +0000760 pos = ::lseek(FD, off, SEEK_SET);
Peter Collingbourne8db7e5e2016-12-09 05:20:43 +0000761#endif
Rafael Espindola642a2212015-04-14 22:54:16 +0000762 if (pos == (uint64_t)-1)
Bob Haarman9ce2d032017-10-24 01:26:22 +0000763 error_detected(std::error_code(errno, std::generic_category()));
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000764 return pos;
Ted Kremeneka2669922009-01-26 21:42:04 +0000765}
766
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000767void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
768 uint64_t Offset) {
Rafael Espindola37b70152015-04-14 15:00:34 +0000769 uint64_t Pos = tell();
770 seek(Offset);
771 write(Ptr, Size);
772 seek(Pos);
773}
774
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000775size_t raw_fd_ostream::preferred_buffer_size() const {
Reid Kleckner2b8c6922018-09-05 00:08:56 +0000776#if defined(_WIN32)
777 // Disable buffering for console devices. Console output is re-encoded from
778 // UTF-8 to UTF-16 on Windows, and buffering it would require us to split the
779 // buffer on a valid UTF-8 codepoint boundary. Terminal buffering is disabled
780 // below on most other OSs, so do the same thing on Windows and avoid that
781 // complexity.
782 if (IsWindowsConsole)
783 return 0;
784 return raw_ostream::preferred_buffer_size();
785#elif !defined(__minix)
786 // Minix has no st_blksize.
Dan Gohman84487b92009-08-13 17:27:29 +0000787 assert(FD >= 0 && "File not yet open!");
788 struct stat statbuf;
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000789 if (fstat(FD, &statbuf) != 0)
790 return 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000791
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000792 // If this is a terminal, don't use buffering. Line buffering
793 // would be a more traditional thing to do, but it's not worth
794 // the complexity.
795 if (S_ISCHR(statbuf.st_mode) && isatty(FD))
796 return 0;
797 // Return the preferred block size.
798 return statbuf.st_blksize;
Dan Gohmanfeaeb362010-05-28 16:50:01 +0000799#else
Dan Gohman84487b92009-08-13 17:27:29 +0000800 return raw_ostream::preferred_buffer_size();
Dan Gohmanfeaeb362010-05-28 16:50:01 +0000801#endif
Dan Gohman84487b92009-08-13 17:27:29 +0000802}
803
Rui Ueyama4d41c332019-08-02 07:22:34 +0000804raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
805 bool bg) {
Rui Ueyamacac8df12019-08-07 08:08:17 +0000806 if (!ColorEnabled)
807 return *this;
808
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000809 if (sys::Process::ColorNeedsFlush())
810 flush();
811 const char *colorcode =
Rui Ueyamacac8df12019-08-07 08:08:17 +0000812 (colors == SAVEDCOLOR)
813 ? sys::Process::OutputBold(bg)
814 : sys::Process::OutputColor(static_cast<char>(colors), bold, bg);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000815 if (colorcode) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000816 size_t len = strlen(colorcode);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000817 write(colorcode, len);
818 // don't account colors towards output characters
819 pos -= len;
820 }
821 return *this;
822}
823
824raw_ostream &raw_fd_ostream::resetColor() {
Rui Ueyamacac8df12019-08-07 08:08:17 +0000825 if (!ColorEnabled)
826 return *this;
827
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000828 if (sys::Process::ColorNeedsFlush())
829 flush();
830 const char *colorcode = sys::Process::ResetColor();
831 if (colorcode) {
Dan Gohmanf199ad62009-07-16 15:24:40 +0000832 size_t len = strlen(colorcode);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000833 write(colorcode, len);
834 // don't account colors towards output characters
835 pos -= len;
836 }
837 return *this;
838}
839
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000840raw_ostream &raw_fd_ostream::reverseColor() {
Rui Ueyamacac8df12019-08-07 08:08:17 +0000841 if (!ColorEnabled)
842 return *this;
843
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000844 if (sys::Process::ColorNeedsFlush())
845 flush();
846 const char *colorcode = sys::Process::OutputReverse();
847 if (colorcode) {
848 size_t len = strlen(colorcode);
849 write(colorcode, len);
850 // don't account colors towards output characters
851 pos -= len;
852 }
853 return *this;
854}
855
Dan Gohmane5929232009-09-11 20:46:33 +0000856bool raw_fd_ostream::is_displayed() const {
857 return sys::Process::FileDescriptorIsDisplayed(FD);
858}
859
Daniel Dunbar04b45832012-07-20 18:29:41 +0000860bool raw_fd_ostream::has_colors() const {
861 return sys::Process::FileDescriptorHasColors(FD);
862}
863
Weiming Zhao1bd40002018-04-11 23:09:20 +0000864void raw_fd_ostream::anchor() {}
865
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000866//===----------------------------------------------------------------------===//
Dan Gohmane9a46912010-08-20 16:44:56 +0000867// outs(), errs(), nulls()
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000868//===----------------------------------------------------------------------===//
Chris Lattner84b94f72008-08-17 01:35:29 +0000869
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000870/// outs() - This returns a reference to a raw_ostream for standard output.
871/// Use it like: outs() << "foo" << "bar";
Owen Anderson93719642008-08-21 00:14:44 +0000872raw_ostream &llvm::outs() {
Reid Kleckner02aeadc2017-08-04 01:39:23 +0000873 // Set buffer settings to model stdout behavior.
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000874 std::error_code EC;
Fangrui Songd9b948b2019-08-05 05:43:48 +0000875 static raw_fd_ostream S("-", EC, sys::fs::OF_None);
Rafael Espindola79be4cc2015-04-13 10:28:56 +0000876 assert(!EC);
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000877 return S;
878}
879
880/// errs() - This returns a reference to a raw_ostream for standard error.
881/// Use it like: errs() << "foo" << "bar";
Owen Anderson93719642008-08-21 00:14:44 +0000882raw_ostream &llvm::errs() {
Dan Gohman443f2d62010-08-20 16:39:41 +0000883 // Set standard error to be unbuffered by default.
884 static raw_fd_ostream S(STDERR_FILENO, false, true);
Chris Lattnerd3723fc2008-08-17 04:13:37 +0000885 return S;
886}
887
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000888/// nulls() - This returns a reference to a raw_ostream which discards output.
889raw_ostream &llvm::nulls() {
890 static raw_null_ostream S;
891 return S;
892}
893
Chris Lattner205af962008-08-23 22:43:04 +0000894//===----------------------------------------------------------------------===//
895// raw_string_ostream
896//===----------------------------------------------------------------------===//
897
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000898raw_string_ostream::~raw_string_ostream() {
899 flush();
900}
901
Dan Gohmanf199ad62009-07-16 15:24:40 +0000902void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
Daniel Dunbardb7a36c2009-03-16 23:29:31 +0000903 OS.append(Ptr, Size);
Chris Lattner205af962008-08-23 22:43:04 +0000904}
905
906//===----------------------------------------------------------------------===//
907// raw_svector_ostream
908//===----------------------------------------------------------------------===//
909
Yaron Keren3d1173b2015-08-13 06:19:52 +0000910uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
Daniel Dunbarb090bf42009-08-19 17:54:29 +0000911
Yaron Keren3d1173b2015-08-13 06:19:52 +0000912void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
913 OS.append(Ptr, Ptr + Size);
Nick Lewyckye2f6fb52015-08-13 18:10:19 +0000914}
Daniel Dunbard882f4b2009-08-18 20:07:36 +0000915
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000916void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
917 uint64_t Offset) {
Yaron Keren3d1173b2015-08-13 06:19:52 +0000918 memcpy(OS.data() + Offset, Ptr, Size);
Daniel Dunbare813cba2009-08-19 18:40:58 +0000919}
920
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000921//===----------------------------------------------------------------------===//
922// raw_null_ostream
923//===----------------------------------------------------------------------===//
924
Dan Gohman4b66b472009-07-27 21:46:02 +0000925raw_null_ostream::~raw_null_ostream() {
926#ifndef NDEBUG
927 // ~raw_ostream asserts that the buffer is empty. This isn't necessary
928 // with raw_null_ostream, but it's better to have raw_null_ostream follow
929 // the rules than to change the rules just for raw_null_ostream.
930 flush();
931#endif
932}
933
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000934void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
935}
936
Chris Lattnerdd3e9aa2009-12-19 01:38:42 +0000937uint64_t raw_null_ostream::current_pos() const {
Daniel Dunbar95a551a2009-07-16 21:17:53 +0000938 return 0;
939}
Rafael Espindola37b70152015-04-14 15:00:34 +0000940
Rafael Espindola4ba9af12015-04-20 13:04:30 +0000941void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
942 uint64_t Offset) {}
Weiming Zhao1bd40002018-04-11 23:09:20 +0000943
944void raw_pwrite_stream::anchor() {}
Richard Trieua87b70d2018-12-29 02:02:13 +0000945
946void buffer_ostream::anchor() {}