/home/arjun/llvm-project/llvm/lib/Support/raw_ostream.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===// |
2 | | // |
3 | | // 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 |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | // |
9 | | // This implements support for bulk buffered stream output. |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | |
13 | | #include "llvm/Support/raw_ostream.h" |
14 | | #include "llvm/ADT/STLExtras.h" |
15 | | #include "llvm/ADT/SmallVector.h" |
16 | | #include "llvm/ADT/StringExtras.h" |
17 | | #include "llvm/Config/config.h" |
18 | | #include "llvm/Support/Compiler.h" |
19 | | #include "llvm/Support/ErrorHandling.h" |
20 | | #include "llvm/Support/FileSystem.h" |
21 | | #include "llvm/Support/Format.h" |
22 | | #include "llvm/Support/FormatVariadic.h" |
23 | | #include "llvm/Support/MathExtras.h" |
24 | | #include "llvm/Support/NativeFormatting.h" |
25 | | #include "llvm/Support/Process.h" |
26 | | #include "llvm/Support/Program.h" |
27 | | #include <algorithm> |
28 | | #include <cctype> |
29 | | #include <cerrno> |
30 | | #include <cstdio> |
31 | | #include <iterator> |
32 | | #include <sys/stat.h> |
33 | | #include <system_error> |
34 | | |
35 | | // <fcntl.h> may provide O_BINARY. |
36 | | #if defined(HAVE_FCNTL_H) |
37 | | # include <fcntl.h> |
38 | | #endif |
39 | | |
40 | | #if defined(HAVE_UNISTD_H) |
41 | | # include <unistd.h> |
42 | | #endif |
43 | | |
44 | | #if defined(__CYGWIN__) |
45 | | #include <io.h> |
46 | | #endif |
47 | | |
48 | | #if defined(_MSC_VER) |
49 | | #include <io.h> |
50 | | #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 |
59 | | #endif |
60 | | |
61 | | #ifdef _WIN32 |
62 | | #include "llvm/Support/ConvertUTF.h" |
63 | | #include "llvm/Support/Windows/WindowsSupport.h" |
64 | | #endif |
65 | | |
66 | | using namespace llvm; |
67 | | |
68 | | constexpr raw_ostream::Colors raw_ostream::BLACK; |
69 | | constexpr raw_ostream::Colors raw_ostream::RED; |
70 | | constexpr raw_ostream::Colors raw_ostream::GREEN; |
71 | | constexpr raw_ostream::Colors raw_ostream::YELLOW; |
72 | | constexpr raw_ostream::Colors raw_ostream::BLUE; |
73 | | constexpr raw_ostream::Colors raw_ostream::MAGENTA; |
74 | | constexpr raw_ostream::Colors raw_ostream::CYAN; |
75 | | constexpr raw_ostream::Colors raw_ostream::WHITE; |
76 | | constexpr raw_ostream::Colors raw_ostream::SAVEDCOLOR; |
77 | | constexpr raw_ostream::Colors raw_ostream::RESET; |
78 | | |
79 | 692 | raw_ostream::~raw_ostream() { |
80 | 692 | // raw_ostream's subclasses should take care to flush the buffer |
81 | 692 | // in their destructors. |
82 | 692 | assert(OutBufCur == OutBufStart && |
83 | 692 | "raw_ostream destructor called with non-empty buffer!"); |
84 | 692 | |
85 | 692 | if (BufferMode == BufferKind::InternalBuffer) |
86 | 690 | delete [] OutBufStart; |
87 | 692 | } |
88 | | |
89 | 690 | size_t raw_ostream::preferred_buffer_size() const { |
90 | 690 | // BUFSIZ is intended to be a reasonable default. |
91 | 690 | return BUFSIZ; |
92 | 690 | } |
93 | | |
94 | 690 | void raw_ostream::SetBuffered() { |
95 | 690 | // Ask the subclass to determine an appropriate buffer size. |
96 | 690 | if (size_t Size = preferred_buffer_size()) |
97 | 690 | SetBufferSize(Size); |
98 | 0 | else |
99 | 0 | // It may return 0, meaning this stream should be unbuffered. |
100 | 0 | SetUnbuffered(); |
101 | 690 | } |
102 | | |
103 | | void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size, |
104 | 690 | BufferKind Mode) { |
105 | 690 | assert(((Mode == BufferKind::Unbuffered && !BufferStart && Size == 0) || |
106 | 690 | (Mode != BufferKind::Unbuffered && BufferStart && Size != 0)) && |
107 | 690 | "stream must be unbuffered or have at least one byte"); |
108 | 690 | // Make sure the current buffer is free of content (we can't flush here; the |
109 | 690 | // child buffer management logic will be in write_impl). |
110 | 690 | assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!"); |
111 | 690 | |
112 | 690 | if (BufferMode == BufferKind::InternalBuffer) |
113 | 690 | delete [] OutBufStart; |
114 | 690 | OutBufStart = BufferStart; |
115 | 690 | OutBufEnd = OutBufStart+Size; |
116 | 690 | OutBufCur = OutBufStart; |
117 | 690 | BufferMode = Mode; |
118 | 690 | |
119 | 690 | assert(OutBufStart <= OutBufEnd && "Invalid size!"); |
120 | 690 | } |
121 | | |
122 | 0 | raw_ostream &raw_ostream::operator<<(unsigned long N) { |
123 | 0 | write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer); |
124 | 0 | return *this; |
125 | 0 | } |
126 | | |
127 | 20 | raw_ostream &raw_ostream::operator<<(long N) { |
128 | 20 | write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer); |
129 | 20 | return *this; |
130 | 20 | } |
131 | | |
132 | 0 | raw_ostream &raw_ostream::operator<<(unsigned long long N) { |
133 | 0 | write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer); |
134 | 0 | return *this; |
135 | 0 | } |
136 | | |
137 | 16 | raw_ostream &raw_ostream::operator<<(long long N) { |
138 | 16 | write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer); |
139 | 16 | return *this; |
140 | 16 | } |
141 | | |
142 | 0 | raw_ostream &raw_ostream::write_hex(unsigned long long N) { |
143 | 0 | llvm::write_hex(*this, N, HexPrintStyle::Lower); |
144 | 0 | return *this; |
145 | 0 | } |
146 | | |
147 | 0 | raw_ostream &raw_ostream::operator<<(Colors C) { |
148 | 0 | if (C == Colors::RESET) |
149 | 0 | resetColor(); |
150 | 0 | else |
151 | 0 | changeColor(C); |
152 | 0 | return *this; |
153 | 0 | } |
154 | | |
155 | 0 | raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) { |
156 | 0 | for (int Idx = 0; Idx < 16; ++Idx) { |
157 | 0 | *this << format("%02" PRIX32, UUID[Idx]); |
158 | 0 | if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9) |
159 | 0 | *this << "-"; |
160 | 0 | } |
161 | 0 | return *this; |
162 | 0 | } |
163 | | |
164 | | |
165 | | raw_ostream &raw_ostream::write_escaped(StringRef Str, |
166 | 0 | bool UseHexEscapes) { |
167 | 0 | for (unsigned char c : Str) { |
168 | 0 | switch (c) { |
169 | 0 | case '\\': |
170 | 0 | *this << '\\' << '\\'; |
171 | 0 | break; |
172 | 0 | case '\t': |
173 | 0 | *this << '\\' << 't'; |
174 | 0 | break; |
175 | 0 | case '\n': |
176 | 0 | *this << '\\' << 'n'; |
177 | 0 | break; |
178 | 0 | case '"': |
179 | 0 | *this << '\\' << '"'; |
180 | 0 | break; |
181 | 0 | default: |
182 | 0 | if (isPrint(c)) { |
183 | 0 | *this << c; |
184 | 0 | break; |
185 | 0 | } |
186 | 0 | |
187 | 0 | // Write out the escaped representation. |
188 | 0 | if (UseHexEscapes) { |
189 | 0 | *this << '\\' << 'x'; |
190 | 0 | *this << hexdigit((c >> 4 & 0xF)); |
191 | 0 | *this << hexdigit((c >> 0) & 0xF); |
192 | 0 | } else { |
193 | 0 | // Always use a full 3-character octal escape. |
194 | 0 | *this << '\\'; |
195 | 0 | *this << char('0' + ((c >> 6) & 7)); |
196 | 0 | *this << char('0' + ((c >> 3) & 7)); |
197 | 0 | *this << char('0' + ((c >> 0) & 7)); |
198 | 0 | } |
199 | 0 | } |
200 | 0 | } |
201 | 0 |
|
202 | 0 | return *this; |
203 | 0 | } |
204 | | |
205 | 0 | raw_ostream &raw_ostream::operator<<(const void *P) { |
206 | 0 | llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower); |
207 | 0 | return *this; |
208 | 0 | } |
209 | | |
210 | 0 | raw_ostream &raw_ostream::operator<<(double N) { |
211 | 0 | llvm::write_double(*this, N, FloatStyle::Exponent); |
212 | 0 | return *this; |
213 | 0 | } |
214 | | |
215 | 690 | void raw_ostream::flush_nonempty() { |
216 | 690 | assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty."); |
217 | 690 | size_t Length = OutBufCur - OutBufStart; |
218 | 690 | OutBufCur = OutBufStart; |
219 | 690 | write_impl(OutBufStart, Length); |
220 | 690 | } |
221 | | |
222 | 1.17k | raw_ostream &raw_ostream::write(unsigned char C) { |
223 | 1.17k | // Group exceptional cases into a single branch. |
224 | 1.17k | if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) { |
225 | 588 | if (LLVM_UNLIKELY(!OutBufStart)) { |
226 | 588 | if (BufferMode == BufferKind::Unbuffered) { |
227 | 0 | write_impl(reinterpret_cast<char*>(&C), 1); |
228 | 0 | return *this; |
229 | 0 | } |
230 | 588 | // Set up a buffer and start over. |
231 | 588 | SetBuffered(); |
232 | 588 | return write(C); |
233 | 588 | } |
234 | 0 | |
235 | 0 | flush_nonempty(); |
236 | 0 | } |
237 | 1.17k | |
238 | 1.17k | *OutBufCur++ = C; |
239 | 588 | return *this; |
240 | 1.17k | } |
241 | | |
242 | 204 | raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) { |
243 | 204 | // Group exceptional cases into a single branch. |
244 | 204 | if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) { |
245 | 102 | if (LLVM_UNLIKELY(!OutBufStart)) { |
246 | 102 | if (BufferMode == BufferKind::Unbuffered) { |
247 | 0 | write_impl(Ptr, Size); |
248 | 0 | return *this; |
249 | 0 | } |
250 | 102 | // Set up a buffer and start over. |
251 | 102 | SetBuffered(); |
252 | 102 | return write(Ptr, Size); |
253 | 102 | } |
254 | 0 | |
255 | 0 | size_t NumBytes = OutBufEnd - OutBufCur; |
256 | 0 |
|
257 | 0 | // If the buffer is empty at this point we have a string that is larger |
258 | 0 | // than the buffer. Directly write the chunk that is a multiple of the |
259 | 0 | // preferred buffer size and put the remainder in the buffer. |
260 | 0 | if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) { |
261 | 0 | assert(NumBytes != 0 && "undefined behavior"); |
262 | 0 | size_t BytesToWrite = Size - (Size % NumBytes); |
263 | 0 | write_impl(Ptr, BytesToWrite); |
264 | 0 | size_t BytesRemaining = Size - BytesToWrite; |
265 | 0 | if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) { |
266 | 0 | // Too much left over to copy into our buffer. |
267 | 0 | return write(Ptr + BytesToWrite, BytesRemaining); |
268 | 0 | } |
269 | 0 | copy_to_buffer(Ptr + BytesToWrite, BytesRemaining); |
270 | 0 | return *this; |
271 | 0 | } |
272 | 0 | |
273 | 0 | // We don't have enough space in the buffer to fit the string in. Insert as |
274 | 0 | // much as possible, flush and start over with the remainder. |
275 | 0 | copy_to_buffer(Ptr, NumBytes); |
276 | 0 | flush_nonempty(); |
277 | 0 | return write(Ptr + NumBytes, Size - NumBytes); |
278 | 0 | } |
279 | 102 | |
280 | 102 | copy_to_buffer(Ptr, Size); |
281 | 102 | |
282 | 102 | return *this; |
283 | 102 | } |
284 | | |
285 | 102 | void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) { |
286 | 102 | assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!"); |
287 | 102 | |
288 | 102 | // Handle short strings specially, memcpy isn't very good at very short |
289 | 102 | // strings. |
290 | 102 | switch (Size) { |
291 | 102 | case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH; |
292 | 0 | case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH; |
293 | 0 | case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH; |
294 | 36 | case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH; |
295 | 36 | case 0: break; |
296 | 66 | default: |
297 | 66 | memcpy(OutBufCur, Ptr, Size); |
298 | 66 | break; |
299 | 102 | } |
300 | 102 | |
301 | 102 | OutBufCur += Size; |
302 | 102 | } |
303 | | |
304 | | // Formatted output. |
305 | 0 | raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) { |
306 | 0 | // If we have more than a few bytes left in our output buffer, try |
307 | 0 | // formatting directly onto its end. |
308 | 0 | size_t NextBufferSize = 127; |
309 | 0 | size_t BufferBytesLeft = OutBufEnd - OutBufCur; |
310 | 0 | if (BufferBytesLeft > 3) { |
311 | 0 | size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft); |
312 | 0 |
|
313 | 0 | // Common case is that we have plenty of space. |
314 | 0 | if (BytesUsed <= BufferBytesLeft) { |
315 | 0 | OutBufCur += BytesUsed; |
316 | 0 | return *this; |
317 | 0 | } |
318 | 0 | |
319 | 0 | // Otherwise, we overflowed and the return value tells us the size to try |
320 | 0 | // again with. |
321 | 0 | NextBufferSize = BytesUsed; |
322 | 0 | } |
323 | 0 |
|
324 | 0 | // If we got here, we didn't have enough space in the output buffer for the |
325 | 0 | // string. Try printing into a SmallVector that is resized to have enough |
326 | 0 | // space. Iterate until we win. |
327 | 0 | SmallVector<char, 128> V; |
328 | 0 |
|
329 | 0 | while (true) { |
330 | 0 | V.resize(NextBufferSize); |
331 | 0 |
|
332 | 0 | // Try formatting into the SmallVector. |
333 | 0 | size_t BytesUsed = Fmt.print(V.data(), NextBufferSize); |
334 | 0 |
|
335 | 0 | // If BytesUsed fit into the vector, we win. |
336 | 0 | if (BytesUsed <= NextBufferSize) |
337 | 0 | return write(V.data(), BytesUsed); |
338 | 0 | |
339 | 0 | // Otherwise, try again with a new size. |
340 | 0 | assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?"); |
341 | 0 | NextBufferSize = BytesUsed; |
342 | 0 | } |
343 | 0 | } |
344 | | |
345 | 0 | raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) { |
346 | 0 | Obj.format(*this); |
347 | 0 | return *this; |
348 | 0 | } |
349 | | |
350 | 0 | raw_ostream &raw_ostream::operator<<(const FormattedString &FS) { |
351 | 0 | unsigned LeftIndent = 0; |
352 | 0 | unsigned RightIndent = 0; |
353 | 0 | const ssize_t Difference = FS.Width - FS.Str.size(); |
354 | 0 | if (Difference > 0) { |
355 | 0 | switch (FS.Justify) { |
356 | 0 | case FormattedString::JustifyNone: |
357 | 0 | break; |
358 | 0 | case FormattedString::JustifyLeft: |
359 | 0 | RightIndent = Difference; |
360 | 0 | break; |
361 | 0 | case FormattedString::JustifyRight: |
362 | 0 | LeftIndent = Difference; |
363 | 0 | break; |
364 | 0 | case FormattedString::JustifyCenter: |
365 | 0 | LeftIndent = Difference / 2; |
366 | 0 | RightIndent = Difference - LeftIndent; |
367 | 0 | break; |
368 | 0 | } |
369 | 0 | } |
370 | 0 | indent(LeftIndent); |
371 | 0 | (*this) << FS.Str; |
372 | 0 | indent(RightIndent); |
373 | 0 | return *this; |
374 | 0 | } |
375 | | |
376 | 0 | raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) { |
377 | 0 | if (FN.Hex) { |
378 | 0 | HexPrintStyle Style; |
379 | 0 | if (FN.Upper && FN.HexPrefix) |
380 | 0 | Style = HexPrintStyle::PrefixUpper; |
381 | 0 | else if (FN.Upper && !FN.HexPrefix) |
382 | 0 | Style = HexPrintStyle::Upper; |
383 | 0 | else if (!FN.Upper && FN.HexPrefix) |
384 | 0 | Style = HexPrintStyle::PrefixLower; |
385 | 0 | else |
386 | 0 | Style = HexPrintStyle::Lower; |
387 | 0 | llvm::write_hex(*this, FN.HexValue, Style, FN.Width); |
388 | 0 | } else { |
389 | 0 | llvm::SmallString<16> Buffer; |
390 | 0 | llvm::raw_svector_ostream Stream(Buffer); |
391 | 0 | llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer); |
392 | 0 | if (Buffer.size() < FN.Width) |
393 | 0 | indent(FN.Width - Buffer.size()); |
394 | 0 | (*this) << Buffer; |
395 | 0 | } |
396 | 0 | return *this; |
397 | 0 | } |
398 | | |
399 | 0 | raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) { |
400 | 0 | if (FB.Bytes.empty()) |
401 | 0 | return *this; |
402 | 0 | |
403 | 0 | size_t LineIndex = 0; |
404 | 0 | auto Bytes = FB.Bytes; |
405 | 0 | const size_t Size = Bytes.size(); |
406 | 0 | HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower; |
407 | 0 | uint64_t OffsetWidth = 0; |
408 | 0 | if (FB.FirstByteOffset.hasValue()) { |
409 | 0 | // Figure out how many nibbles are needed to print the largest offset |
410 | 0 | // represented by this data set, so that we can align the offset field |
411 | 0 | // to the right width. |
412 | 0 | size_t Lines = Size / FB.NumPerLine; |
413 | 0 | uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine; |
414 | 0 | unsigned Power = 0; |
415 | 0 | if (MaxOffset > 0) |
416 | 0 | Power = llvm::Log2_64_Ceil(MaxOffset); |
417 | 0 | OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4); |
418 | 0 | } |
419 | 0 |
|
420 | 0 | // The width of a block of data including all spaces for group separators. |
421 | 0 | unsigned NumByteGroups = |
422 | 0 | alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize; |
423 | 0 | unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1; |
424 | 0 |
|
425 | 0 | while (!Bytes.empty()) { |
426 | 0 | indent(FB.IndentLevel); |
427 | 0 |
|
428 | 0 | if (FB.FirstByteOffset.hasValue()) { |
429 | 0 | uint64_t Offset = FB.FirstByteOffset.getValue(); |
430 | 0 | llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth); |
431 | 0 | *this << ": "; |
432 | 0 | } |
433 | 0 |
|
434 | 0 | auto Line = Bytes.take_front(FB.NumPerLine); |
435 | 0 |
|
436 | 0 | size_t CharsPrinted = 0; |
437 | 0 | // Print the hex bytes for this line in groups |
438 | 0 | for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) { |
439 | 0 | if (I && (I % FB.ByteGroupSize) == 0) { |
440 | 0 | ++CharsPrinted; |
441 | 0 | *this << " "; |
442 | 0 | } |
443 | 0 | llvm::write_hex(*this, Line[I], HPS, 2); |
444 | 0 | } |
445 | 0 |
|
446 | 0 | if (FB.ASCII) { |
447 | 0 | // Print any spaces needed for any bytes that we didn't print on this |
448 | 0 | // line so that the ASCII bytes are correctly aligned. |
449 | 0 | assert(BlockCharWidth >= CharsPrinted); |
450 | 0 | indent(BlockCharWidth - CharsPrinted + 2); |
451 | 0 | *this << "|"; |
452 | 0 |
|
453 | 0 | // Print the ASCII char values for each byte on this line |
454 | 0 | for (uint8_t Byte : Line) { |
455 | 0 | if (isPrint(Byte)) |
456 | 0 | *this << static_cast<char>(Byte); |
457 | 0 | else |
458 | 0 | *this << '.'; |
459 | 0 | } |
460 | 0 | *this << '|'; |
461 | 0 | } |
462 | 0 |
|
463 | 0 | Bytes = Bytes.drop_front(Line.size()); |
464 | 0 | LineIndex += Line.size(); |
465 | 0 | if (LineIndex < Size) |
466 | 0 | *this << '\n'; |
467 | 0 | } |
468 | 0 | return *this; |
469 | 0 | } |
470 | | |
471 | | template <char C> |
472 | 0 | static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) { |
473 | 0 | static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, |
474 | 0 | C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, |
475 | 0 | C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, |
476 | 0 | C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, |
477 | 0 | C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C}; |
478 | 0 |
|
479 | 0 | // Usually the indentation is small, handle it with a fastpath. |
480 | 0 | if (NumChars < array_lengthof(Chars)) |
481 | 0 | return OS.write(Chars, NumChars); |
482 | 0 | |
483 | 0 | while (NumChars) { |
484 | 0 | unsigned NumToWrite = std::min(NumChars, |
485 | 0 | (unsigned)array_lengthof(Chars)-1); |
486 | 0 | OS.write(Chars, NumToWrite); |
487 | 0 | NumChars -= NumToWrite; |
488 | 0 | } |
489 | 0 | return OS; |
490 | 0 | } Unexecuted instantiation: raw_ostream.cpp:_ZL13write_paddingILc32EERN4llvm11raw_ostreamES2_j Unexecuted instantiation: raw_ostream.cpp:_ZL13write_paddingILc0EERN4llvm11raw_ostreamES2_j |
491 | | |
492 | | /// indent - Insert 'NumSpaces' spaces. |
493 | 0 | raw_ostream &raw_ostream::indent(unsigned NumSpaces) { |
494 | 0 | return write_padding<' '>(*this, NumSpaces); |
495 | 0 | } |
496 | | |
497 | | /// write_zeros - Insert 'NumZeros' nulls. |
498 | 0 | raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) { |
499 | 0 | return write_padding<'\0'>(*this, NumZeros); |
500 | 0 | } |
501 | | |
502 | 0 | void raw_ostream::anchor() {} |
503 | | |
504 | | //===----------------------------------------------------------------------===// |
505 | | // Formatted Output |
506 | | //===----------------------------------------------------------------------===// |
507 | | |
508 | | // Out of line virtual method. |
509 | 0 | void format_object_base::home() { |
510 | 0 | } |
511 | | |
512 | | //===----------------------------------------------------------------------===// |
513 | | // raw_fd_ostream |
514 | | //===----------------------------------------------------------------------===// |
515 | | |
516 | | static int getFD(StringRef Filename, std::error_code &EC, |
517 | | sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, |
518 | 0 | sys::fs::OpenFlags Flags) { |
519 | 0 | assert((Access & sys::fs::FA_Write) && |
520 | 0 | "Cannot make a raw_ostream from a read-only descriptor!"); |
521 | 0 |
|
522 | 0 | // Handle "-" as stdout. Note that when we do this, we consider ourself |
523 | 0 | // the owner of stdout and may set the "binary" flag globally based on Flags. |
524 | 0 | if (Filename == "-") { |
525 | 0 | EC = std::error_code(); |
526 | 0 | // If user requested binary then put stdout into binary mode if |
527 | 0 | // possible. |
528 | 0 | if (!(Flags & sys::fs::OF_Text)) |
529 | 0 | sys::ChangeStdoutToBinary(); |
530 | 0 | return STDOUT_FILENO; |
531 | 0 | } |
532 | 0 |
|
533 | 0 | int FD; |
534 | 0 | if (Access & sys::fs::FA_Read) |
535 | 0 | EC = sys::fs::openFileForReadWrite(Filename, FD, Disp, Flags); |
536 | 0 | else |
537 | 0 | EC = sys::fs::openFileForWrite(Filename, FD, Disp, Flags); |
538 | 0 | if (EC) |
539 | 0 | return -1; |
540 | 0 | |
541 | 0 | return FD; |
542 | 0 | } |
543 | | |
544 | | raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC) |
545 | | : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write, |
546 | 0 | sys::fs::OF_None) {} |
547 | | |
548 | | raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, |
549 | | sys::fs::CreationDisposition Disp) |
550 | 0 | : raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {} |
551 | | |
552 | | raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, |
553 | | sys::fs::FileAccess Access) |
554 | | : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, Access, |
555 | 0 | sys::fs::OF_None) {} |
556 | | |
557 | | raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, |
558 | | sys::fs::OpenFlags Flags) |
559 | | : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write, |
560 | 0 | Flags) {} |
561 | | |
562 | | raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC, |
563 | | sys::fs::CreationDisposition Disp, |
564 | | sys::fs::FileAccess Access, |
565 | | sys::fs::OpenFlags Flags) |
566 | 0 | : raw_fd_ostream(getFD(Filename, EC, Disp, Access, Flags), true) {} |
567 | | |
568 | | /// FD is the file descriptor that this writes to. If ShouldClose is true, this |
569 | | /// closes the file when the stream is destroyed. |
570 | | raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered) |
571 | 2 | : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) { |
572 | 2 | if (FD < 0 ) { |
573 | 0 | ShouldClose = false; |
574 | 0 | return; |
575 | 0 | } |
576 | 2 | |
577 | 2 | // Do not attempt to close stdout or stderr. We used to try to maintain the |
578 | 2 | // property that tools that support writing file to stdout should not also |
579 | 2 | // write informational output to stdout, but in practice we were never able to |
580 | 2 | // maintain this invariant. Many features have been added to LLVM and clang |
581 | 2 | // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so |
582 | 2 | // users must simply be aware that mixed output and remarks is a possibility. |
583 | 2 | if (FD <= STDERR_FILENO) |
584 | 2 | ShouldClose = false; |
585 | 2 | |
586 | | #ifdef _WIN32 |
587 | | // Check if this is a console device. This is not equivalent to isatty. |
588 | | IsWindowsConsole = |
589 | | ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR; |
590 | | #endif |
591 | | |
592 | 2 | // Get the starting position. |
593 | 2 | off_t loc = ::lseek(FD, 0, SEEK_CUR); |
594 | | #ifdef _WIN32 |
595 | | // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes. |
596 | | sys::fs::file_status Status; |
597 | | std::error_code EC = status(FD, Status); |
598 | | SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file; |
599 | | #else |
600 | | SupportsSeeking = loc != (off_t)-1; |
601 | 2 | #endif |
602 | 2 | if (!SupportsSeeking) |
603 | 2 | pos = 0; |
604 | 0 | else |
605 | 0 | pos = static_cast<uint64_t>(loc); |
606 | 2 | } |
607 | | |
608 | 2 | raw_fd_ostream::~raw_fd_ostream() { |
609 | 2 | if (FD >= 0) { |
610 | 2 | flush(); |
611 | 2 | if (ShouldClose) { |
612 | 0 | if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD)) |
613 | 0 | error_detected(EC); |
614 | 0 | } |
615 | 2 | } |
616 | 2 | |
617 | | #ifdef __MINGW32__ |
618 | | // On mingw, global dtors should not call exit(). |
619 | | // report_fatal_error() invokes exit(). We know report_fatal_error() |
620 | | // might not write messages to stderr when any errors were detected |
621 | | // on FD == 2. |
622 | | if (FD == 2) return; |
623 | | #endif |
624 | | |
625 | 2 | // If there are any pending errors, report them now. Clients wishing |
626 | 2 | // to avoid report_fatal_error calls should check for errors with |
627 | 2 | // has_error() and clear the error flag with clear_error() before |
628 | 2 | // destructing raw_ostream objects which may have errors. |
629 | 2 | if (has_error()) |
630 | 0 | report_fatal_error("IO failure on output stream: " + error().message(), |
631 | 0 | /*gen_crash_diag=*/false); |
632 | 2 | } |
633 | | |
634 | | #if defined(_WIN32) |
635 | | // The most reliable way to print unicode in a Windows console is with |
636 | | // WriteConsoleW. To use that, first transcode from UTF-8 to UTF-16. This |
637 | | // assumes that LLVM programs always print valid UTF-8 to the console. The data |
638 | | // might not be UTF-8 for two major reasons: |
639 | | // 1. The program is printing binary (-filetype=obj -o -), in which case it |
640 | | // would have been gibberish anyway. |
641 | | // 2. The program is printing text in a semi-ascii compatible codepage like |
642 | | // shift-jis or cp1252. |
643 | | // |
644 | | // Most LLVM programs don't produce non-ascii text unless they are quoting |
645 | | // user source input. A well-behaved LLVM program should either validate that |
646 | | // the input is UTF-8 or transcode from the local codepage to UTF-8 before |
647 | | // quoting it. If they don't, this may mess up the encoding, but this is still |
648 | | // probably the best compromise we can make. |
649 | | static bool write_console_impl(int FD, StringRef Data) { |
650 | | SmallVector<wchar_t, 256> WideText; |
651 | | |
652 | | // Fall back to ::write if it wasn't valid UTF-8. |
653 | | if (auto EC = sys::windows::UTF8ToUTF16(Data, WideText)) |
654 | | return false; |
655 | | |
656 | | // On Windows 7 and earlier, WriteConsoleW has a low maximum amount of data |
657 | | // that can be written to the console at a time. |
658 | | size_t MaxWriteSize = WideText.size(); |
659 | | if (!RunningWindows8OrGreater()) |
660 | | MaxWriteSize = 32767; |
661 | | |
662 | | size_t WCharsWritten = 0; |
663 | | do { |
664 | | size_t WCharsToWrite = |
665 | | std::min(MaxWriteSize, WideText.size() - WCharsWritten); |
666 | | DWORD ActuallyWritten; |
667 | | bool Success = |
668 | | ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten], |
669 | | WCharsToWrite, &ActuallyWritten, |
670 | | /*Reserved=*/nullptr); |
671 | | |
672 | | // The most likely reason for WriteConsoleW to fail is that FD no longer |
673 | | // points to a console. Fall back to ::write. If this isn't the first loop |
674 | | // iteration, something is truly wrong. |
675 | | if (!Success) |
676 | | return false; |
677 | | |
678 | | WCharsWritten += ActuallyWritten; |
679 | | } while (WCharsWritten != WideText.size()); |
680 | | return true; |
681 | | } |
682 | | #endif |
683 | | |
684 | 0 | void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) { |
685 | 0 | assert(FD >= 0 && "File already closed."); |
686 | 0 | pos += Size; |
687 | 0 |
|
688 | | #if defined(_WIN32) |
689 | | // If this is a Windows console device, try re-encoding from UTF-8 to UTF-16 |
690 | | // and using WriteConsoleW. If that fails, fall back to plain write(). |
691 | | if (IsWindowsConsole) |
692 | | if (write_console_impl(FD, StringRef(Ptr, Size))) |
693 | | return; |
694 | | #endif |
695 | |
|
696 | 0 | // The maximum write size is limited to INT32_MAX. A write |
697 | 0 | // greater than SSIZE_MAX is implementation-defined in POSIX, |
698 | 0 | // and Windows _write requires 32 bit input. |
699 | 0 | size_t MaxWriteSize = INT32_MAX; |
700 | 0 |
|
701 | 0 | #if defined(__linux__) |
702 | 0 | // It is observed that Linux returns EINVAL for a very large write (>2G). |
703 | 0 | // Make it a reasonably small value. |
704 | 0 | MaxWriteSize = 1024 * 1024 * 1024; |
705 | 0 | #endif |
706 | 0 |
|
707 | 0 | do { |
708 | 0 | size_t ChunkSize = std::min(Size, MaxWriteSize); |
709 | 0 | ssize_t ret = ::write(FD, Ptr, ChunkSize); |
710 | 0 |
|
711 | 0 | if (ret < 0) { |
712 | 0 | // If it's a recoverable error, swallow it and retry the write. |
713 | 0 | // |
714 | 0 | // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since |
715 | 0 | // raw_ostream isn't designed to do non-blocking I/O. However, some |
716 | 0 | // programs, such as old versions of bjam, have mistakenly used |
717 | 0 | // O_NONBLOCK. For compatibility, emulate blocking semantics by |
718 | 0 | // spinning until the write succeeds. If you don't want spinning, |
719 | 0 | // don't use O_NONBLOCK file descriptors with raw_ostream. |
720 | 0 | if (errno == EINTR || errno == EAGAIN |
721 | 0 | #ifdef EWOULDBLOCK |
722 | 0 | || errno == EWOULDBLOCK |
723 | 0 | #endif |
724 | 0 | ) |
725 | 0 | continue; |
726 | 0 | |
727 | 0 | // Otherwise it's a non-recoverable error. Note it and quit. |
728 | 0 | error_detected(std::error_code(errno, std::generic_category())); |
729 | 0 | break; |
730 | 0 | } |
731 | 0 | |
732 | 0 | // The write may have written some or all of the data. Update the |
733 | 0 | // size and buffer pointer to reflect the remainder that needs |
734 | 0 | // to be written. If there are no bytes left, we're done. |
735 | 0 | Ptr += ret; |
736 | 0 | Size -= ret; |
737 | 0 | } while (Size > 0); |
738 | 0 | } |
739 | | |
740 | 0 | void raw_fd_ostream::close() { |
741 | 0 | assert(ShouldClose); |
742 | 0 | ShouldClose = false; |
743 | 0 | flush(); |
744 | 0 | if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD)) |
745 | 0 | error_detected(EC); |
746 | 0 | FD = -1; |
747 | 0 | } |
748 | | |
749 | 0 | uint64_t raw_fd_ostream::seek(uint64_t off) { |
750 | 0 | assert(SupportsSeeking && "Stream does not support seeking!"); |
751 | 0 | flush(); |
752 | | #ifdef _WIN32 |
753 | | pos = ::_lseeki64(FD, off, SEEK_SET); |
754 | | #elif defined(HAVE_LSEEK64) |
755 | | pos = ::lseek64(FD, off, SEEK_SET); |
756 | | #else |
757 | | pos = ::lseek(FD, off, SEEK_SET); |
758 | | #endif |
759 | 0 | if (pos == (uint64_t)-1) |
760 | 0 | error_detected(std::error_code(errno, std::generic_category())); |
761 | 0 | return pos; |
762 | 0 | } |
763 | | |
764 | | void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size, |
765 | 0 | uint64_t Offset) { |
766 | 0 | uint64_t Pos = tell(); |
767 | 0 | seek(Offset); |
768 | 0 | write(Ptr, Size); |
769 | 0 | seek(Pos); |
770 | 0 | } |
771 | | |
772 | 0 | size_t raw_fd_ostream::preferred_buffer_size() const { |
773 | | #if defined(_WIN32) |
774 | | // Disable buffering for console devices. Console output is re-encoded from |
775 | | // UTF-8 to UTF-16 on Windows, and buffering it would require us to split the |
776 | | // buffer on a valid UTF-8 codepoint boundary. Terminal buffering is disabled |
777 | | // below on most other OSs, so do the same thing on Windows and avoid that |
778 | | // complexity. |
779 | | if (IsWindowsConsole) |
780 | | return 0; |
781 | | return raw_ostream::preferred_buffer_size(); |
782 | | #elif !defined(__minix) |
783 | | // Minix has no st_blksize. |
784 | 0 | assert(FD >= 0 && "File not yet open!"); |
785 | 0 | struct stat statbuf; |
786 | 0 | if (fstat(FD, &statbuf) != 0) |
787 | 0 | return 0; |
788 | 0 | |
789 | 0 | // If this is a terminal, don't use buffering. Line buffering |
790 | 0 | // would be a more traditional thing to do, but it's not worth |
791 | 0 | // the complexity. |
792 | 0 | if (S_ISCHR(statbuf.st_mode) && is_displayed()) |
793 | 0 | return 0; |
794 | 0 | // Return the preferred block size. |
795 | 0 | return statbuf.st_blksize; |
796 | | #else |
797 | | return raw_ostream::preferred_buffer_size(); |
798 | | #endif |
799 | | } |
800 | | |
801 | | raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold, |
802 | 0 | bool bg) { |
803 | 0 | if (!ColorEnabled) |
804 | 0 | return *this; |
805 | 0 | |
806 | 0 | if (sys::Process::ColorNeedsFlush()) |
807 | 0 | flush(); |
808 | 0 | const char *colorcode = |
809 | 0 | (colors == SAVEDCOLOR) |
810 | 0 | ? sys::Process::OutputBold(bg) |
811 | 0 | : sys::Process::OutputColor(static_cast<char>(colors), bold, bg); |
812 | 0 | if (colorcode) { |
813 | 0 | size_t len = strlen(colorcode); |
814 | 0 | write(colorcode, len); |
815 | 0 | // don't account colors towards output characters |
816 | 0 | pos -= len; |
817 | 0 | } |
818 | 0 | return *this; |
819 | 0 | } |
820 | | |
821 | 0 | raw_ostream &raw_fd_ostream::resetColor() { |
822 | 0 | if (!ColorEnabled) |
823 | 0 | return *this; |
824 | 0 | |
825 | 0 | if (sys::Process::ColorNeedsFlush()) |
826 | 0 | flush(); |
827 | 0 | const char *colorcode = sys::Process::ResetColor(); |
828 | 0 | if (colorcode) { |
829 | 0 | size_t len = strlen(colorcode); |
830 | 0 | write(colorcode, len); |
831 | 0 | // don't account colors towards output characters |
832 | 0 | pos -= len; |
833 | 0 | } |
834 | 0 | return *this; |
835 | 0 | } |
836 | | |
837 | 0 | raw_ostream &raw_fd_ostream::reverseColor() { |
838 | 0 | if (!ColorEnabled) |
839 | 0 | return *this; |
840 | 0 | |
841 | 0 | if (sys::Process::ColorNeedsFlush()) |
842 | 0 | flush(); |
843 | 0 | const char *colorcode = sys::Process::OutputReverse(); |
844 | 0 | if (colorcode) { |
845 | 0 | size_t len = strlen(colorcode); |
846 | 0 | write(colorcode, len); |
847 | 0 | // don't account colors towards output characters |
848 | 0 | pos -= len; |
849 | 0 | } |
850 | 0 | return *this; |
851 | 0 | } |
852 | | |
853 | 0 | bool raw_fd_ostream::is_displayed() const { |
854 | 0 | return sys::Process::FileDescriptorIsDisplayed(FD); |
855 | 0 | } |
856 | | |
857 | 0 | bool raw_fd_ostream::has_colors() const { |
858 | 0 | return sys::Process::FileDescriptorHasColors(FD); |
859 | 0 | } |
860 | | |
861 | 0 | void raw_fd_ostream::anchor() {} |
862 | | |
863 | | //===----------------------------------------------------------------------===// |
864 | | // outs(), errs(), nulls() |
865 | | //===----------------------------------------------------------------------===// |
866 | | |
867 | | /// outs() - This returns a reference to a raw_ostream for standard output. |
868 | | /// Use it like: outs() << "foo" << "bar"; |
869 | 0 | raw_ostream &llvm::outs() { |
870 | 0 | // Set buffer settings to model stdout behavior. |
871 | 0 | std::error_code EC; |
872 | 0 | static raw_fd_ostream S("-", EC, sys::fs::OF_None); |
873 | 0 | assert(!EC); |
874 | 0 | return S; |
875 | 0 | } |
876 | | |
877 | | /// errs() - This returns a reference to a raw_ostream for standard error. |
878 | | /// Use it like: errs() << "foo" << "bar"; |
879 | 2 | raw_ostream &llvm::errs() { |
880 | 2 | // Set standard error to be unbuffered by default. |
881 | 2 | static raw_fd_ostream S(STDERR_FILENO, false, true); |
882 | 2 | return S; |
883 | 2 | } |
884 | | |
885 | | /// nulls() - This returns a reference to a raw_ostream which discards output. |
886 | 0 | raw_ostream &llvm::nulls() { |
887 | 0 | static raw_null_ostream S; |
888 | 0 | return S; |
889 | 0 | } |
890 | | |
891 | | //===----------------------------------------------------------------------===// |
892 | | // raw_string_ostream |
893 | | //===----------------------------------------------------------------------===// |
894 | | |
895 | 0 | raw_string_ostream::~raw_string_ostream() { |
896 | 0 | flush(); |
897 | 0 | } |
898 | | |
899 | 0 | void raw_string_ostream::write_impl(const char *Ptr, size_t Size) { |
900 | 0 | OS.append(Ptr, Size); |
901 | 0 | } |
902 | | |
903 | | //===----------------------------------------------------------------------===// |
904 | | // raw_svector_ostream |
905 | | //===----------------------------------------------------------------------===// |
906 | | |
907 | 0 | uint64_t raw_svector_ostream::current_pos() const { return OS.size(); } |
908 | | |
909 | 0 | void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) { |
910 | 0 | OS.append(Ptr, Ptr + Size); |
911 | 0 | } |
912 | | |
913 | | void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size, |
914 | 0 | uint64_t Offset) { |
915 | 0 | memcpy(OS.data() + Offset, Ptr, Size); |
916 | 0 | } |
917 | | |
918 | | //===----------------------------------------------------------------------===// |
919 | | // raw_null_ostream |
920 | | //===----------------------------------------------------------------------===// |
921 | | |
922 | 0 | raw_null_ostream::~raw_null_ostream() { |
923 | 0 | #ifndef NDEBUG |
924 | 0 | // ~raw_ostream asserts that the buffer is empty. This isn't necessary |
925 | 0 | // with raw_null_ostream, but it's better to have raw_null_ostream follow |
926 | 0 | // the rules than to change the rules just for raw_null_ostream. |
927 | 0 | flush(); |
928 | 0 | #endif |
929 | 0 | } |
930 | | |
931 | 0 | void raw_null_ostream::write_impl(const char *Ptr, size_t Size) { |
932 | 0 | } |
933 | | |
934 | 0 | uint64_t raw_null_ostream::current_pos() const { |
935 | 0 | return 0; |
936 | 0 | } |
937 | | |
938 | | void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size, |
939 | 0 | uint64_t Offset) {} |
940 | | |
941 | 0 | void raw_pwrite_stream::anchor() {} |
942 | | |
943 | 0 | void buffer_ostream::anchor() {} |