LCOV - code coverage report
Current view: top level - lib/Support - raw_ostream.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 316 351 90.0 %
Date: 2017-09-14 15:23:50 Functions: 47 55 85.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===--- raw_ostream.cpp - Implement the raw_ostream classes --------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This implements support for bulk buffered stream output.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "llvm/Support/raw_ostream.h"
      15             : #include "llvm/ADT/STLExtras.h"
      16             : #include "llvm/ADT/SmallVector.h"
      17             : #include "llvm/ADT/StringExtras.h"
      18             : #include "llvm/Config/config.h"
      19             : #include "llvm/Support/Compiler.h"
      20             : #include "llvm/Support/ErrorHandling.h"
      21             : #include "llvm/Support/FileSystem.h"
      22             : #include "llvm/Support/Format.h"
      23             : #include "llvm/Support/FormatVariadic.h"
      24             : #include "llvm/Support/MathExtras.h"
      25             : #include "llvm/Support/NativeFormatting.h"
      26             : #include "llvm/Support/Process.h"
      27             : #include "llvm/Support/Program.h"
      28             : #include <algorithm>
      29             : #include <cctype>
      30             : #include <cerrno>
      31             : #include <cstdio>
      32             : #include <iterator>
      33             : #include <sys/stat.h>
      34             : #include <system_error>
      35             : 
      36             : // <fcntl.h> may provide O_BINARY.
      37             : #if defined(HAVE_FCNTL_H)
      38             : # include <fcntl.h>
      39             : #endif
      40             : 
      41             : #if defined(HAVE_UNISTD_H)
      42             : # include <unistd.h>
      43             : #endif
      44             : #if defined(HAVE_SYS_UIO_H) && defined(HAVE_WRITEV)
      45             : #  include <sys/uio.h>
      46             : #endif
      47             : 
      48             : #if defined(__CYGWIN__)
      49             : #include <io.h>
      50             : #endif
      51             : 
      52             : #if defined(_MSC_VER)
      53             : #include <io.h>
      54             : #ifndef STDIN_FILENO
      55             : # define STDIN_FILENO 0
      56             : #endif
      57             : #ifndef STDOUT_FILENO
      58             : # define STDOUT_FILENO 1
      59             : #endif
      60             : #ifndef STDERR_FILENO
      61             : # define STDERR_FILENO 2
      62             : #endif
      63             : #endif
      64             : 
      65             : #ifdef LLVM_ON_WIN32
      66             : #include "Windows/WindowsSupport.h"
      67             : #endif
      68             : 
      69             : using namespace llvm;
      70             : 
      71    38845784 : raw_ostream::~raw_ostream() {
      72             :   // raw_ostream's subclasses should take care to flush the buffer
      73             :   // in their destructors.
      74             :   assert(OutBufCur == OutBufStart &&
      75             :          "raw_ostream destructor called with non-empty buffer!");
      76             : 
      77    19422892 :   if (BufferMode == InternalBuffer)
      78     4237792 :     delete [] OutBufStart;
      79    19422892 : }
      80             : 
      81             : // An out of line virtual method to provide a home for the class vtable.
      82           0 : void raw_ostream::handle() {}
      83             : 
      84     1740352 : size_t raw_ostream::preferred_buffer_size() const {
      85             :   // BUFSIZ is intended to be a reasonable default.
      86     1740352 :   return BUFSIZ;
      87             : }
      88             : 
      89     1764086 : void raw_ostream::SetBuffered() {
      90             :   // Ask the subclass to determine an appropriate buffer size.
      91     1764086 :   if (size_t Size = preferred_buffer_size())
      92     1764086 :     SetBufferSize(Size);
      93             :   else
      94             :     // It may return 0, meaning this stream should be unbuffered.
      95           0 :     SetUnbuffered();
      96     1764086 : }
      97             : 
      98    18702258 : void raw_ostream::SetBufferAndMode(char *BufferStart, size_t Size,
      99             :                                    BufferKind Mode) {
     100             :   assert(((Mode == Unbuffered && !BufferStart && Size == 0) ||
     101             :           (Mode != Unbuffered && BufferStart && Size != 0)) &&
     102             :          "stream must be unbuffered or have at least one byte");
     103             :   // Make sure the current buffer is free of content (we can't flush here; the
     104             :   // child buffer management logic will be in write_impl).
     105             :   assert(GetNumBytesInBuffer() == 0 && "Current buffer is non-empty!");
     106             : 
     107    18702258 :   if (BufferMode == InternalBuffer)
     108    16942797 :     delete [] OutBufStart;
     109    18702258 :   OutBufStart = BufferStart;
     110    18702258 :   OutBufEnd = OutBufStart+Size;
     111    18702258 :   OutBufCur = OutBufStart;
     112    18702258 :   BufferMode = Mode;
     113             : 
     114             :   assert(OutBufStart <= OutBufEnd && "Invalid size!");
     115    18702258 : }
     116             : 
     117    38133881 : raw_ostream &raw_ostream::operator<<(unsigned long N) {
     118    38133881 :   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
     119    38133881 :   return *this;
     120             : }
     121             : 
     122     6207076 : raw_ostream &raw_ostream::operator<<(long N) {
     123     6207076 :   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
     124     6207076 :   return *this;
     125             : }
     126             : 
     127           0 : raw_ostream &raw_ostream::operator<<(unsigned long long N) {
     128           0 :   write_integer(*this, static_cast<uint64_t>(N), 0, IntegerStyle::Integer);
     129           0 :   return *this;
     130             : }
     131             : 
     132        1785 : raw_ostream &raw_ostream::operator<<(long long N) {
     133        1785 :   write_integer(*this, static_cast<int64_t>(N), 0, IntegerStyle::Integer);
     134        1785 :   return *this;
     135             : }
     136             : 
     137      310935 : raw_ostream &raw_ostream::write_hex(unsigned long long N) {
     138      621870 :   llvm::write_hex(*this, N, HexPrintStyle::Lower);
     139      310935 :   return *this;
     140             : }
     141             : 
     142          32 : raw_ostream &raw_ostream::write_uuid(const uuid_t UUID) {
     143         544 :   for (int Idx = 0; Idx < 16; ++Idx) {
     144        1024 :     *this << format("%02" PRIX32, UUID[Idx]);
     145         512 :     if (Idx == 3 || Idx == 5 || Idx == 7 || Idx == 9)
     146         128 :       *this << "-";
     147             :   }
     148          32 :   return *this;
     149             : }
     150             : 
     151             : 
     152      157057 : raw_ostream &raw_ostream::write_escaped(StringRef Str,
     153             :                                         bool UseHexEscapes) {
     154     1385670 :   for (unsigned char c : Str) {
     155     1071556 :     switch (c) {
     156          66 :     case '\\':
     157          66 :       *this << '\\' << '\\';
     158             :       break;
     159         543 :     case '\t':
     160         543 :       *this << '\\' << 't';
     161             :       break;
     162         425 :     case '\n':
     163         425 :       *this << '\\' << 'n';
     164             :       break;
     165          70 :     case '"':
     166          70 :       *this << '\\' << '"';
     167             :       break;
     168     1070452 :     default:
     169     1070452 :       if (std::isprint(c)) {
     170     1054923 :         *this << c;
     171             :         break;
     172             :       }
     173             : 
     174             :       // Write out the escaped representation.
     175       15529 :       if (UseHexEscapes) {
     176         330 :         *this << '\\' << 'x';
     177         495 :         *this << hexdigit((c >> 4 & 0xF));
     178         330 :         *this << hexdigit((c >> 0) & 0xF);
     179             :       } else {
     180             :         // Always use a full 3-character octal escape.
     181       15364 :         *this << '\\';
     182       30728 :         *this << char('0' + ((c >> 6) & 7));
     183       30728 :         *this << char('0' + ((c >> 3) & 7));
     184       15364 :         *this << char('0' + ((c >> 0) & 7));
     185             :       }
     186             :     }
     187             :   }
     188             : 
     189      157057 :   return *this;
     190             : }
     191             : 
     192       12697 : raw_ostream &raw_ostream::operator<<(const void *P) {
     193       25394 :   llvm::write_hex(*this, (uintptr_t)P, HexPrintStyle::PrefixLower);
     194       12697 :   return *this;
     195             : }
     196             : 
     197       28531 : raw_ostream &raw_ostream::operator<<(double N) {
     198       57062 :   llvm::write_double(*this, N, FloatStyle::Exponent);
     199       28531 :   return *this;
     200             : }
     201             : 
     202     2430677 : void raw_ostream::flush_nonempty() {
     203             :   assert(OutBufCur > OutBufStart && "Invalid call to flush_nonempty.");
     204     2430677 :   size_t Length = OutBufCur - OutBufStart;
     205     2430677 :   OutBufCur = OutBufStart;
     206     2430677 :   write_impl(OutBufStart, Length);
     207     2430677 : }
     208             : 
     209    55456365 : raw_ostream &raw_ostream::write(unsigned char C) {
     210             :   // Group exceptional cases into a single branch.
     211    55456365 :   if (LLVM_UNLIKELY(OutBufCur >= OutBufEnd)) {
     212    55158244 :     if (LLVM_UNLIKELY(!OutBufStart)) {
     213    55141160 :       if (BufferMode == Unbuffered) {
     214    54850848 :         write_impl(reinterpret_cast<char*>(&C), 1);
     215    54850848 :         return *this;
     216             :       }
     217             :       // Set up a buffer and start over.
     218      290312 :       SetBuffered();
     219      290312 :       return write(C);
     220             :     }
     221             : 
     222       17084 :     flush_nonempty();
     223             :   }
     224             : 
     225      315205 :   *OutBufCur++ = C;
     226      315205 :   return *this;
     227             : }
     228             : 
     229   426162082 : raw_ostream &raw_ostream::write(const char *Ptr, size_t Size) {
     230             :   // Group exceptional cases into a single branch.
     231   427878704 :   if (LLVM_UNLIKELY(size_t(OutBufEnd - OutBufCur) < Size)) {
     232   358889303 :     if (LLVM_UNLIKELY(!OutBufStart)) {
     233   358641848 :       if (BufferMode == Unbuffered) {
     234   357168074 :         write_impl(Ptr, Size);
     235   357168079 :         return *this;
     236             :       }
     237             :       // Set up a buffer and start over.
     238     1473774 :       SetBuffered();
     239     1473774 :       return write(Ptr, Size);
     240             :     }
     241             : 
     242      247455 :     size_t NumBytes = OutBufEnd - OutBufCur;
     243             : 
     244             :     // If the buffer is empty at this point we have a string that is larger
     245             :     // than the buffer. Directly write the chunk that is a multiple of the
     246             :     // preferred buffer size and put the remainder in the buffer.
     247      247455 :     if (LLVM_UNLIKELY(OutBufCur == OutBufStart)) {
     248             :       assert(NumBytes != 0 && "undefined behavior");
     249        4607 :       size_t BytesToWrite = Size - (Size % NumBytes);
     250        4607 :       write_impl(Ptr, BytesToWrite);
     251        4607 :       size_t BytesRemaining = Size - BytesToWrite;
     252        4607 :       if (BytesRemaining > size_t(OutBufEnd - OutBufCur)) {
     253             :         // Too much left over to copy into our buffer.
     254           0 :         return write(Ptr + BytesToWrite, BytesRemaining);
     255             :       }
     256        4607 :       copy_to_buffer(Ptr + BytesToWrite, BytesRemaining);
     257        4607 :       return *this;
     258             :     }
     259             : 
     260             :     // We don't have enough space in the buffer to fit the string in. Insert as
     261             :     // much as possible, flush and start over with the remainder.
     262      242848 :     copy_to_buffer(Ptr, NumBytes);
     263      242848 :     flush_nonempty();
     264      242848 :     return write(Ptr + NumBytes, Size - NumBytes);
     265             :   }
     266             : 
     267    68989401 :   copy_to_buffer(Ptr, Size);
     268             : 
     269    68989401 :   return *this;
     270             : }
     271             : 
     272    69236856 : void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
     273             :   assert(Size <= size_t(OutBufEnd - OutBufCur) && "Buffer overrun!");
     274             : 
     275             :   // Handle short strings specially, memcpy isn't very good at very short
     276             :   // strings.
     277    69236856 :   switch (Size) {
     278     7228855 :   case 4: OutBufCur[3] = Ptr[3]; LLVM_FALLTHROUGH;
     279     8331225 :   case 3: OutBufCur[2] = Ptr[2]; LLVM_FALLTHROUGH;
     280    44753272 :   case 2: OutBufCur[1] = Ptr[1]; LLVM_FALLTHROUGH;
     281    56037564 :   case 1: OutBufCur[0] = Ptr[0]; LLVM_FALLTHROUGH;
     282             :   case 0: break;
     283    12834270 :   default:
     284    12834270 :     memcpy(OutBufCur, Ptr, Size);
     285    12834270 :     break;
     286             :   }
     287             : 
     288    69236856 :   OutBufCur += Size;
     289    69236856 : }
     290             : 
     291             : // Formatted output.
     292     3472338 : raw_ostream &raw_ostream::operator<<(const format_object_base &Fmt) {
     293             :   // If we have more than a few bytes left in our output buffer, try
     294             :   // formatting directly onto its end.
     295     3472338 :   size_t NextBufferSize = 127;
     296     3472338 :   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
     297     3472338 :   if (BufferBytesLeft > 3) {
     298     2778806 :     size_t BytesUsed = Fmt.print(OutBufCur, BufferBytesLeft);
     299             : 
     300             :     // Common case is that we have plenty of space.
     301     1389403 :     if (BytesUsed <= BufferBytesLeft) {
     302     1388845 :       OutBufCur += BytesUsed;
     303     1388845 :       return *this;
     304             :     }
     305             : 
     306             :     // Otherwise, we overflowed and the return value tells us the size to try
     307             :     // again with.
     308             :     NextBufferSize = BytesUsed;
     309             :   }
     310             : 
     311             :   // If we got here, we didn't have enough space in the output buffer for the
     312             :   // string.  Try printing into a SmallVector that is resized to have enough
     313             :   // space.  Iterate until we win.
     314             :   SmallVector<char, 128> V;
     315             : 
     316             :   while (true) {
     317     2083512 :     V.resize(NextBufferSize);
     318             : 
     319             :     // Try formatting into the SmallVector.
     320     6250536 :     size_t BytesUsed = Fmt.print(V.data(), NextBufferSize);
     321             : 
     322             :     // If BytesUsed fit into the vector, we win.
     323     2083512 :     if (BytesUsed <= NextBufferSize)
     324     4166986 :       return write(V.data(), BytesUsed);
     325             : 
     326             :     // Otherwise, try again with a new size.
     327             :     assert(BytesUsed > NextBufferSize && "Didn't grow buffer!?");
     328             :     NextBufferSize = BytesUsed;
     329             :   }
     330             : }
     331             : 
     332        8512 : raw_ostream &raw_ostream::operator<<(const formatv_object_base &Obj) {
     333       17024 :   SmallString<128> S;
     334        8512 :   Obj.format(*this);
     335       17024 :   return *this;
     336             : }
     337             : 
     338        1888 : raw_ostream &raw_ostream::operator<<(const FormattedString &FS) {
     339        3776 :   if (FS.Str.size() >= FS.Width || FS.Justify == FormattedString::JustifyNone) {
     340          33 :     this->operator<<(FS.Str);
     341          33 :     return *this;
     342             :   }
     343        1855 :   const size_t Difference = FS.Width - FS.Str.size();
     344        1855 :   switch (FS.Justify) {
     345         492 :   case FormattedString::JustifyLeft:
     346         492 :     this->operator<<(FS.Str);
     347         492 :     this->indent(Difference);
     348         492 :     break;
     349        1360 :   case FormattedString::JustifyRight:
     350        1360 :     this->indent(Difference);
     351        1360 :     this->operator<<(FS.Str);
     352        1360 :     break;
     353           3 :   case FormattedString::JustifyCenter: {
     354           3 :     int PadAmount = Difference / 2;
     355           3 :     this->indent(PadAmount);
     356           3 :     this->operator<<(FS.Str);
     357           3 :     this->indent(Difference - PadAmount);
     358           3 :     break;
     359             :   }
     360           0 :   default:
     361           0 :     llvm_unreachable("Bad Justification");
     362             :   }
     363             :   return *this;
     364             : }
     365             : 
     366      617107 : raw_ostream &raw_ostream::operator<<(const FormattedNumber &FN) {
     367      617107 :   if (FN.Hex) {
     368             :     HexPrintStyle Style;
     369      616409 :     if (FN.Upper && FN.HexPrefix)
     370             :       Style = HexPrintStyle::PrefixUpper;
     371      614551 :     else if (FN.Upper && !FN.HexPrefix)
     372             :       Style = HexPrintStyle::Upper;
     373        2402 :     else if (!FN.Upper && FN.HexPrefix)
     374             :       Style = HexPrintStyle::PrefixLower;
     375             :     else
     376        1473 :       Style = HexPrintStyle::Lower;
     377     1849227 :     llvm::write_hex(*this, FN.HexValue, Style, FN.Width);
     378             :   } else {
     379        1396 :     llvm::SmallString<16> Buffer;
     380        1396 :     llvm::raw_svector_ostream Stream(Buffer);
     381         698 :     llvm::write_integer(Stream, FN.DecValue, 0, IntegerStyle::Integer);
     382         698 :     if (Buffer.size() < FN.Width)
     383        1156 :       indent(FN.Width - Buffer.size());
     384         698 :     (*this) << Buffer;
     385             :   }
     386      617107 :   return *this;
     387             : }
     388             : 
     389        3186 : raw_ostream &raw_ostream::operator<<(const FormattedBytes &FB) {
     390        3186 :   if (FB.Bytes.empty())
     391             :     return *this;
     392             : 
     393        3118 :   size_t LineIndex = 0;
     394        3118 :   auto Bytes = FB.Bytes;
     395        3118 :   const size_t Size = Bytes.size();
     396        3118 :   HexPrintStyle HPS = FB.Upper ? HexPrintStyle::Upper : HexPrintStyle::Lower;
     397        3118 :   uint64_t OffsetWidth = 0;
     398        3118 :   if (FB.FirstByteOffset.hasValue()) {
     399             :     // Figure out how many nibbles are needed to print the largest offset
     400             :     // represented by this data set, so that we can align the offset field
     401             :     // to the right width.
     402        1557 :     size_t Lines = Size / FB.NumPerLine;
     403        3114 :     uint64_t MaxOffset = *FB.FirstByteOffset + Lines * FB.NumPerLine;
     404        1557 :     unsigned Power = 0;
     405        1557 :     if (MaxOffset > 0)
     406        1091 :       Power = llvm::Log2_64_Ceil(MaxOffset);
     407        4671 :     OffsetWidth = std::max<uint64_t>(4, llvm::alignTo(Power, 4) / 4);
     408             :   }
     409             : 
     410             :   // The width of a block of data including all spaces for group separators.
     411             :   unsigned NumByteGroups =
     412        6236 :       alignTo(FB.NumPerLine, FB.ByteGroupSize) / FB.ByteGroupSize;
     413        3118 :   unsigned BlockCharWidth = FB.NumPerLine * 2 + NumByteGroups - 1;
     414             : 
     415     1692381 :   while (!Bytes.empty()) {
     416     1689263 :     indent(FB.IndentLevel);
     417             : 
     418     1689263 :     if (FB.FirstByteOffset.hasValue()) {
     419     3375360 :       uint64_t Offset = FB.FirstByteOffset.getValue();
     420     3375360 :       llvm::write_hex(*this, Offset + LineIndex, HPS, OffsetWidth);
     421     1687680 :       *this << ": ";
     422             :     }
     423             : 
     424     3378526 :     auto Line = Bytes.take_front(FB.NumPerLine);
     425             : 
     426     1689263 :     size_t CharsPrinted = 0;
     427             :     // Print the hex bytes for this line in groups
     428    28715836 :     for (size_t I = 0; I < Line.size(); ++I, CharsPrinted += 2) {
     429    27026573 :       if (I && (I % FB.ByteGroupSize) == 0) {
     430     5080860 :         ++CharsPrinted;
     431     5080860 :         *this << " ";
     432             :       }
     433   108106292 :       llvm::write_hex(*this, Line[I], HPS, 2);
     434             :     }
     435             : 
     436     1689263 :     if (FB.ASCII) {
     437             :       // Print any spaces needed for any bytes that we didn't print on this
     438             :       // line so that the ASCII bytes are correctly aligned.
     439             :       assert(BlockCharWidth >= CharsPrinted);
     440     1687682 :       indent(BlockCharWidth - CharsPrinted + 2);
     441     1687682 :       *this << "|";
     442             : 
     443             :       // Print the ASCII char values for each byte on this line
     444    30384196 :       for (uint8_t Byte : Line) {
     445    27008832 :         if (isprint(Byte))
     446       23775 :           *this << static_cast<char>(Byte);
     447             :         else
     448             :           *this << '.';
     449             :       }
     450             :       *this << '|';
     451             :     }
     452             : 
     453     3378526 :     Bytes = Bytes.drop_front(Line.size());
     454     1689263 :     LineIndex += Line.size();
     455     1689263 :     if (LineIndex < Size)
     456             :       *this << '\n';
     457             :   }
     458             :   return *this;
     459             : }
     460             : 
     461             : /// indent - Insert 'NumSpaces' spaces.
     462    20471855 : raw_ostream &raw_ostream::indent(unsigned NumSpaces) {
     463             :   static const char Spaces[] = "                                "
     464             :                                "                                "
     465             :                                "                ";
     466             : 
     467             :   // Usually the indentation is small, handle it with a fastpath.
     468    20471855 :   if (NumSpaces < array_lengthof(Spaces))
     469    20471855 :     return write(Spaces, NumSpaces);
     470             : 
     471           0 :   while (NumSpaces) {
     472             :     unsigned NumToWrite = std::min(NumSpaces,
     473           0 :                                    (unsigned)array_lengthof(Spaces)-1);
     474           0 :     write(Spaces, NumToWrite);
     475           0 :     NumSpaces -= NumToWrite;
     476             :   }
     477             :   return *this;
     478             : }
     479             : 
     480             : //===----------------------------------------------------------------------===//
     481             : //  Formatted Output
     482             : //===----------------------------------------------------------------------===//
     483             : 
     484             : // Out of line virtual method.
     485           0 : void format_object_base::home() {
     486           0 : }
     487             : 
     488             : //===----------------------------------------------------------------------===//
     489             : //  raw_fd_ostream
     490             : //===----------------------------------------------------------------------===//
     491             : 
     492       49331 : static int getFD(StringRef Filename, std::error_code &EC,
     493             :                  sys::fs::OpenFlags Flags) {
     494             :   // Handle "-" as stdout. Note that when we do this, we consider ourself
     495             :   // the owner of stdout and may set the "binary" flag globally based on Flags.
     496       91237 :   if (Filename == "-") {
     497       41906 :     EC = std::error_code();
     498             :     // If user requested binary then put stdout into binary mode if
     499             :     // possible.
     500       41906 :     if (!(Flags & sys::fs::F_Text))
     501       21394 :       sys::ChangeStdoutToBinary();
     502             :     return STDOUT_FILENO;
     503             :   }
     504             : 
     505             :   int FD;
     506        7425 :   EC = sys::fs::openFileForWrite(Filename, FD, Flags);
     507        7425 :   if (EC)
     508             :     return -1;
     509             : 
     510        7117 :   return FD;
     511             : }
     512             : 
     513       49331 : raw_fd_ostream::raw_fd_ostream(StringRef Filename, std::error_code &EC,
     514       49331 :                                sys::fs::OpenFlags Flags)
     515       49331 :     : raw_fd_ostream(getFD(Filename, EC, Flags), true) {}
     516             : 
     517             : /// FD is the file descriptor that this writes to.  If ShouldClose is true, this
     518             : /// closes the file when the stream is destroyed.
     519      170502 : raw_fd_ostream::raw_fd_ostream(int fd, bool shouldClose, bool unbuffered)
     520             :     : raw_pwrite_stream(unbuffered), FD(fd), ShouldClose(shouldClose),
     521      341004 :       Error(false) {
     522      170502 :   if (FD < 0 ) {
     523         308 :     ShouldClose = false;
     524         308 :     return;
     525             :   }
     526             : 
     527             :   // Do not attempt to close stdout or stderr. We used to try to maintain the
     528             :   // property that tools that support writing file to stdout should not also
     529             :   // write informational output to stdout, but in practice we were never able to
     530             :   // maintain this invariant. Many features have been added to LLVM and clang
     531             :   // (-fdump-record-layouts, optimization remarks, etc) that print to stdout, so
     532             :   // users must simply be aware that mixed output and remarks is a possibility.
     533      170194 :   if (FD <= STDERR_FILENO)
     534      157096 :     ShouldClose = false;
     535             : 
     536             :   // Get the starting position.
     537      170194 :   off_t loc = ::lseek(FD, 0, SEEK_CUR);
     538             : #ifdef LLVM_ON_WIN32
     539             :   // MSVCRT's _lseek(SEEK_CUR) doesn't return -1 for pipes.
     540             :   sys::fs::file_status Status;
     541             :   std::error_code EC = status(FD, Status);
     542             :   SupportsSeeking = !EC && Status.type() == sys::fs::file_type::regular_file;
     543             : #else
     544      170194 :   SupportsSeeking = loc != (off_t)-1;
     545             : #endif
     546      170194 :   if (!SupportsSeeking)
     547      155181 :     pos = 0;
     548             :   else
     549       15013 :     pos = static_cast<uint64_t>(loc);
     550             : }
     551             : 
     552      520584 : raw_fd_ostream::~raw_fd_ostream() {
     553      170275 :   if (FD >= 0) {
     554      333436 :     flush();
     555      333436 :     if (ShouldClose && sys::Process::SafelyCloseFileDescriptor(FD))
     556           0 :       error_detected();
     557             :   }
     558             : 
     559             : #ifdef __MINGW32__
     560             :   // On mingw, global dtors should not call exit().
     561             :   // report_fatal_error() invokes exit(). We know report_fatal_error()
     562             :   // might not write messages to stderr when any errors were detected
     563             :   // on FD == 2.
     564             :   if (FD == 2) return;
     565             : #endif
     566             : 
     567             :   // If there are any pending errors, report them now. Clients wishing
     568             :   // to avoid report_fatal_error calls should check for errors with
     569             :   // has_error() and clear the error flag with clear_error() before
     570             :   // destructing raw_ostream objects which may have errors.
     571      170275 :   if (has_error())
     572          11 :     report_fatal_error("IO failure on output stream.", /*GenCrashDiag=*/false);
     573      180045 : }
     574             : 
     575    18116186 : void raw_fd_ostream::write_impl(const char *Ptr, size_t Size) {
     576             :   assert(FD >= 0 && "File already closed.");
     577    18116186 :   pos += Size;
     578             : 
     579             : #ifndef LLVM_ON_WIN32
     580             : #if defined(__linux__)
     581    18116186 :   bool ShouldWriteInChunks = true;
     582             : #else
     583             :   bool ShouldWriteInChunks = false;
     584             : #endif
     585             : #else
     586             :   // Writing a large size of output to Windows console returns ENOMEM. It seems
     587             :   // that, prior to Windows 8, WriteFile() is redirecting to WriteConsole(), and
     588             :   // the latter has a size limit (66000 bytes or less, depending on heap usage).
     589             :   bool ShouldWriteInChunks = !!::_isatty(FD) && !RunningWindows8OrGreater();
     590             : #endif
     591             : 
     592             :   do {
     593    18132157 :     size_t ChunkSize = Size;
     594    18132157 :     if (ChunkSize > 32767 && ShouldWriteInChunks)
     595       15971 :         ChunkSize = 32767;
     596             : 
     597    18132157 :     ssize_t ret = ::write(FD, Ptr, ChunkSize);
     598             : 
     599    18132157 :     if (ret < 0) {
     600             :       // If it's a recoverable error, swallow it and retry the write.
     601             :       //
     602             :       // Ideally we wouldn't ever see EAGAIN or EWOULDBLOCK here, since
     603             :       // raw_ostream isn't designed to do non-blocking I/O. However, some
     604             :       // programs, such as old versions of bjam, have mistakenly used
     605             :       // O_NONBLOCK. For compatibility, emulate blocking semantics by
     606             :       // spinning until the write succeeds. If you don't want spinning,
     607             :       // don't use O_NONBLOCK file descriptors with raw_ostream.
     608       16333 :       if (errno == EINTR || errno == EAGAIN
     609             : #ifdef EWOULDBLOCK
     610       16333 :           || errno == EWOULDBLOCK
     611             : #endif
     612             :           )
     613           0 :         continue;
     614             : 
     615             :       // Otherwise it's a non-recoverable error. Note it and quit.
     616       16333 :       error_detected();
     617             :       break;
     618             :     }
     619             : 
     620             :     // The write may have written some or all of the data. Update the
     621             :     // size and buffer pointer to reflect the remainder that needs
     622             :     // to be written. If there are no bytes left, we're done.
     623    18115824 :     Ptr += ret;
     624    18115824 :     Size -= ret;
     625    18115824 :   } while (Size > 0);
     626    18116186 : }
     627             : 
     628        3249 : void raw_fd_ostream::close() {
     629             :   assert(ShouldClose);
     630        3249 :   ShouldClose = false;
     631        6498 :   flush();
     632        3249 :   if (sys::Process::SafelyCloseFileDescriptor(FD))
     633           0 :     error_detected();
     634        3249 :   FD = -1;
     635        3249 : }
     636             : 
     637        8436 : uint64_t raw_fd_ostream::seek(uint64_t off) {
     638             :   assert(SupportsSeeking && "Stream does not support seeking!");
     639       16872 :   flush();
     640             : #ifdef LLVM_ON_WIN32
     641             :   pos = ::_lseeki64(FD, off, SEEK_SET);
     642             : #elif defined(HAVE_LSEEK64)
     643        8436 :   pos = ::lseek64(FD, off, SEEK_SET);
     644             : #else
     645             :   pos = ::lseek(FD, off, SEEK_SET);
     646             : #endif
     647        8436 :   if (pos == (uint64_t)-1)
     648           0 :     error_detected();
     649        8436 :   return pos;
     650             : }
     651             : 
     652        3586 : void raw_fd_ostream::pwrite_impl(const char *Ptr, size_t Size,
     653             :                                  uint64_t Offset) {
     654        7172 :   uint64_t Pos = tell();
     655        3586 :   seek(Offset);
     656        3586 :   write(Ptr, Size);
     657        3586 :   seek(Pos);
     658        3586 : }
     659             : 
     660       54012 : size_t raw_fd_ostream::preferred_buffer_size() const {
     661             : #if !defined(_MSC_VER) && !defined(__MINGW32__) && !defined(__minix)
     662             :   // Windows and Minix have no st_blksize.
     663             :   assert(FD >= 0 && "File not yet open!");
     664             :   struct stat statbuf;
     665      108024 :   if (fstat(FD, &statbuf) != 0)
     666             :     return 0;
     667             : 
     668             :   // If this is a terminal, don't use buffering. Line buffering
     669             :   // would be a more traditional thing to do, but it's not worth
     670             :   // the complexity.
     671       54012 :   if (S_ISCHR(statbuf.st_mode) && isatty(FD))
     672             :     return 0;
     673             :   // Return the preferred block size.
     674       54012 :   return statbuf.st_blksize;
     675             : #else
     676             :   return raw_ostream::preferred_buffer_size();
     677             : #endif
     678             : }
     679             : 
     680         758 : raw_ostream &raw_fd_ostream::changeColor(enum Colors colors, bool bold,
     681             :                                          bool bg) {
     682         758 :   if (sys::Process::ColorNeedsFlush())
     683           0 :     flush();
     684             :   const char *colorcode =
     685        1406 :     (colors == SAVEDCOLOR) ? sys::Process::OutputBold(bg)
     686        1406 :     : sys::Process::OutputColor(colors, bold, bg);
     687         758 :   if (colorcode) {
     688         758 :     size_t len = strlen(colorcode);
     689         758 :     write(colorcode, len);
     690             :     // don't account colors towards output characters
     691         758 :     pos -= len;
     692             :   }
     693         758 :   return *this;
     694             : }
     695             : 
     696         751 : raw_ostream &raw_fd_ostream::resetColor() {
     697         751 :   if (sys::Process::ColorNeedsFlush())
     698           0 :     flush();
     699         751 :   const char *colorcode = sys::Process::ResetColor();
     700         751 :   if (colorcode) {
     701         751 :     size_t len = strlen(colorcode);
     702         751 :     write(colorcode, len);
     703             :     // don't account colors towards output characters
     704         751 :     pos -= len;
     705             :   }
     706         751 :   return *this;
     707             : }
     708             : 
     709           0 : raw_ostream &raw_fd_ostream::reverseColor() {
     710           0 :   if (sys::Process::ColorNeedsFlush())
     711           0 :     flush();
     712           0 :   const char *colorcode = sys::Process::OutputReverse();
     713           0 :   if (colorcode) {
     714           0 :     size_t len = strlen(colorcode);
     715           0 :     write(colorcode, len);
     716             :     // don't account colors towards output characters
     717           0 :     pos -= len;
     718             :   }
     719           0 :   return *this;
     720             : }
     721             : 
     722        1605 : bool raw_fd_ostream::is_displayed() const {
     723        1605 :   return sys::Process::FileDescriptorIsDisplayed(FD);
     724             : }
     725             : 
     726      127909 : bool raw_fd_ostream::has_colors() const {
     727      127909 :   return sys::Process::FileDescriptorHasColors(FD);
     728             : }
     729             : 
     730             : //===----------------------------------------------------------------------===//
     731             : //  outs(), errs(), nulls()
     732             : //===----------------------------------------------------------------------===//
     733             : 
     734             : /// outs() - This returns a reference to a raw_ostream for standard output.
     735             : /// Use it like: outs() << "foo" << "bar";
     736     1141254 : raw_ostream &llvm::outs() {
     737             :   // Set buffer settings to model stdout behavior.
     738     1141254 :   std::error_code EC;
     739     1148031 :   static raw_fd_ostream S("-", EC, sys::fs::F_None);
     740             :   assert(!EC);
     741     1141254 :   return S;
     742             : }
     743             : 
     744             : /// errs() - This returns a reference to a raw_ostream for standard error.
     745             : /// Use it like: errs() << "foo" << "bar";
     746      374499 : raw_ostream &llvm::errs() {
     747             :   // Set standard error to be unbuffered by default.
     748      374499 :   static raw_fd_ostream S(STDERR_FILENO, false, true);
     749      374499 :   return S;
     750             : }
     751             : 
     752             : /// nulls() - This returns a reference to a raw_ostream which discards output.
     753     8828778 : raw_ostream &llvm::nulls() {
     754     8829876 :   static raw_null_ostream S;
     755     8828778 :   return S;
     756             : }
     757             : 
     758             : //===----------------------------------------------------------------------===//
     759             : //  raw_string_ostream
     760             : //===----------------------------------------------------------------------===//
     761             : 
     762     3151611 : raw_string_ostream::~raw_string_ostream() {
     763     3151608 :   flush();
     764     1575807 : }
     765             : 
     766     1519619 : void raw_string_ostream::write_impl(const char *Ptr, size_t Size) {
     767     1519619 :   OS.append(Ptr, Size);
     768     1519619 : }
     769             : 
     770             : //===----------------------------------------------------------------------===//
     771             : //  raw_svector_ostream
     772             : //===----------------------------------------------------------------------===//
     773             : 
     774     8510338 : uint64_t raw_svector_ostream::current_pos() const { return OS.size(); }
     775             : 
     776   240119108 : void raw_svector_ostream::write_impl(const char *Ptr, size_t Size) {
     777   240119108 :   OS.append(Ptr, Ptr + Size);
     778   240119114 : }
     779             : 
     780        3015 : void raw_svector_ostream::pwrite_impl(const char *Ptr, size_t Size,
     781             :                                       uint64_t Offset) {
     782        6030 :   memcpy(OS.data() + Offset, Ptr, Size);
     783        3015 : }
     784             : 
     785             : //===----------------------------------------------------------------------===//
     786             : //  raw_null_ostream
     787             : //===----------------------------------------------------------------------===//
     788             : 
     789      506312 : raw_null_ostream::~raw_null_ostream() {
     790             : #ifndef NDEBUG
     791             :   // ~raw_ostream asserts that the buffer is empty. This isn't necessary
     792             :   // with raw_null_ostream, but it's better to have raw_null_ostream follow
     793             :   // the rules than to change the rules just for raw_null_ostream.
     794             :   flush();
     795             : #endif
     796      253162 : }
     797             : 
     798           0 : void raw_null_ostream::write_impl(const char *Ptr, size_t Size) {
     799           0 : }
     800             : 
     801           0 : uint64_t raw_null_ostream::current_pos() const {
     802           0 :   return 0;
     803             : }
     804             : 
     805           0 : void raw_null_ostream::pwrite_impl(const char *Ptr, size_t Size,
     806           0 :                                    uint64_t Offset) {}

Generated by: LCOV version 1.13