10b57cec5SDimitry Andric //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This implements support for bulk buffered stream output.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
140b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
150b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
160b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
170b57cec5SDimitry Andric #include "llvm/Config/config.h"
180b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
190b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
200b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
210b57cec5SDimitry Andric #include "llvm/Support/Format.h"
220b57cec5SDimitry Andric #include "llvm/Support/FormatVariadic.h"
230b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
240b57cec5SDimitry Andric #include "llvm/Support/NativeFormatting.h"
250b57cec5SDimitry Andric #include "llvm/Support/Process.h"
260b57cec5SDimitry Andric #include "llvm/Support/Program.h"
270b57cec5SDimitry Andric #include <algorithm>
280b57cec5SDimitry Andric #include <cctype>
290b57cec5SDimitry Andric #include <cerrno>
300b57cec5SDimitry Andric #include <cstdio>
310b57cec5SDimitry Andric #include <iterator>
320b57cec5SDimitry Andric #include <sys/stat.h>
330b57cec5SDimitry Andric #include <system_error>
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric // <fcntl.h> may provide O_BINARY.
360b57cec5SDimitry Andric #if defined(HAVE_FCNTL_H)
370b57cec5SDimitry Andric # include <fcntl.h>
380b57cec5SDimitry Andric #endif
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric #if defined(HAVE_UNISTD_H)
410b57cec5SDimitry Andric # include <unistd.h>
420b57cec5SDimitry Andric #endif
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric #if defined(__CYGWIN__)
450b57cec5SDimitry Andric #include <io.h>
460b57cec5SDimitry Andric #endif
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric #if defined(_MSC_VER)
490b57cec5SDimitry Andric #include <io.h>
500b57cec5SDimitry Andric #ifndef STDIN_FILENO
510b57cec5SDimitry Andric # define STDIN_FILENO 0
520b57cec5SDimitry Andric #endif
530b57cec5SDimitry Andric #ifndef STDOUT_FILENO
540b57cec5SDimitry Andric # define STDOUT_FILENO 1
550b57cec5SDimitry Andric #endif
560b57cec5SDimitry Andric #ifndef STDERR_FILENO
570b57cec5SDimitry Andric # define STDERR_FILENO 2
580b57cec5SDimitry Andric #endif
590b57cec5SDimitry Andric #endif
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric #ifdef _WIN32
620b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
638c27c554SDimitry Andric #include "llvm/Support/Windows/WindowsSupport.h"
640b57cec5SDimitry Andric #endif
650b57cec5SDimitry Andric 
660b57cec5SDimitry Andric using namespace llvm;
670b57cec5SDimitry Andric 
688bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::BLACK;
698bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::RED;
708bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::GREEN;
718bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::YELLOW;
728bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::BLUE;
738bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::MAGENTA;
748bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::CYAN;
758bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::WHITE;
768bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::SAVEDCOLOR;
778bcb0991SDimitry Andric const raw_ostream::Colors raw_ostream::RESET;
788bcb0991SDimitry Andric 
790b57cec5SDimitry Andric raw_ostream::~raw_ostream() {
800b57cec5SDimitry Andric   // raw_ostream's subclasses should take care to flush the buffer
810b57cec5SDimitry Andric   // in their destructors.
820b57cec5SDimitry Andric   assert(OutBufCur == OutBufStart &&
830b57cec5SDimitry Andric          "raw_ostream destructor called with non-empty buffer!");
840b57cec5SDimitry Andric 
85480093f4SDimitry Andric   if (BufferMode == BufferKind::InternalBuffer)
860b57cec5SDimitry Andric     delete [] OutBufStart;
870b57cec5SDimitry Andric }
880b57cec5SDimitry Andric 
890b57cec5SDimitry Andric size_t raw_ostream::preferred_buffer_size() const {
900b57cec5SDimitry Andric   // BUFSIZ is intended to be a reasonable default.
910b57cec5SDimitry Andric   return BUFSIZ;
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric void raw_ostream::SetBuffered() {
950b57cec5SDimitry Andric   // Ask the subclass to determine an appropriate buffer size.
960b57cec5SDimitry Andric   if (size_t Size = preferred_buffer_size())
970b57cec5SDimitry Andric     SetBufferSize(Size);
980b57cec5SDimitry Andric   else
990b57cec5SDimitry Andric     // It may return 0, meaning this stream should be unbuffered.
1000b57cec5SDimitry Andric     SetUnbuffered();
1010b57cec5SDimitry Andric }
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
1040b57cec5SDimitry Andric                                    BufferKind Mode) {
105480093f4SDimitry Andric   assert(((Mode == BufferKind::Unbuffered && !BufferStart && Size == 0) ||
106480093f4SDimitry Andric           (Mode != BufferKind::Unbuffered && BufferStart && Size != 0)) &&
1070b57cec5SDimitry Andric          "stream must be unbuffered or have at least one byte");
1080b57cec5SDimitry Andric   // Make sure the current buffer is free of content (we can't flush here; the
1090b57cec5SDimitry Andric   // child buffer management logic will be in write_impl).
1100b57cec5SDimitry Andric   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
1110b57cec5SDimitry Andric 
112480093f4SDimitry Andric   if (BufferMode == BufferKind::InternalBuffer)
1130b57cec5SDimitry Andric     delete [] OutBufStart;
1140b57cec5SDimitry Andric   OutBufStart = BufferStart;
1150b57cec5SDimitry Andric   OutBufEnd = OutBufStart+Size;
1160b57cec5SDimitry Andric   OutBufCur = OutBufStart;
1170b57cec5SDimitry Andric   BufferMode = Mode;
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric   assert(OutBufStart <= OutBufEnd && "Invalid size!");
1200b57cec5SDimitry Andric }
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(unsigned long N) {
1230b57cec5SDimitry Andric   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
1240b57cec5SDimitry Andric   return *this;
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(long N) {
1280b57cec5SDimitry Andric   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
1290b57cec5SDimitry Andric   return *this;
1300b57cec5SDimitry Andric }
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(unsigned long long N) {
1330b57cec5SDimitry Andric   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
1340b57cec5SDimitry Andric   return *this;
1350b57cec5SDimitry Andric }
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(long long N) {
1380b57cec5SDimitry Andric   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
1390b57cec5SDimitry Andric   return *this;
1400b57cec5SDimitry Andric }
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric raw_ostream &raw_ostream::write_hex(unsigned long long N) {
1430b57cec5SDimitry Andric   llvm::write_hex(*this, N, HexPrintStyle::Lower);
1440b57cec5SDimitry Andric   return *this;
1450b57cec5SDimitry Andric }
1460b57cec5SDimitry Andric 
1478bcb0991SDimitry Andric raw_ostream &raw_ostream::operator<<(Colors C) {
1488bcb0991SDimitry Andric   if (C == Colors::RESET)
1498bcb0991SDimitry Andric     resetColor();
1508bcb0991SDimitry Andric   else
1518bcb0991SDimitry Andric     changeColor(C);
1528bcb0991SDimitry Andric   return *this;
1538bcb0991SDimitry Andric }
1548bcb0991SDimitry Andric 
1550b57cec5SDimitry Andric raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) {
1560b57cec5SDimitry Andric   for (int Idx = 0; Idx < 16; ++Idx) {
1570b57cec5SDimitry Andric     *this << format("%02" PRIX32, UUID[Idx]);
1580b57cec5SDimitry Andric     if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
1590b57cec5SDimitry Andric       *this << "-";
1600b57cec5SDimitry Andric   }
1610b57cec5SDimitry Andric   return *this;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric 
1650b57cec5SDimitry Andric raw_ostream &raw_ostream::write_escaped(StringRef Str,
1660b57cec5SDimitry Andric                                         bool UseHexEscapes) {
1670b57cec5SDimitry Andric   for (unsigned char c : Str) {
1680b57cec5SDimitry Andric     switch (c) {
1690b57cec5SDimitry Andric     case '\\':
1700b57cec5SDimitry Andric       *this << '\\' << '\\';
1710b57cec5SDimitry Andric       break;
1720b57cec5SDimitry Andric     case '\t':
1730b57cec5SDimitry Andric       *this << '\\' << 't';
1740b57cec5SDimitry Andric       break;
1750b57cec5SDimitry Andric     case '\n':
1760b57cec5SDimitry Andric       *this << '\\' << 'n';
1770b57cec5SDimitry Andric       break;
1780b57cec5SDimitry Andric     case '"':
1790b57cec5SDimitry Andric       *this << '\\' << '"';
1800b57cec5SDimitry Andric       break;
1810b57cec5SDimitry Andric     default:
1820b57cec5SDimitry Andric       if (isPrint(c)) {
1830b57cec5SDimitry Andric         *this << c;
1840b57cec5SDimitry Andric         break;
1850b57cec5SDimitry Andric       }
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric       // Write out the escaped representation.
1880b57cec5SDimitry Andric       if (UseHexEscapes) {
1890b57cec5SDimitry Andric         *this << '\\' << 'x';
1900b57cec5SDimitry Andric         *this << hexdigit((c >> 4 & 0xF));
1910b57cec5SDimitry Andric         *this << hexdigit((c >> 0) & 0xF);
1920b57cec5SDimitry Andric       } else {
1930b57cec5SDimitry Andric         // Always use a full 3-character octal escape.
1940b57cec5SDimitry Andric         *this << '\\';
1950b57cec5SDimitry Andric         *this << char('0' + ((c >> 6) & 7));
1960b57cec5SDimitry Andric         *this << char('0' + ((c >> 3) & 7));
1970b57cec5SDimitry Andric         *this << char('0' + ((c >> 0) & 7));
1980b57cec5SDimitry Andric       }
1990b57cec5SDimitry Andric     }
2000b57cec5SDimitry Andric   }
2010b57cec5SDimitry Andric 
2020b57cec5SDimitry Andric   return *this;
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(const void *P) {
2060b57cec5SDimitry Andric   llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
2070b57cec5SDimitry Andric   return *this;
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric 
2100b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(double N) {
2110b57cec5SDimitry Andric   llvm::write_double(*this, N, FloatStyle::Exponent);
2120b57cec5SDimitry Andric   return *this;
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric void raw_ostream::flush_nonempty() {
2160b57cec5SDimitry Andric   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
2170b57cec5SDimitry Andric   size_t Length = OutBufCur - OutBufStart;
2180b57cec5SDimitry Andric   OutBufCur = OutBufStart;
2190b57cec5SDimitry Andric   write_impl(OutBufStart, Length);
2200b57cec5SDimitry Andric }
2210b57cec5SDimitry Andric 
2220b57cec5SDimitry Andric raw_ostream &raw_ostream::write(unsigned char C) {
2230b57cec5SDimitry Andric   // Group exceptional cases into a single branch.
2240b57cec5SDimitry Andric   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
2250b57cec5SDimitry Andric     if (LLVM_UNLIKELY(!OutBufStart)) {
226480093f4SDimitry Andric       if (BufferMode == BufferKind::Unbuffered) {
2270b57cec5SDimitry Andric         write_impl(reinterpret_cast<char*>(&C), 1);
2280b57cec5SDimitry Andric         return *this;
2290b57cec5SDimitry Andric       }
2300b57cec5SDimitry Andric       // Set up a buffer and start over.
2310b57cec5SDimitry Andric       SetBuffered();
2320b57cec5SDimitry Andric       return write(C);
2330b57cec5SDimitry Andric     }
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     flush_nonempty();
2360b57cec5SDimitry Andric   }
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   *OutBufCur++ = C;
2390b57cec5SDimitry Andric   return *this;
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
2430b57cec5SDimitry Andric   // Group exceptional cases into a single branch.
2440b57cec5SDimitry Andric   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
2450b57cec5SDimitry Andric     if (LLVM_UNLIKELY(!OutBufStart)) {
246480093f4SDimitry Andric       if (BufferMode == BufferKind::Unbuffered) {
2470b57cec5SDimitry Andric         write_impl(Ptr, Size);
2480b57cec5SDimitry Andric         return *this;
2490b57cec5SDimitry Andric       }
2500b57cec5SDimitry Andric       // Set up a buffer and start over.
2510b57cec5SDimitry Andric       SetBuffered();
2520b57cec5SDimitry Andric       return write(Ptr, Size);
2530b57cec5SDimitry Andric     }
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric     size_t NumBytes = OutBufEnd - OutBufCur;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric     // If the buffer is empty at this point we have a string that is larger
2580b57cec5SDimitry Andric     // than the buffer. Directly write the chunk that is a multiple of the
2590b57cec5SDimitry Andric     // preferred buffer size and put the remainder in the buffer.
2600b57cec5SDimitry Andric     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
2610b57cec5SDimitry Andric       assert(NumBytes != 0 && "undefined behavior");
2620b57cec5SDimitry Andric       size_t BytesToWrite = Size - (Size % NumBytes);
2630b57cec5SDimitry Andric       write_impl(Ptr, BytesToWrite);
2640b57cec5SDimitry Andric       size_t BytesRemaining = Size - BytesToWrite;
2650b57cec5SDimitry Andric       if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
2660b57cec5SDimitry Andric         // Too much left over to copy into our buffer.
2670b57cec5SDimitry Andric         return write(Ptr + BytesToWrite, BytesRemaining);
2680b57cec5SDimitry Andric       }
2690b57cec5SDimitry Andric       copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
2700b57cec5SDimitry Andric       return *this;
2710b57cec5SDimitry Andric     }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric     // We don't have enough space in the buffer to fit the string in. Insert as
2740b57cec5SDimitry Andric     // much as possible, flush and start over with the remainder.
2750b57cec5SDimitry Andric     copy_to_buffer(Ptr, NumBytes);
2760b57cec5SDimitry Andric     flush_nonempty();
2770b57cec5SDimitry Andric     return write(Ptr + NumBytes, Size - NumBytes);
2780b57cec5SDimitry Andric   }
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric   copy_to_buffer(Ptr, Size);
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric   return *this;
2830b57cec5SDimitry Andric }
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
2860b57cec5SDimitry Andric   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   // Handle short strings specially, memcpy isn't very good at very short
2890b57cec5SDimitry Andric   // strings.
2900b57cec5SDimitry Andric   switch (Size) {
2910b57cec5SDimitry Andric   case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
2920b57cec5SDimitry Andric   case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
2930b57cec5SDimitry Andric   case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
2940b57cec5SDimitry Andric   case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
2950b57cec5SDimitry Andric   case 0: break;
2960b57cec5SDimitry Andric   default:
2970b57cec5SDimitry Andric     memcpy(OutBufCur, Ptr, Size);
2980b57cec5SDimitry Andric     break;
2990b57cec5SDimitry Andric   }
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric   OutBufCur += Size;
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
3040b57cec5SDimitry Andric // Formatted output.
3050b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
3060b57cec5SDimitry Andric   // If we have more than a few bytes left in our output buffer, try
3070b57cec5SDimitry Andric   // formatting directly onto its end.
3080b57cec5SDimitry Andric   size_t NextBufferSize = 127;
3090b57cec5SDimitry Andric   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
3100b57cec5SDimitry Andric   if (BufferBytesLeft > 3) {
3110b57cec5SDimitry Andric     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric     // Common case is that we have plenty of space.
3140b57cec5SDimitry Andric     if (BytesUsed <= BufferBytesLeft) {
3150b57cec5SDimitry Andric       OutBufCur += BytesUsed;
3160b57cec5SDimitry Andric       return *this;
3170b57cec5SDimitry Andric     }
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric     // Otherwise, we overflowed and the return value tells us the size to try
3200b57cec5SDimitry Andric     // again with.
3210b57cec5SDimitry Andric     NextBufferSize = BytesUsed;
3220b57cec5SDimitry Andric   }
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric   // If we got here, we didn't have enough space in the output buffer for the
3250b57cec5SDimitry Andric   // string.  Try printing into a SmallVector that is resized to have enough
3260b57cec5SDimitry Andric   // space.  Iterate until we win.
3270b57cec5SDimitry Andric   SmallVector<char, 128> V;
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric   while (true) {
3300b57cec5SDimitry Andric     V.resize(NextBufferSize);
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric     // Try formatting into the SmallVector.
3330b57cec5SDimitry Andric     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric     // If BytesUsed fit into the vector, we win.
3360b57cec5SDimitry Andric     if (BytesUsed <= NextBufferSize)
3370b57cec5SDimitry Andric       return write(V.data(), BytesUsed);
3380b57cec5SDimitry Andric 
3390b57cec5SDimitry Andric     // Otherwise, try again with a new size.
3400b57cec5SDimitry Andric     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
3410b57cec5SDimitry Andric     NextBufferSize = BytesUsed;
3420b57cec5SDimitry Andric   }
3430b57cec5SDimitry Andric }
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
3460b57cec5SDimitry Andric   SmallString<128> S;
3470b57cec5SDimitry Andric   Obj.format(*this);
3480b57cec5SDimitry Andric   return *this;
3490b57cec5SDimitry Andric }
3500b57cec5SDimitry Andric 
3510b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
3520b57cec5SDimitry Andric   if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) {
3530b57cec5SDimitry Andric     this->operator<<(FS.Str);
3540b57cec5SDimitry Andric     return *this;
3550b57cec5SDimitry Andric   }
3560b57cec5SDimitry Andric   const size_t Difference = FS.Width - FS.Str.size();
3570b57cec5SDimitry Andric   switch (FS.Justify) {
3580b57cec5SDimitry Andric   case FormattedString::JustifyLeft:
3590b57cec5SDimitry Andric     this->operator<<(FS.Str);
3600b57cec5SDimitry Andric     this->indent(Difference);
3610b57cec5SDimitry Andric     break;
3620b57cec5SDimitry Andric   case FormattedString::JustifyRight:
3630b57cec5SDimitry Andric     this->indent(Difference);
3640b57cec5SDimitry Andric     this->operator<<(FS.Str);
3650b57cec5SDimitry Andric     break;
3660b57cec5SDimitry Andric   case FormattedString::JustifyCenter: {
3670b57cec5SDimitry Andric     int PadAmount = Difference / 2;
3680b57cec5SDimitry Andric     this->indent(PadAmount);
3690b57cec5SDimitry Andric     this->operator<<(FS.Str);
3700b57cec5SDimitry Andric     this->indent(Difference - PadAmount);
3710b57cec5SDimitry Andric     break;
3720b57cec5SDimitry Andric   }
3730b57cec5SDimitry Andric   default:
3740b57cec5SDimitry Andric     llvm_unreachable("Bad Justification");
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric   return *this;
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
3800b57cec5SDimitry Andric   if (FN.Hex) {
3810b57cec5SDimitry Andric     HexPrintStyle Style;
3820b57cec5SDimitry Andric     if (FN.Upper && FN.HexPrefix)
3830b57cec5SDimitry Andric       Style = HexPrintStyle::PrefixUpper;
3840b57cec5SDimitry Andric     else if (FN.Upper && !FN.HexPrefix)
3850b57cec5SDimitry Andric       Style = HexPrintStyle::Upper;
3860b57cec5SDimitry Andric     else if (!FN.Upper && FN.HexPrefix)
3870b57cec5SDimitry Andric       Style = HexPrintStyle::PrefixLower;
3880b57cec5SDimitry Andric     else
3890b57cec5SDimitry Andric       Style = HexPrintStyle::Lower;
3900b57cec5SDimitry Andric     llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
3910b57cec5SDimitry Andric   } else {
3920b57cec5SDimitry Andric     llvm::SmallString<16> Buffer;
3930b57cec5SDimitry Andric     llvm::raw_svector_ostream Stream(Buffer);
3940b57cec5SDimitry Andric     llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
3950b57cec5SDimitry Andric     if (Buffer.size() < FN.Width)
3960b57cec5SDimitry Andric       indent(FN.Width - Buffer.size());
3970b57cec5SDimitry Andric     (*this) << Buffer;
3980b57cec5SDimitry Andric   }
3990b57cec5SDimitry Andric   return *this;
4000b57cec5SDimitry Andric }
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
4030b57cec5SDimitry Andric   if (FB.Bytes.empty())
4040b57cec5SDimitry Andric     return *this;
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric   size_t LineIndex = 0;
4070b57cec5SDimitry Andric   auto Bytes = FB.Bytes;
4080b57cec5SDimitry Andric   const size_t Size = Bytes.size();
4090b57cec5SDimitry Andric   HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower;
4100b57cec5SDimitry Andric   uint64_t OffsetWidth = 0;
4110b57cec5SDimitry Andric   if (FB.FirstByteOffset.hasValue()) {
4120b57cec5SDimitry Andric     // Figure out how many nibbles are needed to print the largest offset
4130b57cec5SDimitry Andric     // represented by this data set, so that we can align the offset field
4140b57cec5SDimitry Andric     // to the right width.
4150b57cec5SDimitry Andric     size_t Lines = Size / FB.NumPerLine;
4160b57cec5SDimitry Andric     uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
4170b57cec5SDimitry Andric     unsigned Power = 0;
4180b57cec5SDimitry Andric     if (MaxOffset > 0)
4190b57cec5SDimitry Andric       Power = llvm::Log2_64_Ceil(MaxOffset);
4200b57cec5SDimitry Andric     OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
4210b57cec5SDimitry Andric   }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // The width of a block of data including all spaces for group separators.
4240b57cec5SDimitry Andric   unsigned NumByteGroups =
4250b57cec5SDimitry Andric       alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
4260b57cec5SDimitry Andric   unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric   while (!Bytes.empty()) {
4290b57cec5SDimitry Andric     indent(FB.IndentLevel);
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric     if (FB.FirstByteOffset.hasValue()) {
4320b57cec5SDimitry Andric       uint64_t Offset = FB.FirstByteOffset.getValue();
4330b57cec5SDimitry Andric       llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
4340b57cec5SDimitry Andric       *this << ": ";
4350b57cec5SDimitry Andric     }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric     auto Line = Bytes.take_front(FB.NumPerLine);
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric     size_t CharsPrinted = 0;
4400b57cec5SDimitry Andric     // Print the hex bytes for this line in groups
4410b57cec5SDimitry Andric     for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
4420b57cec5SDimitry Andric       if (I && (I % FB.ByteGroupSize) == 0) {
4430b57cec5SDimitry Andric         ++CharsPrinted;
4440b57cec5SDimitry Andric         *this << " ";
4450b57cec5SDimitry Andric       }
4460b57cec5SDimitry Andric       llvm::write_hex(*this, Line[I], HPS, 2);
4470b57cec5SDimitry Andric     }
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric     if (FB.ASCII) {
4500b57cec5SDimitry Andric       // Print any spaces needed for any bytes that we didn't print on this
4510b57cec5SDimitry Andric       // line so that the ASCII bytes are correctly aligned.
4520b57cec5SDimitry Andric       assert(BlockCharWidth >= CharsPrinted);
4530b57cec5SDimitry Andric       indent(BlockCharWidth - CharsPrinted + 2);
4540b57cec5SDimitry Andric       *this << "|";
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric       // Print the ASCII char values for each byte on this line
4570b57cec5SDimitry Andric       for (uint8_t Byte : Line) {
4580b57cec5SDimitry Andric         if (isPrint(Byte))
4590b57cec5SDimitry Andric           *this << static_cast<char>(Byte);
4600b57cec5SDimitry Andric         else
4610b57cec5SDimitry Andric           *this << '.';
4620b57cec5SDimitry Andric       }
4630b57cec5SDimitry Andric       *this << '|';
4640b57cec5SDimitry Andric     }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric     Bytes = Bytes.drop_front(Line.size());
4670b57cec5SDimitry Andric     LineIndex += Line.size();
4680b57cec5SDimitry Andric     if (LineIndex < Size)
4690b57cec5SDimitry Andric       *this << '\n';
4700b57cec5SDimitry Andric   }
4710b57cec5SDimitry Andric   return *this;
4720b57cec5SDimitry Andric }
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric template <char C>
4750b57cec5SDimitry Andric static raw_ostream &write_padding(raw_ostream &OS, unsigned NumChars) {
4760b57cec5SDimitry Andric   static const char Chars[] = {C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
4770b57cec5SDimitry Andric                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
4780b57cec5SDimitry Andric                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
4790b57cec5SDimitry Andric                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C,
4800b57cec5SDimitry Andric                                C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C};
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric   // Usually the indentation is small, handle it with a fastpath.
4830b57cec5SDimitry Andric   if (NumChars < array_lengthof(Chars))
4840b57cec5SDimitry Andric     return OS.write(Chars, NumChars);
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   while (NumChars) {
4870b57cec5SDimitry Andric     unsigned NumToWrite = std::min(NumChars,
4880b57cec5SDimitry Andric                                    (unsigned)array_lengthof(Chars)-1);
4890b57cec5SDimitry Andric     OS.write(Chars, NumToWrite);
4900b57cec5SDimitry Andric     NumChars -= NumToWrite;
4910b57cec5SDimitry Andric   }
4920b57cec5SDimitry Andric   return OS;
4930b57cec5SDimitry Andric }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric /// indent - Insert 'NumSpaces' spaces.
4960b57cec5SDimitry Andric raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
4970b57cec5SDimitry Andric   return write_padding<' '>(*this, NumSpaces);
4980b57cec5SDimitry Andric }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric /// write_zeros - Insert 'NumZeros' nulls.
5010b57cec5SDimitry Andric raw_ostream &raw_ostream::write_zeros(unsigned NumZeros) {
5020b57cec5SDimitry Andric   return write_padding<'\0'>(*this, NumZeros);
5030b57cec5SDimitry Andric }
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric void raw_ostream::anchor() {}
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5080b57cec5SDimitry Andric //  Formatted Output
5090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric // Out of line virtual method.
5120b57cec5SDimitry Andric void format_object_base::home() {
5130b57cec5SDimitry Andric }
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5160b57cec5SDimitry Andric //  raw_fd_ostream
5170b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric static int getFD(StringRef Filename, std::error_code &EC,
5200b57cec5SDimitry Andric                  sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access,
5210b57cec5SDimitry Andric                  sys::fs::OpenFlags Flags) {
5220b57cec5SDimitry Andric   assert((Access & sys::fs::FA_Write) &&
5230b57cec5SDimitry Andric          "Cannot make a raw_ostream from a read-only descriptor!");
5240b57cec5SDimitry Andric 
5250b57cec5SDimitry Andric   // Handle "-" as stdout. Note that when we do this, we consider ourself
5260b57cec5SDimitry Andric   // the owner of stdout and may set the "binary" flag globally based on Flags.
5270b57cec5SDimitry Andric   if (Filename == "-") {
5280b57cec5SDimitry Andric     EC = std::error_code();
5290b57cec5SDimitry Andric     // If user requested binary then put stdout into binary mode if
5300b57cec5SDimitry Andric     // possible.
5310b57cec5SDimitry Andric     if (!(Flags & sys::fs::OF_Text))
5320b57cec5SDimitry Andric       sys::ChangeStdoutToBinary();
5330b57cec5SDimitry Andric     return STDOUT_FILENO;
5340b57cec5SDimitry Andric   }
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric   int FD;
5370b57cec5SDimitry Andric   if (Access & sys::fs::FA_Read)
5380b57cec5SDimitry Andric     EC = sys::fs::openFileForReadWrite(Filename, FD, Disp, Flags);
5390b57cec5SDimitry Andric   else
5400b57cec5SDimitry Andric     EC = sys::fs::openFileForWrite(Filename, FD, Disp, Flags);
5410b57cec5SDimitry Andric   if (EC)
5420b57cec5SDimitry Andric     return -1;
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric   return FD;
5450b57cec5SDimitry Andric }
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC)
5480b57cec5SDimitry Andric     : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
5490b57cec5SDimitry Andric                      sys::fs::OF_None) {}
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
5520b57cec5SDimitry Andric                                sys::fs::CreationDisposition Disp)
5530b57cec5SDimitry Andric     : raw_fd_ostream(Filename, EC, Disp, sys::fs::FA_Write, sys::fs::OF_None) {}
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
5560b57cec5SDimitry Andric                                sys::fs::FileAccess Access)
5570b57cec5SDimitry Andric     : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, Access,
5580b57cec5SDimitry Andric                      sys::fs::OF_None) {}
5590b57cec5SDimitry Andric 
5600b57cec5SDimitry Andric raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
5610b57cec5SDimitry Andric                                sys::fs::OpenFlags Flags)
5620b57cec5SDimitry Andric     : raw_fd_ostream(Filename, EC, sys::fs::CD_CreateAlways, sys::fs::FA_Write,
5630b57cec5SDimitry Andric                      Flags) {}
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
5660b57cec5SDimitry Andric                                sys::fs::CreationDisposition Disp,
5670b57cec5SDimitry Andric                                sys::fs::FileAccess Access,
5680b57cec5SDimitry Andric                                sys::fs::OpenFlags Flags)
5690b57cec5SDimitry Andric     : raw_fd_ostream(getFD(Filename, EC, Disp, Access, Flags), true) {}
5700b57cec5SDimitry Andric 
5710b57cec5SDimitry Andric /// FD is the file descriptor that this writes to.  If ShouldClose is true, this
5720b57cec5SDimitry Andric /// closes the file when the stream is destroyed.
5730b57cec5SDimitry Andric raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
5740b57cec5SDimitry Andric     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose) {
5750b57cec5SDimitry Andric   if (FD < 0 ) {
5760b57cec5SDimitry Andric     ShouldClose = false;
5770b57cec5SDimitry Andric     return;
5780b57cec5SDimitry Andric   }
5790b57cec5SDimitry Andric 
5800b57cec5SDimitry Andric   // Do not attempt to close stdout or stderr. We used to try to maintain the
5810b57cec5SDimitry Andric   // property that tools that support writing file to stdout should not also
5820b57cec5SDimitry Andric   // write informational output to stdout, but in practice we were never able to
5830b57cec5SDimitry Andric   // maintain this invariant. Many features have been added to LLVM and clang
5840b57cec5SDimitry Andric   // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so
5850b57cec5SDimitry Andric   // users must simply be aware that mixed output and remarks is a possibility.
5860b57cec5SDimitry Andric   if (FD <= STDERR_FILENO)
5870b57cec5SDimitry Andric     ShouldClose = false;
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric #ifdef _WIN32
5900b57cec5SDimitry Andric   // Check if this is a console device. This is not equivalent to isatty.
5910b57cec5SDimitry Andric   IsWindowsConsole =
5920b57cec5SDimitry Andric       ::GetFileType((HANDLE)::_get_osfhandle(fd)) == FILE_TYPE_CHAR;
5930b57cec5SDimitry Andric #endif
5940b57cec5SDimitry Andric 
5950b57cec5SDimitry Andric   // Get the starting position.
5960b57cec5SDimitry Andric   off_t loc = ::lseek(FD, 0, SEEK_CUR);
5970b57cec5SDimitry Andric #ifdef _WIN32
5980b57cec5SDimitry Andric   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
5990b57cec5SDimitry Andric   sys::fs::file_status Status;
6000b57cec5SDimitry Andric   std::error_code EC = status(FD, Status);
6010b57cec5SDimitry Andric   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
6020b57cec5SDimitry Andric #else
6030b57cec5SDimitry Andric   SupportsSeeking = loc != (off_t)-1;
6040b57cec5SDimitry Andric #endif
6050b57cec5SDimitry Andric   if (!SupportsSeeking)
6060b57cec5SDimitry Andric     pos = 0;
6070b57cec5SDimitry Andric   else
6080b57cec5SDimitry Andric     pos = static_cast<uint64_t>(loc);
6090b57cec5SDimitry Andric }
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric raw_fd_ostream::~raw_fd_ostream() {
6120b57cec5SDimitry Andric   if (FD >= 0) {
6130b57cec5SDimitry Andric     flush();
6140b57cec5SDimitry Andric     if (ShouldClose) {
6150b57cec5SDimitry Andric       if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
6160b57cec5SDimitry Andric         error_detected(EC);
6170b57cec5SDimitry Andric     }
6180b57cec5SDimitry Andric   }
6190b57cec5SDimitry Andric 
6200b57cec5SDimitry Andric #ifdef __MINGW32__
6210b57cec5SDimitry Andric   // On mingw, global dtors should not call exit().
6220b57cec5SDimitry Andric   // report_fatal_error() invokes exit(). We know report_fatal_error()
6230b57cec5SDimitry Andric   // might not write messages to stderr when any errors were detected
6240b57cec5SDimitry Andric   // on FD == 2.
6250b57cec5SDimitry Andric   if (FD == 2) return;
6260b57cec5SDimitry Andric #endif
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   // If there are any pending errors, report them now. Clients wishing
6290b57cec5SDimitry Andric   // to avoid report_fatal_error calls should check for errors with
6300b57cec5SDimitry Andric   // has_error() and clear the error flag with clear_error() before
6310b57cec5SDimitry Andric   // destructing raw_ostream objects which may have errors.
6320b57cec5SDimitry Andric   if (has_error())
6330b57cec5SDimitry Andric     report_fatal_error("IO failure on output stream: " + error().message(),
6340b57cec5SDimitry Andric                        /*gen_crash_diag=*/false);
6350b57cec5SDimitry Andric }
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric #if defined(_WIN32)
6380b57cec5SDimitry Andric // The most reliable way to print unicode in a Windows console is with
6390b57cec5SDimitry Andric // WriteConsoleW. To use that, first transcode from UTF-8 to UTF-16. This
6400b57cec5SDimitry Andric // assumes that LLVM programs always print valid UTF-8 to the console. The data
6410b57cec5SDimitry Andric // might not be UTF-8 for two major reasons:
6420b57cec5SDimitry Andric // 1. The program is printing binary (-filetype=obj -o -), in which case it
6430b57cec5SDimitry Andric // would have been gibberish anyway.
6440b57cec5SDimitry Andric // 2. The program is printing text in a semi-ascii compatible codepage like
6450b57cec5SDimitry Andric // shift-jis or cp1252.
6460b57cec5SDimitry Andric //
6470b57cec5SDimitry Andric // Most LLVM programs don't produce non-ascii text unless they are quoting
6480b57cec5SDimitry Andric // user source input. A well-behaved LLVM program should either validate that
6490b57cec5SDimitry Andric // the input is UTF-8 or transcode from the local codepage to UTF-8 before
6500b57cec5SDimitry Andric // quoting it. If they don't, this may mess up the encoding, but this is still
6510b57cec5SDimitry Andric // probably the best compromise we can make.
6520b57cec5SDimitry Andric static bool write_console_impl(int FD, StringRef Data) {
6530b57cec5SDimitry Andric   SmallVector<wchar_t, 256> WideText;
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric   // Fall back to ::write if it wasn't valid UTF-8.
6560b57cec5SDimitry Andric   if (auto EC = sys::windows::UTF8ToUTF16(Data, WideText))
6570b57cec5SDimitry Andric     return false;
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   // On Windows 7 and earlier, WriteConsoleW has a low maximum amount of data
6600b57cec5SDimitry Andric   // that can be written to the console at a time.
6610b57cec5SDimitry Andric   size_t MaxWriteSize = WideText.size();
6620b57cec5SDimitry Andric   if (!RunningWindows8OrGreater())
6630b57cec5SDimitry Andric     MaxWriteSize = 32767;
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   size_t WCharsWritten = 0;
6660b57cec5SDimitry Andric   do {
6670b57cec5SDimitry Andric     size_t WCharsToWrite =
6680b57cec5SDimitry Andric         std::min(MaxWriteSize, WideText.size() - WCharsWritten);
6690b57cec5SDimitry Andric     DWORD ActuallyWritten;
6700b57cec5SDimitry Andric     bool Success =
6710b57cec5SDimitry Andric         ::WriteConsoleW((HANDLE)::_get_osfhandle(FD), &WideText[WCharsWritten],
6720b57cec5SDimitry Andric                         WCharsToWrite, &ActuallyWritten,
6730b57cec5SDimitry Andric                         /*Reserved=*/nullptr);
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric     // The most likely reason for WriteConsoleW to fail is that FD no longer
6760b57cec5SDimitry Andric     // points to a console. Fall back to ::write. If this isn't the first loop
6770b57cec5SDimitry Andric     // iteration, something is truly wrong.
6780b57cec5SDimitry Andric     if (!Success)
6790b57cec5SDimitry Andric       return false;
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric     WCharsWritten += ActuallyWritten;
6820b57cec5SDimitry Andric   } while (WCharsWritten != WideText.size());
6830b57cec5SDimitry Andric   return true;
6840b57cec5SDimitry Andric }
6850b57cec5SDimitry Andric #endif
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
6880b57cec5SDimitry Andric   assert(FD >= 0 && "File already closed.");
6890b57cec5SDimitry Andric   pos += Size;
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric #if defined(_WIN32)
6920b57cec5SDimitry Andric   // If this is a Windows console device, try re-encoding from UTF-8 to UTF-16
6930b57cec5SDimitry Andric   // and using WriteConsoleW. If that fails, fall back to plain write().
6940b57cec5SDimitry Andric   if (IsWindowsConsole)
6950b57cec5SDimitry Andric     if (write_console_impl(FD, StringRef(Ptr, Size)))
6960b57cec5SDimitry Andric       return;
6970b57cec5SDimitry Andric #endif
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric   // The maximum write size is limited to INT32_MAX. A write
7000b57cec5SDimitry Andric   // greater than SSIZE_MAX is implementation-defined in POSIX,
7010b57cec5SDimitry Andric   // and Windows _write requires 32 bit input.
7020b57cec5SDimitry Andric   size_t MaxWriteSize = INT32_MAX;
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric #if defined(__linux__)
7050b57cec5SDimitry Andric   // It is observed that Linux returns EINVAL for a very large write (>2G).
7060b57cec5SDimitry Andric   // Make it a reasonably small value.
7070b57cec5SDimitry Andric   MaxWriteSize = 1024 * 1024 * 1024;
7080b57cec5SDimitry Andric #endif
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric   do {
7110b57cec5SDimitry Andric     size_t ChunkSize = std::min(Size, MaxWriteSize);
7120b57cec5SDimitry Andric     ssize_t ret = ::write(FD, Ptr, ChunkSize);
7130b57cec5SDimitry Andric 
7140b57cec5SDimitry Andric     if (ret < 0) {
7150b57cec5SDimitry Andric       // If it's a recoverable error, swallow it and retry the write.
7160b57cec5SDimitry Andric       //
7170b57cec5SDimitry Andric       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
7180b57cec5SDimitry Andric       // raw_ostream isn't designed to do non-blocking I/O. However, some
7190b57cec5SDimitry Andric       // programs, such as old versions of bjam, have mistakenly used
7200b57cec5SDimitry Andric       // O_NONBLOCK. For compatibility, emulate blocking semantics by
7210b57cec5SDimitry Andric       // spinning until the write succeeds. If you don't want spinning,
7220b57cec5SDimitry Andric       // don't use O_NONBLOCK file descriptors with raw_ostream.
7230b57cec5SDimitry Andric       if (errno == EINTR || errno == EAGAIN
7240b57cec5SDimitry Andric #ifdef EWOULDBLOCK
7250b57cec5SDimitry Andric           || errno == EWOULDBLOCK
7260b57cec5SDimitry Andric #endif
7270b57cec5SDimitry Andric           )
7280b57cec5SDimitry Andric         continue;
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric       // Otherwise it's a non-recoverable error. Note it and quit.
7310b57cec5SDimitry Andric       error_detected(std::error_code(errno, std::generic_category()));
7320b57cec5SDimitry Andric       break;
7330b57cec5SDimitry Andric     }
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric     // The write may have written some or all of the data. Update the
7360b57cec5SDimitry Andric     // size and buffer pointer to reflect the remainder that needs
7370b57cec5SDimitry Andric     // to be written. If there are no bytes left, we're done.
7380b57cec5SDimitry Andric     Ptr += ret;
7390b57cec5SDimitry Andric     Size -= ret;
7400b57cec5SDimitry Andric   } while (Size > 0);
7410b57cec5SDimitry Andric }
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric void raw_fd_ostream::close() {
7440b57cec5SDimitry Andric   assert(ShouldClose);
7450b57cec5SDimitry Andric   ShouldClose = false;
7460b57cec5SDimitry Andric   flush();
7470b57cec5SDimitry Andric   if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
7480b57cec5SDimitry Andric     error_detected(EC);
7490b57cec5SDimitry Andric   FD = -1;
7500b57cec5SDimitry Andric }
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric uint64_t raw_fd_ostream::seek(uint64_t off) {
7530b57cec5SDimitry Andric   assert(SupportsSeeking && "Stream does not support seeking!");
7540b57cec5SDimitry Andric   flush();
7550b57cec5SDimitry Andric #ifdef _WIN32
7560b57cec5SDimitry Andric   pos = ::_lseeki64(FD, off, SEEK_SET);
7570b57cec5SDimitry Andric #elif defined(HAVE_LSEEK64)
7580b57cec5SDimitry Andric   pos = ::lseek64(FD, off, SEEK_SET);
7590b57cec5SDimitry Andric #else
7600b57cec5SDimitry Andric   pos = ::lseek(FD, off, SEEK_SET);
7610b57cec5SDimitry Andric #endif
7620b57cec5SDimitry Andric   if (pos == (uint64_t)-1)
7630b57cec5SDimitry Andric     error_detected(std::error_code(errno, std::generic_category()));
7640b57cec5SDimitry Andric   return pos;
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
7680b57cec5SDimitry Andric                                  uint64_t Offset) {
7690b57cec5SDimitry Andric   uint64_t Pos = tell();
7700b57cec5SDimitry Andric   seek(Offset);
7710b57cec5SDimitry Andric   write(Ptr, Size);
7720b57cec5SDimitry Andric   seek(Pos);
7730b57cec5SDimitry Andric }
7740b57cec5SDimitry Andric 
7750b57cec5SDimitry Andric size_t raw_fd_ostream::preferred_buffer_size() const {
7760b57cec5SDimitry Andric #if defined(_WIN32)
7770b57cec5SDimitry Andric   // Disable buffering for console devices. Console output is re-encoded from
7780b57cec5SDimitry Andric   // UTF-8 to UTF-16 on Windows, and buffering it would require us to split the
7790b57cec5SDimitry Andric   // buffer on a valid UTF-8 codepoint boundary. Terminal buffering is disabled
7800b57cec5SDimitry Andric   // below on most other OSs, so do the same thing on Windows and avoid that
7810b57cec5SDimitry Andric   // complexity.
7820b57cec5SDimitry Andric   if (IsWindowsConsole)
7830b57cec5SDimitry Andric     return 0;
7840b57cec5SDimitry Andric   return raw_ostream::preferred_buffer_size();
7850b57cec5SDimitry Andric #elif !defined(__minix)
7860b57cec5SDimitry Andric   // Minix has no st_blksize.
7870b57cec5SDimitry Andric   assert(FD >= 0 && "File not yet open!");
7880b57cec5SDimitry Andric   struct stat statbuf;
7890b57cec5SDimitry Andric   if (fstat(FD, &statbuf) != 0)
7900b57cec5SDimitry Andric     return 0;
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   // If this is a terminal, don't use buffering. Line buffering
7930b57cec5SDimitry Andric   // would be a more traditional thing to do, but it's not worth
7940b57cec5SDimitry Andric   // the complexity.
7950b57cec5SDimitry Andric   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
7960b57cec5SDimitry Andric     return 0;
7970b57cec5SDimitry Andric   // Return the preferred block size.
7980b57cec5SDimitry Andric   return statbuf.st_blksize;
7990b57cec5SDimitry Andric #else
8000b57cec5SDimitry Andric   return raw_ostream::preferred_buffer_size();
8010b57cec5SDimitry Andric #endif
8020b57cec5SDimitry Andric }
8030b57cec5SDimitry Andric 
8040b57cec5SDimitry Andric raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
8050b57cec5SDimitry Andric                                          bool bg) {
8068bcb0991SDimitry Andric   if (!ColorEnabled)
8078bcb0991SDimitry Andric     return *this;
8088bcb0991SDimitry Andric 
8090b57cec5SDimitry Andric   if (sys::Process::ColorNeedsFlush())
8100b57cec5SDimitry Andric     flush();
8110b57cec5SDimitry Andric   const char *colorcode =
8128bcb0991SDimitry Andric       (colors == SAVEDCOLOR)
8138bcb0991SDimitry Andric           ? sys::Process::OutputBold(bg)
8148bcb0991SDimitry Andric           : sys::Process::OutputColor(static_cast<char>(colors), bold, bg);
8150b57cec5SDimitry Andric   if (colorcode) {
8160b57cec5SDimitry Andric     size_t len = strlen(colorcode);
8170b57cec5SDimitry Andric     write(colorcode, len);
8180b57cec5SDimitry Andric     // don't account colors towards output characters
8190b57cec5SDimitry Andric     pos -= len;
8200b57cec5SDimitry Andric   }
8210b57cec5SDimitry Andric   return *this;
8220b57cec5SDimitry Andric }
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric raw_ostream &raw_fd_ostream::resetColor() {
8258bcb0991SDimitry Andric   if (!ColorEnabled)
8268bcb0991SDimitry Andric     return *this;
8278bcb0991SDimitry Andric 
8280b57cec5SDimitry Andric   if (sys::Process::ColorNeedsFlush())
8290b57cec5SDimitry Andric     flush();
8300b57cec5SDimitry Andric   const char *colorcode = sys::Process::ResetColor();
8310b57cec5SDimitry Andric   if (colorcode) {
8320b57cec5SDimitry Andric     size_t len = strlen(colorcode);
8330b57cec5SDimitry Andric     write(colorcode, len);
8340b57cec5SDimitry Andric     // don't account colors towards output characters
8350b57cec5SDimitry Andric     pos -= len;
8360b57cec5SDimitry Andric   }
8370b57cec5SDimitry Andric   return *this;
8380b57cec5SDimitry Andric }
8390b57cec5SDimitry Andric 
8400b57cec5SDimitry Andric raw_ostream &raw_fd_ostream::reverseColor() {
8418bcb0991SDimitry Andric   if (!ColorEnabled)
8428bcb0991SDimitry Andric     return *this;
8438bcb0991SDimitry Andric 
8440b57cec5SDimitry Andric   if (sys::Process::ColorNeedsFlush())
8450b57cec5SDimitry Andric     flush();
8460b57cec5SDimitry Andric   const char *colorcode = sys::Process::OutputReverse();
8470b57cec5SDimitry Andric   if (colorcode) {
8480b57cec5SDimitry Andric     size_t len = strlen(colorcode);
8490b57cec5SDimitry Andric     write(colorcode, len);
8500b57cec5SDimitry Andric     // don't account colors towards output characters
8510b57cec5SDimitry Andric     pos -= len;
8520b57cec5SDimitry Andric   }
8530b57cec5SDimitry Andric   return *this;
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric 
8560b57cec5SDimitry Andric bool raw_fd_ostream::is_displayed() const {
8570b57cec5SDimitry Andric   return sys::Process::FileDescriptorIsDisplayed(FD);
8580b57cec5SDimitry Andric }
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric bool raw_fd_ostream::has_colors() const {
8610b57cec5SDimitry Andric   return sys::Process::FileDescriptorHasColors(FD);
8620b57cec5SDimitry Andric }
8630b57cec5SDimitry Andric 
8640b57cec5SDimitry Andric void raw_fd_ostream::anchor() {}
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8670b57cec5SDimitry Andric //  outs(), errs(), nulls()
8680b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric /// outs() - This returns a reference to a raw_ostream for standard output.
8710b57cec5SDimitry Andric /// Use it like: outs() << "foo" << "bar";
8720b57cec5SDimitry Andric raw_ostream &llvm::outs() {
8730b57cec5SDimitry Andric   // Set buffer settings to model stdout behavior.
8740b57cec5SDimitry Andric   std::error_code EC;
8758bcb0991SDimitry Andric   static raw_fd_ostream S("-", EC, sys::fs::OF_None);
8760b57cec5SDimitry Andric   assert(!EC);
8770b57cec5SDimitry Andric   return S;
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric 
8800b57cec5SDimitry Andric /// errs() - This returns a reference to a raw_ostream for standard error.
8810b57cec5SDimitry Andric /// Use it like: errs() << "foo" << "bar";
8820b57cec5SDimitry Andric raw_ostream &llvm::errs() {
8830b57cec5SDimitry Andric   // Set standard error to be unbuffered by default.
8840b57cec5SDimitry Andric   static raw_fd_ostream S(STDERR_FILENO, false, true);
8850b57cec5SDimitry Andric   return S;
8860b57cec5SDimitry Andric }
8870b57cec5SDimitry Andric 
8880b57cec5SDimitry Andric /// nulls() - This returns a reference to a raw_ostream which discards output.
8890b57cec5SDimitry Andric raw_ostream &llvm::nulls() {
8900b57cec5SDimitry Andric   static raw_null_ostream S;
8910b57cec5SDimitry Andric   return S;
8920b57cec5SDimitry Andric }
8930b57cec5SDimitry Andric 
8940b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8950b57cec5SDimitry Andric //  raw_string_ostream
8960b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric raw_string_ostream::~raw_string_ostream() {
8990b57cec5SDimitry Andric   flush();
9000b57cec5SDimitry Andric }
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
9030b57cec5SDimitry Andric   OS.append(Ptr, Size);
9040b57cec5SDimitry Andric }
9050b57cec5SDimitry Andric 
9060b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9070b57cec5SDimitry Andric //  raw_svector_ostream
9080b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9090b57cec5SDimitry Andric 
9100b57cec5SDimitry Andric uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
9110b57cec5SDimitry Andric 
9120b57cec5SDimitry Andric void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
9130b57cec5SDimitry Andric   OS.append(Ptr, Ptr + Size);
9140b57cec5SDimitry Andric }
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
9170b57cec5SDimitry Andric                                       uint64_t Offset) {
9180b57cec5SDimitry Andric   memcpy(OS.data() + Offset, Ptr, Size);
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9220b57cec5SDimitry Andric //  raw_null_ostream
9230b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric raw_null_ostream::~raw_null_ostream() {
9260b57cec5SDimitry Andric #ifndef NDEBUG
9270b57cec5SDimitry Andric   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
9280b57cec5SDimitry Andric   // with raw_null_ostream, but it's better to have raw_null_ostream follow
9290b57cec5SDimitry Andric   // the rules than to change the rules just for raw_null_ostream.
9300b57cec5SDimitry Andric   flush();
9310b57cec5SDimitry Andric #endif
9320b57cec5SDimitry Andric }
9330b57cec5SDimitry Andric 
9340b57cec5SDimitry Andric void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
9350b57cec5SDimitry Andric }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric uint64_t raw_null_ostream::current_pos() const {
9380b57cec5SDimitry Andric   return 0;
9390b57cec5SDimitry Andric }
9400b57cec5SDimitry Andric 
9410b57cec5SDimitry Andric void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
9420b57cec5SDimitry Andric                                    uint64_t Offset) {}
9430b57cec5SDimitry Andric 
9440b57cec5SDimitry Andric void raw_pwrite_stream::anchor() {}
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric void buffer_ostream::anchor() {}
947